Example #1
0
/*
 * Do things necessary before run()'ing, such as -I substitution,
 * and then call run().
 */
static void
prerun(int argc, char *argv[])
{
	char **tmp, **tmp2, **avj;
	int repls;

	repls = Rflag;

	if (argc == 0 || repls == 0) {
		*xp = NULL;
		run(argv);
		return;
	}

	avj = argv;

	/*
	 * Allocate memory to hold the argument list, and
	 * a NULL at the tail.
	 */
	tmp = malloc((argc + 1) * sizeof(char**));
	if (tmp == NULL)
		errx(1, "malloc failed");
	tmp2 = tmp;

	/*
	 * Save the first argument and iterate over it, we
	 * cannot do strnsubst() to it.
	 */
	if ((*tmp++ = strdup(*avj++)) == NULL)
		errx(1, "strdup failed");

	/*
	 * For each argument to utility, if we have not used up
	 * the number of replacements we are allowed to do, and
	 * if the argument contains at least one occurrence of
	 * replstr, call strnsubst(), else just save the string.
	 * Iterations over elements of avj and tmp are done
	 * where appropriate.
	 */
	while (--argc) {
		*tmp = *avj++;
		if (repls && strstr(*tmp, replstr) != NULL) {
			strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
			if (repls > 0)
				repls--;
		} else {
			if ((*tmp = strdup(*tmp)) == NULL)
				errx(1, "strdup failed");
			tmp++;
		}
	}

	/*
	 * Run it.
	 */
	*tmp = NULL;
	run(tmp2);

	/*
	 * Walk from the tail to the head, free along the way.
	 */
	for (; tmp2 != tmp; tmp--)
		free(*tmp);
	/*
	 * Now free the list itself.
	 */
	free(tmp2);

	/*
	 * Free the input line buffer, if we have one.
	 */
	if (inpline != NULL) {
		free(inpline);
		inpline = NULL;
	}
}
Example #2
0
static char *get_protocol_scheme(char const **s, unsigned int *err_out) {

    *err_out = UPARSE_ERROR;

    if (NULL == *s) {
        fprintf(stderr,"input s is null\n");
        return NULL;
    }

    // Local copy we can advance.
    char const *c = *s;

    // Choose a sensible limit for a scheme.
    size_t const max_scheme_len = 16;
    char scheme[max_scheme_len+1];
    memset(&scheme[0], 0, sizeof(scheme));

    size_t j = 0;

    bool seen_prefix = false;

    // Copy alpha characters preceeding the ':'
    while (*c) {
        if (SCHEME_DELIM_PREFIX == c[0]) {
            seen_prefix = true;
            // Advance past SCHEME_DELIM_PREFIX, c should be pointing at a SCHEME_SLASH now.
            c++;
            break;
        } else if (!isalpha(*c)) {
            fprintf(stderr,"'%c' is invalid\n",*c);
            return NULL;
        } else if (max_scheme_len == j) {
            fprintf(stderr,"scheme exceeds max scheme len %lu\n",max_scheme_len);
            return NULL;
        } else {
            scheme[j] = c[0];
        }
        c++;
        j++;
    }

    if (!seen_prefix) {
        fprintf(stderr,"no scheme delimiter prefix '%c' found\n",SCHEME_DELIM_PREFIX);
        return NULL;
    }

    // No scheme was found.
    if (0 == j) {
        fprintf(stderr,"no scheme was found\n");
        return NULL;
    }

    // Look for the slashes after SCHEME_DELIM_PREFIX.
    bool seen_slash = false;
    while (*c) {
        if (SCHEME_SLASH == c[0]) {
            seen_slash = true;
            c++;
        } else {
            break;
        }
    }

    if (!seen_slash) {
        fprintf(stderr,"no scheme slash '%c' found\n",SCHEME_SLASH);
        return NULL;
    }

    // Advance pointer past all of the scheme chars and delims.
    *s = c;

    scheme[j] = '\0';
    *err_out = NO_UPARSE_ERROR;
    return strdup(scheme);
}
Example #3
0
int
gluster_put (glfs_t *fs, struct state *state)
{
        int ret = -1;
        glfs_fd_t *fd = NULL;
        char *filename = state->gluster_url->path;
        char *dir_path = strdup (state->gluster_url->path);
        struct stat statbuf;

        if (dir_path == NULL) {
                error (EXIT_FAILURE, errno, "strdup");
                goto out;
        }

        ret = glfs_lstat (fs, filename, &statbuf);
        if (ret != -1 && !state->append && !state->overwrite) {
                errno = EEXIST;
                ret = -1;
                goto out;
        }

        if (state->parents) {
                ret = gluster_create_path (fs, dir_path,
                                get_default_dir_mode_perm ());
                if (ret == -1) {
                        goto out;
                }
        }

        fd = glfs_creat (fs, filename, O_RDWR, get_default_file_mode_perm ());
        if (fd == NULL) {
                ret = -1;
                goto out;
        }

        ret = gluster_lock (fd, F_WRLCK, false);
        if (ret == -1) {
                goto out;
        }

        if (state->append) {
                ret = glfs_lseek (fd, 0, SEEK_END);
                if (ret == -1) {
                        error (0, errno, "seek error: %s", filename);
                        goto out;
                }
        } else {
                ret = glfs_ftruncate (fd, 0);
                if (ret == -1) {
                        error (0, errno, "truncate error: %s", filename);
                        goto out;
                }
        }

        if (gluster_write (STDIN_FILENO, fd) == 0) {
                ret = -1;
        }

out:
        free (dir_path);

        if (fd) {
                glfs_close (fd);
        }

        return ret;
}
Example #4
0
void
parse_options (int argc, char *argv[])
{
        uint16_t port = GLUSTER_DEFAULT_PORT;
        int ret = -1;
        int opt = 0;
        int option_index = 0;
        struct xlator_option *option;

        while (true) {
                opt = getopt_long (argc, argv, "adfo:p:r", long_options,
                                   &option_index);

                if (opt == -1) {
                        break;
                }

                switch (opt) {
                        case 'a':
                                state->append = true;
                                break;
                        case 'd':
                                state->debug = true;
                                break;
                        case 'f':
                                state->overwrite = true;
                                break;
                        case 'o':
                                option = parse_xlator_option (optarg);
                                if (option == NULL) {
                                        error (0, errno, "%s", optarg);
                                        goto err;
                                }

                                if (append_xlator_option (&state->xlator_options, option) == -1) {
                                        error (EXIT_FAILURE, errno, "append_xlator_option: %s", optarg);
                                }

                                break;
                        case 'p':
                                port = strtoport (optarg);
                                if (port == 0) {
                                        exit (EXIT_FAILURE);
                                }

                                break;
                        case 'r':
                                state->parents = true;
                                break;
                        case 'v':
                                printf ("%s (%s) %s\n%s\n%s\n%s\n",
                                        program_invocation_name,
                                        PACKAGE_NAME,
                                        PACKAGE_VERSION,
                                        COPYRIGHT,
                                        LICENSE,
                                        AUTHORS);
                                exit (EXIT_SUCCESS);
                        case 'x':
                                usage (EXIT_SUCCESS);
                        default:
                                goto err;
                }
        }

        if ((argc - option_index) < 2) {
                error (0, 0, "missing operand");
                goto err;
        } else {
                state->url = strdup (argv[argc - 1]);
                if (state->url == NULL) {
                        error (0, errno, "strdup");
                        goto out;
                }

                ret = gluster_parse_url (argv[argc - 1], &(state->gluster_url));
                if (ret == -1) {
                        error (0, EINVAL, "%s", state->url);
                        goto err;
                }

                state->gluster_url->port = port;
        }

        goto out;

err:
        error (EXIT_FAILURE, 0, "Try --help for more information.");
out:
        return;
}
int newtOpenWindow(int left, int top, int width, int height,
			  const char * title) {
    int j, row, col;
    int n;
    int i;

    newtFlushInput();

    if (!currentWindow) {
	currentWindow = windowStack;
    } else {
	currentWindow++;
    }

    currentWindow->left = left;
    currentWindow->top = top;
    currentWindow->width = width;
    currentWindow->height = height;
    currentWindow->title = title ? strdup(title) : NULL;

    currentWindow->buffer = malloc(sizeof(SLsmg_Char_Type) * (width + 3) * (height + 3));

    row = top - 1;
    col = left - 1;
    /* clip to the current screen bounds - msw */
    if (row < 0)
	row = 0;
    if (col < 0)
	col = 0;
    if (left + width > SLtt_Screen_Cols)
	width = SLtt_Screen_Cols - left;
    if (top + height > SLtt_Screen_Rows)
	height = SLtt_Screen_Rows - top;
    n = 0;
    for (j = 0; j < height + 3; j++, row++) {
	SLsmg_gotorc(row, col);
	SLsmg_read_raw(currentWindow->buffer + n,
		       currentWindow->width + 3);
	n += currentWindow->width + 3;
    }

    newtTrashScreen();

    SLsmg_set_color(NEWT_COLORSET_BORDER);
    SLsmg_draw_box(top - 1, left - 1, height + 2, width + 2);

    if (currentWindow->title) {
	i = wstrlen(currentWindow->title,-1) + 4;
	i = ((width - i) / 2) + left;
	SLsmg_gotorc(top - 1, i);
	SLsmg_set_char_set(1);
	SLsmg_write_char(SLSMG_RTEE_CHAR);
	SLsmg_set_char_set(0);
	SLsmg_write_char(' ');
	SLsmg_set_color(NEWT_COLORSET_TITLE);
	SLsmg_write_string((char *)currentWindow->title);
	SLsmg_set_color(NEWT_COLORSET_BORDER);
	SLsmg_write_char(' ');
	SLsmg_set_char_set(1);
	SLsmg_write_char(SLSMG_LTEE_CHAR);
	SLsmg_set_char_set(0);
    }

    SLsmg_set_color(NEWT_COLORSET_WINDOW);
    SLsmg_fill_region(top, left, height, width, ' ');

    SLsmg_set_color(NEWT_COLORSET_SHADOW);
    SLsmg_fill_region(top + height + 1, left, 1, width + 2, ' ');
    SLsmg_fill_region(top, left + width + 1, height + 1, 1, ' ');

    for (i = top; i < (top + height + 1); i++) {
	SLsmg_gotorc(i, left + width + 1);
	SLsmg_write_string(" ");
    }

    return 0;
}
Example #6
0
/**
 * Add a generic link (input or output) to a container
 */
mjrlink_t	*mjr_container_add_link(mjrcontext_t	*ctx,
					container_t	*cntnr,
					unsigned int	id,
					u_char		link_type,
					u_char		link_scope,
					int		link_direction)
{
  list_t	*linklist;
  listent_t	*listent;
  listent_t	*savednext;
  mjrlink_t	*link;
  container_t	*cnt;
  char		linkname[BUFSIZ];

  PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);

#if __DEBUG_CNTNR__
  if (cntnr->id == id)
    fprintf(D_DESC, "[D] %s: linking the same container id:%d\n",
	    __FUNCTION__, id);
#endif

  /* Check if we are linked with container id by other link type */
  linklist = mjr_link_get_by_direction(cntnr, link_direction);
  for (listent = linklist->head; listent; listent = savednext)
    {
      link      = (mjrlink_t *) listent->data;
      cnt       = ctx->reg_containers[link->id];
      savednext = listent->next;

      if (cnt->type == cntnr->type && link->id == id)
	{

#if __DEBUG_CNTNR__
	  fprintf(D_DESC, "[D] %s: already linked with id:%d type:%d/%d\n",
		  __FUNCTION__, id, link->type, link_type);
#endif

	  if (link->type == link_type)
	    {

#if __DEBUG_CNTNR__
	      fprintf(D_DESC,"[D] %s: return existing link id:%d\n", __FUNCTION__, id);
#endif

	      PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, link);
	    }

	  else if ((link->type == MJR_LINK_BLOCK_COND_ALWAYS) &&
		   ((link_type == MJR_LINK_BLOCK_COND_TRUE) ||
		    (link_type == MJR_LINK_BLOCK_COND_FALSE)))
	    {

#if __DEBUG_CNTNR__
	      fprintf(D_DESC,"[D] %s: removing old unconditional link id:%d for condlink type %d\n",
		      __FUNCTION__, id, link_type);
#endif

	      elist_del(linklist, listent->key);
	    }
	}
    }

#if __DEBUG_CNTNR__
  fprintf(D_DESC,"[D] %s: link id:%d -> id:%d type:%d dir:%d\n",
	  __FUNCTION__, cntnr->id, id, link_type, link_direction);
#endif

  /* Create and add the new link */
  XALLOC(__FILE__, __FUNCTION__, __LINE__, link, sizeof(mjrlink_t), NULL);
  link->id   = id;
  link->type = link_type;
  link->scope = link_scope;
  snprintf(linkname, sizeof(linkname), "%u_%u", cntnr->id, id);
  elist_add(linklist, strdup(linkname), link);
  hash_add(&ctx->linkhash, strdup(linkname), link);
  PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, link);
}
Example #7
0
File: dfs_test.c Project: ORNL/ompi
static void process_opens(int fd, short args, void *cbdata)
{
    orte_dfs_request_t *dfs = (orte_dfs_request_t*)cbdata;
    int rc;
    opal_buffer_t *buffer;
    char *scheme, *host, *filename, *hostname;
    orte_process_name_t daemon;
    bool found;
    orte_vpid_t v;
    opal_list_t myvals;
    opal_value_t *kv;

    opal_output(0, "%s PROCESSING OPEN", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));
    /* get the scheme to determine if we can process locally or not */
    if (NULL == (scheme = opal_uri_get_scheme(dfs->uri))) {
        ORTE_ERROR_LOG(ORTE_ERR_BAD_PARAM);
        goto complete;
    }
    opal_output(0, "%s GOT SCHEME", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));

    if (0 != strcmp(scheme, "file")) {
        /* not yet supported */
        orte_show_help("orte_dfs_help.txt", "unsupported-filesystem",
                       true, dfs->uri);
        goto complete;
    }

    /* dissect the uri to extract host and filename/path */
    if (NULL == (filename = opal_filename_from_uri(dfs->uri, &host))) {
        goto complete;
    }
    opal_output(0, "%s GOT FILENAME %s", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), filename);
    if (NULL == host) {
        host = strdup(orte_process_info.nodename);
    }

    /* ident the daemon on that host */
    daemon.jobid = ORTE_PROC_MY_DAEMON->jobid;
    found = false;
    for (v=0; v < orte_process_info.num_daemons; v++) {
        daemon.vpid = v;
        /* fetch the hostname where this daemon is located */
        OBJ_CONSTRUCT(&myvals, opal_list_t);
        if (ORTE_SUCCESS != (rc = opal_dstore.fetch(opal_dstore_internal,
                                                    &daemon,
                                                    OPAL_DSTORE_HOSTNAME, &myvals))) {
            ORTE_ERROR_LOG(rc);
            OPAL_LIST_DESTRUCT(&myvals);
            goto complete;
        }
        kv = (opal_value_t*)opal_list_get_first(&myvals);
        hostname = strdup(kv->data.string);
        OPAL_LIST_DESTRUCT(&myvals);
        opal_output(0, "%s GOT HOST %s HOSTNAME %s", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), host, hostname);
        if (0 == strcmp(host, hostname)) {
            found = true;
            break;
        }
    }
    if (!found) {
        ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
        goto complete;
    }
    opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                        "%s file %s on host %s daemon %s",
                        ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                        filename, host, ORTE_NAME_PRINT(&daemon));

    /* add this request to our local list so we can
     * match it with the returned response when it comes
     */
    dfs->id = req_id++;
    opal_list_append(&requests, &dfs->super);

    /* setup a message for the daemon telling
     * them what file we want to access
     */
    buffer = OBJ_NEW(opal_buffer_t);
    if (OPAL_SUCCESS != (rc = opal_dss.pack(buffer, &dfs->cmd, 1, ORTE_DFS_CMD_T))) {
        ORTE_ERROR_LOG(rc);
        opal_list_remove_item(&requests, &dfs->super);
        goto complete;
    }
    /* pass the request id */
    if (OPAL_SUCCESS != (rc = opal_dss.pack(buffer, &dfs->id, 1, OPAL_UINT64))) {
        ORTE_ERROR_LOG(rc);
        opal_list_remove_item(&requests, &dfs->super);
        goto complete;
    }
    if (OPAL_SUCCESS != (rc = opal_dss.pack(buffer, &filename, 1, OPAL_STRING))) {
        ORTE_ERROR_LOG(rc);
        opal_list_remove_item(&requests, &dfs->super);
        goto complete;
    }
    
    opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                        "%s sending open file request to %s file %s",
                        ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                        ORTE_NAME_PRINT(&daemon),
                        filename);
    /* send it */
    if (0 > (rc = orte_rml.send_buffer_nb(&daemon, buffer,
                                          ORTE_RML_TAG_DFS_CMD,
                                          orte_rml_send_callback, NULL))) {
        ORTE_ERROR_LOG(rc);
        OBJ_RELEASE(buffer);
        opal_list_remove_item(&requests, &dfs->super);
        goto complete;
    }
    /* don't release it */
    return;

 complete:
    /* we get here if an error occurred - execute any
     * pending callback so the proc doesn't hang
     */
    if (NULL != dfs->open_cbfunc) {
        dfs->open_cbfunc(-1, dfs->cbdata);
    }
    OBJ_RELEASE(dfs);
}
Example #8
0
/*
 * Getent implements the functions of cgetent.  If fd is non-negative,
 * *db_array has already been opened and fd is the open file descriptor.  We
 * do this to save time and avoid using up file descriptors for tc=
 * recursions.
 *
 * Getent returns the same success/failure codes as cgetent.  On success, a
 * pointer to a malloc'ed capability record with all tc= capabilities fully
 * expanded and its length (not including trailing ASCII NUL) are left in
 * *cap and *len.
 *
 * Basic algorithm:
 *	+ Allocate memory incrementally as needed in chunks of size BFRAG
 *	  for capability buffer.
 *	+ Recurse for each tc=name and interpolate result.  Stop when all
 *	  names interpolated, a name can't be found, or depth exceeds
 *	  MAX_RECURSION.
 */
static int getent(char **cap, char **db_array, char *nfield, const char *name, size_t *len, int fd, int depth)
{
	DB *capdbp = NULL;
	char *r_end, *rp = NULL, **db_p;	/* pacify gcc */
	int myfd = 0, eof, foundit, retval;
	size_t clen;
	char *record, *cbuf, *newrecord;
	int tc_not_resolved;
	char pbuf[MAXPATHLEN];

	assert(cap != NULL);
	assert(len != NULL);
	assert(db_array != NULL);
	/* fd may be -1 */
	assert(name != NULL);
	/* nfield may be NULL */

	/*
	 * Return with ``loop detected'' error if we've recursed more than
	 * MAX_RECURSION times.
	 */
	if (depth > MAX_RECURSION)
		return (-3);

	/*
	 * Check if we have a top record from cgetset().
         */
	if (depth == 0 && toprec != NULL && cgetmatch(toprec, strdup(name)) == 0) {
		if ((record = malloc (topreclen + BFRAG)) == NULL) {
			errno = ENOMEM;
			return (-2);
		}
		(void)strcpy(record, toprec);	/* XXX: strcpy is safe */
		db_p = db_array;
		rp = record + topreclen + 1;
		r_end = rp + BFRAG;
		goto tc_exp;
	}
	/*
	 * Allocate first chunk of memory.
	 */
	if ((record = malloc(BFRAG)) == NULL) {
		errno = ENOMEM;
		return (-2);
	}
	r_end = record + BFRAG;
	foundit = 0;
	/*
	 * Loop through database array until finding the record.
	 */

	for (db_p = db_array; *db_p != NULL; db_p++) {
		eof = 0;

		/*
		 * Open database if not already open.
		 */

		if (fd >= 0) {
			(void)lseek(fd, (off_t)0, SEEK_SET);
		} else {
			(void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
#if defined(__linux__)
			if ((capdbp->open(capdbp, NULL, pbuf, "", DB_HASH, DB_RDONLY, 0)) == 0) {
#else
			if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0)) != NULL) {
#endif /* !__linux__ */
				free(record);
				retval = cdbget(capdbp, &record, name);
				if (retval < 0) {
					/* no record available */
					(void)capdbp->close(capdbp, 0);
					return (retval);
				}
				/* save the data; close frees it */
				clen = strlen(record);
				cbuf = malloc(clen + 1);
				memmove(cbuf, record, clen + 1);
				if (capdbp->close(capdbp, 0) < 0) {
					int serrno = errno;

					free(cbuf);
					errno = serrno;
					return (-2);
				}
				*len = clen;
				*cap = cbuf;
				return (retval);
			} else {
				fd = open(*db_p, O_RDONLY, 0);
				if (fd < 0) {
					/* No error on unfound file. */
					continue;
				}
				myfd = 1;
			}
		}
		/*
		 * Find the requested capability record ...
		 */
		{
		char buf[BUFSIZ];
		char *b_end, *bp, *cp;
		int c, slash;

		/*
		 * Loop invariants:
		 *	There is always room for one more character in record.
		 *	R_end always points just past end of record.
		 *	Rp always points just past last character in record.
		 *	B_end always points just past last character in buf.
		 *	Bp always points at next character in buf.
		 *	Cp remembers where the last colon was.
		 */
		b_end = buf;
		bp = buf;
		cp = 0;
		slash = 0;
		for (;;) {

			/*
			 * Read in a line implementing (\, newline)
			 * line continuation.
			 */
			rp = record;
			for (;;) {
				if (bp >= b_end) {
					int n;

					n = read(fd, buf, sizeof(buf));
					if (n <= 0) {
						if (myfd)
							(void)close(fd);
						if (n < 0) {
							int serrno = errno;

							free(record);
							errno = serrno;
							return (-2);
						} else {
							fd = -1;
							eof = 1;
							break;
						}
					}
					b_end = buf+n;
					bp = buf;
				}

				c = *bp++;
				if (c == '\n') {
					if (slash) {
						slash = 0;
						rp--;
						continue;
					} else
						break;
				}
				if (slash) {
					slash = 0;
					cp = 0;
				}
				if (c == ':') {
					/*
					 * If the field was `empty' (i.e.
					 * contained only white space), back up
					 * to the colon (eliminating the
					 * field).
					 */
					if (cp)
						rp = cp;
					else
						cp = rp;
				} else if (c == '\\') {
					slash = 1;
				} else if (c != ' ' && c != '\t') {
					/*
					 * Forget where the colon was, as this
					 * is not an empty field.
					 */
					cp = 0;
				}
				*rp++ = c;

				/*
				 * Enforce loop invariant: if no room 
				 * left in record buffer, try to get
				 * some more.
				 */
				if (rp >= r_end) {
					u_int pos;
					size_t newsize;

					pos = rp - record;
					newsize = r_end - record + BFRAG;
					newrecord = realloc(record, newsize);
					if (newrecord == NULL) {
						free(record);
						if (myfd)
							(void)close(fd);
						errno = ENOMEM;
						return (-2);
					}
					record = newrecord;
					r_end = record + newsize;
					rp = record + pos;
				}
			}
			/* Eliminate any white space after the last colon. */
			if (cp)
				rp = cp + 1;
			/* Loop invariant lets us do this. */
			*rp++ = '\0';

			/*
			 * If encountered eof check next file.
			 */
			if (eof)
				break;

			/*
			 * Toss blank lines and comments.
			 */
			if (*record == '\0' || *record == '#')
				continue;

			/*
			 * See if this is the record we want ...
			 */
			if (cgetmatch(record, strdup(name)) == 0) {
				if (nfield == NULL || !nfcmp(nfield, record)) {
					foundit = 1;
					break;	/* found it! */
				}
			}
		}
	}
		if (foundit)
			break;
	}

	if (!foundit)
		return (-1);

	/*
	 * Got the capability record, but now we have to expand all tc=name
	 * references in it ...
	 */
tc_exp:	{
		char *newicap, *s;
		size_t ilen, newilen;
		int diff, iret, tclen;
		char *icap, *scan, *tc, *tcstart, *tcend;

		/*
		 * Loop invariants:
		 *	There is room for one more character in record.
		 *	R_end points just past end of record.
		 *	Rp points just past last character in record.
		 *	Scan points at remainder of record that needs to be
		 *	scanned for tc=name constructs.
		 */
		scan = record;
		tc_not_resolved = 0;
		for (;;) {
			if ((tc = cgetcap(scan, "tc", '=')) == NULL)
				break;

			/*
			 * Find end of tc=name and stomp on the trailing `:'
			 * (if present) so we can use it to call ourselves.
			 */
			s = tc;
			for (;;)
				if (*s == '\0')
					break;
				else
					if (*s++ == ':') {
						*(s - 1) = '\0';
						break;
					}
			tcstart = tc - 3;
			tclen = s - tcstart;
			tcend = s;

			iret = getent(&icap, (char **)&ilen, (char *)db_p, (const char *)&fd, (size_t *)tc, depth+1, 0);
			newicap = icap;		/* Put into a register. */
			newilen = ilen;
			if (iret != 0) {
				/* an error */
				if (iret < -1) {
					if (myfd)
						(void)close(fd);
					free(record);
					return (iret);
				}
				if (iret == 1)
					tc_not_resolved = 1;
				/* couldn't resolve tc */
				if (iret == -1) {
					*(s - 1) = ':';
					scan = s - 1;
					tc_not_resolved = 1;
					continue;
				}
			}
			/* not interested in name field of tc'ed record */
			s = newicap;
			for (;;)
				if (*s == '\0')
					break;
				else
					if (*s++ == ':')
						break;
			newilen -= s - newicap;
			newicap = s;

			/* make sure interpolated record is `:'-terminated */
			s += newilen;
			if (*(s-1) != ':') {
				*s = ':';	/* overwrite NUL with : */
				newilen++;
			}

			/*
			 * Make sure there's enough room to insert the
			 * new record.
			 */
			diff = newilen - tclen;
			if (diff >= r_end - rp) {
				u_int pos, tcpos, tcposend;
				size_t newsize;

				pos = rp - record;
				newsize = r_end - record + diff + BFRAG;
				tcpos = tcstart - record;
				tcposend = tcend - record;
				newrecord = realloc(record, newsize);
				if (newrecord == NULL) {
					free(record);
					if (myfd)
						(void)close(fd);
					free(icap);
					errno = ENOMEM;
					return (-2);
				}
				record = newrecord;
				r_end = record + newsize;
				rp = record + pos;
				tcstart = record + tcpos;
				tcend = record + tcposend;
			}

			/*
			 * Insert tc'ed record into our record.
			 */
			s = tcstart + newilen;
			memmove(s, tcend,  (size_t)(rp - tcend));
			memmove(tcstart, newicap, newilen);
			rp += diff;
			free(icap);

			/*
			 * Start scan on `:' so next cgetcap works properly
			 * (cgetcap always skips first field).
			 */
			scan = s-1;
		}
	}
	/*
	 * Close file (if we opened it), give back any extra memory, and
	 * return capability, length and success.
	 */
	if (myfd)
		(void)close(fd);
	*len = rp - record - 1;	/* don't count NUL */
	if (r_end > rp) {
		if ((newrecord = realloc(record, (size_t)(rp - record))) == NULL) {
			free(record);
			errno = ENOMEM;
			return (-2);
		}
		record = newrecord;
	}

	*cap = record;
	if (tc_not_resolved)
		return (1);
	return (0);
}

/*
 * Cgetent extracts the capability record name from the NULL terminated file
 * array db_array and returns a pointer to a malloc'd copy of it in buf.
 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
 * cgetflag, and cgetstr, but may then be free'd.  0 is returned on success,
 * -1 if the requested record couldn't be found, -2 if a system error was
 * encountered (couldn't open/read a file, etc.), and -3 if a potential
 * reference loop is detected.
 */
int cgetent(char **buf, char **db_array, const char *name)
{
	size_t dummy;

	assert(buf != NULL);
	assert(db_array != NULL);
	assert(name != NULL);

	return (getent(buf, (char **)&dummy, (char *)db_array, (const char *)-1, (size_t *)name, 0, 0));
}
Example #9
0
status_t
vmi_init_custom(
    vmi_instance_t *vmi,
    uint32_t flags,
    vmi_config_t config)
{
    status_t ret = VMI_FAILURE;
    uint32_t config_mode = flags & 0xFF000000;

    if (NULL == config) {
        config_mode |= VMI_CONFIG_NONE;
    }

    if (VMI_CONFIG_GLOBAL_FILE_ENTRY == config_mode) {

        ret = vmi_init(vmi, flags, (char *)config);
        goto _done;

    } else if (VMI_CONFIG_STRING == config_mode) {
        char *name = NULL;

        if (VMI_FILE == (*vmi)->mode) {
            name = strdup((*vmi)->image_type_complete);
        } else {
            name = strdup((*vmi)->image_type);
        }

        ret = vmi_init_private(vmi, flags, VMI_INVALID_DOMID, name,
                (vmi_config_t)config);

    } else if (VMI_CONFIG_GHASHTABLE == config_mode) {

        char *name = NULL;
        unsigned long domid = VMI_INVALID_DOMID;
        GHashTable *configtbl = (GHashTable *)config;
        gpointer idptr = NULL;

        name = (char *)g_hash_table_lookup(configtbl, "name");
        if(g_hash_table_lookup_extended(configtbl, "domid", NULL, &idptr)) {
            domid = *(unsigned long *)idptr;
        }

        if (name != NULL && domid != VMI_INVALID_DOMID) {
            errprint("--specifying both the name and domid is not supported\n");
        } else if (name != NULL) {
            ret = vmi_init_private(vmi, flags, VMI_INVALID_DOMID, name, config);
        } else if (domid != VMI_INVALID_DOMID) {
            ret = vmi_init_private(vmi, flags, domid, NULL, config);
        } else {
            errprint("--you need to specify either the name or the domid\n");
        }

        goto _done;

    } else {
        errprint("Custom configuration input type not defined!\n");
    }

_done:
    return ret;
}
Example #10
0
File: dfs_test.c Project: ORNL/ompi
/* receives take place in an event, so we are free to process
 * the request list without fear of getting things out-of-order
 */
static void recv_dfs(int status, orte_process_name_t* sender,
                     opal_buffer_t* buffer, orte_rml_tag_t tag,
                     void* cbdata)
{
    orte_dfs_cmd_t cmd;
    int32_t cnt;
    orte_dfs_request_t *dfs, *dptr;
    opal_list_item_t *item;
    int remote_fd, rc;
    int64_t i64;
    uint64_t rid;
    orte_dfs_tracker_t *trk;

    /* unpack the command this message is responding to */
    cnt = 1;
    if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &cmd, &cnt, ORTE_DFS_CMD_T))) {
        ORTE_ERROR_LOG(rc);
        return;
    }

    opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                        "%s recvd cmd %d from sender %s",
                        ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), (int)cmd,
                        ORTE_NAME_PRINT(sender));

    switch (cmd) {
    case ORTE_DFS_OPEN_CMD:
        /* unpack the request id */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* unpack the remote fd */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &remote_fd, &cnt, OPAL_INT))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* as the request has been fulfilled, remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd open file - no corresponding request found for local fd %d",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), local_fd);
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }

        /* if the remote_fd < 0, then we had an error, so return
         * the error value to the caller
         */
        if (remote_fd < 0) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd open file response error file %s [error: %d]",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                                dfs->uri, remote_fd);
            if (NULL != dfs->open_cbfunc) {
                dfs->open_cbfunc(remote_fd, dfs->cbdata);
            }
            /* release the request */
            OBJ_RELEASE(dfs);
            return;
        }
        /* otherwise, create a tracker for this file */
        trk = OBJ_NEW(orte_dfs_tracker_t);
        trk->requestor.jobid = ORTE_PROC_MY_NAME->jobid;
        trk->requestor.vpid = ORTE_PROC_MY_NAME->vpid;
        trk->host_daemon.jobid = sender->jobid;
        trk->host_daemon.vpid = sender->vpid;
        trk->filename = strdup(dfs->uri);
        /* define the local fd */
        trk->local_fd = local_fd++;
        /* record the remote file descriptor */
        trk->remote_fd = remote_fd;
        /* add it to our list of active files */
        opal_list_append(&active_files, &trk->super);
        /* return the local_fd to the caller for
         * subsequent operations
         */
        opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                            "%s recvd open file completed for file %s [local fd: %d remote fd: %d]",
                            ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
                            dfs->uri, trk->local_fd, remote_fd);
        if (NULL != dfs->open_cbfunc) {
            dfs->open_cbfunc(trk->local_fd, dfs->cbdata);
        }
        /* release the request */
        OBJ_RELEASE(dfs);
        break;

    case ORTE_DFS_SIZE_CMD:
        /* unpack the request id for this request */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* request was fulfilled, so remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd size - no corresponding request found for local fd %d",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), local_fd);
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }
        /* get the size */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &i64, &cnt, OPAL_INT64))) {
            ORTE_ERROR_LOG(rc);
            OBJ_RELEASE(dfs);
            return;
        }
        /* pass it back to the original caller */
        if (NULL != dfs->size_cbfunc) {
            dfs->size_cbfunc(i64, dfs->cbdata);
        }
        /* release the request */
        OBJ_RELEASE(dfs);
        break;

    case ORTE_DFS_SEEK_CMD:
        /* unpack the request id for this read */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* request was fulfilled, so remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd seek - no corresponding request found for local fd %d",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), local_fd);
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }
        /* get the returned offset/status */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &i64, &cnt, OPAL_INT64))) {
            ORTE_ERROR_LOG(rc);
            OBJ_RELEASE(dfs);
            return;
        }
        /* pass it back to the original caller */
        if (NULL != dfs->seek_cbfunc) {
            dfs->seek_cbfunc(i64, dfs->cbdata);
        }
        /* release the request */
        OBJ_RELEASE(dfs);
        break;

    case ORTE_DFS_READ_CMD:
        /* unpack the request id for this read */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* request was fulfilled, so remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd read - no corresponding request found for local fd %d",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), local_fd);
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }
        /* get the bytes read */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &i64, &cnt, OPAL_INT64))) {
            ORTE_ERROR_LOG(rc);
            OBJ_RELEASE(dfs);
            return;
        }
        if (0 < i64) {
            cnt = i64;
            if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, dfs->read_buffer, &cnt, OPAL_UINT8))) {
                ORTE_ERROR_LOG(rc);
                OBJ_RELEASE(dfs);
                return;
            }
        }
        /* pass them back to the original caller */
        if (NULL != dfs->read_cbfunc) {
            dfs->read_cbfunc(i64, dfs->read_buffer, dfs->cbdata);
        }
        /* release the request */
        OBJ_RELEASE(dfs);
        break;

    case ORTE_DFS_POST_CMD:
        /* unpack the request id for this read */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* request was fulfilled, so remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd post - no corresponding request found",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }
        if (NULL != dfs->post_cbfunc) {
            dfs->post_cbfunc(dfs->cbdata);
        }
        OBJ_RELEASE(dfs);
        break;

    case ORTE_DFS_GETFM_CMD:
        /* unpack the request id for this read */
        cnt = 1;
        if (OPAL_SUCCESS != (rc = opal_dss.unpack(buffer, &rid, &cnt, OPAL_UINT64))) {
            ORTE_ERROR_LOG(rc);
            return;
        }
        /* search our list of requests to find the matching one */
        dfs = NULL;
        for (item = opal_list_get_first(&requests);
             item != opal_list_get_end(&requests);
             item = opal_list_get_next(item)) {
            dptr = (orte_dfs_request_t*)item;
            if (dptr->id == rid) {
                /* request was fulfilled, so remove it */
                opal_list_remove_item(&requests, item);
                dfs = dptr;
                break;
            }
        }
        if (NULL == dfs) {
            opal_output_verbose(1, orte_dfs_base_framework.framework_output,
                                "%s recvd getfm - no corresponding request found",
                                ORTE_NAME_PRINT(ORTE_PROC_MY_NAME));
            ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
            return;
        }
        /* return it to caller */
        if (NULL != dfs->fm_cbfunc) {
            dfs->fm_cbfunc(buffer, dfs->cbdata);
        }
        OBJ_RELEASE(dfs);
        break;

    default:
        opal_output(0, "TEST:DFS:RECV WTF");
        break;
    }
}
bool findHeader(const string& hdrs,const string& hdr_name, 
		size_t& pos1, size_t& pos2, size_t& hdr_start)
{
  unsigned int p;
  char* hdr = strdup(hdr_name.c_str());
  const char* hdrs_c = hdrs.c_str();
  char* hdr_c = hdr;
  const char* hdrs_end = hdrs_c + hdrs.length();
  const char* hdr_end = hdr_c + hdr_name.length(); 

  while(hdr_c != hdr_end){
    if('A' <= *hdr_c && *hdr_c <= 'Z')
      *hdr_c -= 'A' - 'a';
    hdr_c++;
  }

  while(hdrs_c != hdrs_end){

    hdr_c = hdr;

    while((hdrs_c != hdrs_end) && (hdr_c != hdr_end)){

      char c = *hdrs_c;
      if('A' <= *hdrs_c && *hdrs_c <= 'Z')
	c -= 'A' - 'a';

      if(c != *hdr_c)
	break;

      hdr_c++;
      hdrs_c++;
    }

    if(hdr_c == hdr_end)
      break;

    while((hdrs_c != hdrs_end) && (*hdrs_c != '\n'))
      hdrs_c++;

    if(hdrs_c != hdrs_end)
      hdrs_c++;
  }
    
  if(hdr_c == hdr_end){
    hdr_start = hdrs_c - hdrs.c_str();;

    while((hdrs_c != hdrs_end) && (*hdrs_c == ' '))
      hdrs_c++;

    if((hdrs_c != hdrs_end) && (*hdrs_c == ':')){

      hdrs_c++;
      while((hdrs_c != hdrs_end) && (*hdrs_c == ' '))
	hdrs_c++;
	    
      p = hdrs_c - hdrs.c_str();
	    
      string::size_type p_end;
      if((p_end = hdrs.find('\n',p)) != string::npos){
		
	free(hdr);
	// return hdrs.substr(p,p_end-p);
	pos1 = p;
	pos2 = p_end;
	return true;
      }
    }
  }

  free(hdr);
  //    return "";
  return false;
}
Example #12
0
static int SearchString(u32 startaddr, u32 endaddr, int searchtype,
                        const char *searchstr, result_struct *results,
                        u32 *maxresults)
{
   u8 *buf=NULL;
   u32 *buf32=NULL;
   u32 buflen=0;
   u32 counter;
   u32 addr;
   u32 numresults=0;

   buflen=(u32)strlen(searchstr);

   if ((buf32=(u32 *)malloc(buflen*sizeof(u32))) == NULL)
      return 0;

   buf = (u8 *)buf32;

   // Copy string to buffer
   switch (searchtype & 0x70)
   {
      case SEARCHSTRING:
         strcpy((char *)buf, searchstr);
         break;
      case SEARCHREL8BIT:
      case SEARCHREL16BIT:
      {
         char *text;
         char *searchtext=strdup(searchstr);

         // Calculate buffer length and read values into table
         buflen = 0;
         for (text=strtok((char *)searchtext, " ,"); text != NULL; text=strtok(NULL, " ,"))
         {            
            buf32[buflen] = strtoul(text, NULL, 0);
            buflen++;
         }
         free(searchtext);

         break;
      }
   }    

   addr = startaddr;
   counter = 0;

   for (;;)
   {
      // Fetch byte/word/etc.
      switch (searchtype & 0x70)
      {
         case SEARCHSTRING:
         {
            u8 val = MappedMemoryReadByte(addr);
            addr++;

            if (val == buf[counter])
            {
               counter++;
               if (counter == buflen)
                  MappedMemoryAddMatch(addr-buflen, val, searchtype, results, &numresults);
            }
            else
               counter = 0;
            break;
         }
         case SEARCHREL8BIT:
         {
            int diff;
            u32 j;
            u8 val2;
            u8 val = MappedMemoryReadByte(addr);

            for (j = 1; j < buflen; j++)
            {
               // grab the next value
               val2 = MappedMemoryReadByte(addr+j);

               // figure out the diff
               diff = (int)val2 - (int)val;

               // see if there's a match             
               if (((int)buf32[j] - (int)buf32[j-1]) != diff)
                  break;

               if (j == (buflen - 1))
                  MappedMemoryAddMatch(addr, val, searchtype, results, &numresults);

               val = val2;
            }

            addr++;

            break;
         }
         case SEARCHREL16BIT:
         {
            int diff;
            u32 j;
            u16 val2;
            u16 val = MappedMemoryReadWord(addr);

            for (j = 1; j < buflen; j++)
            {
               // grab the next value
               val2 = MappedMemoryReadWord(addr+(j*2));

               // figure out the diff
               diff = (int)val2 - (int)val;

               // see if there's a match             
               if (((int)buf32[j] - (int)buf32[j-1]) != diff)
                  break;

               if (j == (buflen - 1))
                  MappedMemoryAddMatch(addr, val, searchtype, results, &numresults);

               val = val2;
            }

            addr+=2;
            break;
         }
      }    

      if (addr > endaddr || numresults >= maxresults[0])
         break;
   }

   free(buf);
   maxresults[0] = numresults;
   return 1;
}
Example #13
0
File: part.c Project: hallor/u-boot
int blk_get_device_part_str(const char *ifname, const char *dev_part_str,
                            struct blk_desc **dev_desc,
                            disk_partition_t *info, int allow_whole_dev)
{
    int ret = -1;
    const char *part_str;
    char *dup_str = NULL;
    const char *dev_str;
    int dev;
    char *ep;
    int p;
    int part;
    disk_partition_t tmpinfo;

#ifdef CONFIG_SANDBOX
    /*
     * Special-case a pseudo block device "hostfs", to allow access to the
     * host's own filesystem.
     */
    if (0 == strcmp(ifname, "hostfs")) {
        *dev_desc = NULL;
        info->start = 0;
        info->size = 0;
        info->blksz = 0;
        info->bootable = 0;
        strcpy((char *)info->type, BOOT_PART_TYPE);
        strcpy((char *)info->name, "Sandbox host");
#ifdef CONFIG_PARTITION_UUIDS
        info->uuid[0] = 0;
#endif
#ifdef CONFIG_PARTITION_TYPE_GUID
        info->type_guid[0] = 0;
#endif

        return 0;
    }
#endif

#ifdef CONFIG_CMD_UBIFS
    /*
     * Special-case ubi, ubi goes through a mtd, rathen then through
     * a regular block device.
     */
    if (0 == strcmp(ifname, "ubi")) {
        if (!ubifs_is_mounted()) {
            printf("UBIFS not mounted, use ubifsmount to mount volume first!\n");
            return -1;
        }

        *dev_desc = NULL;
        memset(info, 0, sizeof(*info));
        strcpy((char *)info->type, BOOT_PART_TYPE);
        strcpy((char *)info->name, "UBI");
#ifdef CONFIG_PARTITION_UUIDS
        info->uuid[0] = 0;
#endif
        return 0;
    }
#endif

    /* If no dev_part_str, use bootdevice environment variable */
    if (!dev_part_str || !strlen(dev_part_str) ||
            !strcmp(dev_part_str, "-"))
        dev_part_str = getenv("bootdevice");

    /* If still no dev_part_str, it's an error */
    if (!dev_part_str) {
        printf("** No device specified **\n");
        goto cleanup;
    }

    /* Separate device and partition ID specification */
    part_str = strchr(dev_part_str, ':');
    if (part_str) {
        dup_str = strdup(dev_part_str);
        dup_str[part_str - dev_part_str] = 0;
        dev_str = dup_str;
        part_str++;
    } else {
        dev_str = dev_part_str;
    }

    /* Look up the device */
    dev = blk_get_device_by_str(ifname, dev_str, dev_desc);
    if (dev < 0)
        goto cleanup;

    /* Convert partition ID string to number */
    if (!part_str || !*part_str) {
        part = PART_UNSPECIFIED;
    } else if (!strcmp(part_str, "auto")) {
        part = PART_AUTO;
    } else {
        /* Something specified -> use exactly that */
        part = (int)simple_strtoul(part_str, &ep, 16);
        /*
         * Less than whole string converted,
         * or request for whole device, but caller requires partition.
         */
        if (*ep || (part == 0 && !allow_whole_dev)) {
            printf("** Bad partition specification %s %s **\n",
                   ifname, dev_part_str);
            goto cleanup;
        }
    }

    /*
     * No partition table on device,
     * or user requested partition 0 (entire device).
     */
    if (((*dev_desc)->part_type == PART_TYPE_UNKNOWN) ||
            (part == 0)) {
        if (!(*dev_desc)->lba) {
            printf("** Bad device size - %s %s **\n", ifname,
                   dev_str);
            goto cleanup;
        }

        /*
         * If user specified a partition ID other than 0,
         * or the calling command only accepts partitions,
         * it's an error.
         */
        if ((part > 0) || (!allow_whole_dev)) {
            printf("** No partition table - %s %s **\n", ifname,
                   dev_str);
            goto cleanup;
        }

        (*dev_desc)->log2blksz = LOG2((*dev_desc)->blksz);

        info->start = 0;
        info->size = (*dev_desc)->lba;
        info->blksz = (*dev_desc)->blksz;
        info->bootable = 0;
        strcpy((char *)info->type, BOOT_PART_TYPE);
        strcpy((char *)info->name, "Whole Disk");
#ifdef CONFIG_PARTITION_UUIDS
        info->uuid[0] = 0;
#endif
#ifdef CONFIG_PARTITION_TYPE_GUID
        info->type_guid[0] = 0;
#endif

        ret = 0;
        goto cleanup;
    }

    /*
     * Now there's known to be a partition table,
     * not specifying a partition means to pick partition 1.
     */
    if (part == PART_UNSPECIFIED)
        part = 1;

    /*
     * If user didn't specify a partition number, or did specify something
     * other than "auto", use that partition number directly.
     */
    if (part != PART_AUTO) {
        ret = part_get_info(*dev_desc, part, info);
        if (ret) {
            printf("** Invalid partition %d **\n", part);
            goto cleanup;
        }
    } else {
        /*
         * Find the first bootable partition.
         * If none are bootable, fall back to the first valid partition.
         */
        part = 0;
        for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
            ret = part_get_info(*dev_desc, p, info);
            if (ret)
                continue;

            /*
             * First valid partition, or new better partition?
             * If so, save partition ID.
             */
            if (!part || info->bootable)
                part = p;

            /* Best possible partition? Stop searching. */
            if (info->bootable)
                break;

            /*
             * We now need to search further for best possible.
             * If we what we just queried was the best so far,
             * save the info since we over-write it next loop.
             */
            if (part == p)
                tmpinfo = *info;
        }
        /* If we found any acceptable partition */
        if (part) {
            /*
             * If we searched all possible partition IDs,
             * return the first valid partition we found.
             */
            if (p == MAX_SEARCH_PARTITIONS + 1)
                *info = tmpinfo;
        } else {
            printf("** No valid partitions found **\n");
            ret = -1;
            goto cleanup;
        }
    }
    if (strncmp((char *)info->type, BOOT_PART_TYPE, sizeof(info->type)) != 0) {
        printf("** Invalid partition type \"%.32s\""
               " (expect \"" BOOT_PART_TYPE "\")\n",
               info->type);
        ret  = -1;
        goto cleanup;
    }

    (*dev_desc)->log2blksz = LOG2((*dev_desc)->blksz);

    ret = part;
    goto cleanup;

cleanup:
    free(dup_str);
    return ret;
}
Example #14
0
// Parse the query string part of a url and turn it into q query_arg_list_t, which
// is a list of query_key_val_t structs and a count.
query_arg_list_t *get_query_arg_list(char *const query_str, unsigned int *err_out) {

    *err_out = UPARSE_ERROR; 
    
    if (NULL == query_str) {
        *err_out = NO_UPARSE_ERROR; 
        return NULL;
    }

    // stringify the delims for strsep
    char query_pair_delim_str[2];
    snprintf(query_pair_delim_str,2,"%c",QUERY_PAIR_DELIM);
    char query_key_value_delim_str[2];
    snprintf(query_key_value_delim_str,2,"%c",QUERY_KEY_VAL_DELIM);
    
    char *c = query_str;
    size_t const str_len = 256;
    
    char *key = (char *) calloc(str_len, sizeof(char));
    char *val = (char *) calloc(str_len, sizeof(char));
    if ((NULL == key) || (NULL == val)) {
        fprintf(stderr,"key or val is null\n");
        free(key);
        free(val);
        return NULL;
    }
    
    unsigned int const STATE_KEY_READ = 0;
    unsigned int const STATE_VAL_READ = 1;
    unsigned int state = STATE_KEY_READ;
    
    bool valid_key            = false;
    bool valid_val            = false;
    bool valid_query_key_vals = false;
    
    size_t j = 0;
    size_t k = 0;

    size_t key_val_count = 0;
    size_t const max_query_key_vals = 512;
    query_key_val_t **query_key_vals =
        (query_key_val_t **) malloc(max_query_key_vals * sizeof(query_key_val_t *));
    bzero((void *) query_key_vals,max_query_key_vals * sizeof(query_key_val_t *));
    
    while (*c) {
        if (STATE_KEY_READ == state) {
            if (QUERY_PAIR_DELIM == c[0]) {
                fprintf(stderr,"found query pair delim %c when parsing key\n",QUERY_PAIR_DELIM);
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;
            }
            if (QUERY_KEY_VAL_DELIM == c[0]) {
                if (!valid_key) {
                    fprintf(stderr,"found query key/val delim %c but no valid key\n",QUERY_KEY_VAL_DELIM);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    state = STATE_VAL_READ;
                    key[j] = '\0';
                }
            } else {
                if (j == (str_len - 1)) {
                    fprintf(stderr,"key length exceeds %lu\n",str_len);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    *err_out = OVERFLOW_ERROR; 
                    return NULL;
                } else {                    
                    key[j++] = c[0];
                    valid_key = true;
                }
            } 
        } else if (STATE_VAL_READ == state) {
            if (!valid_key) {
                fprintf(stderr,"valid_key = false while parsing val\n");
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;                
            }
            if (QUERY_KEY_VAL_DELIM == c[0]) {
                fprintf(stderr,"parsing val and saw key/val delim %c \n",QUERY_KEY_VAL_DELIM);
                free(key);
                free(val);
                free_query_key_val_t_list(query_key_vals,key_val_count);
                return NULL;                
            }
            if (QUERY_PAIR_DELIM == c[0]) {
                if (!valid_val) {
                    fprintf(stderr,"found query pair delim %c but no valid val\n",QUERY_PAIR_DELIM);
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    val[k] = '\0';
                    query_key_vals[key_val_count] = (query_key_val_t *) malloc(sizeof(query_key_val_t));
                    if (NULL == query_key_vals[key_val_count]) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    query_key_vals[key_val_count]->key = strdup(key);
                    if (NULL == query_key_vals[key_val_count]->key) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]->key\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    query_key_vals[key_val_count]->val = strdup(val);
                    if (NULL == query_key_vals[key_val_count]->val) {
                        fprintf(stderr,"cannot allocate query_key_vals[%lu]->val\n",key_val_count);
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;                        
                    }
                    key_val_count++;
                    if (key_val_count == (max_query_key_vals - 1)) {
                        fprintf(stderr,"query query_key_vals length exceeds %lu\n",max_query_key_vals);
                        *err_out = OVERFLOW_ERROR;
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;
                    }   
                    valid_query_key_vals = true;
                    valid_key = false;
                    valid_val = false;
                    j = 0;
                    k = 0;
                    free(key);
                    free(val);
                    key = (char *) calloc(str_len, sizeof(char));
                    val = (char *) calloc(str_len, sizeof(char));                 
                    if ((NULL == key) || (NULL == val)) {
                        fprintf(stderr,"key or val is null\n");
                        free(key);
                        free(val);
                        free_query_key_val_t_list(query_key_vals,key_val_count);
                        return NULL;
                    }
                    state = STATE_KEY_READ;
                }
            } else {
                if (k == (str_len - 1)) {
                    fprintf(stderr,"val length exceeds %lu\n",str_len);
                    *err_out = OVERFLOW_ERROR;
                    free(key);
                    free(val);
                    free_query_key_val_t_list(query_key_vals,key_val_count);
                    return NULL;
                } else {
                    val[k++] = c[0];
                    valid_val = true;
                }
            }
        } else {
            fprintf(stderr,"unknown parse state\n");
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;
        }
        c++;
    }

    if (valid_key && valid_val) {
        query_key_vals[key_val_count] = (query_key_val_t *) malloc(sizeof(query_key_val_t));
        if (NULL == query_key_vals[key_val_count]) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        query_key_vals[key_val_count]->key = strdup(key);
        if (NULL == query_key_vals[key_val_count]->key) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]->key\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        query_key_vals[key_val_count]->val = strdup(val);
        if (NULL == query_key_vals[key_val_count]->val) {
            fprintf(stderr,"cannot allocate query_key_vals[%lu]->val\n",key_val_count);
            free(key);
            free(val);
            free_query_key_val_t_list(query_key_vals,key_val_count);
            return NULL;                        
        }
        valid_query_key_vals = true;
        key_val_count++;
    }

    free(key);
    free(val);
    
    if (!valid_query_key_vals) {
        fprintf(stderr,"no valid key/val query_key_vals found\n");
        free_query_key_val_t_list(query_key_vals,key_val_count);
        return NULL;
    }

    query_key_vals = (query_key_val_t **) realloc(query_key_vals,key_val_count * sizeof(query_key_val_t *));
    
    query_arg_list_t *query_arg_list =
        (query_arg_list_t *) malloc(sizeof(query_arg_list_t));
    if (NULL == query_arg_list) {
        fprintf(stderr,"cannot allocate query_arg_list\n");
        free_query_key_val_t_list(query_key_vals,key_val_count);
        return NULL;
    }
    bzero((void *) query_arg_list,sizeof(query_arg_list_t));
    query_arg_list->query_key_vals = query_key_vals;
    query_arg_list->count = key_val_count;
    *err_out = NO_UPARSE_ERROR; 
    return query_arg_list;
}
Example #15
0
/**
 * @ingroup VuoBlendMode
 * Same as @c %VuoBlendMode_getString()
 */
char * VuoBlendMode_getSummary(const VuoBlendMode value)
{
	char *valueAsString = "";

	switch (value)
	{
		case VuoBlendMode_Normal:
			valueAsString = "Normal — Alpha";
			break;
		case VuoBlendMode_Multiply:
			valueAsString = "Multiply — b•f";
			break;
		case VuoBlendMode_DarkerComponent:
			valueAsString = "Darker Component — min(b,f)";
			break;
		case VuoBlendMode_DarkerColor:
			valueAsString = "Darker Color — min(b,f)";
			break;
		case VuoBlendMode_LinearBurn:
			valueAsString = "Linear Burn — b+f-1";
			break;
		case VuoBlendMode_ColorBurn:
			valueAsString = "Color Burn — 1-(1-b)/f";
			break;
		case VuoBlendMode_Screen:
			valueAsString = "Screen — 1-(1-b)•(1-f)";
			break;
		case VuoBlendMode_LighterComponent:
			valueAsString = "Lighter Component — max(b,f)";
			break;
		case VuoBlendMode_LighterColor:
			valueAsString = "Lighter Color — max(b,f)";
			break;
		case VuoBlendMode_LinearDodge:
			valueAsString = "Linear Dodge (Add) — b+f";
			break;
		case VuoBlendMode_ColorDodge:
			valueAsString = "Color Dodge — b/(1-f)";
			break;
		case VuoBlendMode_Overlay:
			valueAsString = "Overlay";
			break;
		case VuoBlendMode_SoftLight:
			valueAsString = "Soft Light";
			break;
		case VuoBlendMode_HardLight:
			valueAsString = "Hard Light";
			break;
		case VuoBlendMode_VividLight:
			valueAsString = "Vivid Light";
			break;
		case VuoBlendMode_LinearLight:
			valueAsString = "Linear Light";
			break;
		case VuoBlendMode_PinLight:
			valueAsString = "Pin Light";
			break;
		case VuoBlendMode_HardMix:
			valueAsString = "Hard Mix";
			break;
		case VuoBlendMode_Difference:
			valueAsString = "Difference — abs(b-f)";
			break;
		case VuoBlendMode_Exclusion:
			valueAsString = "Exclusion — b+f-2•b•f";
			break;
		case VuoBlendMode_Subtract:
			valueAsString = "Subtract — b-f";
			break;
		case VuoBlendMode_Divide:
			valueAsString = "Divide — b/f";
			break;
		case VuoBlendMode_Hue:
			valueAsString = "Hue";
			break;
		case VuoBlendMode_Saturation:
			valueAsString = "Saturation";
			break;
		case VuoBlendMode_Color:
			valueAsString = "Color";
			break;
		case VuoBlendMode_Luminosity:
			valueAsString = "Luminosity";
			break;
	}
	return strdup(valueAsString);
}
Example #16
0
url_t *parse_url(char const *const url_string,unsigned int *err_out) {

    *err_out = NO_UPARSE_ERROR;

    url_t *url = (url_t *) malloc(sizeof(url_t));
    if (NULL == url) {
        fprintf(stderr,"cannot allocate url\n");
        return NULL;
    }
    init_url_t(url);

    // get a mutable pointer to the url string, and set a copy that can be freed
    char const *s = strdup(url_string);
    if (NULL == s) {
        fprintf(stderr,"cannot copy url_string\n");
        free_url_t(url);
        return NULL;
    }
    char const *const free_s = s;
    
    char *scheme = get_protocol_scheme(&s,err_out);
    if (NULL == scheme) {
        fprintf(stderr,"cannot get scheme from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        return NULL;
    }
    if (NO_UPARSE_ERROR != *err_out) {
        fprintf(stderr,"cannot get scheme from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        free(scheme);
        return NULL;
    }
    url->scheme = scheme;

    char *host = get_host(&s,err_out);
    if (NULL == host) {
        fprintf(stderr,"cannot get host from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        return NULL;
    }
    if (NO_UPARSE_ERROR != *err_out) {
        fprintf(stderr,"cannot get host from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        free(host);
        return NULL;
    }
    url->host = host;

    int const port = get_port(&s,err_out);
    if (ERROR_PORT == port) {
        fprintf(stderr,"cannot get port from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        return NULL;
    }
    if (NO_UPARSE_ERROR != *err_out) {
        fprintf(stderr,"cannot get port from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        return NULL;
    }
    url->port = port;

    char *path = get_path(&s,err_out);
    if (NULL == path) {
        fprintf(stderr,"cannot get path from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        return NULL;
    }
    if (NO_UPARSE_ERROR != *err_out) {
        fprintf(stderr,"cannot get path from %s\n",url_string);
        free_url_t(url);
        free((void *) free_s);
        free(path);
        return NULL;
    }
    url->path = path;

    char *query = get_query(&s,err_out);
    if ((NULL != query) && (UPARSE_ERROR != *err_out)) {
        url->query = query;
    }
    
    char *fragment = get_fragment(&s,err_out);
    if ((NULL != fragment) && (UPARSE_ERROR != *err_out)) {
        url->fragment = fragment;
    }
    
    free((void *) free_s);
    return url;
}
static int find_gpt_root(struct udev_device *dev, blkid_probe pr, bool test) {

#if defined(GPT_ROOT_NATIVE) && defined(ENABLE_EFI)

        _cleanup_free_ char *root_id = NULL;
        bool found_esp = false;
        blkid_partlist pl;
        int i, nvals, r;

        assert(pr);

        /* Iterate through the partitions on this disk, and see if the
         * EFI ESP we booted from is on it. If so, find the first root
         * disk, and add a property indicating its partition UUID. */

        errno = 0;
        pl = blkid_probe_get_partitions(pr);
        if (!pl)
                return -errno ?: -ENOMEM;

        nvals = blkid_partlist_numof_partitions(pl);
        for (i = 0; i < nvals; i++) {
                blkid_partition pp;
                const char *stype, *sid;
                sd_id128_t type;

                pp = blkid_partlist_get_partition(pl, i);
                if (!pp)
                        continue;

                sid = blkid_partition_get_uuid(pp);
                if (!sid)
                        continue;

                stype = blkid_partition_get_type_string(pp);
                if (!stype)
                        continue;

                if (sd_id128_from_string(stype, &type) < 0)
                        continue;

                if (sd_id128_equal(type, GPT_ESP)) {
                        sd_id128_t id, esp;

                        /* We found an ESP, let's see if it matches
                         * the ESP we booted from. */

                        if (sd_id128_from_string(sid, &id) < 0)
                                continue;

                        r = efi_loader_get_device_part_uuid(&esp);
                        if (r < 0)
                                return r;

                        if (sd_id128_equal(id, esp))
                                found_esp = true;

                } else if (sd_id128_equal(type, GPT_ROOT_NATIVE)) {
                        unsigned long long flags;

                        flags = blkid_partition_get_flags(pp);
                        if (flags & GPT_FLAG_NO_AUTO)
                                continue;

                        /* We found a suitable root partition, let's
                         * remember the first one. */

                        if (!root_id) {
                                root_id = strdup(sid);
                                if (!root_id)
                                        return -ENOMEM;
                        }
                }
        }

        /* We found the ESP on this disk, and also found a root
         * partition, nice! Let's export its UUID */
        if (found_esp && root_id)
                udev_builtin_add_property(dev, test, "ID_PART_GPT_AUTO_ROOT_UUID", root_id);
#endif

        return 0;
}
Example #18
0
	void Plugin::UploadTo (LIBMTP_mtpdevice_t *device, const QByteArray& storageId,
			const QString& localPath, const QString& origPath)
	{
		if (!device->storage)
			LIBMTP_Get_Storage (device, 0);

		auto storage = device->storage;

		while (storage)
		{
			qDebug () << "st" << storage->id;
			if (QByteArray::number (storage->id) == storageId)
				break;
			storage = storage->next;
		}

		if (!storage)
		{
			qWarning () << Q_FUNC_INFO
					<< "could not find storage"
					<< storageId;
			emit uploadFinished (localPath,
					QFile::ResourceError,
					tr ("Unable to find the requested storage."));
			return;
		}

		const auto id = storage->id;
		const auto& info = OrigInfos_.take (origPath);

		qDebug () << "uploading" << localPath << "of type" << GetFileType (info.FileFormat_) << "to" << storage->id;

		auto track = LIBMTP_new_track_t ();
		track->storage_id = id;

		auto getStr = [] (const QString& str) { return strdup (str.toUtf8 ().constData ()); };

		track->filename = getStr (QFileInfo (localPath).fileName ());
		track->album = getStr (info.Album_);
		track->title = getStr (info.TrackTitle_);
		track->genre = getStr (info.Genres_.join ("; "));
		track->artist = getStr (info.Artist_);
		track->tracknumber = info.TrackNumber_;
		track->filetype = GetFileType (info.FileFormat_);
		track->filesize = QFileInfo (localPath).size ();
		track->date = getStr (QString::number (info.AlbumYear_) + "0101T0000.0");

		auto watcher = new QFutureWatcher<UploadInfo> ();
		connect (watcher,
				SIGNAL (finished ()),
				this,
				SLOT (handleUploadFinished ()));
		const auto future = QtConcurrent::run ([=] () -> UploadInfo
			{
				const auto cbData = new CallbackData { this, 0 };
				const auto res = LIBMTP_Send_Track_From_File (device,
						localPath.toUtf8 ().constData (), track,
						TransferCallback, cbData);
				delete cbData;
				return { res, device, localPath, track, info };
			});
		watcher->setFuture (future);
	}
char *VSIStrdup( const char * pszString )

{
    return( strdup( pszString ) );
}