Beispiel #1
0
static void sigver(FILE *in, FILE *out)
    {
    DSA *dsa=NULL;
    char buf[1024];
    char lbuf[1024];
    unsigned char msg[1024];
    char *keyword, *value;
    int n=0;
    int dsa2, L, N;
    const EVP_MD *md = NULL;
    DSA_SIG sg, *sig = &sg;

    sig->r = NULL;
    sig->s = NULL;

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		fputs(buf,out);
		continue;
		}
	fputs(buf,out);
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, &md))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    if (dsa)
		FIPS_dsa_free(dsa);
	    dsa = FIPS_dsa_new();
	    }
	else if(!strcmp(keyword,"P"))
	    dsa->p=hex2bn(value);
	else if(!strcmp(keyword,"Q"))
	    dsa->q=hex2bn(value);
	else if(!strcmp(keyword,"G"))
	    dsa->g=hex2bn(value);
	else if(!strcmp(keyword,"Msg"))
	    n=hex2bin(value,msg);
	else if(!strcmp(keyword,"Y"))
	    dsa->pub_key=hex2bn(value);
	else if(!strcmp(keyword,"R"))
	    sig->r=hex2bn(value);
	else if(!strcmp(keyword,"S"))
	    {
	    EVP_MD_CTX mctx;
	    int r;
	    FIPS_md_ctx_init(&mctx);
	    sig->s=hex2bn(value);

	    FIPS_digestinit(&mctx, md);
	    FIPS_digestupdate(&mctx, msg, n);
	    no_err = 1;
	    r = FIPS_dsa_verify_ctx(dsa, &mctx, sig);
	    no_err = 0;
	    FIPS_md_ctx_cleanup(&mctx);
	
	    fprintf(out, "Result = %c\n\n", r == 1 ? 'P' : 'F');
	    }
	}
    }
Beispiel #2
0
/* Go through the file and parse each line */
int config_parse(const char *unit,
                 const char *filename,
                 FILE *f,
                 const char *sections,
                 ConfigItemLookup lookup,
                 const void *table,
                 bool relaxed,
                 bool allow_include,
                 bool warn,
                 void *userdata) {

    _cleanup_free_ char *section = NULL, *continuation = NULL;
    _cleanup_fclose_ FILE *ours = NULL;
    unsigned line = 0, section_line = 0;
    bool section_ignored = false;
    int r;

    assert(filename);
    assert(lookup);

    if (!f) {
        f = ours = fopen(filename, "re");
        if (!f) {
            /* Only log on request, except for ENOENT,
             * since we return 0 to the caller. */
            if (warn || errno == ENOENT)
                log_full(errno == ENOENT ? LOG_DEBUG : LOG_ERR,
                         "Failed to open configuration file '%s': %m", filename);
            return errno == ENOENT ? 0 : -errno;
        }
    }

    fd_warn_permissions(filename, fileno(f));

    while (!feof(f)) {
        char l[LINE_MAX], *p, *c = NULL, *e;
        bool escaped = false;

        if (!fgets(l, sizeof(l), f)) {
            if (feof(f))
                break;

            log_error_errno(errno, "Failed to read configuration file '%s': %m", filename);
            return -errno;
        }

        truncate_nl(l);

        if (continuation) {
            c = strappend(continuation, l);
            if (!c) {
                if (warn)
                    log_oom();
                return -ENOMEM;
            }

            continuation = mfree(continuation);
            p = c;
        } else
            p = l;

        for (e = p; *e; e++) {
            if (escaped)
                escaped = false;
            else if (*e == '\\')
                escaped = true;
        }

        if (escaped) {
            *(e-1) = ' ';

            if (c)
                continuation = c;
            else {
                continuation = strdup(l);
                if (!continuation) {
                    if (warn)
                        log_oom();
                    return -ENOMEM;
                }
            }

            continue;
        }

        r = parse_line(unit,
                       filename,
                       ++line,
                       sections,
                       lookup,
                       table,
                       relaxed,
                       allow_include,
                       &section,
                       &section_line,
                       &section_ignored,
                       p,
                       userdata);
        free(c);

        if (r < 0) {
            if (warn)
                log_warning_errno(r, "Failed to parse file '%s': %m",
                                  filename);
            return r;
        }
    }

    return 0;
}
parse_code_t parse_config_file (file_option_t opts[], const char *filename)
{
  unsigned int len=80;
  char *line = malloc(len);
  int readoffset, thischar, lineno;
  FILE *file;
  parse_code_t pcode;
  char empty[] = "";

  if (!line) {
      parse_error(parse_syserr, 0, empty, empty);
      return parse_syserr;
  }

  file = fopen (filename, "r");
  if (!file) {
      parse_error (parse_syserr, 0, empty, empty);
      free (line);
      return parse_syserr;
  }

  lineno = 0;
  while (!feof (file)) {

    lineno++;
    readoffset = 0;
    memset (line, 0, len);

    while ((thischar = fgetc(file)) != EOF) {

      if (readoffset + 1 > len) {
	len *= 2;
	line = realloc (line, len);
	if (!line)
	  {
	    parse_error(parse_syserr, 0, empty, empty);
	    fclose (file);
	    return parse_syserr;
	  }
      }

      if (thischar == '\n') {
	line[readoffset] = '\0';
	break;
      }
      else
	line[readoffset] = (unsigned char) thischar;
      readoffset++;

    }

    pcode = parse_line (opts, line);

    if (pcode != parse_ok)
      if (!parse_error(pcode, lineno, filename, line)) {
	free (line);
	return pcode;
      }

  }

  free (line);
  return parse_ok;
}
Beispiel #4
0
/* Go through the file and parse each line */
int config_parse(const char *unit,
                 const char *filename,
                 FILE *f,
                 const char *sections,
                 ConfigItemLookup lookup,
                 void *table,
                 bool relaxed,
                 bool allow_include,
                 void *userdata) {

        _cleanup_free_ char *section = NULL, *continuation = NULL;
        _cleanup_fclose_ FILE *ours = NULL;
        unsigned line = 0, section_line = 0;
        int r;

        assert(filename);
        assert(lookup);

        if (!f) {
                f = ours = fopen(filename, "re");
                if (!f) {
                        log_error("Failed to open configuration file '%s': %m", filename);
                        return -errno;
                }
        }

        fd_warn_permissions(filename, fileno(f));

        while (!feof(f)) {
                char l[LINE_MAX], *p, *c = NULL, *e;
                bool escaped = false;

                if (!fgets(l, sizeof(l), f)) {
                        if (feof(f))
                                break;

                        log_error("Failed to read configuration file '%s': %m", filename);
                        return -errno;
                }

                truncate_nl(l);

                if (continuation) {
                        c = strappend(continuation, l);
                        if (!c)
                                return -ENOMEM;

                        free(continuation);
                        continuation = NULL;
                        p = c;
                } else
                        p = l;

                for (e = p; *e; e++) {
                        if (escaped)
                                escaped = false;
                        else if (*e == '\\')
                                escaped = true;
                }

                if (escaped) {
                        *(e-1) = ' ';

                        if (c)
                                continuation = c;
                        else {
                                continuation = strdup(l);
                                if (!continuation)
                                        return -ENOMEM;
                        }

                        continue;
                }

                r = parse_line(unit,
                               filename,
                               ++line,
                               sections,
                               lookup,
                               table,
                               relaxed,
                               allow_include,
                               &section,
                               &section_line,
                               p,
                               userdata);
                free(c);

                if (r < 0)
                        return r;
        }

        return 0;
}
int main(int argc, char * const argv[])
{
	int r, c, long_optind = 0, err = 0;
	char *line;
	int cargc;
	char *cargv[260];
	sc_context_param_t ctx_param;
	int lcycle = SC_CARDCTRL_LIFECYCLE_ADMIN;

	printf("OpenSC Explorer version %s\n", sc_get_version());

	while (1) {
		c = getopt_long(argc, argv, "r:c:vwm:", options, &long_optind);
		if (c == -1)
			break;
		if (c == '?')
			util_print_usage_and_die(app_name, options, option_help);
		switch (c) {
		case 'r':
			opt_reader = optarg;
			break;
		case 'c':
			opt_driver = optarg;
			break;
		case 'w':
			opt_wait = 1;
			break;
		case 'v':
			verbose++;
			break;
		case 'm':
			opt_startfile = optarg;
			break;
		}
	}

	memset(&ctx_param, 0, sizeof(ctx_param));
	ctx_param.ver      = 0;
	ctx_param.app_name = app_name;

	r = sc_context_create(&ctx, &ctx_param);
	if (r) {
		fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
		return 1;
	}

	if (verbose > 1) {
		ctx->debug = verbose;
		ctx->debug_file = stderr;
        }

	if (opt_driver != NULL) {
		err = sc_set_card_driver(ctx, opt_driver);
		if (err) {
			fprintf(stderr, "Driver '%s' not found!\n", opt_driver);
			err = 1;
			goto end;
		}
	}

	err = util_connect_card(ctx, &card, opt_reader, opt_wait, 0);
	if (err)
		goto end;

	if (opt_startfile) {
		if(*opt_startfile) {
			char startpath[1024];
			char *args[] = { startpath };

			strncpy(startpath, opt_startfile, sizeof(startpath)-1);
			r = do_cd(1, args);
			if (r) {
				printf("unable to select file %s: %s\n",
					opt_startfile, sc_strerror(r));
				return -1;
			}
		}
	} else {
		sc_format_path("3F00", &current_path);
		r = sc_select_file(card, &current_path, &current_file);
		if (r) {
			printf("unable to select MF: %s\n", sc_strerror(r));
			return 1;
		}
	}

	r = sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
	if (r && r != SC_ERROR_NOT_SUPPORTED)
		printf("unable to change lifecycle: %s\n", sc_strerror(r));

	while (1) {
		struct command *cmd;
		char prompt[3*SC_MAX_PATH_STRING_SIZE];

		sprintf(prompt, "OpenSC [%s]> ", path_to_filename(&current_path, '/'));
		line = my_readline(prompt);
		if (line == NULL)
			break;
		cargc = parse_line(line, cargv, DIM(cargv));
		if (cargc < 1)
			continue;
		for (r=cargc; r < (int)DIM(cargv); r++)
			cargv[r] = "";
		cmd = ambiguous_match(cmds, cargv[0]);
		if (cmd == NULL) {
			do_help(0, NULL);
		} else {
			cmd->func(cargc-1, cargv+1);
		}
	}
end:
	die(err);

	return 0; /* not reached */
}
Beispiel #6
0
void
parse_one_file(char *filename)
{
	char *fieldv[MAXFIELDS];
	int fieldc;
	void (*f)(int c, char **v);
	FILE *cf;
	char line[MAXLINELEN];

	snprintf(line, sizeof(line), "reading %s", filename);
	status(line);
	strlcpy(curfilename, filename, sizeof(curfilename));

	if ((cf = fopen(curfilename, "r")) == NULL) {
		warn("%s", curfilename);
		goterror = 1;
		return;
	}

	linenum = 0;
	while (fgets(line, MAXLINELEN, cf) != NULL) {
		linenum++;
		parse_line(line, &fieldc, fieldv, MAXFIELDS);

		if (fieldc < 1)
			continue;

		if (!strcmp(fieldv[0], "srcdirs"))
			f = add_srcdirs;
		else if(!strcmp(fieldv[0], "progs"))
			f = add_progs;
		else if(!strcmp(fieldv[0], "ln"))
			f = add_link;
		else if(!strcmp(fieldv[0], "libs"))
			f = add_libs;
		else if(!strcmp(fieldv[0], "libs_so"))
			f = add_libs_so;
		else if(!strcmp(fieldv[0], "buildopts"))
			f = add_buildopts;
		else if(!strcmp(fieldv[0], "special"))
			f = add_special;
		else {
			warnx("%s:%d: skipping unknown command `%s'",
			    curfilename, linenum, fieldv[0]);
			goterror = 1;
			continue;
		}

		if (fieldc < 2) {
			warnx("%s:%d: %s %s",
			    curfilename, linenum, fieldv[0],
			    "command needs at least 1 argument, skipping");
			goterror = 1;
			continue;
		}

		f(fieldc, fieldv);
	}

	if (ferror(cf)) {
		warn("%s", curfilename);
		goterror = 1;
	}
	fclose(cf);
}
Beispiel #7
0
static errcode_t parse_file(FILE *f, struct parse_state *state,
                            char **ret_modspec)
{
#define BUF_SIZE        2048
    char *bptr;
    errcode_t retval;

    bptr = malloc (BUF_SIZE);
    if (!bptr)
        return ENOMEM;

    while (!feof(f)) {
        if (fgets(bptr, BUF_SIZE, f) == NULL)
            break;
#ifndef PROFILE_SUPPORTS_FOREIGN_NEWLINES
        retval = parse_line(bptr, state, ret_modspec);
        if (retval) {
            free (bptr);
            return retval;
        }
#else
        {
            char *p, *end;

            if (strlen(bptr) >= BUF_SIZE - 1) {
                /* The string may have foreign newlines and
                   gotten chopped off on a non-newline
                   boundary.  Seek backwards to the last known
                   newline.  */
                long offset;
                char *c = bptr + strlen (bptr);
                for (offset = 0; offset > -BUF_SIZE; offset--) {
                    if (*c == '\r' || *c == '\n') {
                        *c = '\0';
                        fseek (f, offset, SEEK_CUR);
                        break;
                    }
                    c--;
                }
            }

            /* First change all newlines to \n */
            for (p = bptr; *p != '\0'; p++) {
                if (*p == '\r')
                    *p = '\n';
            }
            /* Then parse all lines */
            p = bptr;
            end = bptr + strlen (bptr);
            while (p < end) {
                char* newline;
                char* newp;

                newline = strchr (p, '\n');
                if (newline != NULL)
                    *newline = '\0';

                /* parse_line modifies contents of p */
                newp = p + strlen (p) + 1;
                retval = parse_line (p, state, ret_modspec);
                if (retval) {
                    free (bptr);
                    return retval;
                }

                p = newp;
            }
        }
#endif
    }

    free (bptr);
    return 0;
}
Beispiel #8
0
static int
parse_log(void)
{
	pkgentry_t *ent, *look;
	avl_index_t where;
	int num = 0;
	int logfd;
	struct stat stb;
	int mlen = strlen(marker);
	off_t realend;
	ptrdiff_t off;
	char *p, *q, *map;

	logfd = open(PKGLOG, O_RDONLY);

	if (logfd < 0) {
		if (errno == ENOENT)
			return (0);
		progerr(gettext("cannot read "PKGLOG": %s"), strerror(errno));
		exit(2);
	}

	if (fstat(logfd, &stb) != 0) {
		progerr(gettext("cannot stat "PKGLOG": %s"), strerror(errno));
		exit(2);
	}

	if (stb.st_size == 0) {
		(void) close(logfd);
		/* Force pkgdump && remove of the logfile. */
		return (1);
	}

	map = mmap(0, stb.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE,
	    logfd, 0);
	(void) close(logfd);
	if (map == (char *)-1) {
		progerr(gettext("Cannot mmap the "PKGLOG": %s"),
		    strerror(errno));
		exit(2);
	}

	cind = 0;

	realend = stb.st_size;

	if (memcmp(map + realend - mlen, marker, mlen) != 0) {
		progerr(gettext(PKGLOG" is not complete"));

		map[stb.st_size - 1] = '\0'; /* for strstr() */
		realend = 0;
		for (p = map; q = strstr(p, marker); ) {
			if (q == map || q[-1] == '\n')
				realend = q - map + mlen;
			p = q + mlen;
		}
		progerr(gettext("Ignoring %ld bytes from log"),
		    (long)(stb.st_size - realend));
	}

	for (off = 0; off < realend; off += q - p) {
		p = map + off;
		q = memchr(p, '\n', realend - off);
		if (q == NULL)
			break;

		q++;
		num++;
		if (p[0] == '#' || p[0] == '\n') {
			if (memcmp(marker, p, mlen) == 0)
				cind = 0;
			else
				handle_comments(p, q - p);
			continue;
		}

		ent = parse_line(p + 1, q - (p + 1) - 1, p[0] != '-');
		if (ent == NULL)
			continue;
		look = avl_find(list, ent, &where);
		/*
		 * The log can be replayed; so any value of "look" is
		 * not unexpected.
		 */
		switch (p[0]) {
		case '+':
		case '=':
			if (look != NULL)
				swapentry(look, ent);
			else
				avl_insert(list, ent, where);
			break;
		case '-':
			if (look != NULL) {
				avl_remove(list, look);
				freeentry(look);
			}
			freeentry(ent);
			break;
		default:
			freeentry(ent);
			progerr(gettext("log %d: bad line"), num);
			break;
		}
	}
	(void) munmap(map, stb.st_size);

	/* Force pkgdump && remove of the logfile if there are no valid mods. */
	return (num == 0 ? 1 : num);
}
int parse_cmdline_options (int argc, char **argv,
			   ogg123_options_t *ogg123_opts,
			   file_option_t    *file_opts)
{
  int option_index = 1;
  ao_option *temp_options = NULL;
  ao_option ** current_options = &temp_options;
  ao_info *info;
  int temp_driver_id = -1;
  audio_device_t *current;
  int ret;

  while (-1 != (ret = getopt_long(argc, argv, "b:c::d:f:hl:k:K:o:p:qvVx:y:[email protected]:",
				  long_options, &option_index))) {

      switch (ret) {
      case 0:
	if(!strcmp(long_options[option_index].name, "audio-buffer")) {
	  ogg123_opts->buffer_size = 1024 * atoi(optarg);
	} else {
	  status_error(_("Internal error parsing command line options.\n"));
	  exit(1);
	}
	break;
      case 'b':
	ogg123_opts->input_buffer_size = atoi(optarg) * 1024;
	if (ogg123_opts->input_buffer_size < MIN_INPUT_BUFFER_SIZE * 1024) {
	  status_error(_("Input buffer size smaller than minimum size of %dkB."),
		       MIN_INPUT_BUFFER_SIZE);
	  ogg123_opts->input_buffer_size = MIN_INPUT_BUFFER_SIZE * 1024;
	}
	break;
	
      case 'c':
	if (optarg) {
	  char *tmp = strdup (optarg);
	  parse_code_t pcode = parse_line(file_opts, tmp);

	  if (pcode != parse_ok)
	    status_error(_("=== Error \"%s\" while parsing config option from command line.\n"
			 "=== Option was: %s\n"),
			 parse_error_string(pcode), optarg);
	  free (tmp);
	}
	else {
	  /* not using the status interface here */
	  fprintf (stdout, _("Available options:\n"));
	  file_options_describe(file_opts, stdout);
	  exit (0);
	}
	break;
	
      case 'd':
	temp_driver_id = ao_driver_id(optarg);
	if (temp_driver_id < 0) {
	    status_error(_("=== No such device %s.\n"), optarg);
	    exit(1);
	}

	current = append_audio_device(ogg123_opts->devices,
				      temp_driver_id, 
				      NULL, NULL);
	if(ogg123_opts->devices == NULL)
	  ogg123_opts->devices = current;
	current_options = &current->options;
	break;
	
      case 'f':
	if (temp_driver_id >= 0) {

	  info = ao_driver_info(temp_driver_id);
	  if (info->type == AO_TYPE_FILE) {
	    free(current->filename);
	    current->filename = strdup(optarg);
	  } else {
	    status_error(_("=== Driver %s is not a file output driver.\n"),
			 info->short_name);
	    exit(1);
	  }
	} else {
	  status_error(_("=== Cannot specify output file without specifying a driver.\n"));
	  exit (1);
	}
	break;

	case 'k':
	  ogg123_opts->seekpos = strtotime(optarg);
	  break;
	  
	case 'K':
	  ogg123_opts->endpos = strtotime(optarg);
	  break;
	  
	case 'l':
	  ogg123_opts->delay = atoi(optarg);
	  break;
	  
	case 'o':
	  if (optarg && !add_ao_option(current_options, optarg)) {
	    status_error(_("=== Incorrect option format: %s.\n"), optarg);
	    exit(1);
	  }
	  break;

	case 'h':
	  cmdline_usage();
	  exit(0);
	  break;
	  
	case 'p':
	  ogg123_opts->input_prebuffer = atof (optarg);
	  if (ogg123_opts->input_prebuffer < 0.0f || 
	      ogg123_opts->input_prebuffer > 100.0f) {

	    status_error (_("--- Prebuffer value invalid. Range is 0-100.\n"));
	    ogg123_opts->input_prebuffer = 
	      ogg123_opts->input_prebuffer < 0.0f ? 0.0f : 100.0f;
	  }
	  break;

      case 'q':
	ogg123_opts->verbosity = 0;
	break;
	
      case 'v':
	ogg123_opts->verbosity++;
	break;
	
      case 'V':
	status_error(_("ogg123 from %s %s\n"), PACKAGE, VERSION);
	exit(0);
	break;

      case 'x':
	ogg123_opts->nth = atoi(optarg);
	if (ogg123_opts->nth == 0) {
	  status_error(_("--- Cannot play every 0th chunk!\n"));
	  ogg123_opts->nth = 1;
	}
	break;
	  
      case 'y':
	ogg123_opts->ntimes = atoi(optarg);
	if (ogg123_opts->ntimes == 0) {
	  status_error(_("--- Cannot play every chunk 0 times.\n"
		 "--- To do a test decode, use the null output driver.\n"));
	  ogg123_opts->ntimes = 1;
	}
	break;
	
      case 'z':
	ogg123_opts->shuffle = 1;
	break;

      case '@':
	if (playlist_append_from_file(ogg123_opts->playlist, optarg) == 0)
	  status_error(_("--- Cannot open playlist file %s.  Skipped.\n"),
		       optarg);
	break;
		
      case '?':
	break;
	
      default:
	cmdline_usage();
	exit(1);
      }
  }

  /* Sanity check bad option combinations */
  if (ogg123_opts->endpos > 0.0 &&
      ogg123_opts->seekpos > ogg123_opts->endpos) {
    status_error(_("=== Option conflict: End time is before start time.\n"));
    exit(1);
  }


  /* Add last device to device list or use the default device */
  if (temp_driver_id < 0) {

      /* First try config file setting */
      if (ogg123_opts->default_device) {
	  temp_driver_id = ao_driver_id(ogg123_opts->default_device);

	  if (temp_driver_id < 0)
	    status_error(_("--- Driver %s specified in configuration file invalid.\n"),
			 ogg123_opts->default_device);
      }
      
      /* Then try libao autodetect */
      if (temp_driver_id < 0)
	temp_driver_id = ao_default_driver_id();

      /* Finally, give up */
      if (temp_driver_id < 0) {
	status_error(_("=== Could not load default driver and no driver specified in config file. Exiting.\n"));
	exit(1);
      }

      ogg123_opts->devices = append_audio_device(ogg123_opts->devices,
					     temp_driver_id,
					     temp_options, 
					     NULL);
    }


  return optind;
}
Beispiel #10
0
static int loadfile(struct sr_input *in, const char *filename)
{
	int res;
	struct context *ctx;
	struct sr_datafeed_packet packet;
	struct sr_datafeed_meta meta;
	struct sr_config *cfg;
	GIOStatus status;
	gboolean read_new_line;
	gsize term_pos;
	char **columns;
	gsize num_columns;
	int max_columns;

	(void)filename;

	ctx = in->internal;

	/* Send header packet to the session bus. */
	std_session_send_df_header(in->sdi, LOG_PREFIX);

	if (ctx->samplerate) {
		packet.type = SR_DF_META;
		packet.payload = &meta;
		cfg = sr_config_new(SR_CONF_SAMPLERATE,
			g_variant_new_uint64(ctx->samplerate));
		meta.config = g_slist_append(NULL, cfg);
		sr_session_send(in->sdi, &packet);
		sr_config_free(cfg);
	}

	read_new_line = FALSE;

	/* Limit the number of columns to parse. */
	if (ctx->multi_column_mode)
		max_columns = ctx->num_probes;
	else
		max_columns = 1;

	while (TRUE) {
		/*
		 * Skip reading a new line for the first time if the last read
		 * line was not a header because the sample data is not parsed
		 * yet.
		 */
		if (read_new_line || ctx->header) {
			ctx->line_number++;
			status = g_io_channel_read_line_string(ctx->channel,
				ctx->buffer, &term_pos, NULL);

			if (status == G_IO_STATUS_EOF)
				break;

			if (status != G_IO_STATUS_NORMAL) {
				sr_err("Error while reading line %zu.",
					ctx->line_number);
				free_context(ctx);
				return SR_ERR;
			}

			/* Remove line termination character(s). */
			g_string_truncate(ctx->buffer, term_pos);
		}

		read_new_line = TRUE;

		if (!ctx->buffer->len) {
			sr_spew("Blank line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove trailing comment. */
		strip_comment(ctx->buffer, ctx->comment);

		if (!ctx->buffer->len) {
			sr_spew("Comment-only line %zu skipped.",
				ctx->line_number);
			continue;
		}

		if (!(columns = parse_line(ctx, max_columns))) {
			sr_err("Error while parsing line %zu.",
				ctx->line_number);
			free_context(ctx);
			return SR_ERR;
		}

		num_columns = g_strv_length(columns);

		/* Ensure that the first column is not out of bounds. */
		if (!num_columns) {
			sr_err("Column %zu in line %zu is out of bounds.",
				ctx->first_column, ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		/*
		 * Ensure that the number of probes does not exceed the number
		 * of columns in multi column mode.
		 */
		if (ctx->multi_column_mode && num_columns < ctx->num_probes) {
			sr_err("Not enough columns for desired number of probes in line %zu.",
				ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		if (ctx->multi_column_mode)
			res = parse_multi_columns(columns, ctx);
		else
			res = parse_single_column(columns[0], ctx);

		if (res != SR_OK) {
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}

		g_strfreev(columns);

		/*
		 * TODO: Parse sample numbers / timestamps and use it for
		 * decompression.
		 */

		/* Send sample data to the session bus. */
		res = send_samples(in->sdi, ctx->sample_buffer,
			ctx->sample_buffer_size, 1);

		if (res != SR_OK) {
			sr_err("Sending samples failed.");
			free_context(ctx);
			return SR_ERR;
		}
	}

	/* Send end packet to the session bus. */
	packet.type = SR_DF_END;
	sr_session_send(in->sdi, &packet);

	free_context(ctx);

	return SR_OK;
}
Beispiel #11
0
static void
parse_contents(void)
{
	int cnt;
	pkgentry_t *ent, *e2;
	avl_index_t where;
	int num = 0;
	struct stat stb;
	ptrdiff_t off;
	char *p, *q, *map;
	pkgentry_t *lastentry = NULL;
	int d;
	int cntserrs = 0;

	cnt = open(CONTENTS, O_RDONLY);

	cind = 0;

	if (cnt == -1) {
		if (errno == ENOENT)
			return;
		exit(99);
	}

	if (fstat(cnt, &stb) != 0) {
		(void) close(cnt);
		exit(99);
	}
	if (stb.st_size == 0) {
		(void) close(cnt);
		return;
	}

	map = mmap(0, stb.st_size, PROT_READ, MAP_PRIVATE, cnt, 0);
	(void) close(cnt);
	if (map == (char *)-1)
		return;

	(void) madvise(map, stb.st_size, MADV_WILLNEED);

	for (off = 0; off < stb.st_size; off += q - p) {
		p = map + off;
		q = memchr(p, '\n', stb.st_size - off);
		if (q == NULL)
			break;

		q++;
		num++;
		if (p[0] == '#' || p[0] == '\n') {
			handle_comments(p, q - p);
			continue;
		}
		ent = parse_line(p, q - p - 1, B_TRUE);

		if (ent == NULL) {
			cntserrs++;
			continue;
		}

		/*
		 * We save time by assuming the database is sorted; by
		 * using avl_insert_here(), building the tree is nearly free.
		 * lastentry always contains the last entry in the AVL tree.
		 */
		if (lastentry == NULL) {
			avl_add(list, ent);
			lastentry = ent;
		} else if ((d = avlcmp(ent, lastentry)) == 1) {
			avl_insert_here(list, ent, lastentry, AVL_AFTER);
			lastentry = ent;
		} else if (d == 0 ||
		    (e2 = avl_find(list, ent, &where)) != NULL) {
			/*
			 * This can only happen if the contents file is bad;
			 * this can, e.g., happen with the old SQL contents DB,
			 * it didn't sort properly.  Assume the first one
			 * is the correct one, but who knows?
			 */
			if (d == 0)
				e2 = lastentry;
			if (strcmp(ent->line, e2->line) != 0) {
				progerr(gettext("two entries for %.*s"),
				    ent->pathlen, ent->line);
				cntserrs++;
			}
			freeentry(ent);
		} else {
			/* Out of order: not an error for us, really. */
			progerr(gettext("bad read of contents file"));
			logerr(gettext("pathname: Unknown"));
			logerr(gettext(
			    "problem: unable to read pathname field"));
			if (one_shot)
				exit(2);
			avl_insert(list, ent, where);
		}
	}

	cind = 0;

	(void) munmap(map, stb.st_size);

	/* By default, we ignore bad lines, keep them in a copy. */
	if (cntserrs > 0 && stb.st_nlink == 1) {
		char bcf[sizeof (BADCONTENTS)];

		(void) strcpy(bcf, BADCONTENTS);
		if (mktemp(bcf) != NULL) {
			(void) link(CONTENTS, bcf);
			syslog(LOG_WARNING, "A bad contents file was saved: %s",
			    bcf);
		}
	}
}
Beispiel #12
0
static int init(struct sr_input *in, const char *filename)
{
	int res;
	struct context *ctx;
	const char *param;
	GIOStatus status;
	gsize i, term_pos;
	char probe_name[SR_MAX_PROBENAME_LEN + 1];
	struct sr_probe *probe;
	char **columns;
	gsize num_columns;
	char *ptr;

	if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
		sr_err("Context malloc failed.");
		return SR_ERR_MALLOC;
	}

	/* Create a virtual device. */
	in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
	in->internal = ctx;

	/* Set default samplerate. */
	ctx->samplerate = 0;

	/*
	 * Enable auto-detection of the number of probes in multi column mode
	 * and enforce the specification of the number of probes in single
	 * column mode.
	 */
	ctx->num_probes = 0;

	/* Set default delimiter. */
	if (!(ctx->delimiter = g_string_new(","))) {
		sr_err("Delimiter malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/*
	 * Set default comment prefix. Note that an empty comment prefix
	 * disables removing of comments.
	 */
	if (!(ctx->comment = g_string_new(""))) {
		sr_err("Comment malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/* Enable multi column mode by default. */
	ctx->multi_column_mode = TRUE;

	/* Use first column as default single column number. */
	ctx->single_column = 0;

	/*
	 * In multi column mode start parsing sample data at the first column
	 * and in single column mode at the first bit.
	 */
	ctx->first_probe = 0;

	/* Start at the beginning of the file. */
	ctx->start_line = 1;

	/* Disable the usage of the first line as header by default. */
	ctx->header = FALSE;

	/* Set default format for single column mode. */
	ctx->format = FORMAT_BIN;

	if (!(ctx->buffer = g_string_new(""))) {
		sr_err("Line buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	if (in->param) {
		if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
			res = sr_parse_sizestring(param, &ctx->samplerate);

			if (res != SR_OK) {
				sr_err("Invalid samplerate: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "numprobes")))
			ctx->num_probes = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
			if (!strlen(param)) {
				sr_err("Delimiter must be at least one character.");
				free_context(ctx);
				return SR_ERR_ARG;
			}

			if (!g_ascii_strcasecmp(param, "\\t"))
				g_string_assign(ctx->delimiter, "\t");
			else
				g_string_assign(ctx->delimiter, param);
		}

		if ((param = g_hash_table_lookup(in->param, "comment")))
			g_string_assign(ctx->comment, param);

		if ((param = g_hash_table_lookup(in->param, "single-column"))) {
			ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
			ctx->multi_column_mode = FALSE;

			if (param == ptr) {
				sr_err("Invalid single-colum number: %s.",
					param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "first-probe")))
			ctx->first_probe = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "startline"))) {
			ctx->start_line = g_ascii_strtoull(param, NULL, 10);

			if (ctx->start_line < 1) {
				sr_err("Invalid start line: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "header")))
			ctx->header = sr_parse_boolstring(param);

		if ((param = g_hash_table_lookup(in->param, "format"))) {
			if (!g_ascii_strncasecmp(param, "bin", 3)) {
				ctx->format = FORMAT_BIN;
			} else if (!g_ascii_strncasecmp(param, "hex", 3)) {
				ctx->format = FORMAT_HEX;
			} else if (!g_ascii_strncasecmp(param, "oct", 3)) {
				ctx->format = FORMAT_OCT;
			} else {
				sr_err("Invalid format: %s.", param);
				free_context(ctx);
				return SR_ERR;
			}
		}
	}

	if (ctx->multi_column_mode)
		ctx->first_column = ctx->first_probe;
	else
		ctx->first_column = ctx->single_column;

	if (!ctx->multi_column_mode && !ctx->num_probes) {
		sr_err("Number of probes needs to be specified in single column mode.");
		free_context(ctx);
		return SR_ERR;
	}

	if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
		sr_err("Input file '%s' could not be opened.", filename);
		free_context(ctx);
		return SR_ERR;
	}

	while (TRUE) {
		ctx->line_number++;
		status = g_io_channel_read_line_string(ctx->channel,
			ctx->buffer, &term_pos, NULL);

		if (status == G_IO_STATUS_EOF) {
			sr_err("Input file is empty.");
			free_context(ctx);
			return SR_ERR;
		}

		if (status != G_IO_STATUS_NORMAL) {
			sr_err("Error while reading line %zu.",
				ctx->line_number);
			free_context(ctx);
			return SR_ERR;
		}

		if (ctx->start_line > ctx->line_number) {
			sr_spew("Line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove line termination character(s). */
		g_string_truncate(ctx->buffer, term_pos);

		if (!ctx->buffer->len) {
			sr_spew("Blank line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove trailing comment. */
		strip_comment(ctx->buffer, ctx->comment);

		if (ctx->buffer->len)
			break;

		sr_spew("Comment-only line %zu skipped.", ctx->line_number);
	}

	/*
	 * In order to determine the number of columns parse the current line
	 * without limiting the number of columns.
	 */
	if (!(columns = parse_line(ctx, -1))) {
		sr_err("Error while parsing line %zu.", ctx->line_number);
		free_context(ctx);
		return SR_ERR;
	}

	num_columns = g_strv_length(columns);

	/* Ensure that the first column is not out of bounds. */
	if (!num_columns) {
		sr_err("Column %zu in line %zu is out of bounds.",
			ctx->first_column, ctx->line_number);
		g_strfreev(columns);
		free_context(ctx);
		return SR_ERR;
	}

	if (ctx->multi_column_mode) {
		/*
		 * Detect the number of probes in multi column mode
		 * automatically if not specified.
		 */
		if (!ctx->num_probes) {
			ctx->num_probes = num_columns;
			sr_info("Number of auto-detected probes: %zu.",
				ctx->num_probes);
		}

		/*
		 * Ensure that the number of probes does not exceed the number
		 * of columns in multi column mode.
		 */
		if (num_columns < ctx->num_probes) {
			sr_err("Not enough columns for desired number of probes in line %zu.",
				ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}
	}

	for (i = 0; i < ctx->num_probes; i++) {
		if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
			snprintf(probe_name, sizeof(probe_name), "%s",
				columns[i]);
		else
			snprintf(probe_name, sizeof(probe_name), "%zu", i);

		probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, probe_name);

		if (!probe) {
			sr_err("Probe creation failed.");
			free_context(ctx);
			g_strfreev(columns);
			return SR_ERR;
		}

		in->sdi->probes = g_slist_append(in->sdi->probes, probe);
	}

	g_strfreev(columns);

	/*
	 * Calculate the minimum buffer size to store the sample data of the
	 * probes.
	 */
	ctx->sample_buffer_size = (ctx->num_probes + 7) >> 3;

	if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
		sr_err("Sample buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	return SR_OK;
}
Beispiel #13
0
/****************************************************************************
 * returns:
 *	1  - command executed, repeatable
 *	0  - command executed but not repeatable, interrupted commands are
 *	     always considered not repeatable
 *	-1 - not executed (unrecognized, bootd recursion or too many args)
 *           (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
 *           considered unrecognized)
 *
 * WARNING:
 *
 * We must create a temporary copy of the command since the command we get
 * may be the result from getenv(), which returns a pointer directly to
 * the environment data, which may change magicly when the command we run
 * creates or modifies environment variables (like "bootp" does).
 */
static int builtin_run_command(const char *cmd, int flag)
{
	char cmdbuf[CONFIG_SYS_CBSIZE];	/* working copy of cmd		*/
	char *token;			/* start of token in cmdbuf	*/
	char *sep;			/* end of token (separator) in cmdbuf */
	char finaltoken[CONFIG_SYS_CBSIZE];
	char *str = cmdbuf;
	char *argv[CONFIG_SYS_MAXARGS + 1];	/* NULL terminated	*/
	int argc, inquotes;
	int repeatable = 1;
	int rc = 0;

	debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd);
	if (DEBUG_PARSER) {
		/* use printf - string may be loooong */
		printf(cmd ? cmd : "NULL");
		printf("\"\n");
	}
	//clear_ctrlc();		/* forget any previous Control C */

	if (!cmd || !*cmd) {
		return -1;	/* empty command */
	}

	if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
		printf ("## Command too long!\n");
		return -1;
	}

	strcpy (cmdbuf, cmd);

	/* Process separators and check for invalid
	 * repeatable commands
	 */

	debug_parser("[PROCESS_SEPARATORS] %s\n", cmd);
	while (*str) {

		/*
		 * Find separator, or string end
		 * Allow simple escape of ';' by writing "\;"
		 */
		for (inquotes = 0, sep = str; *sep; sep++) {
			if ((*sep=='\'') &&
			    (*(sep-1) != '\\'))
				inquotes=!inquotes;

			if (!inquotes &&
			    (*sep == ';') &&	/* separator		*/
			    ( sep != str) &&	/* past string start	*/
			    (*(sep-1) != '\\'))	/* and NOT escaped	*/
				break;
		}

		/*
		 * Limit the token to data between separators
		 */
		token = str;
		if (*sep) {
			str = sep + 1;	/* start of command for next pass */
			*sep = '\0';
		}
		else
			str = sep;	/* no more commands for next pass */
		debug_parser("token: \"%s\"\n", token);

		/* find macros in this token and replace them */
		process_macros (token, finaltoken);

		/* Extract arguments */
		if ((argc = parse_line (finaltoken, argv)) == 0) {
			rc = -1;	/* no command at all */
			continue;
		}

		if (cmd_process(flag, argc, argv, &repeatable, NULL))
			rc = -1;

		/* Did the user stop this? */
		//if (had_ctrlc ())
		//	return -1;	/* if stopped then not repeatable */
	}

	return rc ? rc : repeatable;
}
Beispiel #14
0
int run_command(const char *cmd)
{
	char cmdbuf[CONFIG_CBSIZE];	/* working copy of cmd		*/
	char *token;			/* start of token in cmdbuf	*/
	char *sep;			/* end of token (separator) in cmdbuf */
	char finaltoken[CONFIG_CBSIZE];
	char *str = cmdbuf;
	char *argv[CONFIG_MAXARGS + 1];	/* NULL terminated	*/
	int argc, inquotes;
	int rc = 0;

#ifdef DEBUG
	pr_debug("[RUN_COMMAND] cmd[%p]=\"", cmd);
	puts (cmd ? cmd : "NULL");	/* use puts - string may be loooong */
	puts ("\"\n");
#endif

	if (!cmd || !*cmd) {
		return -1;	/* empty command */
	}

	if (strlen(cmd) >= CONFIG_CBSIZE) {
		puts ("## Command too long!\n");
		return -1;
	}

	strcpy (cmdbuf, cmd);

	/*
	 * Process separators and check for invalid
	 * repeatable commands
	 */

	pr_debug("[PROCESS_SEPARATORS] %s\n", cmd);

	while (*str) {

		/*
		 * Find separator, or string end
		 * Allow simple escape of ';' by writing "\;"
		 */
		for (inquotes = 0, sep = str; *sep; sep++) {
			if ((*sep=='\'') &&
			    (*(sep-1) != '\\'))
				inquotes=!inquotes;

			if (!inquotes &&
			    (*sep == ';') &&	/* separator		*/
			    ( sep != str) &&	/* past string start	*/
			    (*(sep-1) != '\\'))	/* and NOT escaped	*/
				break;
		}

		/*
		 * Limit the token to data between separators
		 */
		token = str;
		if (*sep) {
			str = sep + 1;	/* start of command for next pass */
			*sep = '\0';
		}
		else {
			str = sep;	/* no more commands for next pass */
		}

		pr_debug("token: \"%s\"\n", token);

		/* find macros in this token and replace them */
		process_macros (token, finaltoken);

		/* Extract arguments */
		if ((argc = parse_line (finaltoken, argv)) == 0) {
			rc = -1;	/* no command at all */
			continue;
		}

		if (execute_command(argc, argv) != COMMAND_SUCCESS)
			rc = -1;
	}

	return rc;
}
Beispiel #15
0
/*
 * Parse a single file
 */
static int parse_file(char *filename)
{
    int val;
    int ret = OMPI_SUCCESS;
    bool showed_no_section_warning = false;
    bool showed_unexpected_tokens_warning = false;
    parsed_section_values_t section;

    reset_section(false, &section);

    /* Open the file */
    ini_filename = filename;
    btl_openib_ini_yyin = fopen(filename, "r");
    if (NULL == btl_openib_ini_yyin) {
        orte_show_help("help-mpi-btl-openib.txt", "ini file:file not found",
                       true, filename);
        ret = OMPI_ERR_NOT_FOUND;
        goto cleanup;
    }

    /* Do the parsing */
    btl_openib_ini_parse_done = false;
    btl_openib_ini_yynewlines = 1;
    btl_openib_ini_init_buffer(btl_openib_ini_yyin);
    while (!btl_openib_ini_parse_done) {
        val = btl_openib_ini_yylex();
        switch (val) {
        case BTL_OPENIB_INI_PARSE_DONE:
            /* This will also set btl_openib_ini_parse_done to true, so just
               break here */
            break;

        case BTL_OPENIB_INI_PARSE_NEWLINE:
            /* blank line!  ignore it */
            break;

        case BTL_OPENIB_INI_PARSE_SECTION:
            /* We're starting a new section; if we have previously
               parsed a section, go see if we can use its values. */
            save_section(&section);

            reset_section(true, &section);
            section.name = strdup(btl_openib_ini_yytext);
            break;

        case BTL_OPENIB_INI_PARSE_SINGLE_WORD:
            if (NULL == section.name) {
                /* Warn that there is no current section, and ignore
                   this parameter */
                if (!showed_no_section_warning) {
                    show_help("ini file:not in a section");
                    showed_no_section_warning = true;
                }
                /* Parse it and then dump it */
                parse_line(&section);
                reset_section(true, &section);
            } else {
                parse_line(&section);
            }
            break;

        default:
            /* anything else is an error */
            if (!showed_unexpected_tokens_warning) {
                show_help("ini file:unexpected token");
                showed_unexpected_tokens_warning = true;
            }
            break;
        }
    }
    save_section(&section);
    fclose(btl_openib_ini_yyin);
    btl_openib_ini_yylex_destroy ();

cleanup:
    reset_section(true, &section);
    if (NULL != key_buffer) {
        free(key_buffer);
        key_buffer = NULL;
        key_buffer_len = 0;
    }
    return ret;
}
Beispiel #16
0
void
wifidisplay_file_params_config(char *file_name, char *cmd_name,
                               t_u8 * pbuf, t_u16 * ie_len_wifidisplay)
{
    FILE *config_file = NULL;
    char *line = NULL;
    t_u8 *extra = NULL, *len_ptr = NULL;
    t_u8 *buffer = pbuf;
    char **args = NULL;
    t_u16 cmd_len_wifidisplay = 0, tlv_len = 0;
    tlvbuf_wifidisplay_ie_format *display_ie_buf = NULL;
    int wifiDisplay_level = 0, ret = 0, coupled_sink_bitmap = 0;
    t_u16 display_device_info, session_mgmt_control_port, wfd_device_throuput;
    t_u8 assoc_bssid[] = { 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE };
    t_u8 alternate_mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    t_u8 peer_mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    t_u8 default_mac[] = { 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE };
    char wfd_mac[20];
    int li = 0, arg_num = 0;
    char *pos = NULL;
    t_u8 cmd_found = 0;
    t_u16 temp;
    t_u16 wfd_session_len;
    t_u8 total_num_device_info, curr_dev_info = 0;
    t_u8 dev_info_dev_add[ETH_ALEN], dev_info_assoc_bssid[ETH_ALEN],
        dev_info_coupled_add[ETH_ALEN];
    t_u16 descriptor_display_device_info, descriptor_wfd_device_throuput;
    t_u8 descriptor_wfd_coupled_sink_status;
    t_u8 wfd_dev_descriptor_arr[120], device_info_desc_len, ind =
        DEVICE_DESCRIPTOR_LEN;
    /* Check if file exists */
    config_file = fopen(file_name, "r");
    if (config_file == NULL) {
        printf("\nERR:Config file can not open.\n");
        return;
    }

    /* Memory allocations */
    line = (char *) malloc(MAX_CONFIG_LINE);
    if (!line) {
        printf("ERR:Cannot allocate memory for line\n");
        goto done;
    }
    memset(line, 0, MAX_CONFIG_LINE);

    extra = (t_u8 *) malloc(MAX_CONFIG_LINE);
    if (!extra) {
        printf("ERR:Cannot allocate memory for extra\n");
        goto done;
    }
    memset(extra, 0, MAX_CONFIG_LINE);

    args = (char **) malloc(sizeof(char *) * MAX_ARGS_NUM);
    if (!args) {
        printf("ERR:Cannot allocate memory for args\n");
        goto done;
    }
    memset(args, 0, (sizeof(char *) * MAX_ARGS_NUM));
    display_ie_buf = (tlvbuf_wifidisplay_ie_format *) buffer;
    display_ie_buf->ElemId = VENDOR_SPECIFIC_IE_TAG;
    len_ptr = buffer + 1;
    memcpy(&display_ie_buf->Oui[0], wifidisplay_oui, sizeof(wifidisplay_oui));
    cmd_len_wifidisplay += 2 + sizeof(wifidisplay_oui);
    while (config_get_line(line, MAX_CONFIG_LINE, config_file, &li, &pos)) {
        arg_num = parse_line(line, args);
        if (!cmd_found && (cmd_name != NULL)
            && strncmp(args[0], cmd_name, strlen(args[0])))
            cmd_found = 1;
        if (strcmp(args[0], "display_dev_info") == 0) {
            wifiDisplay_level = DISPLAY_DEVICE_INFO;
        } else if (strcmp(args[0], "display_assoc_bssid") == 0) {
            wifiDisplay_level = DISPLAY_ASSOCIATED_BSSID;
        } else if (strcmp(args[0], "display_coupled_sink") == 0) {
            wifiDisplay_level = DISPLAY_COUPLED_SINK;
        } else if (strcmp(args[0], "display_session_info") == 0) {
            wifiDisplay_level = DISPLAY_SESSION_INFO;
        } else if (strcmp(args[0], "display_alternate_mac") == 0) {
            wifiDisplay_level = DISPLAY_ALTERNATE_MAC_ADDR;
        } else if (strcmp(args[0], "device_info") == 0) {
            if (is_wifidisplay_input_valid
                (WFD_DEVICE_INFO, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            display_device_info = (t_u16) atoi(args[1]);
        } else if (strcmp(args[0], "mgmt_control_port") == 0) {
            if (is_wifidisplay_input_valid
                (WFD_SESSION_MGMT_CONTROL_PORT, arg_num - 1,
                 args + 1) != SUCCESS) {
                goto done;
            }
            session_mgmt_control_port = (t_u16) atoi(args[1]);
        } else if (strcmp(args[0], "device_throuput") == 0) {
            if (is_wifidisplay_input_valid
                (WFD_DEVICE_THROUGHPUT, arg_num - 1, args + 1) != SUCCESS) {
                goto done;
            }
            wfd_device_throuput = (t_u16) atoi(args[1]);
        } else if (strcmp(args[0], "assoc_bssid") == 0) {
            strncpy(wfd_mac, args[1], 20);
            if ((ret = mac2raw(wfd_mac, assoc_bssid)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
        } else if (strcmp(args[0], "alternate_mac") == 0) {
            strncpy(wfd_mac, args[1], 20);
            if ((ret = mac2raw(wfd_mac, alternate_mac)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
        } else if (strcmp(args[0], "coupled_sink_bitmap") == 0) {
            if (is_wifidisplay_input_valid
                (WFD_COUPLED_SINK, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            coupled_sink_bitmap = (t_u8) atoi(args[1]);
        } else if (strcmp(args[0], "session_info_len") == 0) {
            wfd_session_len = (t_u16) atoi(args[1]);
            total_num_device_info = (wfd_session_len / DEVICE_DESCRIPTOR_LEN);
        } else if (strncmp(args[0], "device_info_descriptor_len", 26) == 0) {
            device_info_desc_len = (t_u16) atoi(args[1]);
        } else if (strncmp(args[0], "device_info_dev_id", 18) == 0) {
            strncpy(wfd_mac, args[1], 20);
            if ((ret = mac2raw(wfd_mac, dev_info_dev_add)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
        } else if (strncmp(args[0], "device_info_assoc_bssid", 18) == 0) {
            strncpy(wfd_mac, args[1], 20);
            if ((ret = mac2raw(wfd_mac, dev_info_assoc_bssid)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
        } else if (strncmp(args[0], "descriptor_device_info", 22) == 0) {
            descriptor_display_device_info = (t_u16) atoi(args[1]);
            temp = htons(descriptor_display_device_info);
            memcpy(&descriptor_display_device_info, &temp, 2);
        } else if (strncmp(args[0], "descriptor_device_throuput", 24) == 0) {
            descriptor_wfd_device_throuput = (t_u16) atoi(args[1]);
            temp = htons(descriptor_wfd_device_throuput);
            memcpy(&descriptor_display_device_info, &temp, 2);
        } else if (strncmp(args[0], "descriptor_cs_bitmap", 20) == 0) {
            descriptor_wfd_coupled_sink_status = (t_u8) atoi(args[1]);
        } else if (strncmp(args[0], "device_info_coupled_address", 27) == 0) {
            strncpy(wfd_mac, args[1], 20);
            if ((ret = mac2raw(wfd_mac, dev_info_coupled_add)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
            if (curr_dev_info > 5) {
                printf("ERR in device descriptor");
                goto done;
            }
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info],
                   &device_info_desc_len, sizeof(t_u8));
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 1],
                   &dev_info_dev_add, ETH_ALEN);
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 7],
                   &dev_info_assoc_bssid, ETH_ALEN);
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 13],
                   &descriptor_display_device_info, sizeof(t_u16));
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 15],
                   &descriptor_wfd_device_throuput, sizeof(t_u16));
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 17],
                   &descriptor_wfd_coupled_sink_status, sizeof(t_u8));
            memcpy(&wfd_dev_descriptor_arr[ind * curr_dev_info + 18],
                   &dev_info_coupled_add, ETH_ALEN);
            curr_dev_info++;
        } else if (strcmp(args[0], "}") == 0) {
            switch (wifiDisplay_level) {
            case DISPLAY_DEVICE_INFO:
                {
                    tlvbuf_wfdisplay_device_info *tlv = NULL;
                    /* Append a new TLV */
                    tlv_len = sizeof(tlvbuf_wfdisplay_device_info);
                    tlv =
                        (tlvbuf_wfdisplay_device_info *) (buffer +
                                                          cmd_len_wifidisplay);
                    cmd_len_wifidisplay += tlv_len;
                    /* Set TLV fields */
                    tlv->tag = TLV_TYPE_WIFIDISPLAY_DEVICE_INFO;
                    tlv->length =
                        htons(tlv_len - (sizeof(t_u8) + sizeof(t_u16)));
                    *ie_len_wifidisplay = cmd_len_wifidisplay;
                    temp = htons(display_device_info);
                    memcpy(&tlv->display_device_info, &temp, 2);
                    temp = htons(session_mgmt_control_port);
                    memcpy(&tlv->session_mgmt_control_port, &temp, 2);
                    temp = htons(wfd_device_throuput);
                    memcpy(&tlv->wfd_device_throuput, &temp, 2);
                    wifiDisplay_level = 0;
                    break;
                }
            case DISPLAY_ASSOCIATED_BSSID:
                {
                    tlvbuf_wfdisplay_assoc_bssid *tlv = NULL;
                    if (memcmp(default_mac, assoc_bssid, ETH_ALEN)) {
                        /* Append a new TLV */
                        tlv_len = sizeof(tlvbuf_wfdisplay_assoc_bssid);
                        tlv =
                            (tlvbuf_wfdisplay_assoc_bssid *) (buffer +
                                                              cmd_len_wifidisplay);
                        cmd_len_wifidisplay += tlv_len;
                        *ie_len_wifidisplay = cmd_len_wifidisplay;
                        /* Set TLV fields */
                        tlv->tag = TLV_TYPE_WIFIDISPLAY_ASSOC_BSSID;
                        tlv->length =
                            htons(tlv_len - (sizeof(t_u8) + sizeof(t_u16)));
                        memcpy(tlv->assoc_bssid, assoc_bssid, ETH_ALEN);

                        wifiDisplay_level = 0;
                    }
                    break;
                }
            case DISPLAY_COUPLED_SINK:
                {
                    tlvbuf_wfdisplay_coupled_sink *tlv = NULL;
                    tlv_len = sizeof(tlvbuf_wfdisplay_coupled_sink);
                    tlv =
                        (tlvbuf_wfdisplay_coupled_sink *) (buffer +
                                                           cmd_len_wifidisplay);
                    cmd_len_wifidisplay += tlv_len;
                    *ie_len_wifidisplay = cmd_len_wifidisplay;
                    /* Set TLV fields */
                    tlv->tag = TLV_TYPE_WIFIDISPLAY_COUPLED_SINK;
                    tlv->length =
                        htons(tlv_len - (sizeof(t_u8) + sizeof(t_u16)));
                    memcpy(tlv->peer_mac, peer_mac, ETH_ALEN);
                    tlv->coupled_sink = coupled_sink_bitmap;
                    wifiDisplay_level = 0;
                }
                break;
            case DISPLAY_SESSION_INFO:
                {
                    tlvbuf_wifi_display_session_info *tlv = NULL;
                    if (curr_dev_info > 0) {
                        tlv_len = DEVICE_DESCRIPTOR_LEN * curr_dev_info + 2;
                        tlv =
                            (tlvbuf_wifi_display_session_info *) (buffer +
                                                                  cmd_len_wifidisplay);
                        cmd_len_wifidisplay += tlv_len;
                        *ie_len_wifidisplay = cmd_len_wifidisplay;
                        /* Set TLV fields */
                        tlv->tag = TLV_TYPE_SESSION_INFO_SUBELEM;
                        tlv->length =
                            htons(tlv_len - (sizeof(t_u8) + sizeof(t_u16)));
                        memcpy((t_u8 *) & tlv->WFDDevInfoDesc,
                               (t_u8 *) & wfd_dev_descriptor_arr,
                               (tlv_len - 2));
                        wifiDisplay_level = 0;
                    }
                }
                break;
            case DISPLAY_ALTERNATE_MAC_ADDR:
                {
                    tlvbuf_wfdisplay_alternate_mac *tlv = NULL;
                    if (memcmp(default_mac, alternate_mac, ETH_ALEN)) {
                        /* Append a new TLV */
                        tlv_len = sizeof(tlvbuf_wfdisplay_alternate_mac);
                        tlv =
                            (tlvbuf_wfdisplay_alternate_mac *) (buffer +
                                                                cmd_len_wifidisplay);
                        cmd_len_wifidisplay += tlv_len;
                        *ie_len_wifidisplay = cmd_len_wifidisplay;
                        /* Set TLV fields */
                        tlv->tag = TLV_TYPE_WIFIDISPLAY_ALTERNATE_MAC;
                        tlv->length =
                            htons(tlv_len - (sizeof(t_u8) + sizeof(t_u16)));
                        memcpy(tlv->alternate_mac, alternate_mac, ETH_ALEN);
                        wifiDisplay_level = 0;
                    }
                }
                break;
            default:
                break;
            }
        }
    }
    *len_ptr = cmd_len_wifidisplay - 2;
  done:
    fclose(config_file);
    if (line)
        free(line);
    if (extra)
        free(extra);
    if (args)
        free(args);
    return;
}
Beispiel #17
0
blargg_err_t M3u_Playlist::parse_()
{
	info_.title     = "";
	info_.artist    = "";
	info_.date      = "";
	info_.composer  = "";
	info_.sequencer = "";
	info_.engineer  = "";
	info_.ripping   = "";
	info_.tagging   = "";
	info_.copyright = "";
	
	int const CR = 13;
	int const LF = 10;
	
	data.end() [-1] = LF; // terminate input
	
	first_error_ = 0;
	bool first_comment = true;
	int line  = 0;
	int count = 0;
	char* in  = data.begin();
	char* last_comment_value = 0;
	while ( in < data.end() )
	{
		// find end of line and terminate it
		line++;
		char* begin = in;
		while ( *in != CR && *in != LF )
		{
			if ( !*in )
				return blargg_err_file_type;
			in++;
		}
		if ( in [0] == CR && in [1] == LF ) // treat CR,LF as a single line
			*in++ = 0;
		*in++ = 0;
		
		// parse line
		if ( *begin == '#' )
		{
			parse_comment( begin, info_, last_comment_value, first_comment );
			first_comment = false;
		}
		else if ( *begin )
		{
			if ( (int) entries.size() <= count )
				RETURN_ERR( entries.resize( count * 2 + 64 ) );
			
			if ( !parse_line( begin, entries [count] ) )
				count++;
			else if ( !first_error_ )
				first_error_ = line;
			first_comment = false;
		}
		else last_comment_value = 0;
	}
	if ( count <= 0 )
		return blargg_err_file_type;
	
	// Treat first comment as title only if another field is also specified
	if ( !(info_.artist [0] | info_.composer [0] | info_.date [0] | info_.engineer [0] | info_.ripping [0] | info_.sequencer [0] | info_.tagging [0] | info_.copyright[0]) )
		info_.title = "";
	
	return entries.resize( count );
}
Beispiel #18
0
/*  @brief Creates a wifidirect_service_discovery request/response and
 *         sends to the driver
 *
 *  Usage: "Usage : wifidirect_discovery_request/response [CONFIG_FILE]"
 *
 *  @param argc     Number of arguments
 *  @param argv     Pointer to the arguments
 *  @return         SUCCESS or FAILURE
 **/
void
wifidisplaycmd_service_discovery(int argc, char *argv[])
{
    wifidisplay_discovery_request *req_buf = NULL;
    wifidisplay_discovery_response *resp_buf = NULL;
    char *line = NULL;
    FILE *config_file = NULL;
    int i, opt, li = 0, arg_num = 0, ret = 0, wifidirect_level = 0;
    char *args[30], *pos = NULL, wifidisplay_mac[20], wifidisplay_cmd[32];
    t_u8 dev_address[ETH_ALEN], cmd_found = 0;
    t_u8 *buffer = NULL, *buf = NULL, *tmp_buffer = NULL;
    t_u8 req_resp = 0;          /* req = 0, resp = 1 */
    t_u16 cmd_len = 0, query_len = 0, vendor_len = 0, service_len = 0;
    t_u16 ie_len_wifidisplay = 0;

    strncpy(wifidisplay_cmd, argv[2], sizeof(wifidisplay_cmd) - 1);
    while ((opt = getopt_long(argc, argv, "+", cmd_options, NULL)) != -1) {
        switch (opt) {
        default:
            print_wifidisplay_discovery_usage();
            return;
        }
    }
    argc -= optind;
    argv += optind;

    /* Check arguments */
    if (argc != 3) {
        printf("ERR:Incorrect number of arguments.\n");
        print_wifidisplay_discovery_usage();
        return;
    }

    /* Check if file exists */
    config_file = fopen(argv[2], "r");
    if (config_file == NULL) {
        printf("\nERR:Config file can not open.\n");
        return;
    }
    line = (char *) malloc(MAX_CONFIG_LINE);
    if (!line) {
        printf("ERR:Cannot allocate memory for line\n");
        goto done;
    }
    memset(line, 0, MAX_CONFIG_LINE);
    buf = (t_u8 *) malloc(MRVDRV_SIZE_OF_CMD_BUFFER);
    if (!buf) {
        printf("ERR:Cannot allocate memory!\n");
        goto done;
    }
    if (strcmp(args[0], "wifidisplay_discovery_response") == 0) {
        t_u8 wfd_oui_header = 6;
        wifidisplay_file_params_config(argv[2], NULL, buf, &ie_len_wifidisplay);
        ie_len_wifidisplay += wfd_oui_header;
        buf += wfd_oui_header;
    } else {
        buf[0] = 0x03;
        buf[1] = TLV_TYPE_WIFIDISPLAY_DEVICE_INFO;
        buf[2] = TLV_TYPE_SESSION_INFO_SUBELEM;
        buf[3] = TLV_TYPE_WIFIDISPLAY_COUPLED_SINK;
        ie_len_wifidisplay = 4;
    }

    /* Parse file and process */
    while (config_get_line(line, MAX_CONFIG_LINE, config_file, &li, &pos)) {
        arg_num = parse_line(line, args);
        if (!cmd_found && strncmp(args[0], wifidisplay_cmd, strlen(args[0])))
            continue;
        cmd_found = 1;
        if (strcmp(args[0], "wifidisplay_discovery_request") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_REQUEST_RESPONSE;
            /* For wifidirect_service_discovery, basic initialization here */
            cmd_len = sizeof(wifidisplay_discovery_request);
            buffer = (t_u8 *) malloc(cmd_len);
            if (!buffer) {
                printf("ERR:Cannot allocate memory!\n");
                goto done;
            }
            req_buf = (wifidisplay_discovery_request *) buffer;
            req_buf->cmd_code = HostCmd_CMD_WIFIDIRECT_SERVICE_DISCOVERY;
            req_buf->size = cmd_len;
            req_buf->seq_num = 0;
            req_buf->result = 0;
        } else if (strcmp(args[0], "wifidisplay_discovery_response") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_REQUEST_RESPONSE;
            req_resp = 1;
            /* For wifidirect_service_discovery, basic initialization here */
            cmd_len = sizeof(wifidisplay_discovery_response);
            buffer = (t_u8 *) malloc(cmd_len);
            if (!buffer) {
                printf("ERR:Cannot allocate memory!\n");
                goto done;
            }
            resp_buf = (wifidisplay_discovery_response *) buffer;
            resp_buf->cmd_code = HostCmd_CMD_WIFIDIRECT_SERVICE_DISCOVERY;
            resp_buf->size = cmd_len;
            resp_buf->seq_num = 0;
            resp_buf->result = 0;

        } else if (strcmp(args[0], "PeerAddr") == 0) {
            strncpy(wifidisplay_mac, args[1], 20 - 1);
            if ((ret = mac2raw(wifidisplay_mac, dev_address)) != SUCCESS) {
                printf("ERR: %s Address \n",
                       ret == FAILURE ? "Invalid MAC" : ret ==
                       WIFIDIRECT_RET_MAC_BROADCAST ? "Broadcast" :
                       "Multicast");
                goto done;
            }
            (!req_resp) ? memcpy(req_buf->peer_mac_addr, dev_address,
                                 ETH_ALEN) : memcpy(resp_buf->peer_mac_addr,
                                                    dev_address, ETH_ALEN);

        } else if (strcmp(args[0], "Category") == 0) {
            if (is_input_valid(WIFIDIRECT_CATEGORY, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;

            }
            (!req_resp) ? (req_buf->category = (t_u8) atoi(args[1])) :
                (resp_buf->category = (t_u8) atoi(args[1]));
        } else if (strcmp(args[0], "Action") == 0) {
            if (is_input_valid(WIFIDIRECT_ACTION, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            (!req_resp) ? (req_buf->action = (t_u8) A2HEXDECIMAL(args[1])) :
                (resp_buf->action = (t_u8) A2HEXDECIMAL(args[1]));
        } else if (strcmp(args[0], "DialogToken") == 0) {
            if (is_input_valid(WIFIDIRECT_DIALOGTOKEN, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            (!req_resp) ? (req_buf->dialog_taken = (t_u8) atoi(args[1])) :
                (resp_buf->dialog_taken = (t_u8) atoi(args[1]));
        } else if (strcmp(args[0], "StatusCode") == 0) {
            resp_buf->status_code = (t_u8) atoi(args[1]);
        } else if (strcmp(args[0], "GasComebackDelay") == 0) {
            if (is_input_valid
                (WIFIDIRECT_GAS_COMEBACK_DELAY, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            resp_buf->gas_reply = (t_u16) A2HEXDECIMAL(args[1]);
            resp_buf->gas_reply = cpu_to_le16(resp_buf->gas_reply);
        } else if (strcmp(args[0], "AdvertizementProtocolIE") == 0) {
            if (is_input_valid(WIFIDIRECT_DISC_ADPROTOIE, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            if (!req_resp) {
                for (i = 0; i < arg_num - 1; i++)
                    req_buf->advertize_protocol_ie[i] =
                        (t_u8) A2HEXDECIMAL(args[i + 1]);
            } else {
                for (i = 0; i < arg_num - 1; i++)
                    resp_buf->advertize_protocol_ie[i] =
                        (t_u8) A2HEXDECIMAL(args[i + 1]);
            }
        } else if (strcmp(args[0], "InfoId") == 0) {
            if (is_input_valid(WIFIDIRECT_DISC_INFOID, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            if (!req_resp) {
                for (i = 0; i < arg_num - 1; i++)
                    req_buf->info_id[i] = (t_u8) A2HEXDECIMAL(args[i + 1]);
            } else {
                for (i = 0; i < arg_num - 1; i++)
                    resp_buf->info_id[i] = (t_u8) A2HEXDECIMAL(args[i + 1]);
            }
            query_len += arg_num - 1;
        } else if (strcmp(args[0], "OUI") == 0) {
            if (is_input_valid(WIFIDIRECT_OUI, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            if (!req_resp) {
                for (i = 0; i < arg_num - 1; i++)
                    req_buf->oui[i] = (t_u8) A2HEXDECIMAL(args[i + 1]);
            } else {
                for (i = 0; i < arg_num - 1; i++)
                    resp_buf->oui[i] = (t_u8) A2HEXDECIMAL(args[i + 1]);
            }
            service_len += arg_num - 1;
            query_len += arg_num - 1;
        } else if (strcmp(args[0], "OUISubType") == 0) {
            if (is_input_valid(WIFIDIRECT_OUISUBTYPE, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            (!req_resp) ? (req_buf->oui_sub_type = (t_u8) atoi(args[1])) :
                (resp_buf->oui_sub_type = (t_u8) atoi(args[1]));
            service_len++;
            query_len++;
        } else if (strcmp(args[0], "QueryRequestLen") == 0 ||
                   strcmp(args[0], "QueryResponseLen") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_QUERY;
        } else if (strcmp(args[0], "RequestLen") == 0 ||
                   strcmp(args[0], "ResponseLen") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_SERVICE;
            query_len += 2;
        } else if (strcmp(args[0], "VendorLen") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_VENDOR;
            service_len += 2;
            query_len += 2;
        } else if (strcmp(args[0], "QueryData") == 0 ||
                   strcmp(args[0], "ResponseData") == 0) {
            wifidirect_level = WIFIDIRECT_DISCOVERY_QUERY_RESPONSE_PER_PROTOCOL;
            tmp_buffer = realloc(buffer, cmd_len + ie_len_wifidisplay);
            if (!tmp_buffer) {
                printf("ERR:Cannot add DNS name to buffer!\n");
                goto done;
            } else {
                buffer = tmp_buffer;
                tmp_buffer = NULL;
            }
            if (!req_resp) {
                for (i = 0; i < ie_len_wifidisplay; i++)
                    req_buf->disc_query[i] = (t_u8) buf[i];
            } else {
                resp_buf = (wifidisplay_discovery_response *) buffer;
                for (i = 0; i < ie_len_wifidisplay; i++)
                    buffer[i + cmd_len] = (t_u8) buf[i];
            }
            cmd_len += (ie_len_wifidisplay);
            vendor_len += (ie_len_wifidisplay);
            service_len += (ie_len_wifidisplay);
            query_len += (ie_len_wifidisplay);
        } else if (strcmp(args[0], "ServiceProtocol") == 0) {
            if (!req_resp) {
                req_buf->service_protocol = (t_u8) atoi(args[1]);
                /* 
                 * For uPnP, due to union allocation, a extra byte
                 * is allocated reduce it here for uPnP
                 */
                if (req_buf->service_protocol == 2)
                    cmd_len--;
            } else {
                resp_buf->service_protocol = (t_u8) atoi(args[1]);
                if (resp_buf->service_protocol == 2)
                    cmd_len--;
            }
            vendor_len++;
            service_len++;
            query_len++;
        } else if (strcmp(args[0], "ServiceUpdateIndicator") == 0) {
            if (is_input_valid
                (WIFIDIRECT_SERVICEUPDATE_INDICATOR, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            (!req_resp) ? (req_buf->service_update_indicator =
                           cpu_to_le16((t_u16) atoi(args[1]))) :
                (resp_buf->service_update_indicator =
                 cpu_to_le16((t_u16) atoi(args[1])));
            service_len += 2;
            query_len += 2;
        } else if (strcmp(args[0], "ServiceTransactionId") == 0) {
            if (is_input_valid
                (WIFIDIRECT_DISC_SERVICETRANSACID, arg_num - 1, args + 1)
                != SUCCESS) {
                goto done;
            }
            (!req_resp) ? (req_buf->service_transaction_id =
                           (t_u8) atoi(args[1])) : (resp_buf->
                                                    service_transaction_id =
                                                    (t_u8) atoi(args[1]));
            vendor_len++;
            service_len++;
            query_len++;
        } else if (strcmp(args[0], "}") == 0) {
            switch (wifidirect_level) {
            case WIFIDIRECT_DISCOVERY_QUERY:
                (!req_resp) ? (req_buf->query_len = cpu_to_le16(query_len)) :
                    (resp_buf->query_len = cpu_to_le16(query_len));
                break;
            case WIFIDIRECT_DISCOVERY_SERVICE:
                (!req_resp) ? (req_buf->request_len =
                               cpu_to_le16(service_len)) : (resp_buf->
                                                            response_len =
                                                            cpu_to_le16
                                                            (service_len));
                break;
            case WIFIDIRECT_DISCOVERY_VENDOR:
                (!req_resp) ? (req_buf->vendor_len = cpu_to_le16(vendor_len)) :
                    (resp_buf->vendor_len = cpu_to_le16(vendor_len));
                break;
            default:
                break;
            }
            if (wifidirect_level) {
                if (wifidirect_level == WIFIDIRECT_DISCOVERY_REQUEST_RESPONSE)
                    break;
                wifidirect_level--;
            }
        }
    }
    /* Send collective command */
    wifidirect_ioctl((t_u8 *) buffer, &cmd_len, cmd_len);
  done:
    fclose(config_file);
    if (buffer)
        free(buffer);
    if (line)
        free(line);
}
Beispiel #19
0
int
main (int   argc,
      char *argv[])
{
    const gchar *gobject_marshallers[] = {
#include	"gmarshal.strings"
    };
    GScanner *scanner;
    GSList *slist, *files = NULL;
    gint i;

    /* parse args and do fast exits */
    parse_args (&argc, &argv);

    /* list input files */
    for (i = 1; i < argc; i++)
        files = g_slist_prepend (files, argv[i]);
    if (files)
        files = g_slist_reverse (files);
    else
        files = g_slist_prepend (files, "/dev/stdin");

    /* setup auxiliary structs */
    scanner = g_scanner_new (&scanner_config_template);
    fout = stdout;
    marshallers = g_hash_table_new (g_str_hash, g_str_equal);

    /* add standard marshallers of the GObject library */
    if (std_includes)
        for (i = 0; i < G_N_ELEMENTS (gobject_marshallers); i++)
        {
            gchar *tmp = g_strdup (gobject_marshallers[i]);

            g_hash_table_insert (marshallers, tmp, tmp);
        }

    /* put out initial heading */
    g_fprintf (fout, "\n");

    if (gen_cheader && std_includes)
    {
        g_fprintf (fout, "#ifndef __%s_MARSHAL_H__\n", marshaller_prefix);
        g_fprintf (fout, "#define __%s_MARSHAL_H__\n\n", marshaller_prefix);
    }

    if ((gen_cheader || gen_cbody) && std_includes)
        g_fprintf (fout, "#include\t<glib-object.h>\n\n");

    if (gen_cheader)
        g_fprintf (fout, "G_BEGIN_DECLS\n");

    /* generate necessary preprocessor directives */
    if (gen_cbody)
        put_marshal_value_getters ();

    /* process input files */
    for (slist = files; slist; slist = slist->next)
    {
        gchar *file = slist->data;
        gint fd;

        if (strcmp (file, "/dev/stdin") == 0)
            /* Mostly for Win32. This is equivalent to opening /dev/stdin */
            fd = dup (0);
        else
            fd = g_open (file, O_RDONLY, 0);

        if (fd < 0)
        {
            g_warning ("failed to open \"%s\": %s", file, g_strerror (errno));
            exit_status |= 1;
            continue;
        }

        /* set file name for error reports */
        scanner->input_name = file;

        /* parse & process file */
        g_scanner_input_file (scanner, fd);

        /* scanning loop, we parse the input until its end is reached,
         * or our sub routine came across invalid syntax
         */
        do
        {
            guint expected_token = G_TOKEN_NONE;

            switch ((guint) g_scanner_peek_next_token (scanner))
            {
            case '\n':
                /* eat newline and restart */
                g_scanner_get_next_token (scanner);
                continue;
            case G_TOKEN_EOF:
                /* done */
                break;
            default:
                /* parse and process signatures */
            {
                Signature signature = { NULL, NULL, NULL };
                GList *node;

                expected_token = parse_line (scanner, &signature);

                /* once we got a valid signature, process it */
                if (expected_token == G_TOKEN_NONE)
                    process_signature (&signature);

                /* clean up signature contents */
                g_free (signature.ploc);
                if (signature.rarg)
                    g_free (signature.rarg->keyword);
                g_free (signature.rarg);
                for (node = signature.args; node; node = node->next)
                {
                    InArgument *iarg = node->data;

                    g_free (iarg->keyword);
                    g_free (iarg);
                }
                g_list_free (signature.args);
            }
            break;
            }

            /* bail out on errors */
            if (expected_token != G_TOKEN_NONE)
            {
                g_scanner_unexp_token (scanner, expected_token, "type name", NULL, NULL, NULL, TRUE);
                exit_status |= 1;
                break;
            }

            g_scanner_peek_next_token (scanner);
        }
        while (scanner->next_token != G_TOKEN_EOF);

        close (fd);
    }

    /* put out trailer */
    if (gen_cheader)
    {
        g_fprintf (fout, "\nG_END_DECLS\n");

        if (std_includes)
            g_fprintf (fout, "\n#endif /* __%s_MARSHAL_H__ */\n", marshaller_prefix);
    }
    g_fprintf (fout, "\n");

    /* clean up */
    g_slist_free (files);
    g_scanner_destroy (scanner);
    g_hash_table_foreach_remove (marshallers, string_key_destroy, NULL);
    g_hash_table_destroy (marshallers);

    return exit_status;
}
Beispiel #20
0
void* process(void *file_chunk)
{
	char* chunk = (char*)file_chunk;
	char* string = (char*)malloc(sizeof(char)*strlen("tester1.txt")+1);
	
//	get_stats();
//	sprintf(string, "tester%f.txt", (i)webstats.local_bytes++);
//	return_stats();
//	
	FILE* file = tmpfile();
	if (file == NULL)
	{
		err_sys("Unable to create temp file\n");
		exit(EXIT_FAILURE);
	}
	fseek(file, 0L, SEEK_SET);
	fwrite(chunk, sizeof(char), strlen(chunk), file);
	rewind(file);
	
//	get_stats();
//	FILE* validation_file = fopen("validation.txt","a");
//	fwrite(chunk, sizeof(char), strlen(chunk), validation_file);
//	fclose(validation_file);
//	return_stats();
	
//	sleep(1);
//	printf("Thread id: %u\n", pthread_self());
//	printf("%s", chunk);

	
	char *linebuffer = (char *) malloc(sizeof(char) * MAX_LINE_SIZE);
	char **field = (char **) malloc(sizeof(char *) * MAX_NUM_FIELDS);
	char *end_date = (char *) malloc(sizeof(char) * MAX_LINE_SIZE);

//	char *s;
//	while((s= fgets(linebuffer, MAX_LINE_SIZE, file))!=NULL)
//		printf("%s", linebuffer);
	char *s = fgets(linebuffer, MAX_LINE_SIZE, file);
	if (s != NULL)
	{
//		printf("linebuffer\n");
//		printf("%s", linebuffer);
		int num = parse_line(linebuffer, " []\"", field);
//		printf("passed line parsing in thread %u\n", pthread_self());
		update_webstats(field);
		printf("Starting date: %s\n",field[3]);
		free_tokens(num, field);
		
		while (fgets(linebuffer, MAX_LINE_SIZE, file) != NULL)
		{
			int num = parse_line(linebuffer, " []\"", field);
//			print_field(field);
			strcpy(end_date, field[3]);
			update_webstats(field);
			free_tokens(num, field);
			strcpy(linebuffer,"");
		}
		printf("Ending date: %s\n", end_date);
//		free(end_date);
//		free(linebuffer);
//		free(field);
		fclose(file);
	}
	else
	{
		fprintf(stderr,"Unable to read chunk. Aborting thread\n");
		exit(EXIT_FAILURE);
	}
	printf("DONE!\n");
	return NULL;
}
Beispiel #21
0
int freenect_process_events(freenect_context *ctx)
{
	/* This is where the magic happens. We read 1 update from the index
	   per call, so this needs to be called in a loop like usual.  If the
	   index line is a Depth/RGB image the provided callback is called.  If
	   the index line is accelerometer data, then it is used to update our
	   internal state.  If you query for the accelerometer data you get the
	   last sensor reading that we have.  The time delays are compensated as
	   best as we can to match those from the original data and current run
	   conditions (e.g., if it takes longer to run this code then we wait less).
	 */
	if (!index_fp)
		open_index();
	char type;
	double record_cur_time;
	unsigned int timestamp, data_size;
	char *data = NULL;
	if (parse_line(&type, &record_cur_time, &timestamp, &data_size, &data))
		return -1;
	// Sleep an amount that compensates for the original and current delays
	// playback_ is w.r.t. the current time
	// record_ is w.r.t. the original time period during the recording
	if (record_prev_time != 0. && playback_prev_time != 0.)
		sleep_highres((record_cur_time - record_prev_time) - (get_time() - playback_prev_time));
	record_prev_time = record_cur_time;
	switch (type) {
		case 'd':
			if (cur_depth_cb && depth_running) {
				void *cur_depth = skip_line(data);
				if (depth_buffer) {
					memcpy(depth_buffer, cur_depth, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT).bytes);
					cur_depth = depth_buffer;
				}
				cur_depth_cb(fake_dev, cur_depth, timestamp);
			}
			break;
		case 'r':
			if (cur_rgb_cb && rgb_running) {
				void *cur_rgb = skip_line(data);
				if (rgb_buffer) {
					memcpy(rgb_buffer, cur_rgb, freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB).bytes);
					cur_rgb = rgb_buffer;
				}
				cur_rgb_cb(fake_dev, cur_rgb, timestamp);
			}
			break;
		case 'a':
			if (data_size == sizeof(state)) {
				memcpy(&state, data, sizeof(state));
			} else if (!already_warned) {
				already_warned = 1;
				printf("\n\nWarning: Accelerometer data has an unexpected"
				       " size [%u] instead of [%u].  The acceleration "
				       "and tilt data will be substituted for dummy "
				       "values.  This data was probably made with an "
				       "older version of record (the upstream interface "
				       "changed).\n\n",
				       data_size, (unsigned int)sizeof state);
			}
			break;
	}
	free(data);
	playback_prev_time = get_time();
	return 0;
}
Beispiel #22
0
/* Run the virtual console emulation for one frame */
void system_frame(int skip_render)
{
    static int iline_table[] = {0xC0, 0xE0, 0xF0};
    int lpf = (sms.display == DISPLAY_NTSC) ? 262 : 313;
    int iline;

    /* Debounce pause key */
    if(input.system & INPUT_PAUSE)
    {
        if(!sms.paused)
        {
            sms.paused = 1;

            z80_set_irq_line(IRQ_LINE_NMI, ASSERT_LINE);
            z80_set_irq_line(IRQ_LINE_NMI, CLEAR_LINE);
        }
    }
    else
    {
         sms.paused = 0;
    }

    text_counter = 0;

    /* End of frame, parse sprites for line 0 on line 261 (VCount=$FF) */
    if(vdp.mode <= 7)
        parse_line(0);

    for(vdp.line = 0; vdp.line < lpf;)
    {
        z80_execute(227);

        iline = iline_table[vdp.extended];

        if(!skip_render)
        {
            render_line(vdp.line);
        }

        if(vdp.line <= iline)
        {
            vdp.left -= 1;
            if(vdp.left == -1)
            {
                vdp.left = vdp.reg[0x0A];
                vdp.hint_pending = 1;

                z80_execute(16);

                if(vdp.reg[0x00] & 0x10)
                {
                    z80_set_irq_line(0, ASSERT_LINE);
                }
            }
        }
        else
        {
            vdp.left = vdp.reg[0x0A];
        }

        if(vdp.line == iline)
        {
            vdp.status |= 0x80;
            vdp.vint_pending = 1;

            z80_execute(16);

            if(vdp.reg[0x01] & 0x20)
            {
                z80_set_irq_line(0, ASSERT_LINE);
            }
        }

        sound_update(vdp.line);

        ++vdp.line;

        if(vdp.mode <= 7)
            parse_line(vdp.line);
    }
}
Beispiel #23
0
int LatentRelevance::read_data(const char* file_name)
{
	// Input file format: label \t x1 \t x2 (example: 1 \t 0.1 0.25 \t 0.3 0.1)
	FILE* fp = fopen(file_name, "r");
	if (fp == NULL) {
		printf("[ERROR] Cannot open %s! Reading data failed!\n", file_name);
		return -1;
	}

	const int MAX_LINE_DATA_LEN = 102400;
	char buf[MAX_LINE_DATA_LEN];

	// Count data number, and allocate data memory
	data_num = 0;
	while (fgets(buf, MAX_LINE_DATA_LEN, fp) != NULL) {
		++data_num;
	}
	
	// Initialize data
	m_data = new data_t[data_num];
	for (int i = 0; i < data_num; ++i) {
		m_data[i].y = 0;
		m_data[i].x = NULL;
		m_data[i].cos = 0.0f;
		m_data[i].score = 0.0f;
		m_data[i].x_ij = NULL;
	}

	rewind(fp);							// Back to the head of the file

	// Parse line data
	int line_num = 0;
	data_num = 0;						// Reset data number (drop invalid line data)
	while (fgets(buf, MAX_LINE_DATA_LEN, fp) != NULL) {
		++line_num;
		if (parse_line(buf, m_data + data_num) != 0) {
			printf("[WARNING] Parsing line %d failed!\n", line_num);
			continue;
		}

		++data_num;
	}

	// Initialize w and v
	if (factorize_mode == 0) {
		if (w == NULL) {
			w = new float[vector_size*vector_size];
			for (int i = 0; i < vector_size * vector_size; ++i) {
				w[i] = 0.0f;
			}
		}
	}
	else if (factorize_mode == 1) {
		if (v == NULL) {
			v = new float[2*vector_size*k];
			for (int i = 0; i < 2 * vector_size * k; ++i) {
				v[i] = 0.0f;
			}
		}
	}

	fclose(fp);
	return 0;
}
Beispiel #24
0
 void ConfigParser::import_line(const char* line) {
   ConfigParser::Entry* entry = parse_line(line);
   if(entry) {
     variables[entry->variable] = entry;
   }
 }
Beispiel #25
0
int main(int argc, const char* argv[])
{
    /* parse command line */
    cmdargs_t args = parse_args(argc, argv);

    /* create collection dir */
    utils::create_directory(args.collection_dir);

    /* (1) create dict */
    std::unordered_map<std::string, uint64_t> dict;
    std::vector<std::pair<uint64_t, std::string> > dict_ids;
    size_t max_id = 0;
    {
        std::unordered_map<std::string, uint64_t> tdict;
        std::ifstream ifs(args.input_file);
        std::string line;
        while (std::getline(ifs, line)) {
            auto line_tokens = parse_line(line, args.byte_alphabet);
            for (const auto& tok : line_tokens)
                tdict[tok]++;
        }
        /* sort by freq */
        for (const auto& did : tdict) {
            dict_ids.emplace_back(did.second, did.first);
        }
        std::sort(dict_ids.begin(), dict_ids.end(), std::greater<std::pair<uint64_t, std::string> >());
        /* create id mapping */
        uint64_t cur_id = NUM_SPECIAL_SYMS;
        for (const auto& did : dict_ids) {
            dict[did.second] = cur_id;
            max_id = cur_id;
            cur_id++;
        }
    }
    /* (2) 2nd pass to transform the integers */
    {
        auto buf = sdsl::write_out_buffer<0>::create(args.collection_dir + "/" + KEY_PREFIX + KEY_TEXT);
        auto int_width = sdsl::bits::hi(max_id) + 1;
        buf.width(int_width);
        std::ifstream ifs(args.input_file);
        std::string line;
        buf.push_back(EOS_SYM); // file starts with EOS_SYM
        while (std::getline(ifs, line)) {
            buf.push_back(PAT_START_SYM); // line starts with PAT_START_SYM
            auto line_tokens = parse_line(line, args.byte_alphabet);
            for (const auto& tok : line_tokens) {
                auto itr = dict.find(tok);
                auto num = itr->second;
                buf.push_back(num);
            }
            buf.push_back(PAT_END_SYM); // line ends with PAT_END_SYM
            buf.push_back(EOS_SYM);
        }
        { // include special 'UNK' sentence to ensure symbol included in CST
            // buf.push_back(PAT_START_SYM);
            buf.push_back(UNKNOWN_SYM);
            // buf.push_back(PAT_END_SYM);
            buf.push_back(EOS_SYM);
        }
        buf.push_back(EOF_SYM);
    }
    /* (3) write vocab file */
    {
        std::ofstream ofs(args.collection_dir + "/" + KEY_PREFIX + KEY_VOCAB);
        // write special symbols
        ofs << "<EOF> 0\n";
        ofs << "<EOS> 1\n";
        ofs << "<UNK> 2\n";
        ofs << "<S> 3\n";
        ofs << "</S> 4\n";
        // write the real vocab
        uint64_t cur_id = NUM_SPECIAL_SYMS;
        for (const auto& did : dict_ids) {
            ofs << did.second << " " << cur_id << "\n";
            cur_id++;
        }
    }

    return 0;
}
Beispiel #26
0
static inline mapnik::csv_line parse_line(std::string const& line_str, char separator, char quote)
{
    auto start = line_str.c_str();
    auto end   = start + line_str.length();
    return parse_line(start, end, separator, quote, 0);
}
/*
 * Parse a single file
 */
static int parse_file(char *filename)
{
    int val;
    int ret = OMPI_SUCCESS;
    bool first_section = true, first_coll = true;
    coll_config_t coll_config;

    memset (&coll_config, 0, sizeof (coll_config));
    reset_collective(&coll_config);

    /* Open the file */
    coll_ml_config_yyin = fopen(filename, "r");
    if (NULL == coll_ml_config_yyin) {
        ML_ERROR(("Failed to open config file %s", filename));
        ret = OMPI_ERR_NOT_FOUND;
        goto cleanup;
    }

    /* Do the parsing */
    coll_ml_config_parse_done = false;
    coll_ml_config_yynewlines = 1;
    coll_ml_config_init_buffer(coll_ml_config_yyin);
    while (!coll_ml_config_parse_done) {
        val = coll_ml_config_yylex();
        switch (val) {
        case COLL_ML_CONFIG_PARSE_DONE:
        case COLL_ML_CONFIG_PARSE_NEWLINE:
            break;
        case COLL_ML_CONFIG_PARSE_COLLECTIVE:
            /* dump all the information to last section that was defined */
            if (!first_coll) {
                ret = save_settings(&coll_config);

                if (OMPI_SUCCESS != ret) {
                    ML_ERROR(("Error in syntax for collective %s", coll_config.coll_name));
                    goto cleanup;
                }
            }
            
            /* reset collective config */
            reset_collective(&coll_config);

            first_coll    = false;
            first_section = true;

            ret = set_collective_name(&coll_config);
            if (OMPI_SUCCESS != ret) {
                goto cleanup;
            }
            break;
        case COLL_ML_CONFIG_PARSE_SECTION:
            if (ML_UNDEFINED == coll_config.coll_id) {
                ML_ERROR(("Collective section wasn't defined !"));
                ret = OMPI_ERROR;
                goto cleanup;
            }

            if (!first_section) {
                /* dump all the information to last section that was defined */
                ret = save_settings(&coll_config);
                if (OMPI_SUCCESS != ret) {
                    ML_ERROR(("Error in syntax for collective %s section %s", coll_config.coll_name,
                              coll_config.section.section_name));
                    goto cleanup;
                }
            }

            first_section = false;

            /* reset all section values */
            reset_section(&coll_config.section);

            /* set new section name */
            ret = set_section_name(&coll_config.section);
            if (OMPI_SUCCESS != ret) {
                goto cleanup;
            }
            break;
        case COLL_ML_CONFIG_PARSE_SINGLE_WORD:
            if (ML_UNDEFINED == coll_config.coll_id ||
                ML_UNDEFINED == coll_config.section.section_id) {
                ML_ERROR(("Collective section or sub-section was not defined !"));
                ret = OMPI_ERROR;
                goto cleanup;
            } else {
                parse_line(&coll_config.section);
            }
            break;

        default:
            /* anything else is an error */
            ML_ERROR(("Unexpected token!"));
            ret = OMPI_ERROR;
            goto cleanup;
            break;
        }
    }

    save_settings(&coll_config);
    fclose(coll_ml_config_yyin);
    coll_ml_config_yylex_destroy ();
    ret = OMPI_SUCCESS;

cleanup:
    reset_collective(&coll_config);
    if (NULL != key_buffer) {
        free(key_buffer);
        key_buffer = NULL;
        key_buffer_len = 0;
    }
    return ret;
}
Beispiel #28
0
/**************************************************************************
 * returns:
 *	1  - command executed, repeatable
 *	0  - command executed but not repeatable, interrupted commands are
 *	     always considered not repeatable
 *	-1 - not executed (unrecognized, bootd recursion or too many args)
 *           (If cmd is NULL or "" or longer than CFG_CBSIZE-1 it is
 *           considered unrecognized)
 *
 * WARNING:
 *
 * We must create a temporary copy of the command since the command we get
 * may be the result from getenv(), which returns a pointer directly to
 * the environment data, which may change magicly when the command we run
 * creates or modifies environment variables (like "bootp" does).
 *************************************************************************/
int run_command (const char *cmd, int flag)
{
	cmd_tbl_t *cmdtp;
	char cmdbuf[CFG_CBSIZE];	/* working copy of cmd		*/
	char *token;							/* start of token in cmdbuf	*/
	char *sep;								/* end of token (separator) in cmdbuf */
	char finaltoken[CFG_CBSIZE];
	char *str = cmdbuf;
	char *argv[CFG_MAXARGS + 1];	/* NULL terminated	*/
	int argc, inquotes;
	int repeatable = 1;
	int rc = 0;

#ifdef DEBUG_PARSER
	printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
	serial_puts (cmd ? cmd : "NULL");	/* use puts - string may be loooong */
	serial_puts ("\"\r\n");
#endif

	clear_ctrlc();		/* forget any previous Control C */

	if (!cmd || !*cmd) {
		return -1;			/* empty command */
	}

	if (strlen(cmd) >= CFG_CBSIZE) {
		serial_puts ("## Command too long!\r\n");
		return -1;
	}

	strcpy (cmdbuf, cmd);

	/* Process separators and check for invalid
	 * repeatable commands
	 */

#ifdef DEBUG_PARSER
	printf ("[PROCESS_SEPARATORS] %s\r\n", cmd);
#endif
	while (*str) {

		/*
		 * Find separator, or string end
		 * Allow simple escape of ';' by writing "\;"
		 */
		for (inquotes = 0, sep = str; *sep; sep++) {
			if ((*sep=='\'') &&
			    (*(sep-1) != '\\'))
				inquotes=!inquotes;

			if (!inquotes &&
			    (*sep == ';') &&	/* separator		*/
			    ( sep != str) &&	/* past string start	*/
			    (*(sep-1) != '\\'))	/* and NOT escaped	*/
				break;
		}

		/*
		 * Limit the token to data between separators
		 */
		token = str;
		if (*sep) {
			str = sep + 1;	/* start of command for next pass */
			*sep = '\0';
		}
		else
			str = sep;	/* no more commands for next pass */
#ifdef DEBUG_PARSER
		printf ("token: \"%s\"\n", token);
#endif

		/* find macros in this token and replace them */
		process_macros (token, finaltoken);

		/* Extract arguments */
		if ((argc = parse_line (finaltoken, argv)) == 0) {
			rc = -1;	/* no command at all */
			continue;
		}

		/* Look up command in command table */
		if ((cmdtp = find_cmd(argv[0])) == NULL) {
			printf ("Unknown command '%s' - try 'help'\r\n", argv[0]);
			rc = -1;	/* give up after bad command */
			continue;
		}

		/* found - check max args */
		if (argc > cmdtp->maxargs) {
			printf ("Usage:\n%s\r\n", cmdtp->usage);
			rc = -1;
			continue;
		}

		/* OK - call function to do the command */
		if ((cmdtp->cmd) (cmdtp, flag, argc, argv) != 0) {
			rc = -1;
		}

		repeatable &= cmdtp->repeatable;

		/* Did the user stop this? */
		if (had_ctrlc ())
			return 0;	/* if stopped then not repeatable */
	}

	return rc ? rc : repeatable;
}
Beispiel #29
0
/*
 * Parse configuration file; if any errors are encountered,
 * list them and exit.
 *
 * Ensure any default values set here are synced with repmgr.conf.sample
 * and any other documentation.
 */
bool
parse_config(t_configuration_options *options)
{
	FILE	   *fp;
	char	   *s,
				buff[MAXLINELENGTH];
	char		name[MAXLEN];
	char		value[MAXLEN];

	/* For sanity-checking provided conninfo string */
	PQconninfoOption *conninfo_options;
	char       *conninfo_errmsg = NULL;

	/* Collate configuration file errors here for friendlier reporting */
	static ErrorList config_errors = { NULL, NULL };

	fp = fopen(config_file_path, "r");

	/*
	 * Since some commands don't require a config file at all, not having one
	 * isn't necessarily a problem.
	 *
	 * If the user explictly provided a configuration file and we can't
	 * read it we'll raise an error.
	 *
	 * If no configuration file was provided, we'll try and read the default\
	 * file if it exists and is readable, but won't worry if it's not.
	 */
	if (fp == NULL)
	{
		if (config_file_provided)
		{
			log_err(_("unable to open provided configuration file '%s'; terminating\n"), config_file_path);
			exit(ERR_BAD_CONFIG);
		}

		log_notice(_("no configuration file provided and default file '%s' not found - "
					 "continuing with default values\n"),
				   DEFAULT_CONFIG_FILE);
		return false;
	}

	/* Initialize configuration options with sensible defaults
	 * note: the default log level is set in log.c and does not need
	 * to be initialised here
	 */
	memset(options->cluster_name, 0, sizeof(options->cluster_name));
	options->node = -1;
	options->upstream_node = NO_UPSTREAM_NODE;
	options->use_replication_slots = 0;
	memset(options->conninfo, 0, sizeof(options->conninfo));
	options->failover = MANUAL_FAILOVER;
	options->priority = DEFAULT_PRIORITY;
	memset(options->node_name, 0, sizeof(options->node_name));
	memset(options->promote_command, 0, sizeof(options->promote_command));
	memset(options->follow_command, 0, sizeof(options->follow_command));
	memset(options->rsync_options, 0, sizeof(options->rsync_options));
	memset(options->ssh_options, 0, sizeof(options->ssh_options));
	memset(options->pg_bindir, 0, sizeof(options->pg_bindir));
	memset(options->pg_ctl_options, 0, sizeof(options->pg_ctl_options));
	memset(options->pg_basebackup_options, 0, sizeof(options->pg_basebackup_options));

	/* default master_response_timeout is 60 seconds */
	options->master_response_timeout = 60;

	/* default to 6 reconnection attempts at intervals of 10 seconds */
	options->reconnect_attempts = 6;
	options->reconnect_interval = 10;

	options->monitor_interval_secs = 2;
	options->retry_promote_interval_secs = 300;

	memset(options->event_notification_command, 0, sizeof(options->event_notification_command));

	options->tablespace_mapping.head = NULL;
	options->tablespace_mapping.tail = NULL;


	/* Read next line */
	while ((s = fgets(buff, sizeof buff, fp)) != NULL)
	{
		bool known_parameter = true;

		/* Parse name/value pair from line */
		parse_line(buff, name, value);

		/* Skip blank lines */
		if (!strlen(name))
			continue;

		/* Skip comments */
		if (name[0] == '#')
			continue;

		/* Copy into correct entry in parameters struct */
		if (strcmp(name, "cluster") == 0)
			strncpy(options->cluster_name, value, MAXLEN);
		else if (strcmp(name, "node") == 0)
			options->node = repmgr_atoi(value, "node", &config_errors);
		else if (strcmp(name, "upstream_node") == 0)
			options->upstream_node = repmgr_atoi(value, "upstream_node", &config_errors);
		else if (strcmp(name, "conninfo") == 0)
			strncpy(options->conninfo, value, MAXLEN);
		else if (strcmp(name, "rsync_options") == 0)
			strncpy(options->rsync_options, value, QUERY_STR_LEN);
		else if (strcmp(name, "ssh_options") == 0)
			strncpy(options->ssh_options, value, QUERY_STR_LEN);
		else if (strcmp(name, "loglevel") == 0)
			strncpy(options->loglevel, value, MAXLEN);
		else if (strcmp(name, "logfacility") == 0)
			strncpy(options->logfacility, value, MAXLEN);
		else if (strcmp(name, "failover") == 0)
		{
			char		failoverstr[MAXLEN];

			strncpy(failoverstr, value, MAXLEN);

			if (strcmp(failoverstr, "manual") == 0)
			{
				options->failover = MANUAL_FAILOVER;
			}
			else if (strcmp(failoverstr, "automatic") == 0)
			{
				options->failover = AUTOMATIC_FAILOVER;
			}
			else
			{
				log_err(_("value for 'failover' must be 'automatic' or 'manual'\n"));
				exit(ERR_BAD_CONFIG);
			}
		}
		else if (strcmp(name, "priority") == 0)
			options->priority = repmgr_atoi(value, "priority", &config_errors);
		else if (strcmp(name, "node_name") == 0)
			strncpy(options->node_name, value, MAXLEN);
		else if (strcmp(name, "promote_command") == 0)
			strncpy(options->promote_command, value, MAXLEN);
		else if (strcmp(name, "follow_command") == 0)
			strncpy(options->follow_command, value, MAXLEN);
		else if (strcmp(name, "master_response_timeout") == 0)
			options->master_response_timeout = repmgr_atoi(value, "master_response_timeout", &config_errors);
		/* 'primary_response_timeout' as synonym for 'master_response_timeout' -
		 * we'll switch terminology in a future release (3.1?)
		 */
		else if (strcmp(name, "primary_response_timeout") == 0)
			options->master_response_timeout = repmgr_atoi(value, "primary_response_timeout", &config_errors);
		else if (strcmp(name, "reconnect_attempts") == 0)
			options->reconnect_attempts = repmgr_atoi(value, "reconnect_attempts", &config_errors);
		else if (strcmp(name, "reconnect_interval") == 0)
			options->reconnect_interval = repmgr_atoi(value, "reconnect_interval", &config_errors);
		else if (strcmp(name, "pg_bindir") == 0)
			strncpy(options->pg_bindir, value, MAXLEN);
		else if (strcmp(name, "pg_ctl_options") == 0)
			strncpy(options->pg_ctl_options, value, MAXLEN);
		else if (strcmp(name, "pg_basebackup_options") == 0)
			strncpy(options->pg_basebackup_options, value, MAXLEN);
		else if (strcmp(name, "logfile") == 0)
			strncpy(options->logfile, value, MAXLEN);
		else if (strcmp(name, "monitor_interval_secs") == 0)
			options->monitor_interval_secs = repmgr_atoi(value, "monitor_interval_secs", &config_errors);
		else if (strcmp(name, "retry_promote_interval_secs") == 0)
			options->retry_promote_interval_secs = repmgr_atoi(value, "retry_promote_interval_secs", &config_errors);
		else if (strcmp(name, "use_replication_slots") == 0)
			/* XXX we should have a dedicated boolean argument format */
			options->use_replication_slots = repmgr_atoi(value, "use_replication_slots", &config_errors);
		else if (strcmp(name, "event_notification_command") == 0)
			strncpy(options->event_notification_command, value, MAXLEN);
		else if (strcmp(name, "event_notifications") == 0)
			parse_event_notifications_list(options, value);
		else if (strcmp(name, "tablespace_mapping") == 0)
			tablespace_list_append(options, value);
		else
		{
			known_parameter = false;
			log_warning(_("%s/%s: unknown name/value pair provided; ignoring\n"), name, value);
		}

		/*
		 * Raise an error if a known parameter is provided with an empty value.
		 * Currently there's no reason why empty parameters are needed; if
		 * we want to accept those, we'd need to add stricter default checking,
		 * as currently e.g. an empty `node` value will be converted to '0'.
		 */
		if (known_parameter == true && !strlen(value)) {
			char	   error_message_buf[MAXLEN] = "";
			snprintf(error_message_buf,
					 MAXLEN,
					 _("no value provided for parameter \"%s\""),
					 name);

			error_list_append(&config_errors, error_message_buf);
		}
	}

	fclose(fp);

	/* Check config settings */

	/* The following checks are for the presence of the parameter */
	if (*options->cluster_name == '\0')
	{
		error_list_append(&config_errors, _("\"cluster\": parameter was not found\n"));
	}

	if (options->node == -1)
	{
		error_list_append(&config_errors, _("\"node\": parameter was not found\n"));
	}

	if (*options->node_name == '\0')
	{
		error_list_append(&config_errors, _("\"node_name\": parameter was not found\n"));
	}

	if (*options->conninfo == '\0')
	{
		error_list_append(&config_errors, _("\"conninfo\": parameter was not found\n"));
	}
	else
	{

		/* Sanity check the provided conninfo string
		 *
		 * NOTE: this verifies the string format and checks for valid options
		 * but does not sanity check values
		 */
		conninfo_options = PQconninfoParse(options->conninfo, &conninfo_errmsg);
		if (conninfo_options == NULL)
		{
			char	   error_message_buf[MAXLEN] = "";
			snprintf(error_message_buf,
					 MAXLEN,
					 _("\"conninfo\": %s"),
					 conninfo_errmsg);

			error_list_append(&config_errors, error_message_buf);
		}

		PQconninfoFree(conninfo_options);
	}

	// exit_with_errors here
	if (config_errors.head != NULL)
	{
		exit_with_errors(&config_errors);
	}
	return true;
}
Beispiel #30
0
static void siggen(FILE *in, FILE *out)
    {
    char buf[1024];
    char lbuf[1024];
    char *keyword, *value;
    int dsa2, L, N;
    const EVP_MD *md = NULL;
    DSA *dsa=NULL;

    while(fgets(buf,sizeof buf,in) != NULL)
	{
	if (!parse_line(&keyword, &value, lbuf, buf))
		{
		fputs(buf,out);
		continue;
		}
	fputs(buf,out);
	if(!strcmp(keyword,"[mod"))
	    {
	    if (!parse_mod(value, &dsa2, &L, &N, &md))
		{
		fprintf(stderr, "Mod Parse Error\n");
		exit (1);
		}
	    if (dsa)
		FIPS_dsa_free(dsa);
	    dsa = FIPS_dsa_new();
	    if (!dsa2 && !dsa_builtin_paramgen(dsa, L, N, md, NULL, 0,
						NULL, NULL, NULL, NULL))
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    if (dsa2 && dsa_builtin_paramgen2(dsa, L, N, md, NULL, 0,
						NULL, NULL, NULL, NULL) <= 0)
			{
			fprintf(stderr, "Parameter Generation error\n");
			exit(1);
			}
	    do_bn_print_name(out, "P",dsa->p);
	    do_bn_print_name(out, "Q",dsa->q);
	    do_bn_print_name(out, "G",dsa->g);
	    fputs("\n", out);
	    }
	else if(!strcmp(keyword,"Msg"))
	    {
	    unsigned char msg[1024];
	    int n;
	    EVP_MD_CTX mctx;
	    DSA_SIG *sig;
	    FIPS_md_ctx_init(&mctx);

	    n=hex2bin(value,msg);

	    if (!DSA_generate_key(dsa))
		exit(1);
	    do_bn_print_name(out, "Y",dsa->pub_key);

	    FIPS_digestinit(&mctx, md);
	    FIPS_digestupdate(&mctx, msg, n);
	    sig = FIPS_dsa_sign_ctx(dsa, &mctx);

	    do_bn_print_name(out, "R",sig->r);
	    do_bn_print_name(out, "S",sig->s);
	    fputs("\n", out);
	    FIPS_dsa_sig_free(sig);
	    FIPS_md_ctx_cleanup(&mctx);
	    }
	}
	if (dsa)
		FIPS_dsa_free(dsa);
    }