Exemplo n.º 1
0
static void parse_line (char *buf)
{
  char  *fields[64];
  size_t fields_num;
  data_set_t *ds;
  int i;

  fields_num = strsplit (buf, fields, 64);
  if (fields_num < 2)
    return;

  ds = (data_set_t *) malloc (sizeof (data_set_t));
  if (ds == NULL)
    return;

  memset (ds, '\0', sizeof (data_set_t));

  sstrncpy (ds->type, fields[0], sizeof (ds->type));

  ds->ds_num = fields_num - 1;
  ds->ds = (data_source_t *) calloc (ds->ds_num, sizeof (data_source_t));
  if (ds->ds == NULL)
    return;

  for (i = 0; i < ds->ds_num; i++)
    if (parse_ds (ds->ds + i, fields[i + 1], strlen (fields[i + 1])) != 0)
    {
      sfree (ds->ds);
      ERROR ("types_list: parse_line: Cannot parse data source #%i "
	  "of data set %s", i, ds->type);
      return;
    }

  plugin_register_data_set (ds);

  sfree (ds->ds);
  sfree (ds);
} /* void parse_line */
Exemplo n.º 2
0
// !say [#channel | $nick] text
void
scriptcmd_say (NetServer *s)
{
  strsplit (CMD[3], BUF, 1);
  if (BUF[1][0] == 0)
    {
      SEND_TEXT (DEST, "%s", HELP_SAY);
      return;
    }
  if (BUF[1][0] == '#')
    {
      int i = 0;
      while (BUF[1][i] != ' ' && BUF[1][i] != 0)
        i++;
      my_strncpy (DEST, BUF[1], i);
      my_strncpy (BUF[2], BUF[1] + i + num_spaces (BUF[1]+i), MSG_SIZE);
      my_strncpy (BUF[1], BUF[2], MSG_SIZE);
    }
  else if (BUF[1][0] == '$')
    {
      int i = 0;
      while (BUF[1][i] != ' ' && BUF[1][i] != 0)
        i++;
      my_strncpy (DEST, BUF[1], i);
      my_strncpy (DEST, DEST+1, CHANNEL_SIZE);
      if (strcasecmp (NICKSERV, DEST) == 0
          || strcasecmp (CHANSERV, DEST) == 0
          || strcasecmp (MEMOSERV, DEST) == 0
          || strcasecmp (OPERSERV, DEST) == 0)
        {
          SEND_TEXT (SOURCE, "Cannot send to IRC Services.");
          return;
        }
      my_strncpy (BUF[2], BUF[1] + i + num_spaces (BUF[1] + i), MSG_SIZE);
      my_strncpy (BUF[1], BUF[2], MSG_SIZE);
    }
  SEND_TEXT (DEST, "%s", BUF[1]);
}
Exemplo n.º 3
0
static int handle_server(struct parsedfile *config, int lineno, char *value) {
    char *ip;

    ip = strsplit(NULL, &value, " ");

    /* We don't verify this ip/hostname at this stage, */
    /* its resolved immediately before use in tsocks.c */
    if (currentcontext->address == NULL)
        currentcontext->address = strdup(ip);
    else {
        if (currentcontext == &(config->defaultserver))
            show_msg(MSGERR, "Only one default SOCKS server "
                   "may be specified at line %d in "
                   "configuration file\n", lineno);
        else
            show_msg(MSGERR, "Only one SOCKS server may be specified "
                   "per path on line %d in configuration "
                   "file. (Path begins on line %d)\n",
                   lineno, currentcontext->lineno);
    }

    return(0);
}
Exemplo n.º 4
0
// !join #channel [key]
void
scriptcmd_join (NetServer *s)
{
  strsplit (CMD[3], BUF, 3);
  if (BUF[1][0] == 0)
    {
      SEND_TEXT (DEST, "%s", HELP_JOIN);
      return;
    }
  int chan_num = CHANNEL_INDEX (BUF[1]);
  if (chan_num != -1)		// if not already in the channel
    {
      SEND_TEXT (DEST, "I'm already on \002%s\002.", BUF[1]);
      return;
    }
  if (!s->channel_add (BUF[1], BUF[2]))
    {
      SEND_TEXT (DEST, "Maximum channels reached.");
      return;
    }
  chan_num = CHANNEL_INDEX (BUF[1]);	// search it's position again
  CHANNELS[chan_num]->irc_join ();	// join it
}
Exemplo n.º 5
0
void Scene::parseLineForSphere(std::string line, Sphere &sphere, const int &material_offset) {

    std::vector<std::string> parts;            // vector for ;-seperated variables

    strsplit(line, ';', parts);        // split line
    if (parts.size() != 3) {
        std::cout << "parseLineForSphere error in line: " << line << std::endl;
        return;
    }
    else {
        Vector3 center = strtoVect(parts[0]);
        float radius = lexical_cast<float>(parts[1]);
        int matID = lexical_cast<int>(parts[2]) + material_offset;

        if (matID >= nummats) {
            cout << "specified material does not exist! Replaced by default" << endl;
            sphere = Sphere(center, radius, &stdDiffuse);
        }
        else {
            sphere = Sphere(center, radius, &materials[matID]);
        }
    }
}
Exemplo n.º 6
0
Arquivo: extra.cpp Projeto: b0nk/mbot
// configuration file's local parser
static void
extra_conf (NetServer *s, c_char bufread)
{
  char buf[2][MSG_SIZE+1];

  strsplit (bufread, buf, 1);

  // add these commands in each new server
  if (strcasecmp (buf[0], "bot") == 0
      && server2extra (s) == NULL)
    {
      extra_add (s);
#ifdef PING_PATH
      s->script.events.add ((void *)extra_event);
#endif
      s->script.cmd_bind (extra_cmd_raw, LEVEL_RAW, "!raw", module.mod, HELP_RAW);
      s->script.cmd_bind (extra_cmd_dccchat, LEVEL_DCCCHAT, "!dccchat", module.mod, HELP_DCCCHAT);
      s->script.cmd_bind (extra_cmd_ping, LEVEL_PING, "!ping", module.mod, HELP_PING);
      s->script.cmd_bind (extra_cmd_scan, LEVEL_SCAN, "!scan", module.mod, HELP_SCAN);
      s->script.cmd_bind (extra_cmd_host, LEVEL_HOST, "!host", module.mod, HELP_HOST);
      s->vars.var_add ("extra_akickping", extra_var);
    }
}
Exemplo n.º 7
0
// !usermask mask newmask
void
scriptcmd_usermask (NetServer *s)
{
  strsplit (CMD[3], BUF, 3);
  if (BUF[2][0] == 0)
    {
      SEND_TEXT (DEST, "%s", HELP_USERMASK);
      return;
    }
  struct ListUsers::user_type *u = USERS.abs_mask2user (BUF[1]);
  if (u == NULL)
    {
      SEND_TEXT (DEST, "User does not exist.");
      return;
    }
  if (USERS.match_mask_level (CMD[0]) > u->level)
    {
      USERS.abs_set_mask (BUF[1], BUF[2]);
      SEND_TEXT (DEST, "Mask \002%s\002 changed to \002%s\002.", BUF[1], BUF[2]);
    }
  else
    SEND_TEXT (DEST, "Not enough access level.");
}
Exemplo n.º 8
0
static struct hostent *
hostent_from_yp(int family, char *line)
{
	struct hostent	*h;
	char		*next, *tokens[10], addr[IN6ADDRSZ];
	int		 i, ntok;

	if ((h = hostent_alloc(family)) == NULL)
		return (NULL);

	for(next = line; line; line = next) {
		if ((next = strchr(line, '\n'))) {
			*next = '\0';
			next += 1;
		}
		ntok = strsplit(line, tokens, 10);
		if (ntok < 2)
			continue;
		if (inet_pton(family, tokens[0], addr) == 1)
			hostent_add_addr(h, addr, family == AF_INET ?
			    INADDRSZ : IN6ADDRSZ);
		i = 2;
		if (!h->h_name)
			hostent_set_cname(h, tokens[1], 0);
		else if (strcmp(h->h_name, tokens[1]))
			i = 1;
		for (; i < ntok; i++)
			hostent_add_alias(h, tokens[i], 0);
	}

	if (h->h_name == NULL) {
		free(h);
		return (NULL);
	}

	return (h);
}
Exemplo n.º 9
0
// !pass password
void
scriptcmd_pass (NetServer *s)
{
  if (DEST[0] == '#')
    {
      SEND_TEXT (DEST, "Do \002not\002 use this command on a channel.");
      return;
    }
  strsplit (CMD[3], BUF, 1);
  if (BUF[1][0] == 0)
    {
      SEND_TEXT (DEST, "%s", HELP_PASS);
      return;
    }
  if (USERS.match_check_pass (CMD[0], BUF[1]))
    {
      USERS.match_set_id (CMD[0], 1);
      mask2nick (CMD[0], BUF[2]);
      s->irc_watch (BUF[2], 1);
      SEND_TEXT (DEST, "Password correct.");
    }
  else
    SEND_TEXT (DEST, "Password \002in\002correct.");
}
Exemplo n.º 10
0
// !cmdlevel !command level
void
scriptcmd_cmdlevel (NetServer *s)
{
  strsplit (CMD[3], BUF, 3);
  if (BUF[2][0] == 0)
    {
      SEND_TEXT (DEST, "%s", HELP_CMDLEVEL);
      return;
    }
  Script::cmd_type *c = s->script.cmd_get (BUF[1]);
  if (c == NULL)
    {
      SEND_TEXT (DEST, "Command \002%s\002 does not exist.", BUF[1]);
      return;
    }
  int level = atoi (BUF[2]);
  if (level > LEVEL_MAX)
    c->level = LEVEL_MAX;
  else if (level < 0)
    c->level = 0;
  else
    c->level = level;
  SEND_TEXT (DEST, "Command \002%s\002's level set to \002%d\002.", BUF[1], c->level);
}
Exemplo n.º 11
0
void JoystickMapper::unserializeMap(string serialConf)
{
    vector<string> splitConf;
    
    splitConf = strsplit(serialConf, ',');
    
    OEInt index = 0;
    for (OEInt i = 0; i < (splitConf.size() / 4); i++)
    {
        JoystickMapperItem item;
        
        OEInt usageId = getItemUsageId(splitConf[index++]);
        
        string usageName = splitConf[index++];
        float sensitivity = getFloat(splitConf[index++]);
        bool reverse = getOEInt(splitConf[index++]);
        
        usageIdMap[usageId].usageId = getItemUsageId(usageName);
        usageIdMap[usageId].type = getItemType(usageName);
        usageIdMap[usageId].sensitivity = sensitivity;
        usageIdMap[usageId].reverse = reverse;
        usageIdMap[usageId].value = 0.5F;
    }
}
Exemplo n.º 12
0
/*
 * Fill in struct group from gr_entry
 */
int
exfiles_copy_group_from_gr_entry(struct group *grbuf, char **gr_entry)
{
    int tmplen = 0;

    tmplen = strlen(gr_entry[0]);
    strncpy(grbuf->gr_name, gr_entry[0], tmplen+1);

    if (strlen(grbuf->gr_name) != tmplen)
        return -1;

    tmplen = strlen(gr_entry[1]);
    strncpy(grbuf->gr_passwd, gr_entry[1], tmplen+1);

    if (strlen(grbuf->gr_passwd) != tmplen)
        return -1;

    grbuf->gr_gid = (gid_t)atoi(gr_entry[2]);

    /* Split the members by comma */
    grbuf->gr_mem = strsplit(gr_entry[3], ',');

    return 0;
}
Exemplo n.º 13
0
static void *us_handle_client (void *arg)
{
	int fdin;
	int fdout;
	FILE *fhin, *fhout;

	fdin = *((int *) arg);
	free (arg);
	arg = NULL;

	DEBUG ("unixsock plugin: us_handle_client: Reading from fd #%i", fdin);

	fdout = dup (fdin);
	if (fdout < 0)
	{
		char errbuf[1024];
		ERROR ("unixsock plugin: dup failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		close (fdin);
		pthread_exit ((void *) 1);
	}

	fhin  = fdopen (fdin, "r");
	if (fhin == NULL)
	{
		char errbuf[1024];
		ERROR ("unixsock plugin: fdopen failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		close (fdin);
		close (fdout);
		pthread_exit ((void *) 1);
		return ((void *) 1);
	}

	fhout = fdopen (fdout, "w");
	if (fhout == NULL)
	{
		char errbuf[1024];
		ERROR ("unixsock plugin: fdopen failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		fclose (fhin); /* this closes fdin as well */
		close (fdout);
		pthread_exit ((void *) 1);
		return ((void *) 1);
	}

	/* change output buffer to line buffered mode */
	if (setvbuf (fhout, NULL, _IOLBF, 0) != 0)
	{
		char errbuf[1024];
		ERROR ("unixsock plugin: setvbuf failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		fclose (fhin);
		fclose (fhout);
		pthread_exit ((void *) 1);
		return ((void *) 0);
	}

	while (42)
	{
		char buffer[1024];
		char buffer_copy[1024];
		char *fields[128];
		int   fields_num;
		int   len;

		errno = 0;
		if (fgets (buffer, sizeof (buffer), fhin) == NULL)
		{
			if ((errno == EINTR) || (errno == EAGAIN))
				continue;

			if (errno != 0)
			{
				char errbuf[1024];
				WARNING ("unixsock plugin: failed to read from socket #%i: %s",
						fileno (fhin),
						sstrerror (errno, errbuf, sizeof (errbuf)));
			}
			break;
		}

		len = strlen (buffer);
		while ((len > 0)
				&& ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r')))
			buffer[--len] = '\0';

		if (len == 0)
			continue;

		sstrncpy (buffer_copy, buffer, sizeof (buffer_copy));

		fields_num = strsplit (buffer_copy, fields,
				sizeof (fields) / sizeof (fields[0]));
		if (fields_num < 1)
		{
			fprintf (fhout, "-1 Internal error\n");
			fclose (fhin);
			fclose (fhout);
			pthread_exit ((void *) 1);
			return ((void *) 1);
		}

		if (strcasecmp (fields[0], "getval") == 0)
		{
			handle_getval (fhout, buffer);
		}
		else if (strcasecmp (fields[0], "getthreshold") == 0)
		{
			handle_getthreshold (fhout, buffer);
		}
		else if (strcasecmp (fields[0], "putval") == 0)
		{
			handle_putval (fhout, buffer);
		}
		else if (strcasecmp (fields[0], "listval") == 0)
		{
			handle_listval (fhout, buffer);
		}
		else if (strcasecmp (fields[0], "putnotif") == 0)
		{
			handle_putnotif (fhout, buffer);
		}
		else if (strcasecmp (fields[0], "flush") == 0)
		{
			handle_flush (fhout, buffer);
		}
		else
		{
			if (fprintf (fhout, "-1 Unknown command: %s\n", fields[0]) < 0)
			{
				char errbuf[1024];
				WARNING ("unixsock plugin: failed to write to socket #%i: %s",
						fileno (fhout),
						sstrerror (errno, errbuf, sizeof (errbuf)));
				break;
			}
		}
	} /* while (fgets) */

	DEBUG ("unixsock plugin: us_handle_client: Exiting..");
	fclose (fhin);
	fclose (fhout);

	pthread_exit ((void *) 0);
	return ((void *) 0);
} /* void *us_handle_client */
Exemplo n.º 14
0
static int
lv_config (const char *key, const char *value)
{
    if (virInitialize () != 0)
        return 1;

    if (il_domains == NULL)
        il_domains = ignorelist_create (1);
    if (il_block_devices == NULL)
        il_block_devices = ignorelist_create (1);
    if (il_interface_devices == NULL)
        il_interface_devices = ignorelist_create (1);

    if (strcasecmp (key, "Connection") == 0) {
        char *tmp = strdup (value);
        if (tmp == NULL) {
            ERROR (PLUGIN_NAME " plugin: Connection strdup failed.");
            return 1;
        }
        sfree (conn_string);
        conn_string = tmp;
        return 0;
    }

    if (strcasecmp (key, "RefreshInterval") == 0) {
        char *eptr = NULL;
        interval = strtol (value, &eptr, 10);
        if (eptr == NULL || *eptr != '\0') return 1;
        return 0;
    }

    if (strcasecmp (key, "Domain") == 0) {
        if (ignorelist_add (il_domains, value)) return 1;
        return 0;
    }
    if (strcasecmp (key, "BlockDevice") == 0) {
        if (ignorelist_add (il_block_devices, value)) return 1;
        return 0;
    }
    if (strcasecmp (key, "InterfaceDevice") == 0) {
        if (ignorelist_add (il_interface_devices, value)) return 1;
        return 0;
    }

    if (strcasecmp (key, "IgnoreSelected") == 0) {
        if (IS_TRUE (value))
        {
            ignorelist_set_invert (il_domains, 0);
            ignorelist_set_invert (il_block_devices, 0);
            ignorelist_set_invert (il_interface_devices, 0);
        }
        else
        {
            ignorelist_set_invert (il_domains, 1);
            ignorelist_set_invert (il_block_devices, 1);
            ignorelist_set_invert (il_interface_devices, 1);
        }
        return 0;
    }

    if (strcasecmp (key, "HostnameFormat") == 0) {
        char *value_copy;
        char *fields[HF_MAX_FIELDS];
        int i, n;

        value_copy = strdup (value);
        if (value_copy == NULL) {
            ERROR (PLUGIN_NAME " plugin: strdup failed.");
            return -1;
        }

        n = strsplit (value_copy, fields, HF_MAX_FIELDS);
        if (n < 1) {
            sfree (value_copy);
            ERROR (PLUGIN_NAME " plugin: HostnameFormat: no fields");
            return -1;
        }

        for (i = 0; i < n; ++i) {
            if (strcasecmp (fields[i], "hostname") == 0)
                hostname_format[i] = hf_hostname;
            else if (strcasecmp (fields[i], "name") == 0)
                hostname_format[i] = hf_name;
            else if (strcasecmp (fields[i], "uuid") == 0)
                hostname_format[i] = hf_uuid;
            else {
                ERROR (PLUGIN_NAME " plugin: unknown HostnameFormat field: %s", fields[i]);
                sfree (value_copy);
                return -1;
            }
        }
        sfree (value_copy);

        for (i = n; i < HF_MAX_FIELDS; ++i)
            hostname_format[i] = hf_none;

        return 0;
    }

    if (strcasecmp (key, "PluginInstanceFormat") == 0) {
        char *value_copy;
        char *fields[PLGINST_MAX_FIELDS];
        int i, n;

        value_copy = strdup (value);
        if (value_copy == NULL) {
            ERROR (PLUGIN_NAME " plugin: strdup failed.");
            return -1;
        }

        n = strsplit (value_copy, fields, PLGINST_MAX_FIELDS);
        if (n < 1) {
            sfree (value_copy);
            ERROR (PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
            return -1;
        }

        for (i = 0; i < n; ++i) {
            if (strcasecmp (fields[i], "none") == 0) {
                plugin_instance_format[i] = plginst_none;
                break;
            } else if (strcasecmp (fields[i], "name") == 0)
                plugin_instance_format[i] = plginst_name;
            else if (strcasecmp (fields[i], "uuid") == 0)
                plugin_instance_format[i] = plginst_uuid;
            else {
                ERROR (PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s", fields[i]);
                sfree (value_copy);
                return -1;
            }
        }
        sfree (value_copy);

        for (i = n; i < PLGINST_MAX_FIELDS; ++i)
            plugin_instance_format[i] = plginst_none;

        return 0;
    }

    if (strcasecmp (key, "InterfaceFormat") == 0) {
        if (strcasecmp (value, "name") == 0)
            interface_format = if_name;
        else if (strcasecmp (value, "address") == 0)
            interface_format = if_address;
        else if (strcasecmp (value, "number") == 0)
            interface_format = if_number;
        else {
            ERROR (PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
            return -1;
        }
        return 0;
    }

    /* Unrecognised option. */
    return -1;
}
Exemplo n.º 15
0
/* rnmrtk_read_parms(): read the parameter file corresponding to an RNMRTK
 * data file.
 * @fname: the data filename.
 * @par: pointer to the output parameter structure.
 */
int rnmrtk_read_parms (const char *fname, struct rnmrtk_parms *par) {
  /* declare a few required variables:
   * @pfname: parameter file name.
   * @buf: buffer holding parameter file lines.
   * @nfields: number of strings in the fields array.
   * @fields: string array of space-delimited fields.
   * @i: general purpose loop counter.
   * @fh: parameter file handle.
   */
  char *pfname, buf[N_BUF];
  unsigned int i, nfields;
  char **fields;
  FILE *fh;

  /* declare variables required for parsing layout lines:
   * @dim: main dimension index.
   * @sub: sub-dimension index.
   * @pts: point count.
   */
  int dim, sub, pts;

  /* initialize the parameter structure contents. */
  memset(par, 0, sizeof(struct rnmrtk_parms));

  /* build the parameter filename string. */
  pfname = rnmrtk_parfile(fname);

  /* check that the string was created successfully. */
  if (!pfname)
    throw("failed to allocate parameter filename");

  /* open the parameter file. */
  fh = fopen(pfname, "rb");

  /* check that the file was opened. */
  if (!fh)
    throw("failed to open '%s'", pfname);

  /* loop until we've read the entire file. */
  while (!feof(fh)) {
    /* read a new line from the file. */
    if (fgets(buf, N_BUF, fh)) {
      /* trim trailing newlines from the string. */
      strnltrim((char*) buf);

      /* split the line by whitespace. */
      fields = strsplit(buf, " ", &nfields);

      /* trim the fields and convert everything to lowercase. */
      strvtrim(fields, nfields);
      strvcompact(fields, &nfields);
      strvtolower(fields, nfields);

      /* determine which parameter line we've tokenized. */
      if (strcmp(fields[0], RNMRTK_PARLINE_FORMAT) == 0) {
        /* parse all available format line fields. */
        if (nfields >= 2) {
          /* parse the endianness of the data. */
          if (strcmp(fields[1], RNMRTK_ENDIAN_BIG) == 0)
            par->endian = BYTES_ENDIAN_BIG;
          else if (strcmp(fields[1], RNMRTK_ENDIAN_LITTLE) == 0)
            par->endian = BYTES_ENDIAN_LITTLE;
          else
            throw("invalid endianness '%s'", fields[1]);
        }
        if (nfields >= 3) {
          /* parse the word style of the data. */
          if (strcmp(fields[2], RNMRTK_WTYPE_INT) == 0)
            par->isflt = 0;
          else if (strcmp(fields[2], RNMRTK_WTYPE_FLT) == 0)
            par->isflt = 1;
          else
            throw("invalid word type '%s'", fields[2]);
        }
        if (nfields >= 4) {
          /* parse the header size. */
          par->nheader = atoi(fields[3]);
        }
        if (nfields >= 5) {
          /* parse the record length. */
          par->reclen = atoi(fields[4]);
        }
        if (nfields >= 6) {
          /* parse the padding size. */
          par->nbegin = atoi(fields[5]);
        }
        if (nfields >= 7) {
          /* parse the end padding. */
          par->nend = atoi(fields[6]);
        }
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_DOM) == 0) {
        /* store the number of dimensions. */
        par->nd = nfields - 1;

        /* check the number of dimensions. */
        if (par->nd < 1 || par->nd > RNMRTK_MAXDIM)
          throw("invalid dimension count %u", par->nd);

        /* parse the 'dom' line fields. */
        for (i = 0; i < par->nd; i++) {
          /* check that the first character is 't'. */
          if (fields[i + 1][0] != 't' || strlen(fields[i + 1]) < 2)
            throw("invalid field '%s' on '%s'", fields[i + 1], fields[0]);

          /* parse the dimension index. */
          par->ord[i] = atoi(fields[i + 1] + 1);
        }
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_N) == 0) {
        /* check for correct field count. */
        if (nfields != 2 * par->nd + 1)
          throw("invalid field count of %u on '%s'", nfields, fields[0]);

        /* parse the 'n' line fields. */
        for (i = 0; i < par->nd; i++) {
          /* parse the size value. */
          par->sz[i] = atoi(fields[2 * i + 1]);

          /* parse the complex flag. */
          if (strcmp(fields[2 * i + 2], RNMRTK_NTYPE_REAL) == 0)
            par->cx[i] = 0;
          else if (strcmp(fields[2 * i + 2], RNMRTK_NTYPE_COMPLEX) == 0)
            par->cx[i] = 1;
          else
            throw("invalid real/complex field '%s'", fields[2 * i + 2]);
        }
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_LAYOUT) == 0) {
        /* parse the 'layout' line fields. */
        for (i = 1; i < nfields; i++) {
          /* attempt to parse each layout field form. */
          if (sscanf(fields[i], "t%d-%d:%d", &dim, &sub, &pts) == 3 &&
              dim > 0 && dim <= par->nd) {
            /* store the parsed point count. */
            par->layout[dim - 1][sub] = pts;
          }
          else if (sscanf(fields[i], "t%d:%d", &dim, &pts) == 2 &&
                   dim > 0 && dim <= par->nd) {
            /* store the parsed point count. */
            par->layout[dim - 1][1] = pts;
          }
          else
            throw("invalid %s field '%s'", fields[0], fields[i]);
        }
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_SF) == 0) {
        /* check for correct field count. */
        if (nfields != par->nd + 1)
          throw("invalid field count of %u on '%s'", nfields, fields[0]);

        /* parse the 'sf' line fields. */
        for (i = 0; i < par->nd; i++)
          par->sf[i] = atof(fields[i + 1]);
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_PPM) == 0) {
        /* check for correct field count. */
        if (nfields != par->nd + 1)
          throw("invalid field count of %u on '%s'", nfields, fields[0]);

        /* parse the 'ppm' line fields. */
        for (i = 0; i < par->nd; i++)
          par->ppm[i] = atof(fields[i + 1]);
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_QUAD) == 0) {
        /* check for correct field count. */
        if (nfields != par->nd + 1)
          throw("invalid field count of %u on '%s'", nfields, fields[0]);

        /* parse the 'quad' line fields. */
        for (i = 0; i < par->nd; i++) {
          /* determine the quadrature setting. */
          if (strcmp(fields[i + 1], RNMRTK_QUADSTR_TPPI) == 0)
            par->quad[i] = RNMRTK_QUAD_TPPI;
          else if (strcmp(fields[i + 1], RNMRTK_QUADSTR_STATES) == 0)
            par->quad[i] = RNMRTK_QUAD_STATES;
          else if (strcmp(fields[i + 1], RNMRTK_QUADSTR_STATESTPPI) == 0)
            par->quad[i] = RNMRTK_QUAD_STATESTPPI;
          else
            throw("invalid quadrature '%s'", fields[i + 1]);
        }
      }
      else if (strcmp(fields[0], RNMRTK_PARLINE_SW) == 0) {
        /* check for correct field count. */
        if (nfields != par->nd + 1)
          throw("invalid field count of %u on '%s'", nfields, fields[0]);

        /* parse the 'sw' line fields. */
        for (i = 0; i < par->nd; i++)
          par->sw[i] = atof(fields[i + 1]);
      }

      /* free the fields string array. */
      strvfree(fields, nfields);
    }
  }

  /* close the parameter file. */
  fclose(fh);

  /* free the parameter filename. */
  free(pfname);

  /* return success. */
  return 1;
}
Exemplo n.º 16
0
int worker_process(epdata_t *epd, int thread_at)
{
    //printf("worker_process\n");
    working_at_fd = epd->fd;
    //network_send_error(epd, 503, "Lua Error: main function not found !!!");return 0;
    //network_send(epd, "aaa", 3);network_be_end(epd);return 0;

    if(epd->ssl && !epd->ssl_verify) {
        network_send_error(epd, 400, "No required SSL certificate was send");
        return 0;
    }

    lua_State *L = epd->L;

    if(!L) {
        epd->L = new_lua_thread(_L);

        if(!epd->L) {
            network_send_error(epd, 503, "Lua Error: Thread pool full !!!");
            return 0;
        }

        lua_pushlightuserdata(epd->L, epd);
        lua_setglobal(epd->L, "__epd__");

        L = epd->L;
    }

    lua_getglobal(L, "process");

    update_timeout(epd->timeout_ptr, STEP_PROCESS_TIMEOUT + 100);

    int init_tables = 0;
    char *pt1 = NULL, *pt2 = NULL, *t1 = NULL, *t2 = NULL, *t3 = NULL;

    int is_form_post = 0;
    char *cookies = NULL;
    pt1 = epd->headers;
    int i = 0;

    epd->uri = NULL;
    epd->host = NULL;
    epd->query = NULL;
    epd->http_ver = NULL;
    epd->referer = NULL;
    epd->user_agent = NULL;
    epd->if_modified_since = NULL;

    //epd->start_time = longtime();

    while(t1 = strtok_r(pt1, "\n", &pt1)) {
        if(++i == 1) { /// first line
            t2 = strtok_r(t1, " ", &t1);
            t3 = strtok_r(t1, " ", &t1);
            epd->http_ver = strtok_r(t1, " ", &t1);

            if(!epd->http_ver) {
                return 1;

            } else {
                if(init_tables == 0) {
                    lua_newtable(L); //headers
                }
            }

            int len = strlen(epd->http_ver);

            if(epd->http_ver[len - 1] == 13) { // CR == 13
                epd->http_ver[len - 1] = '\0';
            }

            if(t2 && t3) {
                for(t1 = t2 ; *t1 ; *t1 = toupper(*t1), t1++);

                epd->method = t2;
                lua_pushstring(L, t2);
                lua_setfield(L, -2, "method");
                t1 = strtok_r(t3, "?", &t3);
                t2 = strtok_r(t3, "?", &t3);
                epd->uri = t1;
                lua_pushstring(L, t1);
                lua_setfield(L, -2, "uri");

                if(t2) {
                    epd->query = (t2 - 1);
                    epd->query[0] = '?';
                    lua_pushstring(L, epd->query);
                    lua_setfield(L, -2, "query");
                }
            }

            continue;
        }

        t2 = strtok_r(t1, ":", &t1);

        if(t2) {
            if(t2[0] == '\r') {
                break;
            }

            for(t3 = t2; *t3; ++t3) {
                *t3 = *t3 >= 'A' && *t3 <= 'Z' ? *t3 | 0x60 : *t3;
            }

            t3 = t2 + strlen(t2) + 1; //strtok_r ( t1, ":", &t1 )

            if(t3) {
                int len = strlen(t3);

                if(t3[len - 1] == 13) { /// 13 == CR
                    t3[len - 1] = '\0';
                    len -= 1;
                }

                if(len < 1) {
                    break;
                }

                lua_pushstring(L, t3 + (t3[0] == ' ' ? 1 : 0));
                lua_setfield(L, -2, t2);

                /// check content-type
                if(t2[0] == 'h' && epd->host == NULL && strcmp(t2, "host") == 0) {
                    char *_t = strstr(t3, ":");

                    if(_t) {
                        _t[0] = '\0';
                    }

                    epd->host = t3 + (t3[0] == ' ' ? 1 : 0);

                } else if(t2[1] == 'o' && strcmp(t2, "content-type") == 0) {
                    if(stristr(t3, "x-www-form-urlencoded", len)) {
                        is_form_post = 1;

                    } else if(stristr(t3, "multipart/form-data", len)) {
                        epd->boundary = (char *)stristr(t3, "boundary=", len - 2);

                        if(epd->boundary) {
                            epd->boundary += 9;
                        }
                    }

                } else if(!cookies && t2[1] == 'o' && strcmp(t2, "cookie") == 0) {
                    cookies = t3 + (t3[0] == ' ' ? 1 : 0);

                } else if(!epd->user_agent && t2[1] == 's' && strcmp(t2, "user-agent") == 0) {
                    epd->user_agent = t3 + (t3[0] == ' ' ? 1 : 0);

                } else if(!epd->referer && t2[1] == 'e' && strcmp(t2, "referer") == 0) {
                    epd->referer = t3 + (t3[0] == ' ' ? 1 : 0);

                } else if(!epd->if_modified_since && t2[1] == 'f' && strcmp(t2, "if-modified-since") == 0) {
                    epd->if_modified_since = t3 + (t3[0] == ' ' ? 1 : 0);
                }
            }
        }
    }

    char *client_ip = inet_ntoa(epd->client_addr);
    lua_pushstring(L, client_ip);
    lua_setfield(L, -2, "remote-addr");
    int l = sizeof(struct sockaddr);
    struct sockaddr_in addr;
    getsockname(epd->fd, (struct sockaddr *) &addr, &l);
    lua_pushstring(L, inet_ntoa(addr.sin_addr));
    lua_setfield(L, -2, "server-addr");

    lua_setglobal(L, "headers");

    lua_newtable(L); /// _GET

    if(epd->query) { /// parse query string /?a=1&b=2
        char *last = NULL;
        int plen = 0;
        int qlen = strlen(epd->query) - 1;

        t1 = (char *)strsplit(epd->query + 1, qlen, "&", &last, &plen);
        char kk[256] = {0};

        while(t1) {
            char *last2 = NULL;
            int plen2 = 0;
            int plen3 = 0;

            t2 = (char *)strsplit(t1, plen, "=", &last2, &plen2);
            t3 = (char *)strsplit(t1, plen, "=", &last2, &plen3);

            if(t2 && plen2 > 0 && plen3 > 0 && plen2 <= 4096 && plen3 <= 4096) {
                size_t dlen;
                u_char *p;
                u_char *src, *dst;

                p = (u_char *)&buf_4096;
                p[0] = '\0';
                dst = p;
                dlen = urldecode(&p, (u_char **)&t3, plen3, RAW_UNESCAPE_URL);
                lua_pushlstring(L, (char *) p, dlen);

                p[0] = '\0';
                dst = p;

                dlen = urldecode(&dst, (u_char **)&t2, plen2, RAW_UNESCAPE_URL);
                p[dlen] = '\0';
                lua_setfield(L, -2, p);
            }

            t1 = (char *)strsplit(epd->query + 1, qlen, "&", &last, &plen);
        }
    }

    lua_setglobal(L, "_GET");

    lua_newtable(L); /// _COOKIE

    if(cookies) {
        while(t1 = strtok_r(cookies, ";", &cookies)) {
            t2 = strtok_r(t1, "=", &t1);
            t3 = strtok_r(t1, "=", &t1);

            if(t2 && t3 && strlen(t2) > 0 && strlen(t3) > 0) {
                size_t len, dlen;
                u_char *p;
                u_char *src, *dst;
                len = strlen(t3);
                p = malloc(len);
                p[0] = '\0';
                dst = p;
                dlen = urldecode(&dst, (u_char **)&t3, len, RAW_UNESCAPE_URL);
                lua_pushlstring(L, (char *) p, dlen);

                len = strlen(t2);

                if(len > 4096) {
                    free(p);
                    p = malloc(len);
                }

                p[0] = '\0';
                dst = p;

                dlen = urldecode(&dst, (u_char **)&t2, len, RAW_UNESCAPE_URL);
                p[dlen] = '\0';
                lua_setfield(L, -2, p + (p[0] == ' ' ? 1 : 0));
                free(p);
            }
        }
    }

    lua_setglobal(L, "_COOKIE");

    lua_pushnil(L);
    lua_setglobal(L, "__body_buf");

    epd->vhost_root = get_vhost_root(epd->host, &epd->vhost_root_len);

    memcpy(buf_4096, epd->vhost_root, epd->vhost_root_len + 1);
    sprintf(buf_4096 + epd->vhost_root_len + 1, "?.lua;%s/lua-libs/?.lua;", process_chdir);

    lua_pushstring(L, buf_4096);
    lua_getglobal(L, "package");
    lua_insert(L, -2); //-1 bufres -2 package
    lua_setfield(L, -2, "path"); //-1: path -2: package
    lua_pop(L, 1); //void

    lua_pushlstring(L, epd->vhost_root, epd->vhost_root_len); /// host root

    lua_setglobal(L, "__root");

    lua_pushstring(L, epd->vhost_root + epd->vhost_root_len); /// index-route.lua file

    epd->iov[0].iov_base = NULL;
    epd->iov[0].iov_len = 0;
    epd->iov[1].iov_base = NULL;
    epd->iov[1].iov_len = 0;

    lua_routed = 0;

    if(lua_resume(L, 1) == LUA_ERRRUN && lua_isstring(L, -1)) {
        LOGF(ERR, "Lua:error %s", lua_tostring(L, -1));
        network_send_error(epd, 503, lua_tostring(L, -1));
        lua_pop(L, 1);
    }

    return 0;
}
Exemplo n.º 17
0
static char *
amfs_parse_defaults(am_node *mp, mntfs *mf, char *def_opts)
{
  char *dflts;
  char *dfl;
  char **rvec = NULL;
  struct mnt_map *mm = (mnt_map *) mf->mf_private;

  dlog("determining /defaults entry value");

  /*
   * Find out if amd.conf overrode any map-specific /defaults.
   */
  if (mm->cfm && mm->cfm->cfm_defaults) {
    dlog("map %s map_defaults override: %s", mf->mf_mount, mm->cfm->cfm_defaults);
    dflts = xstrdup(mm->cfm->cfm_defaults);
  } else if (mapc_search(mm, "/defaults", &dflts) == 0) {
    dlog("/defaults gave %s", dflts);
  } else {
    return def_opts;		/* if nothing found */
  }

  /* trim leading '-' in case thee's one */
  if (*dflts == '-')
    dfl = dflts + 1;
  else
    dfl = dflts;

  /*
   * Chop the defaults up
   */
  rvec = strsplit(dfl, ' ', '\"');

  if (gopt.flags & CFM_SELECTORS_IN_DEFAULTS) {
    /*
     * Pick whichever first entry matched the list of selectors.
     * Strip the selectors from the string, and assign to dfl the
     * rest of the string.
     */
    if (rvec) {
      am_opts ap;
      am_ops *pt;
      char **sp = rvec;
      while (*sp) {		/* loop until you find something, if any */
	memset((char *) &ap, 0, sizeof(am_opts));
	/*
	 * This next routine cause many spurious "expansion of ... is"
	 * messages, which are ignored, b/c all we need out of this
	 * routine is to match selectors.  These spurious messages may
	 * be wrong, esp. if they try to expand ${key} b/c it will
	 * get expanded to "/defaults"
	 */
	pt = ops_match(&ap, *sp, "", mp->am_path, "/defaults",
		       mp->am_parent->am_al->al_mnt->mf_info);
	free_opts(&ap);	/* don't leak */
	if (pt == &amfs_error_ops) {
	  plog(XLOG_MAP, "did not match defaults for \"%s\"", *sp);
	} else {
	  dfl = strip_selectors(*sp, "/defaults");
	  plog(XLOG_MAP, "matched default selectors \"%s\"", dfl);
	  break;
	}
	++sp;
      }
    }
  } else {			/* not selectors_in_defaults */
    /*
     * Extract first value
     */
    dfl = rvec[0];
  }

  /*
   * If there were any values at all...
   */
  if (dfl) {
    /*
     * Log error if there were other values
     */
    if (!(gopt.flags & CFM_SELECTORS_IN_DEFAULTS) && rvec[1]) {
      dlog("/defaults chopped into %s", dfl);
      plog(XLOG_USER, "More than a single value for /defaults in %s", mf->mf_info);
    }

    /*
     * Prepend to existing defaults if they exist,
     * otherwise just use these defaults.
     */
    if (*def_opts && *dfl) {
      size_t l = strlen(def_opts) + strlen(dfl) + 2;
      char *nopts = (char *) xmalloc(l);
      xsnprintf(nopts, l, "%s;%s", dfl, def_opts);
      XFREE(def_opts);
      def_opts = nopts;
    } else if (*dfl) {
      def_opts = strealloc(def_opts, dfl);
    }
  }

  XFREE(dflts);

  /* don't need info vector any more */
  if (rvec)
    XFREE(rvec);

  return def_opts;
}
Exemplo n.º 18
0
static int apache_read_host (user_data_t *user_data) /* {{{ */
{
	int i;

	char *ptr;
	char *saveptr;
	char *lines[16];
	int   lines_num = 0;

	char *fields[4];
	int   fields_num;

	apache_t *st;

	st = user_data->data;

	assert (st->url != NULL);
	/* (Assured by `config_add') */

	if (st->curl == NULL)
	{
		int status;

		status = init_host (st);
		if (status != 0)
			return (-1);
	}
	assert (st->curl != NULL);

	st->apache_buffer_fill = 0;
	if (curl_easy_perform (st->curl) != CURLE_OK)
	{
		ERROR ("apache: curl_easy_perform failed: %s",
				st->apache_curl_error);
		return (-1);
	}

	/* fallback - server_type to apache if not set at this time */
	if (st->server_type == -1)
	{
		WARNING ("apache plugin: Unable to determine server software "
				"automatically. Will assume Apache.");
		st->server_type = APACHE;
	}

	ptr = st->apache_buffer;
	saveptr = NULL;
	while ((lines[lines_num] = strtok_r (ptr, "\n\r", &saveptr)) != NULL)
	{
		ptr = NULL;
		lines_num++;

		if (lines_num >= 16)
			break;
	}

	for (i = 0; i < lines_num; i++)
	{
		fields_num = strsplit (lines[i], fields, 4);

		if (fields_num == 3)
		{
			if ((strcmp (fields[0], "Total") == 0)
					&& (strcmp (fields[1], "Accesses:") == 0))
				submit_derive ("apache_requests", "",
						atoll (fields[2]), st);
			else if ((strcmp (fields[0], "Total") == 0)
					&& (strcmp (fields[1], "kBytes:") == 0))
				submit_derive ("apache_bytes", "",
						1024LL * atoll (fields[2]), st);
		}
		else if (fields_num == 2)
		{
			if (strcmp (fields[0], "Scoreboard:") == 0)
				submit_scoreboard (fields[1], st);
			else if ((strcmp (fields[0], "BusyServers:") == 0) /* Apache 1.* */
					|| (strcmp (fields[0], "BusyWorkers:") == 0) /* Apache 2.* */)
				submit_gauge ("apache_connections", NULL, atol (fields[1]), st);
			else if ((strcmp (fields[0], "IdleServers:") == 0) /* Apache 1.x */
					|| (strcmp (fields[0], "IdleWorkers:") == 0) /* Apache 2.x */)
				submit_gauge ("apache_idle_workers", NULL, atol (fields[1]), st);
		}
	}

	st->apache_buffer_fill = 0;

	return (0);
} /* }}} int apache_read_host */
Exemplo n.º 19
0
static int read_file(const char *path) {
  FILE *fh;
  char key_buffer[4096];
  char value_buffer[4096];
  char *key_ptr;
  char *value_ptr;
  char *key_fields[256];
  char *value_fields[256];
  int key_fields_num;
  int value_fields_num;
  int status;
  int i;

  fh = fopen(path, "r");
  if (fh == NULL) {
    ERROR("protocols plugin: fopen (%s) failed: %s.", path,
          sstrerror(errno, key_buffer, sizeof(key_buffer)));
    return (-1);
  }

  status = -1;
  while (42) {
    clearerr(fh);
    key_ptr = fgets(key_buffer, sizeof(key_buffer), fh);
    if (key_ptr == NULL) {
      if (feof(fh) != 0) {
        status = 0;
        break;
      } else if (ferror(fh) != 0) {
        ERROR("protocols plugin: Reading from %s failed.", path);
        break;
      } else {
        ERROR("protocols plugin: fgets failed for an unknown reason.");
        break;
      }
    } /* if (key_ptr == NULL) */

    value_ptr = fgets(value_buffer, sizeof(value_buffer), fh);
    if (value_ptr == NULL) {
      ERROR("protocols plugin: read_file (%s): Could not read values line.",
            path);
      break;
    }

    key_ptr = strchr(key_buffer, ':');
    if (key_ptr == NULL) {
      ERROR("protocols plugin: Could not find protocol name in keys line.");
      break;
    }
    *key_ptr = 0;
    key_ptr++;

    value_ptr = strchr(value_buffer, ':');
    if (value_ptr == NULL) {
      ERROR("protocols plugin: Could not find protocol name "
            "in values line.");
      break;
    }
    *value_ptr = 0;
    value_ptr++;

    if (strcmp(key_buffer, value_buffer) != 0) {
      ERROR("protocols plugin: Protocol names in keys and values lines "
            "don't match: `%s' vs. `%s'.",
            key_buffer, value_buffer);
      break;
    }

    key_fields_num =
        strsplit(key_ptr, key_fields, STATIC_ARRAY_SIZE(key_fields));
    value_fields_num =
        strsplit(value_ptr, value_fields, STATIC_ARRAY_SIZE(value_fields));

    if (key_fields_num != value_fields_num) {
      ERROR("protocols plugin: Number of fields in keys and values lines "
            "don't match: %i vs %i.",
            key_fields_num, value_fields_num);
      break;
    }

    for (i = 0; i < key_fields_num; i++) {
      if (values_list != NULL) {
        char match_name[2 * DATA_MAX_NAME_LEN];

        ssnprintf(match_name, sizeof(match_name), "%s:%s", key_buffer,
                  key_fields[i]);

        if (ignorelist_match(values_list, match_name))
          continue;
      } /* if (values_list != NULL) */

      submit(key_buffer, key_fields[i], value_fields[i]);
    } /* for (i = 0; i < key_fields_num; i++) */
  }   /* while (42) */

  fclose(fh);

  return (status);
} /* int read_file */
Exemplo n.º 20
0
static int interface_read (void)
{
#if HAVE_GETIFADDRS
	struct ifaddrs *if_list;
	struct ifaddrs *if_ptr;

/* Darwin/Mac OS X and possible other *BSDs */
#if HAVE_STRUCT_IF_DATA
#  define IFA_DATA if_data
#  define IFA_RX_BYTES ifi_ibytes
#  define IFA_TX_BYTES ifi_obytes
#  define IFA_RX_PACKT ifi_ipackets
#  define IFA_TX_PACKT ifi_opackets
#  define IFA_RX_ERROR ifi_ierrors
#  define IFA_TX_ERROR ifi_oerrors
/* #endif HAVE_STRUCT_IF_DATA */

#elif HAVE_STRUCT_NET_DEVICE_STATS
#  define IFA_DATA net_device_stats
#  define IFA_RX_BYTES rx_bytes
#  define IFA_TX_BYTES tx_bytes
#  define IFA_RX_PACKT rx_packets
#  define IFA_TX_PACKT tx_packets
#  define IFA_RX_ERROR rx_errors
#  define IFA_TX_ERROR tx_errors
#else
#  error "No suitable type for `struct ifaddrs->ifa_data' found."
#endif

	struct IFA_DATA *if_data;

	if (getifaddrs (&if_list) != 0)
		return (-1);

	for (if_ptr = if_list; if_ptr != NULL; if_ptr = if_ptr->ifa_next)
	{
		if (if_ptr->ifa_addr != NULL && if_ptr->ifa_addr->sa_family == AF_LINK) {
			if_data = (struct IFA_DATA *) if_ptr->ifa_data;

			if_submit (if_ptr->ifa_name, "if_octets",
				if_data->IFA_RX_BYTES,
				if_data->IFA_TX_BYTES);
			if_submit (if_ptr->ifa_name, "if_packets",
				if_data->IFA_RX_PACKT,
				if_data->IFA_TX_PACKT);
			if_submit (if_ptr->ifa_name, "if_errors",
				if_data->IFA_RX_ERROR,
				if_data->IFA_TX_ERROR);
		}
	}

	freeifaddrs (if_list);
/* #endif HAVE_GETIFADDRS */

#elif KERNEL_LINUX
	FILE *fh;
	char buffer[1024];
	derive_t incoming, outgoing;
	char *device;

	char *dummy;
	char *fields[16];
	int numfields;

	if ((fh = fopen ("/proc/net/dev", "r")) == NULL)
	{
		char errbuf[1024];
		WARNING ("interface plugin: fopen: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	while (fgets (buffer, 1024, fh) != NULL)
	{
		if (!(dummy = strchr(buffer, ':')))
			continue;
		dummy[0] = '\0';
		dummy++;

		device = buffer;
		while (device[0] == ' ')
			device++;

		if (device[0] == '\0')
			continue;

		numfields = strsplit (dummy, fields, 16);

		if (numfields < 11)
			continue;

		incoming = atoll (fields[0]);
		outgoing = atoll (fields[8]);
		if_submit (device, "if_octets", incoming, outgoing);

		incoming = atoll (fields[1]);
		outgoing = atoll (fields[9]);
		if_submit (device, "if_packets", incoming, outgoing);

		incoming = atoll (fields[2]);
		outgoing = atoll (fields[10]);
		if_submit (device, "if_errors", incoming, outgoing);

		incoming = atoll (fields[3]);
		outgoing = atoll (fields[11]);
		if_submit (device, "if_dropped", incoming, outgoing);
	}

	fclose (fh);
/* #endif KERNEL_LINUX */

#elif HAVE_LIBKSTAT
	int i;
	derive_t rx;
	derive_t tx;
	char iname[DATA_MAX_NAME_LEN];

	if (kc == NULL)
		return (-1);

	for (i = 0; i < numif; i++)
	{
		if (kstat_read (kc, ksp[i], NULL) == -1)
			continue;

		if (unique_name)
			ssnprintf(iname, sizeof(iname), "%s_%d_%s", ksp[i]->ks_module, ksp[i]->ks_instance, ksp[i]->ks_name);
		else
			sstrncpy(iname, ksp[i]->ks_name, sizeof(iname));

		/* try to get 64bit counters */
		rx = get_kstat_value (ksp[i], "rbytes64");
		tx = get_kstat_value (ksp[i], "obytes64");
		/* or fallback to 32bit */
		if (rx == -1LL)
			rx = get_kstat_value (ksp[i], "rbytes");
		if (tx == -1LL)
			tx = get_kstat_value (ksp[i], "obytes");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (iname, "if_octets", rx, tx);

		/* try to get 64bit counters */
		rx = get_kstat_value (ksp[i], "ipackets64");
		tx = get_kstat_value (ksp[i], "opackets64");
		/* or fallback to 32bit */
		if (rx == -1LL)
			rx = get_kstat_value (ksp[i], "ipackets");
		if (tx == -1LL)
			tx = get_kstat_value (ksp[i], "opackets");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (iname, "if_packets", rx, tx);

		/* no 64bit error counters yet */
		rx = get_kstat_value (ksp[i], "ierrors");
		tx = get_kstat_value (ksp[i], "oerrors");
		if ((rx != -1LL) || (tx != -1LL))
			if_submit (iname, "if_errors", rx, tx);
	}
/* #endif HAVE_LIBKSTAT */

#elif defined(HAVE_LIBSTATGRAB)
	sg_network_io_stats *ios;
	int i, num;

	ios = sg_get_network_io_stats (&num);

	for (i = 0; i < num; i++)
		if_submit (ios[i].interface_name, "if_octets", ios[i].rx, ios[i].tx);
/* #endif HAVE_LIBSTATGRAB */

#elif defined(HAVE_PERFSTAT)
	perfstat_id_t id;
	int i, ifs;

	if ((nif =  perfstat_netinterface(NULL, NULL, sizeof(perfstat_netinterface_t), 0)) < 0)
	{
		char errbuf[1024];
		WARNING ("interface plugin: perfstat_netinterface: %s",
			sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	if (pnif != nif || ifstat == NULL)
	{
		free(ifstat);
		ifstat = malloc(nif * sizeof (*ifstat));
	}
	pnif = nif;

	id.name[0]='\0';
	if ((ifs = perfstat_netinterface(&id, ifstat, sizeof(perfstat_netinterface_t), nif)) < 0)
	{
		char errbuf[1024];
		WARNING ("interface plugin: perfstat_netinterface (interfaces=%d): %s",
			nif, sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	for (i = 0; i < ifs; i++)
	{
		if_submit (ifstat[i].name, "if_octets", ifstat[i].ibytes, ifstat[i].obytes);
		if_submit (ifstat[i].name, "if_packets", ifstat[i].ipackets ,ifstat[i].opackets);
		if_submit (ifstat[i].name, "if_errors", ifstat[i].ierrors, ifstat[i].oerrors );
	}
#endif /* HAVE_PERFSTAT */

	return (0);
} /* int interface_read */
Exemplo n.º 21
0
static int swap_read_combined (void) /* {{{ */
{
	FILE *fh;
	char buffer[1024];

	uint8_t have_data = 0;
	gauge_t swap_used   = 0.0;
	gauge_t swap_cached = 0.0;
	gauge_t swap_free   = 0.0;
	gauge_t swap_total  = 0.0;

	fh = fopen ("/proc/meminfo", "r");
	if (fh == NULL)
	{
		char errbuf[1024];
		WARNING ("swap plugin: fopen (/proc/meminfo) failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		return (-1);
	}

	while (fgets (buffer, sizeof (buffer), fh) != NULL)
	{
		char *fields[8];
		int numfields;

		numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
		if (numfields < 2)
			continue;

		if (strcasecmp (fields[0], "SwapTotal:") == 0)
		{
			swap_total = strtod (fields[1], /* endptr = */ NULL);
			have_data |= 0x01;
		}
		else if (strcasecmp (fields[0], "SwapFree:") == 0)
		{
			swap_free = strtod (fields[1], /* endptr = */ NULL);
			have_data |= 0x02;
		}
		else if (strcasecmp (fields[0], "SwapCached:") == 0)
		{
			swap_cached = strtod (fields[1], /* endptr = */ NULL);
			have_data |= 0x04;
		}
	}

	fclose (fh);

	if (have_data != 0x07)
		return (ENOENT);

	if (isnan (swap_total)
			|| (swap_total <= 0.0)
			|| ((swap_free + swap_cached) > swap_total))
		return (EINVAL);

	swap_used = swap_total - (swap_free + swap_cached);

	swap_submit_gauge (NULL, "used",   1024.0 * swap_used);
	swap_submit_gauge (NULL, "free",   1024.0 * swap_free);
	swap_submit_gauge (NULL, "cached", 1024.0 * swap_cached);

	return (0);
} /* }}} int swap_read_combined */
Exemplo n.º 22
0
static int read_acpi_callback (char const *dir, /* {{{ */
		char const *power_supply,
		void *user_data)
{
	int *battery_index = user_data;

	gauge_t current = NAN;
	gauge_t voltage = NAN;
	gauge_t charge  = NAN;
	_Bool charging = 0;

	char const *plugin_instance;
	char filename[PATH_MAX];
	char buffer[1024];

	FILE *fh;

	ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
	fh = fopen (filename, "r");
	if ((fh = fopen (filename, "r")) == NULL)
	{
		if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
			return (0);
		else
			return (errno);
	}

	/*
	 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
	 * [11:00] <@tokkee> present:                 yes
	 * [11:00] <@tokkee> capacity state:          ok
	 * [11:00] <@tokkee> charging state:          charging
	 * [11:00] <@tokkee> present rate:            1724 mA
	 * [11:00] <@tokkee> remaining capacity:      4136 mAh
	 * [11:00] <@tokkee> present voltage:         12428 mV
	 */
	while (fgets (buffer, sizeof (buffer), fh) != NULL)
	{
		char *fields[8];
		int numfields;

		numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
		if (numfields < 3)
			continue;

		if ((strcmp (fields[0], "charging") == 0)
				&& (strcmp (fields[1], "state:") == 0))
		{
			if (strcmp (fields[2], "charging") == 0)
				charging = 1;
			else
				charging = 0;
			continue;
		}

		/* FIXME: The unit of "present rate" depends on the battery.
		 * Modern batteries export watts, not amperes, i.e. it's not a
		 * current anymore. We should check if the fourth column
		 * contains "mA" and only use a current then. Otherwise, export
		 * a power. */
		if ((strcmp (fields[0], "present") == 0)
				&& (strcmp (fields[1], "rate:") == 0))
			strtogauge (fields[2], &current);
		else if ((strcmp (fields[0], "remaining") == 0)
				&& (strcmp (fields[1], "capacity:") == 0))
			strtogauge (fields[2], &charge);
		else if ((strcmp (fields[0], "present") == 0)
				&& (strcmp (fields[1], "voltage:") == 0))
			strtogauge (fields[2], &voltage);
	} /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */

	fclose (fh);

	if (!charging)
		current *= -1.0;

	/* FIXME: This is a dirty hack for backwards compatibility: The battery
	 * plugin, for a very long time, has had the plugin_instance
	 * hard-coded to "0". So, to keep backwards compatibility, we'll use
	 * "0" for the first battery we find and the power_supply name for all
	 * following. This should be reverted in a future major version. */
	plugin_instance = (*battery_index == 0) ? "0" : power_supply;
	(*battery_index)++;

	battery_submit (plugin_instance, "charge", charge / 1000.0);
	battery_submit (plugin_instance, "current", current / 1000.0);
	battery_submit (plugin_instance, "voltage", voltage / 1000.0);

	return 0;
} /* }}} int read_acpi_callback */
Exemplo n.º 23
0
static int read_pmu (void) /* {{{ */
{
	int i;

	/* The upper limit here is just a safeguard. If there is a system with
	 * more than 100 batteries, this can easily be increased. */
	for (i = 0; i < 100; i++)
	{
		FILE *fh;

		char buffer[1024];
		char filename[PATH_MAX];
		char plugin_instance[DATA_MAX_NAME_LEN];

		gauge_t current = NAN;
		gauge_t voltage = NAN;
		gauge_t charge  = NAN;

		ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
		if (access (filename, R_OK) != 0)
			break;

		ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);

		fh = fopen (filename, "r");
		if (fh == NULL)
		{
			if (errno == ENOENT)
				break;
			else if ((errno == EAGAIN) || (errno == EINTR))
				continue;
			else
				return (errno);
		}

		while (fgets (buffer, sizeof (buffer), fh) != NULL)
		{
			char *fields[8];
			int numfields;

			numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
			if (numfields < 3)
				continue;

			if (strcmp ("current", fields[0]) == 0)
				strtogauge (fields[2], &current);
			else if (strcmp ("voltage", fields[0]) == 0)
				strtogauge (fields[2], &voltage);
			else if (strcmp ("charge", fields[0]) == 0)
				strtogauge (fields[2], &charge);
		}

		fclose (fh);
		fh = NULL;

		battery_submit (plugin_instance, "charge", charge / 1000.0);
		battery_submit (plugin_instance, "current", current / 1000.0);
		battery_submit (plugin_instance, "voltage", voltage / 1000.0);
	}

	if (i == 0)
		return (ENOENT);
	return (0);
} /* }}} int read_pmu */
Exemplo n.º 24
0
std::string extract_fractions(const std::string &fluid_string, std::vector<double> &fractions)
{
    if (has_fractions_in_string(fluid_string))
    {
        fractions.clear();
        std::vector<std::string> names;

        // Break up into pairs - like "Ethane[0.5]&Methane[0.5]" -> ("Ethane[0.5]","Methane[0.5]")
        std::vector<std::string> pairs = strsplit(fluid_string, '&');

        for (std::size_t i = 0; i < pairs.size(); ++i)
        {
            const std::string &fluid = pairs[i];

            // Must end with ']'
            if (fluid[fluid.size()-1] != ']')
                throw ValueError(format("Fluid entry [%s] must end with ']' character",pairs[i].c_str()));

            // Split at '[', but first remove the ']' from the end by taking a substring
            std::vector<std::string> name_fraction = strsplit(fluid.substr(0, fluid.size()-1), '[');

            if (name_fraction.size() != 2){throw ValueError(format("Could not break [%s] into name/fraction", fluid.substr(0, fluid.size()-1).c_str()));}

            // Convert fraction to a double
            char *pEnd;
            const std::string &name = name_fraction[0], &fraction = name_fraction[1];
            double f = strtod(fraction.c_str(), &pEnd);

            // If pEnd points to the last character in the string, it wasn't able to do the conversion
            if (pEnd == &(fraction[fraction.size()-1])){throw ValueError(format("Could not convert [%s] into number", fraction.c_str()));}

            // And add to vector
            fractions.push_back(f);

            // Add name
            names.push_back(name);
        }

        if (get_debug_level()>10) std::cout << format("%s:%d: Detected fractions of %s for %s.",__FILE__,__LINE__,vec_to_string(fractions).c_str(), (strjoin(names, "&")).c_str());
        // Join fluids back together
        return strjoin(names, "&");
    }
    else if (has_solution_concentration(fluid_string))
    {
        fractions.clear();
        double x;

        std::vector<std::string> fluid_parts = strsplit(fluid_string,'-');
        // Check it worked
        if (fluid_parts.size() != 2){
            throw ValueError(format("Format of incompressible solution string [%s] is invalid, should be like \"EG-20%\" or \"EG-0.2\" ", fluid_string.c_str()) );
        }

        // Convert the concentration into a string
        char* pEnd;
        x = strtod(fluid_parts[1].c_str(), &pEnd);

        // Check if per cent or fraction syntax is used
        if (!strcmp(pEnd,"%")){    x *= 0.01;}
        fractions.push_back(x);
        if (get_debug_level()>10) std::cout << format("%s:%d: Detected incompressible concentration of %s for %s.",__FILE__,__LINE__,vec_to_string(fractions).c_str(), fluid_parts[0].c_str());
        return fluid_parts[0];
    }
    else
    {
        return fluid_string;
    }
}
Exemplo n.º 25
0
static int swap_read_io (void) /* {{{ */
{
	FILE *fh;
	char buffer[1024];

	_Bool old_kernel = 0;

	uint8_t have_data = 0;
	derive_t swap_in  = 0;
	derive_t swap_out = 0;

	fh = fopen ("/proc/vmstat", "r");
	if (fh == NULL)
	{
		/* /proc/vmstat does not exist in kernels <2.6 */
		fh = fopen ("/proc/stat", "r");
		if (fh == NULL)
		{
			char errbuf[1024];
			WARNING ("swap: fopen: %s",
					sstrerror (errno, errbuf, sizeof (errbuf)));
			return (-1);
		}
		else
			old_kernel = 1;
	}

	while (fgets (buffer, sizeof (buffer), fh) != NULL)
	{
		char *fields[8];
		int numfields;

		numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));

		if (!old_kernel)
		{
			if (numfields != 2)
				continue;

			if (strcasecmp ("pswpin", fields[0]) == 0)
			{
				strtoderive (fields[1], &swap_in);
				have_data |= 0x01;
			}
			else if (strcasecmp ("pswpout", fields[0]) == 0)
			{
				strtoderive (fields[1], &swap_out);
				have_data |= 0x02;
			}
		}
		else /* if (old_kernel) */
		{
			if (numfields != 3)
				continue;

			if (strcasecmp ("page", fields[0]) == 0)
			{
				strtoderive (fields[1], &swap_in);
				strtoderive (fields[2], &swap_out);
			}
		}
	} /* while (fgets) */

	fclose (fh);

	if (have_data != 0x03)
		return (ENOENT);

	if (report_bytes)
	{
		swap_in = swap_in * pagesize;
		swap_out = swap_out * pagesize;
	}

	swap_submit_derive (NULL, "in",  swap_in);
	swap_submit_derive (NULL, "out", swap_out);

	return (0);
} /* }}} int swap_read_io */
Exemplo n.º 26
0
/* Returns zero on success, less than zero on socket error and greater than
 * zero on other errors. */
static int conn_read_netlink(void) {
#if HAVE_STRUCT_LINUX_INET_DIAG_REQ
  int fd;
  struct inet_diag_msg *r;
  char buf[8192];

  /* If this fails, it's likely a permission problem. We'll fall back to
   * reading this information from files below. */
  fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
  if (fd < 0) {
    ERROR("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
          "NETLINK_INET_DIAG) failed: %s",
          sstrerror(errno, buf, sizeof(buf)));
    return (-1);
  }

  struct sockaddr_nl nladdr = {.nl_family = AF_NETLINK};

  struct nlreq req = {
      .nlh.nlmsg_len = sizeof(req),
      .nlh.nlmsg_type = TCPDIAG_GETSOCK,
      /* NLM_F_ROOT: return the complete table instead of a single entry.
       * NLM_F_MATCH: return all entries matching criteria (not implemented)
       * NLM_F_REQUEST: must be set on all request messages */
      .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
      .nlh.nlmsg_pid = 0,
      /* The sequence_number is used to track our messages. Since netlink is not
       * reliable, we don't want to end up with a corrupt or incomplete old
       * message in case the system is/was out of memory. */
      .nlh.nlmsg_seq = ++sequence_number,
      .r.idiag_family = AF_INET,
      .r.idiag_states = 0xfff,
      .r.idiag_ext = 0};

  struct iovec iov = {.iov_base = &req, .iov_len = sizeof(req)};

  struct msghdr msg = {.msg_name = (void *)&nladdr,
                       .msg_namelen = sizeof(nladdr),
                       .msg_iov = &iov,
                       .msg_iovlen = 1};

  if (sendmsg(fd, &msg, 0) < 0) {
    ERROR("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
          sstrerror(errno, buf, sizeof(buf)));
    close(fd);
    return (-1);
  }

  iov.iov_base = buf;
  iov.iov_len = sizeof(buf);

  while (1) {
    int status;
    struct nlmsghdr *h;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = (void *)&nladdr;
    msg.msg_namelen = sizeof(nladdr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    status = recvmsg(fd, (void *)&msg, /* flags = */ 0);
    if (status < 0) {
      if ((errno == EINTR) || (errno == EAGAIN))
        continue;

      ERROR("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
            sstrerror(errno, buf, sizeof(buf)));
      close(fd);
      return (-1);
    } else if (status == 0) {
      close(fd);
      DEBUG("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
            "reply from netlink socket.");
      return (0);
    }

    h = (struct nlmsghdr *)buf;
    while (NLMSG_OK(h, status)) {
      if (h->nlmsg_seq != sequence_number) {
        h = NLMSG_NEXT(h, status);
        continue;
      }

      if (h->nlmsg_type == NLMSG_DONE) {
        close(fd);
        return (0);
      } else if (h->nlmsg_type == NLMSG_ERROR) {
        struct nlmsgerr *msg_error;

        msg_error = NLMSG_DATA(h);
        WARNING("tcpconns plugin: conn_read_netlink: Received error %i.",
                msg_error->error);

        close(fd);
        return (1);
      }

      r = NLMSG_DATA(h);

      /* This code does not (need to) distinguish between IPv4 and IPv6. */
      conn_handle_ports(ntohs(r->id.idiag_sport), ntohs(r->id.idiag_dport),
                        r->idiag_state);

      h = NLMSG_NEXT(h, status);
    } /* while (NLMSG_OK) */
  }   /* while (1) */

  /* Not reached because the while() loop above handles the exit condition. */
  return (0);
#else
  return (1);
#endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
} /* int conn_read_netlink */

static int conn_handle_line(char *buffer) {
  char *fields[32];
  int fields_len;

  char *endptr;

  char *port_local_str;
  char *port_remote_str;
  uint16_t port_local;
  uint16_t port_remote;

  uint8_t state;

  int buffer_len = strlen(buffer);

  while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
    buffer[--buffer_len] = '\0';
  if (buffer_len <= 0)
    return (-1);

  fields_len = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
  if (fields_len < 12) {
    DEBUG("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
    return (-1);
  }

  port_local_str = strchr(fields[1], ':');
  port_remote_str = strchr(fields[2], ':');

  if ((port_local_str == NULL) || (port_remote_str == NULL))
    return (-1);
  port_local_str++;
  port_remote_str++;
  if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
    return (-1);

  endptr = NULL;
  port_local = (uint16_t)strtol(port_local_str, &endptr, 16);
  if ((endptr == NULL) || (*endptr != '\0'))
    return (-1);

  endptr = NULL;
  port_remote = (uint16_t)strtol(port_remote_str, &endptr, 16);
  if ((endptr == NULL) || (*endptr != '\0'))
    return (-1);

  endptr = NULL;
  state = (uint8_t)strtol(fields[3], &endptr, 16);
  if ((endptr == NULL) || (*endptr != '\0'))
    return (-1);

  return (conn_handle_ports(port_local, port_remote, state));
} /* int conn_handle_line */

static int conn_read_file(const char *file) {
  FILE *fh;
  char buffer[1024];

  fh = fopen(file, "r");
  if (fh == NULL)
    return (-1);

  while (fgets(buffer, sizeof(buffer), fh) != NULL) {
    conn_handle_line(buffer);
  } /* while (fgets) */

  fclose(fh);

  return (0);
} /* int conn_read_file */
/* #endif KERNEL_LINUX */

#elif HAVE_SYSCTLBYNAME
/* #endif HAVE_SYSCTLBYNAME */

#elif HAVE_LIBKVM_NLIST
#endif /* HAVE_LIBKVM_NLIST */

static int conn_config(const char *key, const char *value) {
  if (strcasecmp(key, "ListeningPorts") == 0) {
    if (IS_TRUE(value))
      port_collect_listening = 1;
    else
      port_collect_listening = 0;
  } else if ((strcasecmp(key, "LocalPort") == 0) ||
             (strcasecmp(key, "RemotePort") == 0)) {
    port_entry_t *pe;
    int port = atoi(value);

    if ((port < 1) || (port > 65535)) {
      ERROR("tcpconns plugin: Invalid port: %i", port);
      return (1);
    }

    pe = conn_get_port_entry((uint16_t)port, 1 /* create */);
    if (pe == NULL) {
      ERROR("tcpconns plugin: conn_get_port_entry failed.");
      return (1);
    }

    if (strcasecmp(key, "LocalPort") == 0)
      pe->flags |= PORT_COLLECT_LOCAL;
    else
      pe->flags |= PORT_COLLECT_REMOTE;
  } else if (strcasecmp(key, "AllPortsSummary") == 0) {
    if (IS_TRUE(value))
      port_collect_total = 1;
    else
      port_collect_total = 0;
  } else {
    return (-1);
  }

  return (0);
} /* int conn_config */

#if KERNEL_LINUX
static int conn_init(void) {
  if (port_collect_total == 0 && port_list_head == NULL)
    port_collect_listening = 1;

  return (0);
} /* int conn_init */

static int conn_read(void) {
  int status;

  conn_reset_port_entry();

  if (linux_source == SRC_NETLINK) {
    status = conn_read_netlink();
  } else if (linux_source == SRC_PROC) {
    int errors_num = 0;

    if (conn_read_file("/proc/net/tcp") != 0)
      errors_num++;
    if (conn_read_file("/proc/net/tcp6") != 0)
      errors_num++;

    if (errors_num < 2)
      status = 0;
    else
      status = ENOENT;
  } else /* if (linux_source == SRC_DUNNO) */
  {
    /* Try to use netlink for getting this data, it is _much_ faster on systems
     * with a large amount of connections. */
    status = conn_read_netlink();
    if (status == 0) {
      INFO("tcpconns plugin: Reading from netlink succeeded. "
           "Will use the netlink method from now on.");
      linux_source = SRC_NETLINK;
    } else {
      INFO("tcpconns plugin: Reading from netlink failed. "
           "Will read from /proc from now on.");
      linux_source = SRC_PROC;

      /* return success here to avoid the "plugin failed" message. */
      return (0);
    }
  }

  if (status == 0)
    conn_submit_all();
  else
    return (status);

  return (0);
} /* int conn_read */
/*!
 * @brief Waits for a native message string and sends a native response.
 *
 * Commands: finish, validate, validateBogus, reinitialise
 *
 * @return -1 on error,
 *          0 on success
 *          1 if end of program desired.
 */
static
int wait_for_and_process_native_message(void)
/* ========================================================================= */
{
#define MAX_BUF_LEN 1024
#define DELIMS "~"
	char inbuf[MAX_BUF_LEN], outbuf[MAX_BUF_LEN];
	unsigned int inlen, outlen;
	char *cmd, *dn, *options_str, *nameserver, *addr, *tab_id, *saveptr;
	int options_num;
	int val_ret;
	char *tmp;

	printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n", "Waiting for native input.");

	inbuf[0] = '\0';
	inlen = 0;
	if (fread(&inlen, 4, 1, stdin) != 1) {
		printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n",
		    "Cannot read input length.");
		return -1;
	}
	if (fread(inbuf, 1, inlen, stdin) != inlen) {
		printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n",
		    "Cannot read message.");
		return -1;
	}
	inbuf[inlen] = '\0';
	printf_debug(DEBUG_PREFIX_DNSSEC, "IN %d %s\n", inlen, inbuf);

	/* First and last character is '"' .*/
	--inlen;
	inbuf[inlen] = '\0';
	cmd = strsplit(inbuf + 1, DELIMS, &saveptr);
	/*
	 * TODO -- strtok_r()?
	 * Use a tokeniser which can handle empty strings.
	 */
	if (strcmp(cmd, "finish") == 0) {
		/* Just tell that exit is desired. */
		return 1;
	} else if (strcmp(cmd, "initialise") == 0) {
		printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n", "Initialising.");

		dnssec_validation_init();

		/* Generate output. */
		if (snprintf(outbuf, MAX_BUF_LEN, "\"%sRet~ok\"",
		        cmd) >= MAX_BUF_LEN) {
			/* Error. */
			printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n",
			    "Error while creating response string.");
			return -1;
		}

		outlen = strlen(outbuf);

		printf_debug(DEBUG_PREFIX_DNSSEC, "OUT %d %s\n", outlen,
		    outbuf);
		/* Write and flush. */
		fwrite(&outlen, 4, 1, stdout);
		fputs(outbuf, stdout);
		fflush(stdout);
	} else if (strcmp(cmd, "reinitialise") == 0) {
		printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n", "Reinitialising.");

		dnssec_validation_deinit();
		dnssec_validation_init();

		/* Generate no output. */
	} else if ((strcmp(cmd, "validate") == 0) ||
	           (strcmp(cmd, "validateBogus") == 0)) {
		/* Tokenise input. */
		dn = strsplit(NULL, DELIMS, &saveptr);
		options_str = strsplit(NULL, DELIMS, &saveptr);
		nameserver = strsplit(NULL, DELIMS, &saveptr);
		addr = strsplit(NULL, DELIMS, &saveptr);
		tab_id = strsplit(NULL, DELIMS, &saveptr);

		if (('\0' == nameserver[0]) ||
		    (strcmp("sysresolver", nameserver) == 0)) {
			nameserver = NULL;
		}

		options_num = strtol(options_str, NULL, 10);

		val_ret = dnssec_validate(dn, options_num, nameserver, addr,
		    &tmp);

		/* Generate output. */
		if (snprintf(outbuf, MAX_BUF_LEN,
		        "\"%sRet~%s~%d~%s~%s~%s~%s\"", cmd, dn, val_ret, tmp,
		        addr, tab_id, PACKAGE_VERSION) >= MAX_BUF_LEN) {
			/* Error. */
			printf_debug(DEBUG_PREFIX_DNSSEC, "%s\n",
			    "Error while creating response string.");
			return -1;
		}

		outlen = strlen(outbuf);

		printf_debug(DEBUG_PREFIX_DNSSEC, "OUT %d %s\n", outlen,
		    outbuf);
		/* Write and flush. */
		fwrite(&outlen, 4, 1, stdout);
		fputs(outbuf, stdout);
		fflush(stdout);
	} else {
		/* No action. */
		printf_debug(DEBUG_PREFIX_DNSSEC, "Undefined command '%s'.\n",
		    cmd);
	}

	return 0;
#undef MAX_BUF_LEN
#undef DELIMS
}
Exemplo n.º 28
0
static int
amfs_program_exec(char *info)
{
  char **xivec;
  int error;

  /*
   * Split copy of command info string
   */
  info = strdup(info);
  if (info == 0)
    return ENOBUFS;
  xivec = strsplit(info, ' ', '\'');

  /*
   * Put stdout to stderr
   */
  (void) fclose(stdout);
  if (!logfp)
    logfp = stderr;		/* initialize before possible first use */
  (void) dup(fileno(logfp));
  if (fileno(logfp) != fileno(stderr)) {
    (void) fclose(stderr);
    (void) dup(fileno(logfp));
  }

  /*
   * Try the exec
   */
  if (amuDebug(D_FULL)) {
    char **cp = xivec;
    plog(XLOG_DEBUG, "executing (un)mount command...");
    while (*cp) {
      plog(XLOG_DEBUG, "arg[%ld] = '%s'", (long) (cp - xivec), *cp);
      cp++;
    }
  }

  if (xivec[0] == 0 || xivec[1] == 0) {
    errno = EINVAL;
    plog(XLOG_USER, "1st/2nd args missing to (un)mount program");
  } else {
    (void) execv(xivec[0], xivec + 1);
  }

  /*
   * Save error number
   */
  error = errno;
  plog(XLOG_ERROR, "exec failed: %m");

  /*
   * Free allocate memory
   */
  XFREE(info);
  XFREE(xivec);

  /*
   * Return error
   */
  return error;
}
Exemplo n.º 29
0
static int iptables_config(const char *key, const char *value) {
  /* int ip_value; */
  protocol_version_t ip_version = 0;

  if (strcasecmp(key, "Chain") == 0)
    ip_version = IPV4;
  else if (strcasecmp(key, "Chain6") == 0)
    ip_version = IPV6;
  else
    return 1;

  ip_chain_t temp = {0};
  ip_chain_t *final, **list;
  char *table;
  char *chain;

  char *value_copy;
  char *fields[4];
  int fields_num;

  value_copy = strdup(value);
  if (value_copy == NULL) {
    ERROR("strdup failed: %s", STRERRNO);
    return 1;
  }

  /*
   *  Time to fill the temp element
   *  Examine value string, it should look like:
   *  Chain[6] <table> <chain> [<comment|num> [name]]
   */

  /* set IPv4 or IPv6 */
  temp.ip_version = ip_version;

  /* Chain <table> <chain> [<comment|num> [name]] */
  fields_num = strsplit(value_copy, fields, 4);
  if (fields_num < 2) {
    free(value_copy);
    return 1;
  }

  table = fields[0];
  chain = fields[1];

  size_t table_len = strlen(table) + 1;
  if (table_len > sizeof(temp.table)) {
    ERROR("Table `%s' too long.", table);
    free(value_copy);
    return 1;
  }
  sstrncpy(temp.table, table, table_len);

  size_t chain_len = strlen(chain) + 1;
  if (chain_len > sizeof(temp.chain)) {
    ERROR("Chain `%s' too long.", chain);
    free(value_copy);
    return 1;
  }
  sstrncpy(temp.chain, chain, chain_len);

  if (fields_num >= 3) {
    char *comment = fields[2];
    int rule = atoi(comment);

    if (rule) {
      temp.rule.num = rule;
      temp.rule_type = RTYPE_NUM;
    } else {
      temp.rule.comment = strdup(comment);
      if (temp.rule.comment == NULL) {
        free(value_copy);
        return 1;
      }
      temp.rule_type = RTYPE_COMMENT;
    }
  } else {
    temp.rule_type = RTYPE_COMMENT_ALL;
  }

  if (fields_num >= 4)
    sstrncpy(temp.name, fields[3], sizeof(temp.name));

  free(value_copy);
  value_copy = NULL;
  table = NULL;
  chain = NULL;

  list = realloc(chain_list, (chain_num + 1) * sizeof(ip_chain_t *));
  if (list == NULL) {
    ERROR("realloc failed: %s", STRERRNO);
    sfree(temp.rule.comment);
    return 1;
  }

  chain_list = list;
  final = malloc(sizeof(*final));
Exemplo n.º 30
0
std::string getSolutionName(std::string name){ // TODO Solutions: Remove as soon as possible
	// Split into fluid, concentration pair
	std::vector<std::string> fluid_concentration = strsplit(std::string(name),'-');
	return fluid_concentration[0];
}