Beispiel #1
0
static int pipefs_ioctl(fs_cookie _fs, fs_vnode _v, file_cookie _cookie, int op, void *buf, size_t len)
{
	struct pipefs *fs = _fs;
	struct pipefs_vnode *v = _v;
	struct pipefs_cookie *cookie = _cookie;
	int err = 0;

	TRACE(("pipefs_ioctl: vnode 0x%x, cookie 0x%x, op %d, buf 0x%x, len 0x%x\n", _v, _cookie, op, buf, len));

	ASSERT(cookie->s == &v->stream);

	switch(v->stream.type) {
		case STREAM_TYPE_PIPE:
			switch(op) {
				case _PIPEFS_IOCTL_CREATE_ANONYMOUS: {
					int new_fds[2];
					struct pipefs_vnode *new_v;

					if(v != fs->anon_vnode) {
						err = ERR_INVALID_ARGS;
						goto err;
					}

					// create a new vnode
					new_v = pipefs_create_vnode(fs, "", STREAM_TYPE_PIPE);
					if(new_v == NULL) {
						err = ERR_NO_MEMORY;
						goto err;
					}

					// it's an anonymous pipe
					new_v->stream.u.pipe.flags |= PIPE_FLAGS_ANONYMOUS;

					// add it to the hash table
					mutex_lock(&fs->hash_lock);
					hash_insert(fs->vnode_list_hash, new_v);
					mutex_unlock(&fs->hash_lock);

					// open the two endpoints
					new_fds[0] = vfs_open_vnid(fs->id, new_v->id, 0, false);
					if(new_fds[0] < 0) {
						// XXX may leak vnode
						err = new_fds[0];
						goto err;
					}

					new_fds[1] = vfs_open_vnid(fs->id, new_v->id, 0, false);
					if(new_fds[1] < 0) {
						// XXX may leak vnode
						vfs_close(new_fds[0], false);
						err = new_fds[1];
						goto err;
					}

					err = user_memcpy(buf, new_fds, sizeof(new_fds));
					break;
				}
				default:
					err = ERR_INVALID_ARGS;
			}
			break;
		default:
			err = ERR_VFS_WRONG_STREAM_TYPE;
	}

err:
	return err;
}
Beispiel #2
0
static string
do_line (kpathsea kpse, string line)
{
  unsigned len;
  string start;
  string value, var;
  string prog = NULL;

  /* Skip leading whitespace.  */
  while (*line && ISSPACE (*line))
    line++;

  /* More to do only if we have non-comment material left.  */
  if (*line == 0 || *line == '%' || *line == '#')
    return NULL;

  /* Remove trailing comment: a % or # preceded by whitespace.  Also
     remove any whitespace before that.  For example, the value for
       foo = a#b  %something
     is a#b.  */
  value = line + strlen (line) - 1; /* start at end of line */
  while (value > line) {            
    if (*value == '%' || *value == '#') {
      value--;                      /* move before comment char */
      while (ISSPACE (*value))
        *value-- = 0;               /* wipe out as much preceding whitespace
      continue;                        (and comment) as we find */
    }
    value--;                        /* move before the new null byte */
  }

  /* The variable name is everything up to the next space or = or `.'.  */
  start = line;
  while (*line && !ISSPACE (*line) && *line != '=' && *line != '.')
    line++;

  /* `line' is now one character past the end of the variable name.  */
  len = line - start;
  if (len == 0) {
    return ("No cnf variable name");
  }
  
  var = (string) xmalloc (len + 1);
  strncpy (var, start, len);
  var[len] = 0;

  /* If the variable is qualified with a program name, find out which. */
  while (*line && ISSPACE (*line))
    line++;
  if (*line == '.') {
    /* Skip spaces, then everything up to the next space or =.  */
    line++;
    while (ISSPACE (*line))
      line++;
    start = line;
    while (*line && !ISSPACE (*line) && *line != '=')
      line++;

    /* It's annoying to repeat all this, but making a tokenizing
       subroutine would be just as long and annoying.  */
    len = line - start;
    prog = (string) xmalloc (len + 1);
    strncpy (prog, start, len);
    prog[len] = 0;
  }

  /* Skip whitespace, an optional =, more whitespace.  */
  while (*line && ISSPACE (*line))
    line++;
  if (*line == '=') {
    line++;
    while (*line && ISSPACE (*line))
      line++;
  }

  /* The value is whatever remains.  Remove trailing whitespace.  */
  start = line;
  len = strlen (start);
  while (len > 0 && ISSPACE (start[len - 1]))
    len--;
  if (len == 0) {
    return ("No cnf value");
  }
  
  value = (string) xmalloc (len + 1);
  strncpy (value, start, len);
  value[len] = 0;

  /* Suppose we want to write a single texmf.cnf that can be used under
     both Windows and Unix. This is feasible except for the path
     separators: : on Unix, ; on Windows. We can't switch Windows to
     allowing :, since : is the drive separator. So we switch Unix to
     allowing ;. On the other hand, we don't want to change IS_ENV_SEP
     and all the rest.

     So, translate all ;'s in the path values to :'s if we'd normally
     use :. (Fortunately we don't use ; as a normal character in values.)  */

  if (IS_ENV_SEP(':')) {
      string loc;
      for (loc = value; *loc; loc++) {
          if (*loc == ';')
              *loc = ':';
      }
  }

  /* We want TEXINPUTS.prog to override plain TEXINPUTS.  The simplest
     way is to put both in the hash table (so we don't have to write
     hash_delete and hash_replace, and keep track of values' sources),
     and then look up the .prog version first in `kpse_cnf_get'.  */
  if (prog) {
    string lhs = concat3 (var, ".", prog);
    free (var);
    free (prog);
    var = lhs;
  }
  /* last-ditch debug */
  /* fprintf (stderr, "kpse/cnf.c hash_insert(%s,%s)\n", var, value); */
  hash_insert (&(kpse->cnf_hash), var, value);

  /* We should check that anything remaining is preceded by a comment
     character, but we don't.  Sorry.  */
  return NULL;
}
Beispiel #3
0
static int
startElement_METRIC(void *data, const char *el, const char **attr)
{
    xmldata_t *xmldata = (xmldata_t *)data;
    ganglia_slope_t slope = GANGLIA_SLOPE_UNSPECIFIED;
    struct xml_tag *xt;
    struct type_tag *tt;
    datum_t *hash_datum = NULL;
    datum_t *rdatum;
    datum_t hashkey, hashval;
    const char *name = NULL;
    const char *metricval = NULL;
    const char *type = NULL;
    int do_summary;
    int i, edge, carbon_ret;
    hash_t *summary;
    Metric_t *metric;

    if (!xmldata->host_alive ) return 0;

    /* Get name for hash key, and val/type for summaries. */
    for(i = 0; attr[i]; i+=2)
    {
        xt = in_xml_list(attr[i], strlen(attr[i]));
        if (!xt) continue;

        switch (xt->tag)
        {
        case NAME_TAG:
            name = attr[i+1];
            hashkey.data = (void*) name;
            hashkey.size =  strlen(name) + 1;
            break;
        case VAL_TAG:
            metricval = attr[i+1];
            break;
        case TYPE_TAG:
            type = attr[i+1];
            break;
        case SLOPE_TAG:
            slope = cstr_to_slope(attr[i+1]);
        default:
            break;
        }
    }

    metric = &(xmldata->metric);
    memset((void*) metric, 0, sizeof(*metric));

    /* Summarize all numeric metrics */
    do_summary = 0;
    tt = in_type_list(type, strlen(type));
    if (!tt) return 0;

    if (tt->type==INT || tt->type==UINT || tt->type==FLOAT)
        do_summary = 1;

    /* Only keep metric details if we are the authority on this cluster. */
    if (authority_mode(xmldata))
    {
        /* Save the data to a round robin database if the data source is alive
         */
        fillmetric(attr, metric, type);
        if (metric->dmax && metric->tn > metric->dmax)
            return 0;

        if (do_summary && !xmldata->ds->dead && !xmldata->rval)
        {
            debug_msg("Updating host %s, metric %s",
                      xmldata->hostname, name);
            if ( gmetad_config.write_rrds == 1 )
                xmldata->rval = write_data_to_rrd(xmldata->sourcename,
                                                  xmldata->hostname, name, metricval, NULL,
                                                  xmldata->ds->step, xmldata->source.localtime, slope);
            if (gmetad_config.carbon_server) // if the user has specified a carbon server, send the metric to carbon as well
                carbon_ret=write_data_to_carbon(xmldata->sourcename, xmldata->hostname, name, metricval,xmldata->source.localtime);
        }
        metric->id = METRIC_NODE;
        metric->report_start = metric_report_start;
        metric->report_end = metric_report_end;


        edge = metric->stringslen;
        metric->name = addstring(metric->strings, &edge, name);
        metric->stringslen = edge;

        /* Set local idea of T0. */
        metric->t0 = xmldata->now;
        metric->t0.tv_sec -= metric->tn;

        /* Trim metric structure to the correct length. */
        hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;
        hashval.data = (void*) metric;

        /* Update full metric in cluster host table. */
        rdatum = hash_insert(&hashkey, &hashval, xmldata->host.metrics);
        if (!rdatum)
        {
            err_msg("Could not insert %s metric", name);
        }
    }

    /* Always update summary for numeric metrics. */
    if (do_summary)
    {
        summary = xmldata->source.metric_summary;
        hash_datum = hash_lookup(&hashkey, summary);
        if (!hash_datum)
        {
            if (!authority_mode(xmldata))
            {
                metric = &(xmldata->metric);
                memset((void*) metric, 0, sizeof(*metric));
                fillmetric(attr, metric, type);
            }
            /* else we have already filled in the metric above. */
        }
        else
        {
            memcpy(&xmldata->metric, hash_datum->data, hash_datum->size);
            datum_free(hash_datum);
            metric = &(xmldata->metric);

            switch (tt->type)
            {
            case INT:
            case UINT:
            case FLOAT:
                metric->val.d += (double)
                                 strtod(metricval, (char**) NULL);
                break;
            default:
                break;
            }
        }

        metric->num++;
        metric->t0 = xmldata->now; /* tell cleanup thread we are using this */

        /* Trim metric structure to the correct length. Tricky. */
        hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;
        hashval.data = (void*) metric;

        /* Update metric in summary table. */
        rdatum = hash_insert(&hashkey, &hashval, summary);
        if (!rdatum) err_msg("Could not insert %s metric", name);
    }
    return 0;
}
Beispiel #4
0
/* Change provided package to a package which provides it.
 * For AUR packages, this also downloads and extracts PKGBUILD in cwd.
 * In addition, the "normalized" packages will be cached in hashdb->pkg_from
 *
 * @param curl curl handle
 * @param hashdb hash database
 * @param pkg package name
 * @param resolve_lvl level of dep resolution. RESOLVE_THOROUGH forces
 *        downloading of AUR PKGBUILDs
 *
 * returns the "normalized" package if present, NULL on failure
 */
static const char *normalize_package(CURL *curl, struct pw_hashdb *hashdb,
                                     const char *pkgname, int resolve_lvl)
{
    const char *provided = NULL;
    struct pkgpair pkgpair;
    struct pkgpair *pkgptr;
    enum pkgfrom_t *pkgfrom;

    pkgpair.pkgname = pkgname;
    pkgpair.pkg = NULL;

    /* If we know where pkg is from and it's not AUR / it's from AUR and
     * already downloaded, done */
    pkgfrom = hashmap_search(hashdb->pkg_from, (void *) pkgname);
    if (pkgfrom) {
        if (*pkgfrom != PKG_FROM_AUR ||
                hash_search(hashdb->aur_downloaded, (void *) pkgname)) {
            return pkgname;
        }

        goto search_aur;
    }

    /* If it's in local db and not AUR, done */
    if (hash_search(hashdb->local, &pkgpair)) {
        if (hash_search(hashdb->aur, &pkgpair)) {
            goto search_aur;
        }
        hashmap_insert(hashdb->pkg_from, (void *) pkgname, &hashdb->pkg_from_local);
        return pkgname;
    }

    /* Search provides cache */
    provided = hashmap_search(hashdb->provides_cache, (void *) pkgname);
    if (provided) {
        return provided;
    }

    /* Search local provides */
    pkgptr = hashbst_tree_search(hashdb->local_provides, (void *) pkgname,
                                 hashdb->local, provides_search);
    if (pkgptr) {
        /* Cache in provides and pkg_from */
        hashmap_insert(hashdb->provides_cache, (void *) pkgname,
                       (void *) pkgptr->pkgname);
        hashmap_insert(hashdb->pkg_from, (void *) pkgptr->pkgname, &hashdb->pkg_from_local);
        return pkgptr->pkgname;
    }

    /* Search sync provides tree in local db
     * TODO: Is there a meaning to this?
     * local provides are obtained from local packages.
     * sync provides are obtained from sync packages.
     * So searching for sync provides in local database is kind of...
     */
    pkgptr = hashbst_tree_search(hashdb->sync_provides, (void *) pkgname,
                                 hashdb->local, provides_search);

    if (pkgptr) {
        /* Cache in pkg_from */
        hashmap_insert(hashdb->pkg_from, (void *) pkgptr->pkgname, &hashdb->pkg_from_local);
        return pkgptr->pkgname;
    }

    /* Search sync db */
    if (hash_search(hashdb->sync, &pkgpair)) {
        hashmap_insert(hashdb->pkg_from, (void *) pkgname, &hashdb->pkg_from_sync);
        return pkgname;
    }

    /* Sync provides */
    pkgptr = hashbst_tree_search(hashdb->sync_provides, (void *) pkgname,
                                 hashdb->sync, provides_search);
    if (pkgptr) {
        hashmap_insert(hashdb->pkg_from, (void *) pkgptr->pkgname,
                       &hashdb->pkg_from_sync);
        hashmap_insert(hashdb->provides_cache, (void *) pkgname, (void *) pkgptr->pkgname);
        return pkgptr->pkgname;
    }

search_aur:
    pkgpair.pkgname = pkgname;
    pkgpair.pkg = NULL;

    /* For non RESOLVE_THOROUGH, don't bother downloading PKGBUILD of updated
     * AUR packages
     */
    if (resolve_lvl != RESOLVE_THOROUGH) {
        if (hash_search(hashdb->aur, &pkgpair) &&
                !hash_search(hashdb->aur_outdated, (void *) pkgname)) {
            goto done;
        }
    }

    /* Download and extract from AUR */
    if (dl_extract_single_package(curl, pkgname, NULL, 0)) {
        return NULL;
    }

    hash_insert(hashdb->aur_downloaded, (void *) pkgname);
    hashmap_insert(hashdb->pkg_from, (void *) pkgname, &hashdb->pkg_from_aur);

done:
    return pkgname;
}
Beispiel #5
0
int main()
{
	struct hash *my_hash, *my_hash2;
	int x;

	/* Testing Hash with Linked List items */

	struct list_t *root, *root2, *root3;
    int a=43,b=63,c=99,d=70,e=25,f=17,g=57,h=69,i=111,j=120,k=70,l=73,m=75;

    root = list_init();
    root2 = list_init();
    root3 = list_init();

	root = list_remove_rear(root);
    root = list_remove_any(root,&k);
    root = list_remove_front(root);

    list_insert_rear(root, &a);
    list_insert_rear(root, &b);
    
    root = list_insert_after(root,&c,3);
    list_insert_rear(root, &d);
    
    root = list_insert_front(root, &e);
    root = list_insert_front(root, &f);
    
    list_insert_rear(root, &g);
    root = list_remove_front(root);
    
    list_insert_rear(root, &h);
    
    root = list_insert_after(root,&i,5);
    root = list_insert_after(root,&j,120);
    
    root = list_remove_any(root,&k);

    root = list_remove_front(root);
    list_insert_rear(root, &l);
    root = list_remove_any(root,&l);

    list_insert_rear(root, &m);
    
    
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    root = list_remove_rear(root);
    

	my_hash = hash_init("list");

	hash_insert(my_hash, "key1", root);
	hash_insert(my_hash, "key2", root2);
	hash_insert(my_hash, "key3", root3);

	printf("%s\n",my_hash->hash_type);

	char* s_val = "key2";
	char* r_val = hash_get(my_hash, s_val);
	printf("%s - %s\n", s_val, r_val);
	hash_iterate(my_hash);
	hash_destroy(my_hash);

	/* Testing Hash with Binary Tree items */

	struct node *root_node = NULL, *root_node2 = NULL, *root_node3 = NULL;

	root_node = insert(root_node,5,NULL);
    root_node = delete_node(root_node,5);
    root_node = insert(root_node,7,NULL);
    root_node = insert(root_node,3,NULL);
    root_node = insert(root_node,6,NULL);
    root_node = insert(root_node,9,NULL);
    root_node = insert(root_node,12,NULL);
    root_node = insert(root_node,1,NULL);
    print_preorder(root_node);
    root_node = delete_node(root_node,7);

    my_hash2 = hash_init("tree");
	hash_insert(my_hash2, "key1", root_node);
	hash_insert(my_hash2, "key2", root_node2);
	hash_insert(my_hash2, "key3", root_node3);

	hash_iterate(my_hash2);
	hash_destroy(my_hash2);

	return 0;
}
int
utimecmp (char const *dst_name,
	  struct stat const *dst_stat,
	  struct stat const *src_stat,
	  int options)
{
  /* Things to watch out for:

     The code uses a static hash table internally and is not safe in the
     presence of signals, multiple threads, etc.

     int and long int might be 32 bits.  Many of the calculations store
     numbers up to 2 billion, and multiply by 10; they have to avoid
     multiplying 2 billion by 10, as this exceeds 32-bit capabilities.

     time_t might be unsigned.  */

  verify (TYPE_IS_INTEGER (time_t));
  verify (TYPE_TWOS_COMPLEMENT (int));

  /* Destination and source time stamps.  */
  time_t dst_s = dst_stat->st_mtime;
  time_t src_s = src_stat->st_mtime;
  int dst_ns = get_stat_mtime_ns (dst_stat);
  int src_ns = get_stat_mtime_ns (src_stat);

  if (options & UTIMECMP_TRUNCATE_SOURCE)
    {
      /* Look up the time stamp resolution for the destination device.  */

      /* Hash table for devices.  */
      static Hash_table *ht;

      /* Information about the destination file system.  */
      static struct fs_res *new_dst_res;
      struct fs_res *dst_res;

      /* Time stamp resolution in nanoseconds.  */
      int res;

      if (! ht)
	ht = hash_initialize (16, NULL, dev_info_hash, dev_info_compare, free);
      if (! new_dst_res)
	{
	  new_dst_res = xmalloc (sizeof *new_dst_res);
	  new_dst_res->resolution = 2 * BILLION;
	  new_dst_res->exact = false;
	}
      new_dst_res->dev = dst_stat->st_dev;
      dst_res = hash_insert (ht, new_dst_res);
      if (! dst_res)
	xalloc_die ();

      if (dst_res == new_dst_res)
	{
	  /* NEW_DST_RES is now in use in the hash table, so allocate a
	     new entry next time.  */
	  new_dst_res = NULL;
	}

      res = dst_res->resolution;

      if (! dst_res->exact)
	{
	  /* This file system's resolution is not known exactly.
	     Deduce it, and store the result in the hash table.  */

	  time_t dst_a_s = dst_stat->st_atime;
	  time_t dst_c_s = dst_stat->st_ctime;
	  time_t dst_m_s = dst_s;
	  int dst_a_ns = get_stat_atime_ns (dst_stat);
	  int dst_c_ns = get_stat_ctime_ns (dst_stat);
	  int dst_m_ns = dst_ns;

	  /* Set RES to an upper bound on the file system resolution
	     (after truncation due to SYSCALL_RESOLUTION) by inspecting
	     the atime, ctime and mtime of the existing destination.
	     We don't know of any file system that stores atime or
	     ctime with a higher precision than mtime, so it's valid to
	     look at them too.  */
	  {
	    bool odd_second = (dst_a_s | dst_c_s | dst_m_s) & 1;

	    if (SYSCALL_RESOLUTION == BILLION)
	      {
		if (odd_second | dst_a_ns | dst_c_ns | dst_m_ns)
		  res = BILLION;
	      }
	    else
	      {
		int a = dst_a_ns;
		int c = dst_c_ns;
		int m = dst_m_ns;

		/* Write it this way to avoid mistaken GCC warning
		   about integer overflow in constant expression.  */
		int SR10 = SYSCALL_RESOLUTION;  SR10 *= 10;

		if ((a % SR10 | c % SR10 | m % SR10) != 0)
		  res = SYSCALL_RESOLUTION;
		else
		  for (res = SR10, a /= SR10, c /= SR10, m /= SR10;
		       (res < dst_res->resolution
			&& (a % 10 | c % 10 | m % 10) == 0);
		       res *= 10, a /= 10, c /= 10, m /= 10)
		    if (res == BILLION)
		      {
			if (! odd_second)
			  res *= 2;
			break;
		      }
	      }

	    dst_res->resolution = res;
	  }

	  if (SYSCALL_RESOLUTION < res)
	    {
	      struct timespec timespec[2];
	      struct stat dst_status;

	      /* Ignore source time stamp information that must necessarily
		 be lost when filtered through utimens.  */
	      src_ns -= src_ns % SYSCALL_RESOLUTION;

	      /* If the time stamps disagree widely enough, there's no need
		 to interrogate the file system to deduce the exact time
		 stamp resolution; return the answer directly.  */
	      {
		time_t s = src_s & ~ (res == 2 * BILLION);
		if (src_s < dst_s || (src_s == dst_s && src_ns <= dst_ns))
		  return 1;
		if (dst_s < s
		    || (dst_s == s && dst_ns < src_ns - src_ns % res))
		  return -1;
	      }

	      /* Determine the actual time stamp resolution for the
		 destination file system (after truncation due to
		 SYSCALL_RESOLUTION) by setting the access time stamp of the
		 destination to the existing access time, except with
		 trailing nonzero digits.  */

	      timespec[0].tv_sec = dst_a_s;
	      timespec[0].tv_nsec = dst_a_ns;
	      timespec[1].tv_sec = dst_m_s | (res == 2 * BILLION);
	      timespec[1].tv_nsec = dst_m_ns + res / 9;

	      /* Set the modification time.  But don't try to set the
		 modification time of symbolic links; on many hosts this sets
		 the time of the pointed-to file.  */
	      if (S_ISLNK (dst_stat->st_mode)
		  || utimens (dst_name, timespec) != 0)
		return -2;

	      /* Read the modification time that was set.  It's safe to call
		 'stat' here instead of worrying about 'lstat'; either the
		 caller used 'stat', or the caller used 'lstat' and found
		 something other than a symbolic link.  */
	      {
		int stat_result = stat (dst_name, &dst_status);

		if (stat_result
		    | (dst_status.st_mtime ^ dst_m_s)
		    | (get_stat_mtime_ns (&dst_status) ^ dst_m_ns))
		  {
		    /* The modification time changed, or we can't tell whether
		       it changed.  Change it back as best we can.  */
		    timespec[1].tv_sec = dst_m_s;
		    timespec[1].tv_nsec = dst_m_ns;
		    utimens (dst_name, timespec);
		  }

		if (stat_result != 0)
		  return -2;
	      }

	      /* Determine the exact resolution from the modification time
		 that was read back.  */
	      {
		int old_res = res;
		int a = (BILLION * (dst_status.st_mtime & 1)
			 + get_stat_mtime_ns (&dst_status));

		res = SYSCALL_RESOLUTION;

		for (a /= res; a % 10 != 0; a /= 10)
		  {
		    if (res == BILLION)
		      {
			res *= 2;
			break;
		      }
		    res *= 10;
		    if (res == old_res)
		      break;
		  }
	      }
	    }

	  dst_res->resolution = res;
	  dst_res->exact = true;
	}

      /* Truncate the source's time stamp according to the resolution.  */
      src_s &= ~ (res == 2 * BILLION);
      src_ns -= src_ns % res;
    }

  /* Compare the time stamps and return -1, 0, 1 accordingly.  */
  return (dst_s < src_s ? -1
	  : dst_s > src_s ? 1
	  : dst_ns < src_ns ? -1
	  : dst_ns > src_ns);
}
Beispiel #7
0
int parse(FILE *file)
{
  int head = read_header(file);

  if(head == false){
    printf("Invalid Clean C compiled file");
    return 1;
  }

  hash_t *var_map = malloc(sizeof(hash_t));
  hash_init(var_map, 1024);

  int ch = fgetc(file);
  while(ch != EOF){
    CODE code = ch - '0';
    switch(code){
      case PUSHS : {
        char type = read_type(file);
        if(type == 'S'){
          int length;
          fscanf(file, "%d", &length);
          char word[length+1];
          fgets(word, length+1, file);
          word[length+1]='\0';
          push(word);
        }
        break;
      }
      case PUSHV : {
        int length;
        fscanf(file, "%d", &length);
        char var[length+1];
        fgets(var, length+1, file);
        char *value = hash_lookup(var_map, var);
        push(value);
        break;
      }
      case ASSIGN : {
        int length;
        fscanf(file, "%d", &length);
        char var[length+1];
        fgets(var, length+1, file);

        char *value = pop();
        hash_insert(var_map, var, value);

        break;
      }
      case PRINT : {
        char *output = pop();
        printf("%s\n", output);
        break;
      }
      case END :
        return 0;
    }
    ch = fgetc(file);
  }

  free(var_map);
  return 0;
}
Beispiel #8
0
/*
 * Handles protocol-level commands that store data
 *
 * Returns false to signify a protocol-level error condition, true otherwise
 */
bool
cache_store(command_action_t command, network_buffer_t buffer)
{
    command_t cmd = command->command;;
    hash_entry_t he;
    memory_zone_t zone;
    memory_bucket_t bucket;
    cache_object_t co;
    int offset;
    uint32_t i;

    he = hash_search(command->action.store.hash,
                     command->action.store.key,
                     command->action.store.keylen);
    if (he != NULL && cmd == COMMAND_ADD) {
        /* If key is currently in use, add fails */
        command->response.store.response = COMMAND_RESPONSE_NOT_STORED;
        return (true);
    }

    if ((zone = memory_get_zone(command->action.store.size)) == NULL)
        return (false);    

    for (i = 0; i < zone->bucket_count; ++i) {
        bucket = zone->buckets[i];

        /* No free entries, continue to next bucket */
        if (bucket->mask == 0) {
            continue;
        }

        // 1 bucket
        if ((co = (cache_object_t)malloc(sizeof(*co) + sizeof(cache_object_bucket_t))) == NULL)
        {
            return (false);
        }

        offset = ffs(bucket->mask);
        bucket->mask &= ~(1 << offset);

        memcpy(&buffer->buffer[buffer->offset],
               &bucket->bucket + offset * zone->quantum,
               command->action.store.size);

        co->size = command->action.store.size;
        co->flags = command->action.store.flags;
        co->refcnt = 0;
        co->buckets = 1;
        co->data[0].fd = zone->zone_fd;
        co->data[0].offset = bucket->offset + (offset * zone->quantum);

        if (hash_insert(command->action.store.hash,
                        command->action.store.key,
                        command->action.store.keylen,
                        co)) {
            command->response.store.response = COMMAND_RESPONSE_STORED;

print_storage();

            return (true);
        } else {
        }

        command->response.store.response = COMMAND_RESPONSE_NOT_STORED;

//        free(
//        unset bit
    }

    return (false);
}
Beispiel #9
0
static int write_js_structure(void *mydata, int optflags,
                              const molfile_atom_t *atoms) {
  jshandle *js = (jshandle *) mydata;
  int i;

  js->optflags |= JSOPT_STRUCTURE;

  if (optflags & MOLFILE_OCCUPANCY)
    js->optflags |= JSOPT_OCCUPANCY;

  if (optflags & MOLFILE_BFACTOR)
    js->optflags |= JSOPT_BFACTOR;

  if (optflags & MOLFILE_BFACTOR)
    js->optflags |= JSOPT_BFACTOR;

  if (optflags & MOLFILE_MASS)
    js->optflags |= JSOPT_MASS;

  if (optflags & MOLFILE_CHARGE)
    js->optflags |= JSOPT_CHARGE;
 
  if (optflags & MOLFILE_RADIUS)
    js->optflags |= JSOPT_RADIUS;

  if (optflags & MOLFILE_ATOMICNUMBER)
    js->optflags |= JSOPT_ATOMICNUMBER;

  /* write flags data to the file */
  fio_write_int32(js->fd, js->optflags); 
printf("jsplugin) writing option flags: %0x08x\n", js->optflags);

printf("jsplugin) writing structure...\n");
  /* determine whether or not this file contains structure info or not */
  if (js->optflags & JSOPT_STRUCTURE) {
    int numatomnames, numatomtypes, numresnames, numsegids, numchains;
    char **atomnames = NULL;
    char **atomtypes = NULL;
    char **resnames = NULL;
    char **segids = NULL;
    char **chains = NULL;
    short *shortbuf = NULL; /* temp buf for encoding atom records */
    int *intbuf = NULL;     /* temp buf for encoding atom records */
    float *fltbuf = NULL;   /* temp buf for encoding atom records */

    hash_t tmphash;         /* temporary hash table */
    hash_t atomnamehash;
    hash_t atomtypehash;
    hash_t resnamehash;
    hash_t segidhash;
    hash_t chainhash;
    int hashcnt;


printf("jsplugin) counting atom names, types, etc...\n");
    /* generate hash tables to count the number of unique strings */
    hash_init(&tmphash, 127);
    for (i=0; i<js->natoms; i++)
      hash_insert(&tmphash, atoms[i].name, 0);
    numatomnames = tmphash.entries; /* XXX need a query API for this... */
    hash_destroy(&tmphash);

    hash_init(&tmphash, 127);
    for (i=0; i<js->natoms; i++)
      hash_insert(&tmphash, atoms[i].type, 0);
    numatomtypes = tmphash.entries; /* XXX need a query API for this... */
    hash_destroy(&tmphash);

    hash_init(&tmphash, 127);
    for (i=0; i<js->natoms; i++)
      hash_insert(&tmphash, atoms[i].resname, 0);
    numresnames = tmphash.entries; /* XXX need a query API for this... */
    hash_destroy(&tmphash);

    hash_init(&tmphash, 127);
    for (i=0; i<js->natoms; i++)
      hash_insert(&tmphash, atoms[i].segid, 0);
    numsegids = tmphash.entries; /* XXX need a query API for this... */
    hash_destroy(&tmphash);

    hash_init(&tmphash, 127);
    for (i=0; i<js->natoms; i++)
      hash_insert(&tmphash, atoms[i].chain, 0);
    numchains = tmphash.entries; /* XXX need a query API for this... */
    hash_destroy(&tmphash);
 
printf("jsplugin) writing unique string counts...\n");
printf("jsplugin) %d %d %d %d %d\n",
       numatomnames, numatomtypes, numresnames, numsegids, numchains);

    /* write block of name string table sizes */
    fio_write_int32(js->fd, numatomnames); 
    fio_write_int32(js->fd, numatomtypes); 
    fio_write_int32(js->fd, numresnames);
    fio_write_int32(js->fd, numsegids);
    fio_write_int32(js->fd, numchains); 

printf("jsplugin) writing string tables...\n");

    atomnames = (char **) malloc(numatomnames * sizeof(char *));
    atomtypes = (char **) malloc(numatomtypes * sizeof(char *));
    resnames = (char **) malloc(numresnames * sizeof(char *));
    segids = (char **) malloc(numsegids * sizeof(char *));
    chains = (char **) malloc(numchains * sizeof(char *));

printf("jsplugin)   atom names...\n");
    /* generate and write out the string tables */
    hash_init(&atomnamehash, 127);
    for (hashcnt=0,i=0; i<js->natoms; i++) {
      /* add a new string table entry for hash inserts that don't yet exist */
      if (hash_insert(&atomnamehash, atoms[i].name, hashcnt) == HASH_FAIL) {
        atomnames[hashcnt] = (char *) malloc(16 * sizeof(char));
        strcpy(atomnames[hashcnt], atoms[i].name);
        hashcnt++;
      }
    }
    for (i=0; i<numatomnames; i++) {
      fio_fwrite(atomnames[i], 16 * sizeof(char), 1, js->fd);
    }


printf("jsplugin)   atom types...\n");
    hash_init(&atomtypehash, 127);
    for (hashcnt=0,i=0; i<js->natoms; i++) {
      /* add a new string table entry for hash inserts that don't yet exist */
      if (hash_insert(&atomtypehash, atoms[i].type, hashcnt) == HASH_FAIL) {
        atomtypes[hashcnt] = (char *) malloc(16 * sizeof(char));
        strcpy(atomtypes[hashcnt], atoms[i].type);
        hashcnt++;
      }
    }
    for (i=0; i<numatomtypes; i++) {
      fio_fwrite(atomtypes[i], 16 * sizeof(char), 1, js->fd);
    }


printf("jsplugin)   residue names...\n");
    hash_init(&resnamehash, 127);
    for (hashcnt=0,i=0; i<js->natoms; i++) {
      /* add a new string table entry for hash inserts that don't yet exist */
      if (hash_insert(&resnamehash, atoms[i].resname, hashcnt) == HASH_FAIL) {
        resnames[hashcnt] = (char *) malloc(8 * sizeof(char));
        strcpy(resnames[hashcnt], atoms[i].resname);
        hashcnt++;
      }
    }
    for (i=0; i<numresnames; i++) {
      fio_fwrite(resnames[i], 8 * sizeof(char), 1, js->fd);
    }


printf("jsplugin)   segment names...\n");
    hash_init(&segidhash, 127);
    for (hashcnt=0,i=0; i<js->natoms; i++) {
      /* add a new string table entry for hash inserts that don't yet exist */
      if (hash_insert(&segidhash, atoms[i].segid, hashcnt) == HASH_FAIL) {
        segids[hashcnt] = (char *) malloc(8 * sizeof(char));
        strcpy(segids[hashcnt], atoms[i].segid);
        hashcnt++;
      }
    }
    for (i=0; i<numsegids; i++) {
      fio_fwrite(segids[i], 8 * sizeof(char), 1, js->fd);
    }


printf("jsplugin)   chain names...\n");
    hash_init(&chainhash, 127);
    for (hashcnt=0,i=0; i<js->natoms; i++) {
      /* add a new string table entry for hash inserts that don't yet exist */
      if (hash_insert(&chainhash, atoms[i].chain, hashcnt) == HASH_FAIL) {
        chains[hashcnt] = (char *) malloc(2 * sizeof(char));
        strcpy(chains[hashcnt], atoms[i].chain);
        hashcnt++;
      }
    }
    for (i=0; i<numchains; i++) {
      fio_fwrite(chains[i], 2 * sizeof(char), 1, js->fd);
    }


printf("jsplugin) writing numeric field tables...\n");
    /* write out all of the atom fields */
    shortbuf = (void *) malloc(js->natoms * sizeof(short));

    /* write out atom names */
    for (i=0; i<js->natoms; i++) {
      shortbuf[i] = hash_lookup(&atomnamehash, atoms[i].name);
    }    
    fio_fwrite(shortbuf, js->natoms * sizeof(short), 1, js->fd);

    /* write out atom types */
    for (i=0; i<js->natoms; i++) {
      shortbuf[i] = hash_lookup(&atomtypehash, atoms[i].type);
    }    
    fio_fwrite(shortbuf, js->natoms * sizeof(short), 1, js->fd);

    /* write out resnames */
    for (i=0; i<js->natoms; i++) {
      shortbuf[i] = hash_lookup(&resnamehash, atoms[i].resname);
    }    
    fio_fwrite(shortbuf, js->natoms * sizeof(short), 1, js->fd);
    
    /* write out segids */
    for (i=0; i<js->natoms; i++) {
      shortbuf[i] = hash_lookup(&segidhash, atoms[i].segid);
    }    
    fio_fwrite(shortbuf, js->natoms * sizeof(short), 1, js->fd);

    /* write out chains */
    for (i=0; i<js->natoms; i++) {
      shortbuf[i] = hash_lookup(&chainhash, atoms[i].chain);
    }    
    fio_fwrite(shortbuf, js->natoms * sizeof(short), 1, js->fd);

    if (shortbuf != NULL) {
      free(shortbuf);
      shortbuf=NULL;
    }

    /* done with hash tables */
    hash_destroy(&atomnamehash);
    hash_destroy(&atomtypehash);
    hash_destroy(&resnamehash);
    hash_destroy(&segidhash);
    hash_destroy(&chainhash);


    /* 
     * write out integer data blocks 
     */
    intbuf = (int *) malloc(js->natoms * sizeof(int));

printf("jsplugin)   residue indices...\n");
    /* write out resid */
    for (i=0; i<js->natoms; i++) {
      intbuf[i] = atoms[i].resid;
    }    
    fio_fwrite(intbuf, js->natoms * sizeof(int), 1, js->fd);
     
    if (intbuf != NULL) {
      free(intbuf);
      intbuf = NULL;
    }

printf("jsplugin) writing optional per-atom tables...\n");
    /*
     * write out optional single-precision float data blocks
     */ 
    if (js->optflags & (JSOPT_OCCUPANCY | JSOPT_BFACTOR | 
        JSOPT_MASS | JSOPT_RADIUS | JSOPT_CHARGE)) 
      fltbuf = (void *) malloc(js->natoms * sizeof(float));

    /* write out optional data if it exists */

    if (js->optflags & JSOPT_OCCUPANCY) {
printf("jsplugin)   writing occupancy...\n");
      for (i=0; i<js->natoms; i++) {
        fltbuf[i] = atoms[i].occupancy;
      }    
      fio_fwrite(fltbuf, js->natoms * sizeof(float), 1, js->fd);
    }

    if (js->optflags & JSOPT_BFACTOR) {
printf("jsplugin)   writing bfactor...\n");
      for (i=0; i<js->natoms; i++) {
        fltbuf[i] = atoms[i].bfactor;
      }    
      fio_fwrite(fltbuf, js->natoms * sizeof(float), 1, js->fd);
    }

    if (js->optflags & JSOPT_MASS) { 
printf("jsplugin)   writing mass...\n");
      for (i=0; i<js->natoms; i++) {
        fltbuf[i] = atoms[i].mass;
      }    
      fio_fwrite(fltbuf, js->natoms * sizeof(float), 1, js->fd);
    }

    if (js->optflags & JSOPT_CHARGE) { 
printf("jsplugin)   writing charge...\n");
      for (i=0; i<js->natoms; i++) {
        fltbuf[i] = atoms[i].charge;
      }    
      fio_fwrite(fltbuf, js->natoms * sizeof(float), 1, js->fd);
    }

    if (js->optflags & JSOPT_RADIUS) { 
printf("jsplugin)   writing radius...\n");
      for (i=0; i<js->natoms; i++) {
        fltbuf[i] = atoms[i].radius;
      }    
      fio_fwrite(fltbuf, js->natoms * sizeof(float), 1, js->fd);
    }

    if (fltbuf != NULL) {
      free(fltbuf);
      fltbuf=NULL;
    }


    /*
     * write out optional integer data blocks
     */ 
    if (js->optflags & JSOPT_ATOMICNUMBER)
      intbuf = (void *) malloc(js->natoms * sizeof(int));

    if (js->optflags & JSOPT_ATOMICNUMBER) { 
printf("jsplugin)   writing atomic number...\n");
      for (i=0; i<js->natoms; i++) {
        intbuf[i] = atoms[i].atomicnumber;
      }    
      fio_fwrite(intbuf, js->natoms * sizeof(int), 1, js->fd);
    }

    if (intbuf != NULL) {
      free(intbuf);
      intbuf = NULL;
    }


    /*
     * write out bonds and fractional bond orders
     */ 
    if (js->optflags & JSOPT_BONDS) {
printf("jsplugin) writing bonds...\n");
      fio_fwrite(&js->nbonds, sizeof(int), 1, js->fd);
      fio_fwrite(js->bondfrom, js->nbonds * sizeof(int), 1, js->fd);
      fio_fwrite(js->bondto, js->nbonds * sizeof(int), 1, js->fd);

      if (js->optflags & JSOPT_BONDORDERS) {
printf("jsplugin) writing bond orders...\n");
        fio_fwrite(js->bondorders, js->nbonds * sizeof(float), 1, js->fd);
      }
    }

    /*
     * write out angles/dihedrals/impropers/cross-terms
     */
    if (js->optflags & JSOPT_ANGLES) {
printf("jsplugin) writing angles/dihedrals/impropers...\n");
      fio_fwrite(&js->numangles, sizeof(int), 1, js->fd);
      fio_fwrite(js->angles, sizeof(int)*3*js->numangles, 1, js->fd);

      fio_fwrite(&js->numdihedrals, sizeof(int), 1, js->fd);
      fio_fwrite(js->dihedrals, sizeof(int)*4*js->numdihedrals, 1, js->fd);

      fio_fwrite(&js->numimpropers, sizeof(int), 1, js->fd);
      fio_fwrite(js->impropers, sizeof(int)*4*js->numimpropers, 1, js->fd);
    }
    if (js->optflags & JSOPT_CTERMS) {
printf("jsplugin) writing cross-terms\n");
      fio_fwrite(&js->numcterms, sizeof(int), 1, js->fd);
      fio_fwrite(js->cterms, sizeof(int)*8*js->numcterms, 1, js->fd);
    }

    return MOLFILE_SUCCESS;
  }

  /* else, we have no structure information */
  return MOLFILE_NOSTRUCTUREDATA;
}
Beispiel #10
0
static void
insert_new (Hash_table *ht, const void *ent)
{
  void *e = hash_insert (ht, ent);
  ASSERT (e == ent);
}
Beispiel #11
0
int
main (int argc, char **argv)
{
  unsigned int i;
  unsigned int k;
  unsigned int table_size[] = {1, 2, 3, 4, 5, 23, 53};
  Hash_table *ht;
  Hash_tuning tuning;

  hash_reset_tuning (&tuning);
  tuning.shrink_threshold = 0.3;
  tuning.shrink_factor = 0.707;
  tuning.growth_threshold = 1.5;
  tuning.growth_factor = 2.0;
  tuning.is_n_buckets = true;

  if (1 < argc)
    {
      unsigned int seed;
      if (get_seed (argv[1], &seed) != 0)
        {
          fprintf (stderr, "invalid seed: %s\n", argv[1]);
          exit (EXIT_FAILURE);
        }

      srand (seed);
    }

  for (i = 0; i < ARRAY_CARDINALITY (table_size); i++)
    {
      size_t sz = table_size[i];
      ht = hash_initialize (sz, NULL, hash_pjw, hash_compare_strings, NULL);
      ASSERT (ht);
      insert_new (ht, "a");
      {
        char *str1 = strdup ("a");
        char *str2;
        ASSERT (str1);
        str2 = hash_insert (ht, str1);
        ASSERT (str1 != str2);
        ASSERT (STREQ (str1, str2));
        free (str1);
      }
      insert_new (ht, "b");
      insert_new (ht, "c");
      i = 0;
      ASSERT (hash_do_for_each (ht, walk, &i) == 3);
      ASSERT (i == 7);
      {
        void *buf[5] = { NULL };
        ASSERT (hash_get_entries (ht, NULL, 0) == 0);
        ASSERT (hash_get_entries (ht, buf, 5) == 3);
        ASSERT (STREQ (buf[0], "a") || STREQ (buf[0], "b") || STREQ (buf[0], "c"));
      }
      ASSERT (hash_delete (ht, "a"));
      ASSERT (hash_delete (ht, "a") == NULL);
      ASSERT (hash_delete (ht, "b"));
      ASSERT (hash_delete (ht, "c"));

      ASSERT (hash_rehash (ht, 47));
      ASSERT (hash_rehash (ht, 467));

      /* Free an empty table. */
      hash_clear (ht);
      hash_free (ht);

      ht = hash_initialize (sz, NULL, hash_pjw, hash_compare_strings, NULL);
      ASSERT (ht);

      insert_new (ht, "z");
      insert_new (ht, "y");
      insert_new (ht, "x");
      insert_new (ht, "w");
      insert_new (ht, "v");
      insert_new (ht, "u");

      hash_clear (ht);
      ASSERT (hash_get_n_entries (ht) == 0);
      hash_free (ht);

      /* Test pointer hashing.  */
      ht = hash_initialize (sz, NULL, NULL, NULL, NULL);
      ASSERT (ht);
      {
        char *str = strdup ("a");
        ASSERT (str);
        insert_new (ht, "a");
        insert_new (ht, str);
        ASSERT (hash_lookup (ht, str) == str);
        free (str);
      }
      hash_free (ht);
    }

  hash_reset_tuning (&tuning);
  tuning.shrink_threshold = 0.3;
  tuning.shrink_factor = 0.707;
  tuning.growth_threshold = 1.5;
  tuning.growth_factor = 2.0;
  tuning.is_n_buckets = true;
  /* Invalid tuning.  */
  ht = hash_initialize (4651, &tuning, hash_pjw, hash_compare_strings,
                        hash_freer);
  ASSERT (!ht);

  /* Alternate tuning.  */
  tuning.growth_threshold = 0.89;

  /* Run with default tuning, then with custom tuning settings.  */
  for (k = 0; k < 2; k++)
    {
      Hash_tuning const *tune = (k == 0 ? NULL : &tuning);
      /* Now, each entry is malloc'd.  */
      ht = hash_initialize (4651, tune, hash_pjw,
                            hash_compare_strings, hash_freer);
      ASSERT (ht);
      for (i = 0; i < 10000; i++)
        {
          unsigned int op = rand () % 10;
          switch (op)
            {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
              {
                char buf[50];
                char const *p = uinttostr (i, buf);
                char *p_dup = strdup (p);
                ASSERT (p_dup);
                insert_new (ht, p_dup);
              }
              break;

            case 6:
              {
                size_t n = hash_get_n_entries (ht);
                ASSERT (hash_rehash (ht, n + rand () % 20));
              }
              break;

            case 7:
              {
                size_t n = hash_get_n_entries (ht);
                size_t delta = rand () % 20;
                if (delta < n)
                  ASSERT (hash_rehash (ht, n - delta));
              }
              break;

            case 8:
            case 9:
              {
                /* Delete a random entry.  */
                size_t n = hash_get_n_entries (ht);
                if (n)
                  {
                    size_t kk = rand () % n;
                    void const *p;
                    void *v;
                    for (p = hash_get_first (ht); kk;
                         --kk, p = hash_get_next (ht, p))
                      {
                        /* empty */
                      }
                    ASSERT (p);
                    v = hash_delete (ht, p);
                    ASSERT (v);
                    free (v);
                  }
                break;
              }
            }
          ASSERT (hash_table_ok (ht));
        }

      hash_free (ht);
    }

  return 0;
}
Beispiel #12
0
/* Open the configuration file, and parse it line by line. */
int hcfg_load(hcfg_t *cfg, const char *filename)
{
    FILE *fd;
    char buf[4096];
    char *head, *next, *tail, *key, *val;
    int linenum = 1;

    if (strcmp(filename, "-") == 0)
        fd = stdin;
    else {
        fd = fopen(filename, "r");
        if (!fd) {
            perror("Error parsing configuration data");
            return -1;
        }
    }

    head = buf;
    tail = buf;
    while (!feof(fd)) {
        int count;

        tail += fread(tail, sizeof(char), sizeof(buf) - (tail - buf + 1), fd);
        *tail = '\0';

        while (head < tail) {
            count = line_count(head);
            if (count == 0 && !feof(fd))
                break;

            next = hcfg_parse(head, &key, &val);
            if (!next)
                break;

            if (key && val) {
                keyval_t *entry = hash_find(cfg, key);

                if (entry != NULL && entry->key != NULL) {
                    fprintf(stderr, "Warning: Line %d: Redefinition of"
                            " configuration key %s.\n", linenum, key);
                }

                if (hash_insert(cfg, key, val) != 0) {
                    fprintf(stderr, "Error: Internal hash table error.\n");
                    fclose(fd);
                    return -1;
                }
            }
            linenum += count;
            head = next;
        }

        /* Parse error detected. */
        if (!next)
            break;

        /* Full buffer with no newline. */
        if (tail - head == sizeof(buf) - 1)
            break;

        /* Move remaining data to front of buffer. */
        if (head != buf) {
            next = buf;
            while (head < tail)
                *(next++) = *(head++);
            tail = next;
            head = buf;
        }
    }
    if (fclose(fd) != 0) {
        perror("Error parsing configuration data");
        return -1;
    }

    if (head != tail) {
        fprintf(stderr, "Parse error in file %s line %d: ", filename, linenum);
        if (tail - head == sizeof(buf) - 1)
            fprintf(stderr, "Line buffer overflow.\n");
        else if (key == NULL)
            fprintf(stderr, "Invalid key string.\n");
        else if (val == NULL)
            fprintf(stderr, "No key/value separator character (=).\n");
        return -1;
    }

    return 0;
}
Beispiel #13
0
int hcfg_set(hcfg_t *cfg, const char *key, const char *val)
{
    if (val == NULL)
        return hash_delete(cfg, key);
    return hash_insert(cfg, key, val);
}
Beispiel #14
0
/* StructSpecifier semantic handle function */
TypePtr sem_structspecifier_handle(NodePtr node) {
    uint_32 rule = node->content.rule;
    symbol **mlist;
    symbol *current_node, *new_stype, *struct_node;
    TypePtr type;
    NodePtr opttag;
    char *struct_name;
    int count, i;

    if (STRUCTSPECIFIER__STRUCT_OPTTAG_LC_DEFLIST_RC == rule) {
        new_stype = (symbol *)malloc(sizeof(symbol));
        type = (TypePtr)malloc(sizeof(Type));
        type->kind = STRUCTURE;
        type->array_status = -1;
        mlist = (symbol **)malloc(20 * sizeof(symbol *));
        count = sem_deflist_handle(get_child(node, 3), mlist, 0);
        
        if (count > 0) {
            type->u.structure = mlist[0];
            current_node = type->u.structure;
            for (i = 1; i < count; ++i) {
                current_node->tail = mlist[i];
                current_node = current_node->tail;
            }
        }
        new_stype->name = (char *)malloc(strlen("struct:") \
          + 20);
        /* solve the name of struct, 
         * 2012 05 26 - 12:30
         * */
        opttag = get_child(node, 1);

        if (iNULL != opttag->content.id)
            sprintf(new_stype->name, "struct:%s", \
              get_child(opttag, 0)->content.str_value);
        else 
            sprintf(new_stype->name, "struct:%d", current_id + 1);
        JDEBUG_OUT_COM("new_stype->name: %s\n", new_stype->name);
        new_stype->type = type;
        new_stype->tail = NULL;
        
        //free(mlist);
        /* insert the struct type into the symbolic table */
        hash_insert(&symbol_table, new_stype);
/*
        printf("--------------test----------------\n");
        current_node = new_stype;
        printf("[Struct Detail] name: %s\n", current_node->name);
        current_node = current_node->type->u.structure;
        while (current_node != NULL) {
            JDEBUG_OUT_COM("name: %s type: %d \n", current_node->name, current_node->type->kind);
            current_node = current_node->tail;
        }
        printf("--------------------test end-----------------------\n");
        */
        
        return new_stype->type; //to change
    }
    else if (STRUCTSPECIFIER__STRUCT_TAG == rule) {
        JDEBUG_OUT_COM("sem_STRUCTSPECIFIER__STRUCT_TAG\n"); struct_name = (char *)malloc(strlen("struct:")+20);
        sprintf(struct_name, "struct:%s", \
          get_child(get_child(node, 1), 0)->content.str_value);
        JDEBUG_OUT_COM("%s, %s\n", get_child(get_child(node, 1), 0)->content.str_value, struct_name);
        struct_node = hash_get(symbol_table, struct_name);
        assert(NULL != struct_node);
        return struct_node->type;
    }
    else {
        printf("Unknown STRUCT SPECIFIER\n");
        exit(-1);
    }
}
Beispiel #15
0
/*
 * Construct an iCalendar property value from XML content.
 */
static icalvalue *xml_element_to_icalvalue(xmlNodePtr xtype,
        icalvalue_kind kind)
{
    icalvalue *value = NULL;
    xmlNodePtr node;
    xmlChar *content = NULL;

    switch (kind) {

    case ICAL_GEO_VALUE: {
        struct icalgeotype geo;

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <latitude> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "latitude")) {
            syslog(LOG_WARNING,
                   "Expected <latitude> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        geo.lat = atof((const char *) content);

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <longitude> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "longitude")) {
            syslog(LOG_WARNING,
                   "Expected <longitude> XML element, received %s", node->name);
            break;
        }

        xmlFree(content);
        content = xmlNodeGetContent(node);
        geo.lon = atof((const char *) content);

        value = icalvalue_new_geo(geo);

        break;
    }

    case ICAL_PERIOD_VALUE: {
        struct icalperiodtype p;

        p.start = p.end = icaltime_null_time();
        p.duration = icaldurationtype_from_int(0);

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <start> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "start")) {
            syslog(LOG_WARNING,
                   "Expected <start> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        p.start = icaltime_from_string((const char *) content);
        if (icaltime_is_null_time(p.start)) break;

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <end> / <duration> XML element");
            break;
        }
        else if (!xmlStrcmp(node->name, BAD_CAST "end")) {
            xmlFree(content);
            content = xmlNodeGetContent(node);
            p.end = icaltime_from_string((const char *) content);
            if (icaltime_is_null_time(p.end)) break;
        }
        else if (!xmlStrcmp(node->name, BAD_CAST "duration")) {
            xmlFree(content);
            content = xmlNodeGetContent(node);
            p.duration = icaldurationtype_from_string((const char *) content);
            if (icaldurationtype_as_int(p.duration) == 0) break;
        }
        else {
            syslog(LOG_WARNING,
                   "Expected <end> / <duration> XML element, received %s",
                   node->name);
            break;
        }

        value = icalvalue_new_period(p);

        break;
    }

    case ICAL_RECUR_VALUE: {
        struct buf rrule = BUF_INITIALIZER;
        struct hash_table byrules;
        struct icalrecurrencetype rt;
        char *sep = "";

        construct_hash_table(&byrules, 10, 1);

        /* create an iCal RRULE string from xCal <recur> sub-elements */
        for (node = xmlFirstElementChild(xtype); node;
                node = xmlNextElementSibling(node)) {

            content = xmlNodeGetContent(node);
            if (!xmlStrncmp(node->name, BAD_CAST "by", 2)) {
                /* BY* rules can have a list of values -
                   assemble them using a hash table */
                struct buf *vals =
                    hash_lookup((const char *) node->name, &byrules);

                if (vals) {
                    /* append this value to existing list */
                    buf_printf(vals, ",%s", (char *) content);
                }
                else {
                    /* create new list with this valiue */
                    vals = xzmalloc(sizeof(struct buf));
                    buf_setcstr(vals, (char *) content);
                    hash_insert((char *) node->name, vals, &byrules);
                }
            }
            else {
                /* single value rpart */
                buf_printf(&rrule, "%s%s=%s", sep,
                           ucase((char *) node->name), (char *) content);
                sep = ";";
            }

            xmlFree(content);
            content = NULL;
        }

        /* append the BY* rules to RRULE buffer */
        hash_enumerate(&byrules,
                       (void (*)(const char*, void*, void*)) &append_byrule,
                       &rrule);
        free_hash_table(&byrules, NULL);

        /* parse our iCal RRULE string */
        rt = icalrecurrencetype_from_string(buf_cstring(&rrule));
        buf_free(&rrule);

        if (rt.freq != ICAL_NO_RECURRENCE) value = icalvalue_new_recur(rt);

        break;
    }

    case ICAL_REQUESTSTATUS_VALUE: {
        struct icalreqstattype rst = { ICAL_UNKNOWN_STATUS, NULL, NULL };
        short maj, min;

        node = xmlFirstElementChild(xtype);
        if (!node) {
            syslog(LOG_WARNING, "Missing <code> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "code")) {
            syslog(LOG_WARNING,
                   "Expected <code> XML element, received %s", node->name);
            break;
        }

        content = xmlNodeGetContent(node);
        if (sscanf((const char *) content, "%hd.%hd", &maj, &min) == 2) {
            rst.code = icalenum_num_to_reqstat(maj, min);
        }
        if (rst.code == ICAL_UNKNOWN_STATUS) {
            syslog(LOG_WARNING, "Unknown request-status code");
            break;
        }

        node = xmlNextElementSibling(node);
        if (!node) {
            syslog(LOG_WARNING, "Missing <description> XML element");
            break;
        }
        else if (xmlStrcmp(node->name, BAD_CAST "description")) {
            syslog(LOG_WARNING,
                   "Expected <description> XML element, received %s",
                   node->name);
            break;
        }

        xmlFree(content);
        content = xmlNodeGetContent(node);
        rst.desc = (const char *) content;

        node = xmlNextElementSibling(node);
        if (node) {
            if (xmlStrcmp(node->name, BAD_CAST "data")) {
                syslog(LOG_WARNING,
                       "Expected <data> XML element, received %s", node->name);
                break;
            }

            xmlFree(content);
            content = xmlNodeGetContent(node);
            rst.debug = (const char *) content;
        }

        value = icalvalue_new_requeststatus(rst);
        break;
    }

    case ICAL_UTCOFFSET_VALUE: {
        int n, utcoffset, hours, minutes, seconds = 0;
        char sign;

        content = xmlNodeGetContent(xtype);
        n = sscanf((const char *) content, "%c%02d:%02d:%02d",
                   &sign, &hours, &minutes, &seconds);

        if (n < 3) {
            syslog(LOG_WARNING, "Unexpected utc-offset format");
            break;
        }

        utcoffset = hours*3600 + minutes*60 + seconds;

        if (sign == '-') utcoffset = -utcoffset;

        value = icalvalue_new_utcoffset(utcoffset);
        break;
    }

    default:
        content = xmlNodeGetContent(xtype);
        value = icalvalue_new_from_string(kind, (const char *) content);
        break;
    }

    if (content) xmlFree(content);

    return value;
}
Beispiel #16
0
/* -Su
 * @param targets list of strings
 * @param hashdb hash database
 */
static int upgrade_pkgs(alpm_list_t *targets, struct pw_hashdb *hashdb)
{
	alpm_list_t *i;
	alpm_list_t *target_pkgs = NULL;
	alpm_list_t *final_targets = NULL;
	struct graph *graph;
	struct stack *topost;
	int ret = 0;

	char cwd[PATH_MAX];
	if (!targets) {
		return 0;
	}

	if (!getcwd(cwd, PATH_MAX)) {
		return error(PW_ERR_GETCWD);
	}

	if (chdir(powaur_dir)) {
		return error(PW_ERR_CHDIR);
	}

	/* Enable debugging resolution */
	graph_enable_debug_resolve();

	graph = graph_new((pw_hash_fn) sdbm, (pw_hashcmp_fn) strcmp);
	topost = stack_new(sizeof(int));

	for (i = targets; i; i = i->next) {
		target_pkgs = alpm_list_add(target_pkgs, i->data);
		/* Insert into outdated AUR packages to avoid dling up to date ones */
		hash_insert(hashdb->aur_outdated, (void *) i->data);
		/* Add the targets into graph to prevent those w/o deps to not get upgraded */
		graph_add_vertex(graph, (void *) i->data);
	}

	printf("Resolving dependencies... Please wait\n");
	/* Build dep graph for all packages */
	build_dep_graph(&graph, hashdb, target_pkgs, RESOLVE_IMMEDIATE);
	ret = graph_toposort(graph, topost);
	if (ret) {
		printf("Cyclic dependencies detected!\n");
		goto cleanup;
	}

	graph_disable_debug_resolve();

	final_targets = topo_get_targets(hashdb, graph, topost);
	if (final_targets) {
		topo_install(hashdb, final_targets);
	}

cleanup:
	/* Install in topo order */
	graph_free(graph);
	stack_free(topost);
	alpm_list_free(target_pkgs);
	alpm_list_free(final_targets);
	if (chdir(cwd)) {
		return error(PW_ERR_RESTORECWD);
	}

	return ret;
}
Beispiel #17
0
/** Build KW table
 *  --------------
 *  Pre-insert the keywords into the kwtable
 *
 *  Uses NUMKEYWORDS and hashinsert from utility to add entries from 
 *      char *keywords[] into the struct hashentry *kwtable
 */
void initialize_kwtable()
{

    struct identifier *newkw;

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "auto";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "begin";
    newkw->id = KW_JUMPLABEL;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "break";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "case";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "char";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = INTEGRAL;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "const";
    newkw->id = KW_TYPEQUALIFIER;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "continue";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "default";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "do";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "double";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = FLOATING;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "else";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "enum";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "extern";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "float";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = FLOATING;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "for";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "goto";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "if";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "int";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = INTEGRAL;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "long";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = INTEGRAL;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "register";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "return";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "short";
    newkw->id = KW_TYPESPECIFIER;
    //newkw->type_specifier = INTEGRAL;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "signed";
    newkw->id = KW_TYPESPECIFIER;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "sizeof";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "static";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "struct";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "switch";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "typedef";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "union";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "unsigned";
    newkw->id = KW_TYPESPECIFIER;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "void";
    newkw->id = KW_TYPESPECIFIER;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "volatile";
    newkw->id = KW_TYPEQUALIFIER;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "while";
    newkw->id = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "*";
    newkw->id = 0;
    newkw->type.keyword = 1;
    newkw->type.identifier = 0;
    newkw->type.op = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "&";
    newkw->id = 0;
    newkw->type.keyword = 1;
    newkw->type.identifier = 0;
    newkw->type.op = 0;
    hash_insert(kwtable, newkw);

    newkw = malloc(sizeof(struct identifier));
    newkw->lexeme = "=";
    newkw->id = 0;
    newkw->type.keyword = 1;
    newkw->type.identifier = 0;
    newkw->type.op = 0;
    hash_insert(kwtable, newkw);

}
Beispiel #18
0
int read_sofile(const char *path, struct hash_control **hash, int *size)
{
	char line[BUFSIZ];
	char *msgid = NULL, *msgstr = NULL;
	FILE *fp;

	if (path == NULL || size == NULL || hash == NULL)
		return -1;

	fp = fopen(path, "r");
	*size = 0;
	*hash = hash_new();

	if (fp == NULL)
		return -1;

	while (fgets(line, sizeof(line), fp) != NULL) {
		if (line[0] == '#')
			continue;
		if (strncmp(line, "msgid", 5) == 0) {
			int pos1 = strstr(line, " \"") - line;
			int pos2 = strrchr(line, '\"') - line;

			if (pos1 < pos2 - 2) {
				char *t;

				msgid = strndup(line + pos1 + 2, pos2 - pos1 - 2);
				if (msgid == NULL)
					continue;
				t = strdup(msgid);

				if (t == NULL) {
					free(msgid);
					msgid = NULL;
				}

				convert_c_style_string(t, pos2 - pos1 - 2 + 1, msgid);

				free(msgid);
				msgid = t;
			}
		} else if (strncmp(line, "msgstr", 6) == 0) {
			int pos1 = strstr(line, " \"") - line;
			int pos2 = strrchr(line, '\"') - line;

			if (pos1 < pos2 - 2) {
				char *t;

				msgstr = strndup(line + pos1 + 2, pos2 - pos1 - 2);
				if (msgid == NULL)
					continue;
				t = strdup(msgstr);

				if (t == NULL) {
					free(msgid);
					msgid = NULL;
				}

				convert_c_style_string(t, pos2 - pos1 - 2 + 1, msgstr);
				free(msgstr);
				msgstr = t;
			}
		}
		if (msgid && msgstr) {
			const char *str = hash_insert(*hash, msgid, msgstr);

			if (str == NULL) {
				(*size)++;
			}
			msgid = NULL;
			msgstr = NULL;
		}
	}

	fclose(fp);

	return 0;
}
Beispiel #19
0
// type is IF_TYPE_LOOPBACK, IF_TYPE_ETHERNET
//int if_register_interface(const char *path, ifnet **_i)
int if_register_interface(int type, ifnet **_i, phantom_device_t *dev)
{
    ifnet *i;
    //int type;
    int err;
    ifaddr *address;

    i = kmalloc(sizeof(ifnet));
    if(!i) {
        err = ERR_NO_MEMORY;
        goto err;
    }
    memset(i, 0, sizeof(ifnet));

    i->dev = dev;

    if(dev != 0 && (i->dev->dops.write == 0 || i->dev->dops.read == 0) )
        panic("dev has no read or write!");



    /* open the device * /
     if(!strcmp(path, "loopback")) {
     // the 'loopback' device is special
     type = IF_TYPE_LOOPBACK;
     i->fd = -1;
     } else {
     i->fd = sys_open(path, 0);
     if(i->fd < 0) {
     err = i->fd;
     goto err1;
     }
     // find the device's type
      err = sys_ioctl(i->fd, IOCTL_NET_IF_GET_TYPE, &type, sizeof(type));
      if(err < 0) {
      goto err2;
      }
      } */

    // find the appropriate function calls to the link layer drivers
    switch(type) {
    case IF_TYPE_LOOPBACK:
        i->link_input = &loopback_input;
        i->link_output = &loopback_output;
        i->mtu = 65535;
        break;
    case IF_TYPE_ETHERNET:

        assert(dev);

        i->link_input = &ethernet_input;
        i->link_output = &ethernet_output;
        i->mtu = ETHERNET_MAX_SIZE - ETHERNET_HEADER_SIZE;

        /* bind the ethernet link address */
        address = kmalloc(sizeof(ifaddr));
        address->addr.len = 6;
        address->addr.type = ADDR_TYPE_ETHERNET;

        if( dev->dops.get_address == 0 )
        {
            err = ERR_NET_GENERAL;
            kfree(address);
            goto err2;
        }

        err = dev->dops.get_address(dev, &address->addr.addr[0], 6);
        if(err < 0) {
            err = ERR_NET_GENERAL;
            kfree(address);
            goto err2;
        }

        /*err = sys_ioctl(i->fd, IOCTL_NET_IF_GET_ADDR, &address->addr.addr[0], 6);
        if(err < 0) {
            kfree(address);
            goto err2;
        }*/

        address->broadcast.len = 6;
        address->broadcast.type = ADDR_TYPE_ETHERNET;
        memset(&address->broadcast.addr[0], 0xff, 6);
        address->netmask.type = ADDR_TYPE_NULL;
        if_bind_link_address(i, address);
        break;
    default:
        err = ERR_NET_GENERAL;
        goto err1;
    }

    i->id = ATOMIC_ADD_AND_FETCH(&next_id, 1);
    //strlcpy(i->path, path, sizeof(i->path));
    i->type = type;
    i->rx_thread = -1;
    i->tx_thread = -1;

    //i->tx_queue_sem = sem_create(0, "tx_queue_sem");
    hal_sem_init( &(i->tx_queue_sem), "IF TX sem" );
    hal_mutex_init(&i->tx_queue_lock, "IF TX Q");
    fixed_queue_init(&i->tx_queue, TX_QUEUE_SIZE);

    mutex_lock(&ifhash_lock);
    hash_insert(ifhash, i);
    mutex_unlock(&ifhash_lock);

    // don't need threads for loopback if
    if(type != IF_TYPE_LOOPBACK)
    {
        /* start the rx and tx threads on this interface */
        err = if_boot_interface(i);
        if(err < 0)
            goto err2;

        //bootp(i);
    }
    *_i = i;


    return NO_ERROR;

err2:
    //sys_close(i->fd);
err1:
    kfree(i);
err:
    return err;
}
Beispiel #20
0
/**
 ** DESCRIPTION
 ** 	Add hashtable item for each link found in a line from the stream
 ** 	if hostname or ip != NULL then checks if link refers to hostname or ip
 ** 	includes arguments after '?' as query string
 **
 ** RETURN VALUE
 **	The number of links found
 **/
int parse_links( 	const char * line, const char * hostname, 
						const char * ip, char * curdir )
{
	struct linkz	* lk;	

	char	* ptr		= NULL;
	char	* linkn	= NULL;
	char	* query 	= NULL;
	char 	* tfree 	= NULL;
	char	* start	= NULL;

	int	count 	= 0;
	int	proto 	= 0;
	int	match 	= 0;
	int	found		= 0;
	int	updat		= 0;	
	
	if ( line )
		ptr = xstrdup(line);
	else 	
		return 0;

	if ( !ptr )
		return 0;

	tfree = ptr;	
	
	do
	{
		start = ptr ;
	
		if ( (ptr = xstrstr( start, HREF )) )
		{
			ptr += strlen ( HREF );
			NEXTFIELD( ptr );
			found = 1;
		}
		else if ( (ptr = xstrstr( start, FRAME )) )
		{
			if ( (ptr += strlen( FRAME ))
					&& (ptr = xstrstr( ptr, SRC )) )
			{
				if ( (ptr += strlen( SRC )) )	
				{
					NEXTFIELD( ptr );
					found = 1;
				}
			}
		}
		if ( !ISNULL(ptr) && found )
		{
			found = 0;

			if ( !strncasecmp( ptr, "http://", 7 ))
				proto = 7;
			else if ( !strncasecmp( ptr, "javascript:", 11 ))
				continue;
			else if ( !strncasecmp( ptr, "mailto:", 7 ))
				continue; 
			else if ( !strncasecmp( ptr, "news:", 5 ))
				continue;
			else if ( !strncasecmp( ptr, "ftp://", 6 ))
				continue; 
			else if ( !strncasecmp( ptr, "https://", 8 ))
				continue;
					
			if ( proto ) 
			{
				ptr += proto;
				proto = 0;

				if ( hostname )
				{
					if ( !strncasecmp( ptr, hostname, strlen(hostname)) )
						match = 1;
				}
				if ( ip )
				{
					if ( !strncasecmp( ptr, ip, strlen(ip)) )
						match = 1;
				}		
				if ( !match && (hostname || ip) ) 
				{	
					continue;
				}
				else 
				{
					ptr = strchr( ptr, '/' );
					match = 0;
				}
			}
			if ( !ISNULL(ptr) )
			{
				boolean relative = FALSE;
				char	* p = strpbrk( ptr, "#\" '\t\r\n>" ); 

				linkn = ptr;

				if ( p )
				{
					ptr = p + 1;
					*p = 0;
				}

				if ( (query = strchr( linkn, '?')) ) 
					*query++ = 0;
					
				updat = 0;

				if ( !linkn[0] || (linkn[0]=='/' && !linkn[2])  )
					continue;

				if ( strpbrk( linkn, "=<>?&" ) )
					continue;

				if ( !EXT_ISALLOWED( linkn ) )
				{
					debug( "Skipping unallowed file type: %s\n", linkn );
					continue;
				}
				if ( ISRELATIVE( linkn  ) ) 
				{
					relative = TRUE;
					linkn = fix_relative( linkn, curdir );
				}
				if ( (lk = (struct linkz *)hash_get_value( linkn, HTlinks )) )
				{
					if ( !query || ((query) && (lk->flags & LDYNAMIC)) )
						continue;
				}

        		lk = (struct linkz *)xmalloc(sizeof(struct linkz));

				debug( "Link: %s\n", linkn );

				if ( query )
				{
					if ( updat ) 
						lk->flags &= ~LVISITED;

					lk->flags |= LCACHED;
					lk->flags |= LDYNAMIC;
					lk->query = xstrdup( query );
					debug( "Query: %s\n", query );
				}
				
				hash_insert( linkn, lk, HTlinks );
				if ( relative == TRUE ) xfree( linkn );
				updat ^= updat;
				count++ ;
			}
		}
	}
	while( ptr );	

	xfree( tfree );
	return count;
}
Beispiel #21
0
/*向hash表中插入一组数据*/
void insert_str(struct HashTable *table, char *key, char *value)
{
	hash_insert(table, key, value);struct HashTable *var_table;
}
Beispiel #22
0
static void
do_line P1C(string, line)
{
  unsigned len;
  string start;
  string value, var;
  string prog = NULL;
  
  /* Skip leading whitespace.  */
  while (ISSPACE (*line))
    line++;
  
  /* More to do only if we have non-comment material left.  */
  if (*line == 0 || *line == '%' || *line == '#')
    return;
  
  /* The variable name is everything up to the next space or = or `.'.  */
  start = line;
  while (!ISSPACE (*line) && *line != '=' && *line != '.')
    line++;

  /* `line' is now one character past the end of the variable name.  */
  len = line - start;
  var = (string)xmalloc (len + 1);
  strncpy (var, start, len);
  var[len] = 0;
  
  /* If the variable is qualified with a program name, find out which. */
  while (ISSPACE (*line))
    line++;
  if (*line == '.') {
    /* Skip spaces, then everything up to the next space or =.  */
    line++;
    while (ISSPACE (*line))
      line++;
    start = line;
    while (!ISSPACE (*line) && *line != '=')
      line++;

    /* It's annoying to repeat all this, but making a tokenizing
       subroutine would be just as long and annoying.  */
    len = line - start;
    prog = (string)xmalloc (len + 1);
    strncpy (prog, start, len);
    prog[len] = 0;
  }

  /* Skip whitespace, an optional =, more whitespace.  */
  while (ISSPACE (*line))
    line++;
  if (*line == '=') {
    line++;
    while (ISSPACE (*line))
      line++;
  }
  
  /* The value is whatever remains.  Remove trailing whitespace.  */
  start = line;
  len = strlen (start);
  while (len > 0 && ISSPACE (start[len - 1]))
    len--;
  
  value = (string)xmalloc (len + 1);
  strncpy (value, start, len);
  value[len] = 0;

  /* Suppose we want to write a single texmf.cnf that can be used under
     both NT and Unix.  This is feasible except for the path separators
     : on Unix, ; on NT.  We can't switch NT to allowing :'s, since :
     is the drive separator.  So we switch Unix to allowing ;'s.  On the
     other hand, we don't want to change IS_ENV_SEP and all the rest.
     
     So, simply translate all ;'s in the path
     values to :'s if we are a Unix binary.  (Fortunately we don't use ;
     in other kinds of texmf.cnf values.)
     
     If you really want to put ; in your filenames, add
     -DALLOW_SEMICOLON_IN_FILENAMES.  (And there's no way to get :'s in
     your filenames, sorry.)  */
     
#if IS_ENV_SEP(':') && !defined (ALLOW_SEMICOLON_IN_FILENAMES)
  {
    string loc;
    for (loc = value; *loc; loc++) {
      if (*loc == ';')
        *loc = ':';
    }
  }
#endif

  /* We want TEXINPUTS.prog to override plain TEXINPUTS.  The simplest
     way is to put both in the hash table (so we don't have to write
     hash_delete and hash_replace, and keep track of values' sources),
     and then look up the .prog version first in `kpse_cnf_get'.  */
  if (prog) {
    string lhs = concat3 (var, ".", prog);
    free (var);
    free (prog);
    var = lhs;
  }
  hash_insert (&cnf_hash, var, value);
  
  /* We could check that anything remaining is preceded by a comment
     character, but let's not bother.  */
}
Beispiel #23
0
void build_dep_graph(struct graph **graph, struct pw_hashdb *hashdb,
                     alpm_list_t *targets, int resolve_lvl)
{
    if (!graph) {
        return;
    }

    if (!*graph) {
        *graph = graph_new((pw_hash_fn) sdbm, (pw_hashcmp_fn) strcmp);
    }

    struct stack *st = stack_new(sizeof(struct pkgpair));
    struct hash_table *resolved = hash_new(HASH_TABLE, (pw_hash_fn) sdbm,
                                           (pw_hashcmp_fn) strcmp);
    struct hash_table *immediate = hash_new(HASH_TABLE, (pw_hash_fn) sdbm,
                                            (pw_hashcmp_fn) strcmp);
    int ret;
    struct pkgpair pkgpair, deppkg;
    alpm_list_t *i;
    alpm_list_t *deps;

    CURL *curl;
    curl = curl_easy_new();
    if (!curl) {
        error(PW_ERR_CURL_INIT);
        return;
    }

    /* Push all packages down stack */
    for (i = targets; i; i = i->next) {
        pkgpair.pkgname = i->data;
        pkgpair.pkg = NULL;
        stack_push(st, &pkgpair);
    }

    while (!stack_empty(st)) {
        stack_pop(st, &pkgpair);
        deps = NULL;

        if (hash_search(resolved, (void *) pkgpair.pkgname)) {
            goto cleanup_deps;
        }

        ret = crawl_resolve(curl, hashdb, &pkgpair, &deps, resolve_lvl);
        if (ret) {
            pw_fprintf(PW_LOG_ERROR, stderr, "Error in resolving packages.\n");
            goto cleanup;
        }

        for (i = deps; i; i = i->next) {
            deppkg.pkgname = i->data;
            deppkg.pkg = NULL;

            /* immediate vs thorough resolve */
            should_we_continue_resolving(curl, hashdb, st, &deppkg, resolve_lvl);

            /* dep --> current */
            graph_add_edge(*graph, i->data, (void *) pkgpair.pkgname);
        }

        hash_insert(resolved, (void *) pkgpair.pkgname);

        /* Add immediate dependencies, for pretty printing purposes */
        add_immediate_deps(hashdb, pkgpair.pkgname, deps, immediate);
cleanup_deps:
        alpm_list_free(deps);
    }

cleanup:
    hash_free(resolved);
    hash_free(immediate);
    stack_free(st);
    curl_easy_cleanup(curl);
}
Beispiel #24
0
static long
count_entry (char *ent, int top, dev_t last_dev)
{
  long size;

  if (((top && opt_dereference_arguments)
       ? stat (ent, &stat_buf)
       : (*xstat) (ent, &stat_buf)) < 0)
    {
      error (0, errno, "%s", path->text);
      exit_status = 1;
      return 0;
    }

  if (!opt_count_all
      && stat_buf.st_nlink > 1
      && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
    return 0;			/* Have counted this already.  */

  if (output_size == size_bytes)
    size = stat_buf.st_size;
  else
    size = ST_NBLOCKS (stat_buf);

  tot_size += size;

  if (S_ISDIR (stat_buf.st_mode))
    {
      unsigned pathlen;
      dev_t dir_dev;
      char *name_space;
      char *namep;
      struct saved_cwd cwd;
      int through_symlink;
      struct stat e_buf;

      dir_dev = stat_buf.st_dev;

      if (opt_one_file_system && !top && last_dev != dir_dev)
	return 0;		/* Don't enter a new file system.  */

#ifndef S_ISDIR
# define S_ISDIR(s) 0
#endif
      /* If we're dereferencing symlinks and we're about to chdir through
	 a symlink, remember the current directory so we can return to it
	 later.  In other cases, chdir ("..") works fine.  */
      through_symlink = (xstat == stat
			 && lstat (ent, &e_buf) == 0
			 && S_ISLNK (e_buf.st_mode));
      if (through_symlink)
	if (save_cwd (&cwd))
	  exit (1);

      if (chdir (ent) < 0)
	{
	  error (0, errno, _("cannot change to directory %s"), path->text);
	  exit_status = 1;
	  return 0;
	}

      errno = 0;
      name_space = savedir (".", stat_buf.st_size);
      if (name_space == NULL)
	{
	  if (errno)
	    {
	      error (0, errno, "%s", path->text);
	      if (through_symlink)
		{
		  if (restore_cwd (&cwd, "..", path->text))
		    exit (1);
		  free_cwd (&cwd);
		}
	      else if (chdir ("..") < 0)
		  error (1, errno, _("cannot change to `..' from directory %s"),
			 path->text);
	      exit_status = 1;
	      return 0;
	    }
	  else
	    error (1, 0, _("virtual memory exhausted"));
	}

      /* Remember the current path.  */

      str_concatc (path, "/");
      pathlen = path->length;

      namep = name_space;
      while (*namep != 0)
	{
	  str_concatc (path, namep);

	  size += count_entry (namep, 0, dir_dev);

	  str_trunc (path, pathlen);
	  namep += strlen (namep) + 1;
	}
      free (name_space);
      if (through_symlink)
	{
	  restore_cwd (&cwd, "..", path->text);
	  free_cwd (&cwd);
	}
      else if (chdir ("..") < 0)
        error (1, errno,
	       _("cannot change to `..' from directory %s"), path->text);

      str_trunc (path, pathlen - 1); /* Remove the "/" we added.  */
      if (!opt_summarize_only || top)
	{
	  if (opt_human_readable)
	    {
	      char buf[LONGEST_HUMAN_READABLE + 1];
	      printf("%s\t%s\n",
		     human_readable (size, buf, LONGEST_HUMAN_READABLE + 1),
		     path->length > 0 ? path->text : "/");
	    }
	  else
	    {
	      printf ("%ld\t%s\n", (output_size == size_bytes
				    ? size
				    : convert_blocks (size, output_size)),
		      path->length > 0 ? path->text : "/");
	    }
	  fflush (stdout);
	}
      return opt_separate_dirs ? 0 : size;
    }
  else if (opt_all || top)
    {
      /* FIXME: make this an option.  */
      int print_only_dir_size = 0;
      if (!print_only_dir_size)
	{
	  if (opt_human_readable)
	    {
	      char buf[LONGEST_HUMAN_READABLE + 1];
	      printf("%s\t%s\n",
		     human_readable (size, buf, LONGEST_HUMAN_READABLE + 1),
		     path->length > 0 ? path->text : "/");
	    }
	  else
	    {
	      printf ("%ld\t%s\n", output_size == size_bytes ? size
		      : convert_blocks (size, output_size),
		      path->text);
	    }
	  fflush (stdout);
	}
    }

  return size;
}
Beispiel #25
0
Datei: mh.c Projekt: hww3/pexts
int mh_check_mailbox(CONTEXT *ctx, int *index_hint)
{
  char buf[_POSIX_PATH_MAX], b1[LONG_STRING], b2[LONG_STRING];
  struct stat st, st_cur;
  short modified = 0, have_new = 0, occult = 0;
  struct maildir *md, *p;
  struct maildir **last;
  HASH *fnames;
  int i, j;
  
  if(!option (OPTCHECKNEW))
    return 0;
  
  if(ctx->magic == M_MH)
  {
    strfcpy(buf, ctx->path, sizeof(buf));
    if(stat(buf, &st) == -1)
      return -1;

    /* create .mh_sequences when there isn't one. */
    snprintf (buf, sizeof (buf), "%s/.mh_sequences", ctx->path);
    if (stat (buf, &st_cur) == -1)
    {
      if (errno == ENOENT)
      {
	char *tmp;
	FILE *fp = NULL;

	if (mh_mkstemp (ctx, &fp, &tmp) == 0)
	{
	  safe_fclose (&fp);
	  if (safe_rename (tmp, buf) == -1)
	    unlink (tmp);
	  safe_free ((void **) &tmp);
	}
	
	if (stat (buf, &st_cur) == -1)
	  modified = 1;
      }
      else
	modified = 1;
    }
  }
  else if(ctx->magic == M_MAILDIR)
  {
    snprintf(buf, sizeof(buf), "%s/new", ctx->path);
    if(stat(buf, &st) == -1)
      return -1;
    
    snprintf(buf, sizeof(buf), "%s/cur", ctx->path);
    if(stat(buf, &st_cur) == -1)			/* XXX - name is bad. */
      modified = 1;

  }
  
  if(!modified && ctx->magic == M_MAILDIR && st_cur.st_mtime > ctx->mtime_cur)
    modified = 1;
  
  if(!modified && ctx->magic == M_MH && (st.st_mtime > ctx->mtime || st_cur.st_mtime > ctx->mtime_cur))
    modified = 1;
  
  if(modified || (ctx->magic == M_MAILDIR && st.st_mtime > ctx->mtime))
    have_new = 1;
  
  if(!modified && !have_new)
    return 0;

  ctx->mtime_cur = st_cur.st_mtime;
  ctx->mtime = st.st_mtime;

#if 0
  if(Sort != SORT_ORDER)
  {
    short old_sort;
    
    old_sort = Sort;
    Sort = SORT_ORDER;
    mutt_sort_headers(ctx, 1);
    Sort = old_sort;
  }
#endif

  md = NULL;
  last = &md;

  if(ctx->magic == M_MAILDIR)
  {
    if(have_new)
      maildir_parse_dir(ctx, &last, "new", NULL);
    if(modified)
      maildir_parse_dir(ctx, &last, "cur", NULL);
  }
  else if(ctx->magic == M_MH)
  {
    struct mh_sequences mhs;
    memset (&mhs, 0, sizeof (mhs));
    maildir_parse_dir (ctx, &last, NULL, NULL);
    mh_read_sequences (&mhs, ctx->path);
    mh_update_maildir (md, &mhs);
    mhs_free_sequences (&mhs);
  }

  /* check for modifications and adjust flags */

  fnames = hash_create (1031);
  
  for(p = md; p; p = p->next)
  {
    if(ctx->magic == M_MAILDIR)
    {
      maildir_canon_filename(b2, p->h->path, sizeof(b2));
      p->canon_fname = safe_strdup(b2);
    }
    else
      p->canon_fname = safe_strdup(p->h->path);
    
    hash_insert(fnames, p->canon_fname, p, 0);
  }

  
  for(i = 0; i < ctx->msgcount; i++)
  {
    ctx->hdrs[i]->active = 0;

    if(ctx->magic == M_MAILDIR)
      maildir_canon_filename(b1, ctx->hdrs[i]->path, sizeof(b1));
    else
      strfcpy(b1, ctx->hdrs[i]->path, sizeof(b1));

    dprint(2, (debugfile, "%s:%d: mh_check_mailbox(): Looking for %s.\n", __FILE__, __LINE__, b1));
    
    if((p = hash_find(fnames, b1)) && p->h &&
       mbox_strict_cmp_headers(ctx->hdrs[i], p->h))
    {
      /* found the right message */

      dprint(2, (debugfile, "%s:%d: Found.  Flags before: %s%s%s%s%s\n", __FILE__, __LINE__,
		 ctx->hdrs[i]->flagged ? "f" : "",
		 ctx->hdrs[i]->deleted ? "D" : "",
		 ctx->hdrs[i]->replied ? "r" : "",
		 ctx->hdrs[i]->old     ? "O" : "",
		 ctx->hdrs[i]->read    ? "R" : ""));

      if(mutt_strcmp(ctx->hdrs[i]->path, p->h->path))
	mutt_str_replace (&ctx->hdrs[i]->path, p->h->path);

      if(modified)
      {
	if(!ctx->hdrs[i]->changed)
	{
	  mutt_set_flag (ctx, ctx->hdrs[i], M_FLAG, p->h->flagged);
	  mutt_set_flag (ctx, ctx->hdrs[i], M_REPLIED, p->h->replied);
	  mutt_set_flag (ctx, ctx->hdrs[i], M_READ, p->h->read);
	}

	mutt_set_flag(ctx, ctx->hdrs[i], M_OLD, p->h->old);
      }

      ctx->hdrs[i]->active = 1;

      dprint(2, (debugfile, "%s:%d:         Flags after: %s%s%s%s%s\n", __FILE__, __LINE__,
		 ctx->hdrs[i]->flagged ? "f" : "",
		 ctx->hdrs[i]->deleted ? "D" : "",
		 ctx->hdrs[i]->replied ? "r" : "",
		 ctx->hdrs[i]->old     ? "O" : "",
		 ctx->hdrs[i]->read    ? "R" : ""));

      mutt_free_header(&p->h);
    }
    else if (ctx->magic == M_MAILDIR && !modified && !strncmp("cur/", ctx->hdrs[i]->path, 4))
    {
      /* If the cur/ part wasn't externally modified for a maildir
       * type folder, assume the message is still active. Actually,
       * we simply don't know.
       */

      ctx->hdrs[i]->active = 1;
    }
    else if (modified || (ctx->magic == M_MAILDIR && !strncmp("new/", ctx->hdrs[i]->path, 4)))
    {
      
      /* Mailbox was modified, or a new message vanished. */

      /* Note: This code will _not_ apply for a new message which
       * is just moved to cur/, as this would modify cur's time
       * stamp and lead to modified == 1.  Thus, we'd have parsed
       * the complete folder above, and the message would have
       * been found in the look-up table.
       */
      
      dprint(2, (debugfile, "%s:%d: Not found.  Flags were: %s%s%s%s%s\n", __FILE__, __LINE__,
		 ctx->hdrs[i]->flagged ? "f" : "",
		 ctx->hdrs[i]->deleted ? "D" : "",
		 ctx->hdrs[i]->replied ? "r" : "",
		 ctx->hdrs[i]->old     ? "O" : "",
		 ctx->hdrs[i]->read    ? "R" : ""));
      
      occult = 1;

    }
  }

  /* destroy the file name hash */

  hash_destroy(&fnames, NULL);

  /* If we didn't just get new mail, update the tables. */
  
  if(modified || occult)
  {
    short old_sort;
    int old_count;

#ifndef LIBMUTT
    if (Sort != SORT_ORDER)
    {
      old_sort = Sort;
      Sort = SORT_ORDER;
      mutt_sort_headers (ctx, 1);
      Sort = old_sort;
    }
#endif
  
    old_count = ctx->msgcount;
    for (i = 0, j = 0; i < old_count; i++)
    {
      if (ctx->hdrs[i]->active && index_hint && *index_hint == i)
	*index_hint = j;

      if (ctx->hdrs[i]->active)
	ctx->hdrs[i]->index = j++;
    }
    mx_update_tables(ctx, 0);
  }

  /* Incorporate new messages */

  maildir_move_to_context(ctx, &md);

  return (modified || occult) ? M_REOPENED : have_new ? M_NEW_MAIL : 0;
}
Beispiel #26
0
/* Add all ZONEs and LINKs in the given directory to the hash table */
void do_zonedir(const char *dir, struct hash_table *tzentries,
		struct zoneinfo *info)
{
    DIR *dirp;
    struct dirent *dirent;

    signals_poll();

    if (verbose) printf("Rebuilding %s\n", dir);

    dirp = opendir(dir);
    if (!dirp) {
	fprintf(stderr, "can't open zoneinfo directory %s\n", dir);
    }

    while ((dirent = readdir(dirp))) {
	char path[2048], *tzid;
	int plen;
	struct stat sbuf;
	struct zoneinfo *zi;

	if (*dirent->d_name == '.') continue;	    

	plen = snprintf(path, sizeof(path), "%s/%s", dir, dirent->d_name);
	lstat(path, &sbuf);

	if (S_ISDIR(sbuf.st_mode)) {
	    /* Path is a directory (region) */
	  do_zonedir(path, tzentries, info);
	}
	else if (S_ISLNK(sbuf.st_mode)) {
	    /* Path is a symlink (alias) */
	    char link[1024], *alias;
	    ssize_t llen;

	    /* Isolate tzid in path */
	    if ((llen = readlink(path, link, sizeof(link))) < 0) continue;
	    link[llen-4] = '\0';  /* Trim ".ics" */
	    for (tzid = link; !strncmp(tzid, "../", 3); tzid += 3);

	    /* Isolate alias in path */
	    path[plen-4] = '\0';  /* Trim ".ics" */
	    alias = path + strlen(config_dir) + strlen("zoneinfo") + 2;

	    if (verbose) printf("\tLINK: %s -> %s\n", alias, tzid);

	    /* Create hash entry for alias */
	    if (!(zi = hash_lookup(alias, tzentries))) {
		zi = xzmalloc(sizeof(struct zoneinfo));
		hash_insert(alias, zi, tzentries);
	    }
	    zi->type = ZI_LINK;
	    appendstrlist(&zi->data, tzid);

	    /* Create/update hash entry for tzid */
	    if (!(zi = hash_lookup(tzid, tzentries))) {
		zi = xzmalloc(sizeof(struct zoneinfo));
		hash_insert(tzid, zi, tzentries);
	    }
	    zi->type = ZI_ZONE;
	    appendstrlist(&zi->data, alias);
	}
	else if (S_ISREG(sbuf.st_mode)) {
	    /* Path is a regular file (zone) */
	    int fd;
	    const char *base = NULL;
	    size_t len = 0;
	    icalcomponent *ical, *comp;
	    icalproperty *prop;

	    /* Parse the iCalendar file for important properties */
	    if ((fd = open(path, O_RDONLY)) == -1) continue;
	    map_refresh(fd, 1, &base, &len, MAP_UNKNOWN_LEN, path, NULL);
	    close(fd);

	    ical = icalparser_parse_string(base);
	    map_free(&base, &len);

	    if (!ical) continue;  /* skip non-iCalendar files */

	    comp = icalcomponent_get_first_component(ical,
						     ICAL_VTIMEZONE_COMPONENT);
	    prop = icalcomponent_get_first_property(comp, ICAL_TZID_PROPERTY);
	    tzid = (char *) icalproperty_get_value_as_string(prop);

	    if (verbose) printf("\tZONE: %s\n", tzid);

	    /* Create/update hash entry for tzid */
	    if (!(zi = hash_lookup(tzid, tzentries))) {
		zi = xzmalloc(sizeof(struct zoneinfo));
		hash_insert(tzid, zi, tzentries);
	    }
	    zi->type = ZI_ZONE;
	    prop = icalcomponent_get_first_property(comp,
						    ICAL_LASTMODIFIED_PROPERTY);
	    zi->dtstamp = icaltime_as_timet(icalproperty_get_lastmodified(prop));

	    icalcomponent_free(ical);

	    /* Check overall lastmod */
	    if (zi->dtstamp > info->dtstamp) info->dtstamp = zi->dtstamp;
	}
	else {
	    fprintf(stderr, "unknown path type %s\n", path);
	}
    }

    closedir(dirp);
}
Beispiel #27
0
static int
startElement_HOST(void *data, const char *el, const char **attr)
{
    xmldata_t *xmldata = (xmldata_t *)data;
    datum_t *hash_datum = NULL;
    datum_t *rdatum;
    datum_t hashkey, hashval;
    struct xml_tag *xt;
    uint32_t tn=0;
    uint32_t tmax=0;
    uint32_t reported=0;
    const char *name = NULL;
    int edge;
    int i;
    Host_t *host;
    hash_t *hosts;

    /* Check if the host is up. */
    for (i = 0; attr[i]; i+=2)
    {
        xt = in_xml_list (attr[i], strlen(attr[i]));
        if (!xt) continue;

        if (xt->tag == REPORTED_TAG)
            reported = strtoul(attr[i+1], (char **)NULL, 10);
        else if (xt->tag == TN_TAG)
            tn = atoi(attr[i+1]);
        else if (xt->tag == TMAX_TAG)
            tmax = atoi(attr[i+1]);
        else if (xt->tag == NAME_TAG)
            name = attr[i+1];
    }

    /* Is this host alive? For pre-2.5.0, we use the 60-second
     * method, otherwise we use the host's TN and TMAX attrs.
     */
    xmldata->host_alive = (xmldata->old || !tmax) ?
                          abs(xmldata->source.localtime - reported) < 60 :
                          tn < tmax * 4;

    if (xmldata->host_alive)
        xmldata->source.hosts_up++;
    else
        xmldata->source.hosts_down++;

    /* Only keep host details if we are the authority on this cluster. */
    if (!authority_mode(xmldata))
        return 0;

    host = &(xmldata->host);

    /* Use node Name for hash key (Query processing
     * requires a name key).
     */
    xmldata->hostname = realloc(xmldata->hostname, strlen(name)+1);
    strcpy(xmldata->hostname, name);

    /* Convert name to lower case - host names can't be
     * case sensitive
     */
    /*for(i = 0; name[i] != 0; i++)
        xmldata->hostname[i] = tolower(name[i]);
    xmldata->hostname[i] = 0; */

    hashkey.data = (void*) name;
    hashkey.size =  strlen(name) + 1;

    hosts = xmldata->source.authority;
    hash_datum = hash_lookup (&hashkey, hosts);
    if (!hash_datum)
    {
        memset((void*) host, 0, sizeof(*host));

        host->id = HOST_NODE;
        host->report_start = host_report_start;
        host->report_end = host_report_end;

        /* Only create one hash table for the host's metrics. Not user/builtin
         * like gmond. */
        host->metrics = hash_create(DEFAULT_METRICSIZE);
        if (!host->metrics)
        {
            err_msg("Could not create metric hash for host %s", name);
            return 1;
        }
    }
    else
    {
        /* Copy the stored host data into our Host buffer in xmldata. */
        memcpy(host, hash_datum->data, hash_datum->size);
        datum_free(hash_datum);
    }

    /* Edge has the same invariant as in fillmetric(). */
    edge = 0;

    host->location = -1;
    host->tags = -1;
    host->reported = reported;
    host->tn = tn;
    host->tmax = tmax;
    /* sacerdoti: Host TN tracks what gmond sees. TN=0 when gmond received last
     * heartbeat from node. Works because clocks move at same speed, and TN is
     * a relative timespan. */
    host->t0 = xmldata->now;
    host->t0.tv_sec -= host->tn;

    /* We will store this host in the cluster's authority table. */
    for(i = 0; attr[i]; i+=2)
    {
        xt = in_xml_list (attr[i], strlen(attr[i]));
        if (!xt) continue;

        switch( xt->tag )
        {
        case IP_TAG:
            host->ip = addstring(host->strings, &edge, attr[i+1]);
            break;
        case DMAX_TAG:
            host->dmax = strtoul(attr[i+1], (char **)NULL, 10);
            break;
        case LOCATION_TAG:
            host->location = addstring(host->strings, &edge, attr[i+1]);
            break;
        case TAGS_TAG:
            host->tags = addstring(host->strings, &edge, attr[i+1]);
            break;
        case STARTED_TAG:
            host->started = strtoul(attr[i+1], (char **)NULL, 10);
            break;
        default:
            break;
        }
    }
    host->stringslen = edge;

    /* Trim structure to the correct length. */
    hashval.size = sizeof(*host) - GMETAD_FRAMESIZE + host->stringslen;
    hashval.data = host;

    /* We dont care if this is an insert or an update. */
    rdatum = hash_insert(&hashkey, &hashval, hosts);
    if (!rdatum) {
        err_msg("Could not insert host %s", name);
        return 1;
    }
    return 0;
}
Beispiel #28
0
int main(int argc, char **argv)
{
    int opt, r = 0;
    char *alt_config = NULL, *pub = NULL, *ver = NULL, *winfile = NULL;
    char prefix[2048];
    enum { REBUILD, WINZONES, NONE } op = NONE;

    if ((geteuid()) == 0 && (become_cyrus(/*ismaster*/0) != 0)) {
	fatal("must run as the Cyrus user", EC_USAGE);
    }

    while ((opt = getopt(argc, argv, "C:r:vw:")) != EOF) {
	switch (opt) {
	case 'C': /* alt config file */
	    alt_config = optarg;
	    break;

	case 'r':
	    if (op == NONE) {
		op = REBUILD;
		pub = optarg;
		ver = strchr(optarg, ':');
		if (ver) *ver++ = '\0';
		else usage();
	    }
	    else usage();
	    break;

	case 'v':
	    verbose = 1;
	    break;

	case 'w':
	    if (op == NONE) {
		op = WINZONES;
		winfile = optarg;
	    }
	    else usage();
	    break;

	default:
	    usage();
	}
    }

    cyrus_init(alt_config, "ctl_zoneinfo", 0, 0);

    signals_set_shutdown(&shut_down);
    signals_add_handlers(0);

    snprintf(prefix, sizeof(prefix), "%s%s", config_dir, FNAME_ZONEINFODIR);

    switch (op) {
    case REBUILD: {
	struct hash_table tzentries;
	struct zoneinfo *info;
	struct txn *tid = NULL;
	char buf[1024];
	FILE *fp;

	construct_hash_table(&tzentries, 500, 1);

	/* Add INFO record (overall lastmod and TZ DB source version) */
	info = xzmalloc(sizeof(struct zoneinfo));
	info->type = ZI_INFO;
	appendstrlist(&info->data, pub);
	appendstrlist(&info->data, ver);
	hash_insert(INFO_TZID, info, &tzentries);

	/* Add LEAP record (last updated and hash) */
	snprintf(buf, sizeof(buf), "%s%s", prefix, FNAME_LEAPSECFILE);
	if (verbose) printf("Processing leap seconds file %s\n", buf);
	if (!(fp = fopen(buf, "r"))) {
	    fprintf(stderr, "Could not open leap seconds file %s\n", buf);
	}
	else {
	    struct zoneinfo *leap = xzmalloc(sizeof(struct zoneinfo));
	    leap->type = ZI_INFO;

	    while(fgets(buf, sizeof(buf), fp)) {
		if (buf[0] == '#') {
		    /* comment line */

		    if (buf[1] == '$') {
			/* last updated */
			unsigned long last;

			sscanf(buf+2, "\t%lu", &last);
			leap->dtstamp = last - NIST_EPOCH_OFFSET;
		    }
		    else if (buf[1] == 'h') {
			/* hash */
			char *p, *hash = buf+3 /* skip "#h\t" */;

			/* trim trailing whitespace */
			for (p = hash + strlen(hash); isspace(*--p); *p = '\0');
			appendstrlist(&leap->data, hash);
		    }
		}
	    }
	    fclose(fp);

	    hash_insert(LEAP_TZID, leap, &tzentries);
	    info->dtstamp = leap->dtstamp;
	}

	/* Add ZONE/LINK records */
	do_zonedir(prefix, &tzentries, info);

	zoneinfo_open(NULL);

	/* Store records */
	hash_enumerate(&tzentries, &store_zoneinfo, &tid);

	zoneinfo_close(tid);

	free_hash_table(&tzentries, &free_zoneinfo);
	break;
    }

    case WINZONES: {
	xmlParserCtxtPtr ctxt;
	xmlDocPtr doc;
	xmlNodePtr node;
	struct buf tzidbuf = BUF_INITIALIZER;
	struct buf aliasbuf = BUF_INITIALIZER;

	if (verbose) printf("Processing Windows Zone file %s\n", winfile);

	/* Parse the XML file */
	ctxt = xmlNewParserCtxt();
	if (!ctxt) {
	    fprintf(stderr, "Failed to create XML parser context\n");
	    break;
	}

	doc = xmlCtxtReadFile(ctxt, winfile, NULL, 0);
	xmlFreeParserCtxt(ctxt);
	if (!doc) {
	    fprintf(stderr, "Failed to parse XML document\n");
	    break;
	}

	node = xmlDocGetRootElement(doc);
	if (!node || xmlStrcmp(node->name, BAD_CAST "supplementalData")) {
	    fprintf(stderr, "Incorrect root node\n");
	    goto done;
	}

	for (node = xmlFirstElementChild(node);
	     node && xmlStrcmp(node->name, BAD_CAST "windowsZones");
	     node = xmlNextElementSibling(node));
	if (!node) {
	    fprintf(stderr, "Missing windowsZones node\n");
	    goto done;
	}

	node = xmlFirstElementChild(node);
	if (!node || xmlStrcmp(node->name, BAD_CAST "mapTimezones")) {
	    fprintf(stderr, "Missing mapTimezones node\n");
	    goto done;
	}

	if (chdir(prefix)) {
	    fprintf(stderr, "chdir(%s) failed\n", prefix);
	    goto done;
	}

	for (node = xmlFirstElementChild(node);
	     node;
	     node = xmlNextElementSibling(node)) {
	    if (!xmlStrcmp(node->name, BAD_CAST "mapZone") &&
		!xmlStrcmp(xmlGetProp(node, BAD_CAST "territory"),
			   BAD_CAST "001")) {
		const char *tzid, *alias;

		buf_setcstr(&tzidbuf,
			    (const char *) xmlGetProp(node, BAD_CAST "type"));
		buf_appendcstr(&tzidbuf, ".ics");
		tzid = buf_cstring(&tzidbuf);
		buf_setcstr(&aliasbuf,
			    (const char *) xmlGetProp(node, BAD_CAST "other"));
		buf_appendcstr(&aliasbuf, ".ics");
		alias = buf_cstring(&aliasbuf);

		if (verbose) printf("\tLINK: %s -> %s\n", alias, tzid);

		if (symlink(tzid, alias)) {
		    if (errno == EEXIST) {
			struct stat sbuf;

			if (stat(alias, &sbuf)) {
			    fprintf(stderr, "stat(%s) failed: %s\n",
				    alias, strerror(errno));
			    errno = EEXIST;
			}
			else if (sbuf.st_mode & S_IFLNK) {
			    char link[MAX_MAILBOX_PATH+1];
			    int n = readlink(alias, link, MAX_MAILBOX_PATH);

			    if (n == -1) {
				fprintf(stderr, "readlink(%s) failed: %s\n",
					alias, strerror(errno));
				errno = EEXIST;
			    }
			    else if (n == (int) strlen(tzid) &&
				     !strncmp(tzid, link, n)) {
				errno = 0;
			    }
			}
		    }

		    if (errno) {
			fprintf(stderr, "symlink(%s, %s) failed: %s\n",
				tzid, alias, strerror(errno));
		    }
		}
	    }
	}

  done:
	buf_free(&aliasbuf);
	buf_free(&tzidbuf);
	xmlFreeDoc(doc);
	break;
    }

    case NONE:
	r = 2;
	usage();
	break;
    }

    cyrus_done();

    return r;
}
Beispiel #29
0
/* XXX - There is an issue which will cause a failure if there are more than 16
  EXTRA_ELEMENTs.  This is a problem with the size of the data structure that
  is used to hold the metric information.
*/
static int
startElement_EXTRA_ELEMENT (void *data, const char *el, const char **attr)
{
    xmldata_t *xmldata = (xmldata_t *)data;
    int edge;
    struct xml_tag *xt;
    int i, name_off, value_off;
    Metric_t metric;
    char *name = getfield(xmldata->metric.strings, xmldata->metric.name);
    datum_t *rdatum;
    datum_t hashkey, hashval;
    datum_t *hash_datum = NULL;

    if (!xmldata->host_alive)
        return 0;

    /* Only keep extra element details if we are the authority on this cluster. */
    if (!authority_mode(xmldata))
        return 0;

    hashkey.data = (void*) name;
    hashkey.size =  strlen(name) + 1;

    hash_datum = hash_lookup (&hashkey, xmldata->host.metrics);
    if (!hash_datum)
        return 0;

    memcpy(&metric, hash_datum->data, hash_datum->size);
    datum_free(hash_datum);

    /* Check to make sure that we don't try to add more
        extra elements than the array can handle.
    */
    if (metric.ednameslen >= MAX_EXTRA_ELEMENTS)
    {
        debug_msg("Can not add more extra elements for [%s].  Capacity of %d reached[%s].",
                  name, MAX_EXTRA_ELEMENTS);
        return 0;
    }

    edge = metric.stringslen;

    name_off = value_off = -1;
    for(i = 0; attr[i]; i+=2)
    {
        xt = in_xml_list(attr[i], strlen(attr[i]));
        if (!xt)
            continue;
        switch (xt->tag)
        {
        case NAME_TAG:
            name_off = i;
            break;
        case VAL_TAG:
            value_off = i;
            break;
        default:
            break;
        }
    }

    if ((name_off >= 0) && (value_off >= 0))
    {
        const char *new_name = attr[name_off+1];
        const char *new_value = attr[value_off+1];

        metric.ednames[metric.ednameslen++] = addstring(metric.strings, &edge, new_name);
        metric.edvalues[metric.edvalueslen++] = addstring(metric.strings, &edge, new_value);

        metric.stringslen = edge;

        hashkey.data = (void*)name;
        hashkey.size =  strlen(name) + 1;

        /* Trim metric structure to the correct length. */
        hashval.size = sizeof(metric) - GMETAD_FRAMESIZE + metric.stringslen;
        hashval.data = (void*) &metric;

        /* Update full metric in cluster host table. */
        rdatum = hash_insert(&hashkey, &hashval, xmldata->host.metrics);
        if (!rdatum)
        {
            err_msg("Could not insert %s metric", name);
        }
        else
        {
            hash_t *summary = xmldata->source.metric_summary;
            Metric_t sum_metric;

            /* do not add every SPOOF_HOST element to the summary table.
               if the same metric is SPOOF'd on more than ~MAX_EXTRA_ELEMENTS hosts
               then its summary table is destroyed.
             */
            if ( strlen(new_name) == 10 && !strcasecmp(new_name, SPOOF_HOST) )
                return 0;

            /* only update summary if metric is in hash */
            hash_datum = hash_lookup(&hashkey, summary);

            if (hash_datum) {
                int found = FALSE;

                memcpy(&sum_metric, hash_datum->data, hash_datum->size);
                datum_free(hash_datum);

                for (i = 0; i < sum_metric.ednameslen; i++) {
                    char *chk_name = getfield(sum_metric.strings, sum_metric.ednames[i]);
                    char *chk_value = getfield(sum_metric.strings, sum_metric.edvalues[i]);

                    /* If the name and value already exists, skip adding the strings. */
                    if (!strcasecmp(chk_name, new_name) && !strcasecmp(chk_value, new_value)) {
                        found = TRUE;
                        break;
                    }
                }
                if (!found) {
                    edge = sum_metric.stringslen;
                    sum_metric.ednames[sum_metric.ednameslen++] = addstring(sum_metric.strings, &edge, new_name);
                    sum_metric.edvalues[sum_metric.edvalueslen++] = addstring(sum_metric.strings, &edge, new_value);
                    sum_metric.stringslen = edge;
                }

                /* Trim graph display sum_metric at (352, 208) now or when in startElement_EXTRA_ELEMENT
                metric structure to the correct length. Tricky. */
                hashval.size = sizeof(sum_metric) - GMETAD_FRAMESIZE + sum_metric.stringslen;
                hashval.data = (void*) &sum_metric;

                /* Update metric in summary table. */
                rdatum = hash_insert(&hashkey, &hashval, summary);
                if (!rdatum)
                    err_msg("Could not insert summary %s metric", name);
            }
        }
    }

    return 0;
}
Beispiel #30
0
static int pipefs_mount(fs_cookie *_fs, fs_id id, const char *pipefs, void *args, vnode_id *root_vnid)
{
	struct pipefs *fs;
	struct pipefs_vnode *v;
	struct pipefs_vnode *anon_v;
	int err;

	TRACE(("pipefs_mount: entry\n"));

	if(thepipefs) {
		dprintf("double mount of pipefs attempted\n");
		err = ERR_GENERAL;
		goto err;
	}

	fs = kmalloc(sizeof(struct pipefs));
	if(fs == NULL) {
		err = ERR_NO_MEMORY;
		goto err;
	}

	fs->id = id;
	fs->next_vnode_id = 0;

	err = mutex_init(&fs->hash_lock, "pipefs_mutex");
	if(err < 0) {
		goto err1;
	}

	fs->vnode_list_hash = hash_init(PIPEFS_HASH_SIZE, offsetof(struct pipefs_vnode, all_next),
		&pipefs_vnode_compare_func, &pipefs_vnode_hash_func);
	if(fs->vnode_list_hash == NULL) {
		err = ERR_NO_MEMORY;
		goto err2;
	}

	// create a vnode
	v = pipefs_create_vnode(fs, "", STREAM_TYPE_DIR);
	if(v == NULL) {
		err = ERR_NO_MEMORY;
		goto err3;
	}

	// set it up
	v->parent = v;

	fs->root_vnode = v;

	hash_insert(fs->vnode_list_hash, v);

	*root_vnid = v->id;
	*_fs = fs;

	// create the anonymous pipe
	anon_v = pipefs_create_vnode(fs, "anon", STREAM_TYPE_PIPE);
	if(anon_v == NULL) {
		err = ERR_NO_MEMORY;
		goto err4;
	}

	// set it up
	anon_v->parent = v;
	fs->anon_vnode = anon_v;

	hash_insert(fs->vnode_list_hash, anon_v);
	mutex_lock(&v->stream.u.dir.dir_lock);
	pipefs_insert_in_dir(v, anon_v);
	mutex_unlock(&v->stream.u.dir.dir_lock);

	thepipefs = fs;

	return 0;

err4:
	pipefs_delete_vnode(fs, v, true);
err3:
	hash_uninit(fs->vnode_list_hash);
err2:
	mutex_destroy(&fs->hash_lock);
err1:
	kfree(fs);
err:
	return err;
}