Exemplo n.º 1
0
Arquivo: at.c Projeto: 2asoft/freebsd
static void
writefile(time_t runtimer, char queue)
{
/* This does most of the work if at or batch are invoked for writing a job.
 */
    long jobno;
    char *ap, *ppos, *mailname;
    struct passwd *pass_entry;
    struct stat statbuf;
    int fdes, lockdes, fd2;
    FILE *fp, *fpin;
    struct sigaction act;
    char **atenv;
    int ch;
    mode_t cmask;
    struct flock lock;
    
#ifdef __FreeBSD__
    (void) setlocale(LC_TIME, "");
#endif

/* Install the signal handler for SIGINT; terminate after removing the
 * spool file if necessary
 */
    act.sa_handler = sigc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    sigaction(SIGINT, &act, NULL);

    ppos = atfile + strlen(ATJOB_DIR);

    /* Loop over all possible file names for running something at this
     * particular time, see if a file is there; the first empty slot at any
     * particular time is used.  Lock the file LFILE first to make sure
     * we're alone when doing this.
     */

    PRIV_START

    if ((lockdes = open(LFILE, O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR)) < 0)
	perr("cannot open lockfile " LFILE);

    lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
    lock.l_len = 0;

    act.sa_handler = alarmc;
    sigemptyset(&(act.sa_mask));
    act.sa_flags = 0;

    /* Set an alarm so a timeout occurs after ALARMC seconds, in case
     * something is seriously broken.
     */
    sigaction(SIGALRM, &act, NULL);
    alarm(ALARMC);
    fcntl(lockdes, F_SETLKW, &lock);
    alarm(0);

    if ((jobno = nextjob()) == EOF)
	perr("cannot generate job number");

    sprintf(ppos, "%c%5lx%8lx", queue, 
	    jobno, (unsigned long) (runtimer/60));

    for(ap=ppos; *ap != '\0'; ap ++)
	if (*ap == ' ')
	    *ap = '0';

    if (stat(atfile, &statbuf) != 0)
	if (errno != ENOENT)
	    perr("cannot access " ATJOB_DIR);

    /* Create the file. The x bit is only going to be set after it has
     * been completely written out, to make sure it is not executed in the
     * meantime.  To make sure they do not get deleted, turn off their r
     * bit.  Yes, this is a kluge.
     */
    cmask = umask(S_IRUSR | S_IWUSR | S_IXUSR);
    if ((fdes = creat(atfile, O_WRONLY)) == -1)
	perr("cannot create atjob file"); 

    if ((fd2 = dup(fdes)) <0)
	perr("error in dup() of job file");

    if(fchown(fd2, real_uid, real_gid) != 0)
	perr("cannot give away file");

    PRIV_END

    /* We no longer need suid root; now we just need to be able to write
     * to the directory, if necessary.
     */

    REDUCE_PRIV(DAEMON_UID, DAEMON_GID)

    /* We've successfully created the file; let's set the flag so it 
     * gets removed in case of an interrupt or error.
     */
    fcreated = 1;

    /* Now we can release the lock, so other people can access it
     */
    lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0;
    lock.l_len = 0;
    fcntl(lockdes, F_SETLKW, &lock);
    close(lockdes);

    if((fp = fdopen(fdes, "w")) == NULL)
	panic("cannot reopen atjob file");

    /* Get the userid to mail to, first by trying getlogin(),
     * then from LOGNAME, finally from getpwuid().
     */
    mailname = getlogin();
    if (mailname == NULL)
	mailname = getenv("LOGNAME");

    if ((mailname == NULL) || (mailname[0] == '\0') 
	|| (strlen(mailname) >= MAXLOGNAME) || (getpwnam(mailname)==NULL))
    {
	pass_entry = getpwuid(real_uid);
	if (pass_entry != NULL)
	    mailname = pass_entry->pw_name;
    }

    if (atinput != (char *) NULL)
    {
	fpin = freopen(atinput, "r", stdin);
	if (fpin == NULL)
	    perr("cannot open input file");
    }
    fprintf(fp, "#!/bin/sh\n# atrun uid=%ld gid=%ld\n# mail %*s %d\n",
	(long) real_uid, (long) real_gid, MAXLOGNAME - 1, mailname,
	send_mail);

    /* Write out the umask at the time of invocation
     */
    fprintf(fp, "umask %lo\n", (unsigned long) cmask);

    /* Write out the environment. Anything that may look like a
     * special character to the shell is quoted, except for \n, which is
     * done with a pair of "'s.  Don't export the no_export list (such
     * as TERM or DISPLAY) because we don't want these.
     */
    for (atenv= environ; *atenv != NULL; atenv++)
    {
	int export = 1;
	char *eqp;

	eqp = strchr(*atenv, '=');
	if (eqp == NULL)
	    eqp = *atenv;
	else
	{
	    size_t i;
	    for (i=0; i<sizeof(no_export)/sizeof(no_export[0]); i++)
	    {
		export = export
		    && (strncmp(*atenv, no_export[i], 
				(size_t) (eqp-*atenv)) != 0);
	    }
	    eqp++;
	}

	if (export)
	{
	    (void)fputs("export ", fp);
	    fwrite(*atenv, sizeof(char), eqp-*atenv, fp);
	    for(ap = eqp;*ap != '\0'; ap++)
	    {
		if (*ap == '\n')
		    fprintf(fp, "\"\n\"");
		else
		{
		    if (!isalnum(*ap)) {
			switch (*ap) {
			  case '%': case '/': case '{': case '[':
			  case ']': case '=': case '}': case '@':
			  case '+': case '#': case ',': case '.':
			  case ':': case '-': case '_':
			    break;
			  default:
			    fputc('\\', fp);
			    break;
			}
		    }
		    fputc(*ap, fp);
		}
	    }
	    fputc('\n', fp);
	    
	}
    }	
Exemplo n.º 2
0
static int command_inject(args_t * args)
{
	assert(args != NULL);

	struct stat st;
	if (stat(args->path, &st) != 0) {
		ERRNO(errno);
		return -1;
	}

	if (!S_ISREG(st.st_mode)) {
		ERRNO(errno);
		return -1;
	}

	FILE *i = fopen(args->path, "r");
	if (i == NULL) {
		ERRNO(errno);
		return-1;
	}

	FILE *o = fopen(args->file, "w");
	if (o == NULL) {
		ERRNO(errno);
		return -1;
	}

#define INPUT_SIZE		(4096 - (4096 / ECC_SIZE))
	char input[INPUT_SIZE];	// 4KB less 512 ECC bytes
#undef INPUT_SIZE

	size_t count = 0;
	while (count < st.st_size) {
		clearerr(i);

		size_t rc = fread(input, 1, sizeof input, i);
		if (rc == 0) {
			int err = ferror(i);
			if (err) {
				ERRNO(errno);
				return -1;
			} else
				break;
		}

		count += rc;

#define OUTPUT_SIZE		4096
		char output[OUTPUT_SIZE];
#undef OUTPUT_SIZE

		memset(output + sizeof input, 0, sizeof output - sizeof input);

		rc = (rc + 7) & ~7;	// 8-byte alignment

		ssize_t injected_size = 0;
		if (args->p8 == f_P8)
			injected_size =
			    p8_ecc_inject(output, sizeof output, input, rc);
		else
			injected_size =
			    sfc_ecc_inject(output, sizeof output, input, rc);
		if (injected_size < 0) {
			ERRNO(errno);
			return -1;
		}

		clearerr(o);
		rc = fwrite(output, 1, injected_size, o);
		if (rc == 0) {
			int err = ferror(o);
			if (err) {
				ERRNO(errno);
				return -1;
			}
		}
	}

	if (fclose(i) == EOF) {
		ERRNO(errno);
		return -1;
	}

	if (fclose(o) == EOF) {
		ERRNO(errno);
		return -1;
	}

	return 0;
}
Exemplo n.º 3
0
static int command_hexdump(args_t * args)
{
	assert(args != NULL);

	struct stat st;
	if (stat(args->path, &st) != 0) {
		ERRNO(errno);
		return -1;
	}

	if (!S_ISREG(st.st_mode)) {
		ERRNO(errno);
		return -1;
	}

	FILE *i = fopen(args->path, "r");
	if (i == NULL) {
		ERRNO(errno);
		return -1;
	}

	FILE *o = stdout;
	if (args->file != NULL) {
		o = fopen(args->file, "w");
		if (o == NULL) {
			ERRNO(errno);
			return -1;
		}
	}
#define INPUT_SIZE 		4086
	char input[INPUT_SIZE];	// multiple of 9-bytes
#undef INPUT_SIZE

	if (setvbuf(i, NULL, _IOFBF, __round_pow2(sizeof input)) != 0) {
		ERRNO(errno);
		return -1;
	}

	size_t count = 0;
	while (count < st.st_size) {
		clearerr(i);

		size_t rc = fread(input, 1, sizeof input, i);
		if (rc == 0) {
			int err = ferror(i);
			if (err) {
				ERRNO(errno);
				return -1;
			} else
				break;
		}

		if (args->p8 == f_P8)
			p8_ecc_dump(o, count, input, rc);
		else
			sfc_ecc_dump(o, count, input, rc);

		count += rc;
	}

	if (fclose(i) == EOF) {
		ERRNO(errno);
		return -1;
	}

	if (o != stdout) {
		if (fclose(o) == EOF) {
			ERRNO(errno);
			return -1;
		}
	}

	return 0;
}
Exemplo n.º 4
0
static int
gpsd_start(
	int     unit,
	peerT * peer)
{
	clockprocT * const pp = peer->procptr;
	gpsd_unitT * const up = emalloc_zero(sizeof(*up));

	struct stat sb;

	/* initialize the unit structure */
	up->fdt      = -1;
	up->addr     = s_gpsd_addr;
	up->tickpres = TICKOVER_LOW;

	/* setup refclock processing */
	up->unit    = unit;
	pp->unitptr = (caddr_t)up;
	pp->io.fd   = -1;
	pp->io.clock_recv = gpsd_receive;
	pp->io.srcclock   = peer;
	pp->io.datalen    = 0;
	pp->a_lastcode[0] = '\0';
	pp->lencode       = 0;
	pp->clockdesc     = DESCRIPTION;
	memcpy(&pp->refid, REFID, 4);

	/* Initialize miscellaneous variables */
	peer->precision = PRECISION;

	/* Create the device name and check for a Character Device. It's
	 * assumed that GPSD was started with the same link, so the
	 * names match. (If this is not practicable, we will have to
	 * read the symlink, if any, so we can get the true device
	 * file.)
	 */
	if (-1 == myasprintf(&up->device, "%s%u", s_dev_stem, unit)) {
	    msyslog(LOG_ERR, "%s clock device name too long",
		    refnumtoa(&peer->srcadr));
	    goto dev_fail;
	}
	if (-1 == stat(up->device, &sb) || !S_ISCHR(sb.st_mode)) {
		msyslog(LOG_ERR, "%s: '%s' is not a character device",
			refnumtoa(&peer->srcadr), up->device);
	    goto dev_fail;
	}
	LOGIF(CLOCKINFO,
	      (LOG_NOTICE, "%s: startup, device is '%s'",
	       refnumtoa(&peer->srcadr), up->device));
	return TRUE;

dev_fail:
	/* On failure, remove all UNIT ressources and declare defeat. */

	INSIST (up);
	free(up->device);
	free(up);

	pp->unitptr = (caddr_t)NULL;
	return FALSE;
}
Exemplo n.º 5
0
    int
main(int argc, char *argv[])
{
    int		found = 0;
    FILE	*fd;
#ifdef WIN3264
    int		i;
    struct stat st;
    char	icon[BUFSIZE];
    char	path[BUFSIZE];
    char	popup_path[BUFSIZE];

    /* The nsis uninstaller calls us with a "-nsis" argument. */
    if (argc == 2 && stricmp(argv[1], "-nsis") == 0)
	interactive = FALSE;
    else
#endif
	interactive = TRUE;

    /* Initialize this program. */
    do_inits(argv);

    printf("This program will remove the following items:\n");

#ifdef WIN3264
    if (popup_gvim_path(popup_path))
    {
	printf(" - the \"Edit with Vim\" entry in the popup menu\n");
	printf("   which uses \"%s\"\n", popup_path);
	if (interactive)
	    printf("\nRemove it (y/n)? ");
	if (!interactive || confirm())
	{
	    remove_popup();
	    /* Assume the "Open With" entry can be removed as well, don't
	     * bother the user with asking him again. */
	    remove_openwith();
	}
    }
    else if (openwith_gvim_path(popup_path))
    {
	printf(" - the Vim \"Open With...\" entry in the popup menu\n");
	printf("   which uses \"%s\"\n", popup_path);
	printf("\nRemove it (y/n)? ");
	if (confirm())
	    remove_openwith();
    }

    if (get_shell_folder_path(path, "desktop"))
    {
	printf("\n");
	for (i = 0; i < ICON_COUNT; ++i)
	{
	    sprintf(icon, "%s\\%s", path, icon_link_names[i]);
	    if (stat(icon, &st) == 0)
	    {
		printf(" - the \"%s\" icon on the desktop\n", icon_names[i]);
		++found;
	    }
	}
	if (found > 0)
	{
	    if (interactive)
		printf("\nRemove %s (y/n)? ", found > 1 ? "them" : "it");
	    if (!interactive || confirm())
		remove_icons();
	}
    }

    if (get_shell_folder_path(path, VIM_STARTMENU)
	    && stat(path, &st) == 0)
    {
	printf("\n - the \"%s\" entry in the Start Menu\n", VIM_STARTMENU);
	if (interactive)
	    printf("\nRemove it (y/n)? ");
	if (!interactive || confirm())
	    remove_start_menu();
    }
#endif

    printf("\n");
    found = remove_batfiles(0);
    if (found > 0)
    {
	if (interactive)
	    printf("\nRemove %s (y/n)? ", found > 1 ? "them" : "it");
	if (!interactive || confirm())
	    remove_batfiles(1);
    }

    fd = fopen("gvim.exe", "r");
    if (fd != NULL)
    {
	fclose(fd);
	printf("gvim.exe detected.  Attempting to unregister gvim with OLE\n");
	system("gvim.exe -silent -unregister");
    }

    delete_uninstall_key();

    if (interactive)
    {
	printf("\nYou may now want to delete the Vim executables and runtime files.\n");
	printf("(They are still where you unpacked them.)\n");
    }

    if (interactive)
    {
	rewind(stdin);
	printf("\nPress Enter to exit...");
	(void)getchar();
    }
    else
	sleep(3);

    return 0;
}
int get_file_size(char *name) {
	struct stat filestatus;
	stat(name, &filestatus );
	return filestatus.st_size;
}
Exemplo n.º 7
0
static gboolean read_persistent_state(GAPersistentState *pstate,
                                      const gchar *path, gboolean frozen)
{
    GKeyFile *keyfile = NULL;
    GError *gerr = NULL;
    struct stat st;
    gboolean ret = true;

    g_assert(pstate);

    if (stat(path, &st) == -1) {
        /* it's okay if state file doesn't exist, but any other error
         * indicates a permissions issue or some other misconfiguration
         * that we likely won't be able to recover from.
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       path, strerror(errno));
            ret = false;
            goto out;
        }

        /* file doesn't exist. initialize state to default values and
         * attempt to save now. (we could wait till later when we have
         * modified state we need to commit, but if there's a problem,
         * such as a missing parent directory, we want to catch it now)
         *
         * there is a potential scenario where someone either managed to
         * update the agent from a version that didn't use a key store
         * while qemu-ga thought the filesystem was frozen, or
         * deleted the key store prior to issuing a fsfreeze, prior
         * to restarting the agent. in this case we go ahead and defer
         * initial creation till we actually have modified state to
         * write, otherwise fail to recover from freeze.
         */
        set_persistent_state_defaults(pstate);
        if (!frozen) {
            ret = write_persistent_state(pstate, path);
            if (!ret) {
                g_critical("unable to create state file at path %s", path);
                ret = false;
                goto out;
            }
        }
        ret = true;
        goto out;
    }

    keyfile = g_key_file_new();
    g_key_file_load_from_file(keyfile, path, 0, &gerr);
    if (gerr) {
        g_critical("error loading persistent state from path: %s, %s",
                   path, gerr->message);
        ret = false;
        goto out;
    }

    persistent_state_from_keyfile(pstate, keyfile);

out:
    if (keyfile) {
        g_key_file_free(keyfile);
    }
    if (gerr) {
        g_error_free(gerr);
    }

    return ret;
}
Exemplo n.º 8
0
Arquivo: tod.c Projeto: peterSVS/APIRI
int tod_set(const struct timeval *tv, const int *tzsec_off)
{
	struct stat sb;
	struct timeval tval;
        struct tm tm;
	rule_struct dst_rules[2];
	char buf[64+TZ_BUFLEN] = {'T','Z','i','f','2', 0};
	char *tzstr = &buf[54];
	int tzoff, dstoff;
	int fd;

	tzset();
	if ((tzsec_off != NULL) && (*tzsec_off != -timezone)) {
		// We must set the timezone offset but preserve any existing DST rule
		
		// Read existing DST Rule ?
		// is /etc/localtime present?
		if (stat("/etc/localtime", &sb) == 0) {
			if (get_dst_rules(dst_rules) == -1)
				return -1;
			// modify rule info and rewrite
			tzoff = -(*tzsec_off);
			dstoff = tzoff - (dst_rules[0].gmt_offset - dst_rules[1].gmt_offset);
			// Fill std offset
			tzstr += sprintf(tzstr, "\nATCST%2.2d:%2.2d:%2.2d",
				tzoff/3600, (tzoff%3600)/60, (tzoff%3600)%60);
			// Fill dst rules, if any
			if (!!dst_rules[1].tzname[0]) {
				// Fill dst offset
				tzstr += sprintf(tzstr, "ATCDT%2.2d:%2.2d:%2.2d",
					dstoff/3600, (dstoff%3600)/60, (dstoff%3600)%60);
				// Fill begin dst rule
				tzstr += sprintf(tzstr, ",M%d.%d.%d/%2.2ld:%2.2ld:%2.2ld",
					dst_rules[0].month,
					dst_rules[0].week,
					dst_rules[0].day,
					dst_rules[0].dst_offset/3600,
					(dst_rules[0].dst_offset%3600)/60,
					(dst_rules[0].dst_offset%3600)%60);
				// Fill end dst rule
				tzstr += sprintf(tzstr, ",M%d.%d.%d/%2.2ld:%2.2ld:%2.2ld",
					dst_rules[1].month,
					dst_rules[1].week,
					dst_rules[1].day,
					dst_rules[1].dst_offset/3600,
					(dst_rules[1].dst_offset%3600)/60,
					(dst_rules[1].dst_offset%3600)%60);
			}
			*tzstr++ = '\n';
			// Write to temp file
			fd = open("/etc/localtime~", O_RDWR|O_CREAT|O_TRUNC);
			if (fd >= 0) {
				write(fd, buf, (tzstr-buf));
				fsync(fd);
				close(fd);
			} else {
				return -1;
			}
			// Rename to actual filename (or move to /usr/share/zoneinfo and link?)
			if (rename("/etc/localtime~", "/etc/localtime") == -1)
				return -1;			
		}
		// Update globals with new timezone
		tzset();
	}
	
	if (tv != NULL) {
		tval = *tv;
                if (tzsec_off == NULL)
                        tzset();
                gmtime_r(&tval.tv_sec, &tm);
                tm.tm_isdst = -1;
                if (mktime(&tm) == -1)
                        return -1;
		tval.tv_sec += timezone - ((daylight && tm.tm_isdst)?3600:0);
		settimeofday(&tval, NULL);
	}
	return 0;
}
Exemplo n.º 9
0
void list_modules()
{
	DIR* dir = NULL;
	struct dirent *dp = NULL;
	char *moddir  = NULL;

	moddir = get_module_dir();
	if(moddir == NULL)
	{
		error("Failure getting module directory! (Perhaps set MPG123_MODDIR?)");
		exit(-1); /* TODO: change this to return a value instead of exit()! */
	}
	/* Open the module directory */
	dir = opendir(moddir);
	if (dir==NULL) {
		error2("Failed to open the module directory (%s): %s\n", PKGLIBDIR, strerror(errno));
		free(moddir);
		exit(-1);
	}
	
	if(chdir(moddir) != 0)
	{
		error2("Failed to enter module directory (%s): %s\n", PKGLIBDIR, strerror(errno));
		closedir( dir );
		free(moddir);
		exit(-1);
	}
	/* Display the program title */
	/* print_title(stderr); */

	/* List the output modules */
	printf("\n");
	printf("Available modules\n");
	printf("-----------------\n");
	
	while( (dp = readdir(dir)) != NULL ) {
		struct stat fst;
		if(stat(dp->d_name, &fst) != 0) continue;
		if(S_ISREG(fst.st_mode)) /* Allow links? */
		{
			char* ext = dp->d_name + strlen( dp->d_name ) - strlen( MODULE_FILE_SUFFIX );
			if (strcmp(ext, MODULE_FILE_SUFFIX) == 0)
			{
				char *module_name = NULL;
				char *module_type = NULL;
				char *uscore_pos = NULL;
				mpg123_module_t *module = NULL;
				
				/* Extract the module type */
				module_type = strdup( dp->d_name );
				uscore_pos = strchr( module_type, '_' );
				if (uscore_pos==NULL || (uscore_pos>=module_type+strlen(module_type)+1) )
				{
					free(module_type);
					continue;
				}
				
				*uscore_pos = '\0';
				
				/* Extract the short name of the module */
				module_name = strdup( dp->d_name + strlen( module_type ) + 1 );
				module_name[ strlen( module_name ) - strlen( MODULE_FILE_SUFFIX ) ] = '\0';
				/* Open the module */
				module = open_module_here(module_type, module_name);
				if (module) {
					printf("%-15s%s  %s\n", module->name, module_type, module->description );
				
					/* Close the module again */
					close_module( module );
				}
				free( module_name );
				free( module_type );
			}
		}
	}

	closedir( dir );
	free(moddir);
	exit(0);
}
Exemplo n.º 10
0
int
main(int argc, char *argv[])
{
	struct stat	 sb;
	struct timeval	 start;
	fstype_t	*fstype;
	fsinfo_t	 fsoptions;
	fsnode		*root;
	int	 	 ch, i, len;
	char		*subtree;
	char		*specfile;

	setprogname(argv[0]);

	debug = 0;
	if ((fstype = get_fstype(DEFAULT_FSTYPE)) == NULL)
		errx(1, "Unknown default fs type `%s'.", DEFAULT_FSTYPE);

		/* set default fsoptions */
	(void)memset(&fsoptions, 0, sizeof(fsoptions));
	fsoptions.fd = -1;
	fsoptions.sectorsize = -1;

	if (fstype->prepare_options)
		fstype->prepare_options(&fsoptions);

	specfile = NULL;
	if (gettimeofday(&start, NULL) == -1)
		err(1, "Unable to get system time");

	start_time.tv_sec = start.tv_sec;
	start_time.tv_nsec = start.tv_usec * 1000;

	while ((ch = getopt(argc, argv, "B:b:Dd:f:F:M:m:N:o:ps:S:t:xZ")) != -1) {
		switch (ch) {

		case 'B':
			if (strcmp(optarg, "be") == 0 ||
			    strcmp(optarg, "4321") == 0 ||
			    strcmp(optarg, "big") == 0) {
#if BYTE_ORDER == LITTLE_ENDIAN
				fsoptions.needswap = 1;
#endif
			} else if (strcmp(optarg, "le") == 0 ||
			    strcmp(optarg, "1234") == 0 ||
			    strcmp(optarg, "little") == 0) {
#if BYTE_ORDER == BIG_ENDIAN
				fsoptions.needswap = 1;
#endif
			} else {
				warnx("Invalid endian `%s'.", optarg);
				usage();
			}
			break;

		case 'b':
			len = strlen(optarg) - 1;
			if (optarg[len] == '%') {
				optarg[len] = '\0';
				fsoptions.freeblockpc =
				    strsuftoll("free block percentage",
					optarg, 0, 99);
			} else {
				fsoptions.freeblocks =
				    strsuftoll("free blocks",
					optarg, 0, LLONG_MAX);
			}
			break;

		case 'D':
			dupsok = 1;
			break;

		case 'd':
			debug = strtoll(optarg, NULL, 0);
			break;

		case 'f':
			len = strlen(optarg) - 1;
			if (optarg[len] == '%') {
				optarg[len] = '\0';
				fsoptions.freefilepc =
				    strsuftoll("free file percentage",
					optarg, 0, 99);
			} else {
				fsoptions.freefiles =
				    strsuftoll("free files",
					optarg, 0, LLONG_MAX);
			}
			break;

		case 'F':
			specfile = optarg;
			break;

		case 'M':
			fsoptions.minsize =
			    strsuftoll("minimum size", optarg, 1LL, LLONG_MAX);
			break;

		case 'N':
			if (! setup_getid(optarg))
				errx(1,
			    "Unable to use user and group databases in `%s'",
				    optarg);
			break;

		case 'm':
			fsoptions.maxsize =
			    strsuftoll("maximum size", optarg, 1LL, LLONG_MAX);
			break;
			
		case 'o':
		{
			char *p;

			while ((p = strsep(&optarg, ",")) != NULL) {
				if (*p == '\0')
					errx(1, "Empty option");
				if (! fstype->parse_options(p, &fsoptions))
					usage();
			}
			break;
		}
		case 'p':
			/* Deprecated in favor of 'Z' */
			fsoptions.sparse = 1;
			break;

		case 's':
			fsoptions.minsize = fsoptions.maxsize =
			    strsuftoll("size", optarg, 1LL, LLONG_MAX);
			break;

		case 'S':
			fsoptions.sectorsize =
			    (int)strsuftoll("sector size", optarg,
				1LL, INT_MAX);
			break;

		case 't':
			/* Check current one and cleanup if necessary. */
			if (fstype->cleanup_options)
				fstype->cleanup_options(&fsoptions);
			fsoptions.fs_specific = NULL;
			if ((fstype = get_fstype(optarg)) == NULL)
				errx(1, "Unknown fs type `%s'.", optarg);
			fstype->prepare_options(&fsoptions);
			break;

		case 'x':
			fsoptions.onlyspec = 1;
			break;

		case 'Z':
			/* Superscedes 'p' for compatibility with NetBSD makefs(8) */
			fsoptions.sparse = 1;
			break;

		case '?':
		default:
			usage();
			/* NOTREACHED */

		}
	}
	if (debug) {
		printf("debug mask: 0x%08x\n", debug);
		printf("start time: %ld.%ld, %s",
		    (long)start_time.tv_sec, (long)start_time.tv_nsec,
		    ctime(&start_time.tv_sec));
	}
	argc -= optind;
	argv += optind;

	if (argc < 2)
		usage();

	/* -x must be accompanied by -F */
	if (fsoptions.onlyspec != 0 && specfile == NULL)
		errx(1, "-x requires -F mtree-specfile.");

	/* Accept '-' as meaning "read from standard input". */
	if (strcmp(argv[1], "-") == 0)
		sb.st_mode = S_IFREG;
	else {
		if (stat(argv[1], &sb) == -1)
			err(1, "Can't stat `%s'", argv[1]);
	}

	switch (sb.st_mode & S_IFMT) {
	case S_IFDIR:		/* walk the tree */
		subtree = argv[1];
		TIMER_START(start);
		root = walk_dir(subtree, ".", NULL, NULL);
		TIMER_RESULTS(start, "walk_dir");
		break;
	case S_IFREG:		/* read the manifest file */
		subtree = ".";
		TIMER_START(start);
		root = read_mtree(argv[1], NULL);
		TIMER_RESULTS(start, "manifest");
		break;
	default:
		errx(1, "%s: not a file or directory", argv[1]);
		/* NOTREACHED */
	}

	/* append extra directory */
	for (i = 2; i < argc; i++) {
		if (stat(argv[i], &sb) == -1)
			err(1, "Can't stat `%s'", argv[i]);
		if (!S_ISDIR(sb.st_mode))
			errx(1, "%s: not a directory", argv[i]);
		TIMER_START(start);
		root = walk_dir(argv[i], ".", NULL, root);
		TIMER_RESULTS(start, "walk_dir2");
	}

	if (specfile) {		/* apply a specfile */
		TIMER_START(start);
		apply_specfile(specfile, subtree, root, fsoptions.onlyspec);
		TIMER_RESULTS(start, "apply_specfile");
	}

	if (debug & DEBUG_DUMP_FSNODES) {
		printf("\nparent: %s\n", subtree);
		dump_fsnodes(root);
		putchar('\n');
	}

				/* build the file system */
	TIMER_START(start);
	fstype->make_fs(argv[0], subtree, root, &fsoptions);
	TIMER_RESULTS(start, "make_fs");

	free_fsnodes(root);

	exit(0);
	/* NOTREACHED */
}
Exemplo n.º 11
0
static int open_dso(const char * path, pid_t * pidp, rpm_loff_t *fsizep)
{
    static const char * cmd = NULL;
    static int initted = 0;
    int fdno;

    if (!initted) {
	cmd = rpmExpand("%{?__prelink_undo_cmd}", NULL);
	initted++;
    }

    if (pidp) *pidp = 0;

    if (fsizep) {
	struct stat sb, * st = &sb;
	if (stat(path, st) < 0)
	    return -1;
	*fsizep = st->st_size;
    }

    fdno = open(path, O_RDONLY);
    if (fdno < 0)
	return fdno;

    if (!(cmd && *cmd))
	return fdno;

    if (pidp != NULL && is_prelinked(fdno)) {
	int pipes[2];
	pid_t pid;

	close(fdno);
	pipes[0] = pipes[1] = -1;
	if (pipe(pipes) < 0)
	    return -1;

	pid = fork();
	if (pid < 0) {
	    close(pipes[0]);
	    close(pipes[1]);
	    return -1;
	}

	if (pid == 0) {
	    ARGV_t av, lib;
	    int dfd;
	    argvSplit(&av, cmd, " ");

	    close(pipes[0]);
	    dfd = dup2(pipes[1], STDOUT_FILENO);
	    close(pipes[1]);
	    if (dfd >= 0 && (lib = argvSearch(av, "library", NULL)) != NULL) {
		*lib = (char *) path;
		unsetenv("MALLOC_CHECK_");
		execve(av[0], av+1, environ);
	    }
	    _exit(127); /* not normally reached */
	} else {
	    *pidp = pid;
	    fdno = pipes[0];
	    close(pipes[1]);
	}
    }

    return fdno;
}
Exemplo n.º 12
0
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <common.cxx>
#include <tar>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

CASE("Reading single entry tar file")
{
  tar::Reader r;
  struct stat st;
  int res = stat("test-single.tar", &st);
  EXPECT(res != -1);
  size_t size = st.st_size;
  int fd = open("test-single.tar", O_RDONLY);
  EXPECT_NOT(fd == -1);
  const uint8_t *mem = (const uint8_t *)mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  tar::Tar tar = r.read_uncompressed(mem, size);
  EXPECT(tar.num_elements() == 1);
  auto names = tar.element_names();
  EXPECT(names.size() == 1);
  const auto& elements = tar.elements();
  EXPECT(elements.size() == 1);
  const auto& e = elements.at(0);
  EXPECT_NOT(e.is_dir());
  EXPECT(e.typeflag_is_set());
  EXPECT(e.typeflag() == REGTYPE); // regular file
Exemplo n.º 13
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;
}
Exemplo n.º 14
0
void
running_check(int check_type)
{
    int        total_num=0, i, j, k;
    FILE      *fp;
    char       line[2][LEN_40960];
    char       filename[LEN_128] = {0};
    char       tmp[10][LEN_4096];
    char       check[LEN_40960] = {0};
    char       host_name[LEN_64] = {0};
    struct     module *mod = NULL;
    struct     stat statbuf;
    time_t     nowtime;
    double    *st_array;

    /* get hostname */
    if (0 != gethostname(host_name, sizeof(host_name))) {
        do_debug(LOG_FATAL, "tsar -check: gethostname err, errno=%d", errno);
    }
    i = 0;
    while (host_name[i]) {
        if (!isprint(host_name[i++])) {
            host_name[i-1] = '\0';
            break;
        }
    }
    memset(tmp, 0, 10 * LEN_4096);
    sprintf(check, "%s\ttsar\t", host_name);
    sprintf(filename, "%s", conf.output_file_path);
    fp = fopen(filename, "r");
    if (!fp) {
        do_debug(LOG_FATAL, "unable to open the log file %s.\n", filename);
    }
    /* check file update time */
    stat(filename, &statbuf);
    time(&nowtime);
    if (nowtime - statbuf.st_mtime > 300) {
        do_debug(LOG_FATAL, "/var/log/tsar.data is far away from now, now time is %d, last time is %d", nowtime, statbuf.st_mtime);
    }
    /* get file len */
    memset(&line[0], 0, LEN_40960);
    total_num =0;
    /* find two \n from end*/
    if (fseek(fp, -1, SEEK_END) != 0) {
        do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
    }
    while (1) {
        if (fgetc(fp) == '\n') {
            ++total_num;
        }
        if (total_num == 3) {
            break;
        }
        if (fseek(fp, -2, SEEK_CUR) != 0) {
            /* just 1 or 2 line, goto file header */
            if (fseek(fp, 0, SEEK_SET) != 0) {
                do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
            }
            break;
        }
    }
    /*FIX ME*/
    if (total_num == 0) {
        if (fclose(fp) < 0) {
            do_debug(LOG_FATAL, "fclose error:%s", strerror(errno));
        }
        memset(filename, 0, sizeof(filename));
        sprintf(filename, "%s.1", conf.output_file_path);
        fp = fopen(filename, "r");
        if (!fp) {
            do_debug(LOG_FATAL, "unable to open the log file %s.\n", filename);
        }
        total_num = 0;
        memset(&line[0], 0, 2 * LEN_40960);
        /* count tsar.data.1 lines */
        if (fseek(fp, -1, SEEK_END) != 0) {
            do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
        }
        while (1) {
            if (fgetc(fp) == '\n') {
                ++total_num;
            }
            if (total_num == 3) {
                break;
            }
            if (fseek(fp, -2, SEEK_CUR) != 0) {
                if (fseek(fp, 0, SEEK_SET) != 0) {
                    do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
                }
                break;
            }
        }
        if (total_num < 2) {
            do_debug(LOG_FATAL, "not enough lines at log file %s.\n", filename);
        }

        memset(&line[0], 0, LEN_40960);
        if (!fgets(line[0], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }
        memset(&line[1], 0, LEN_40960);
        if (!fgets(line[1], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }

    } else if (total_num == 1) {
        memset(&line[1], 0, LEN_40960);
        if (!fgets(line[1], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }
        if (fclose(fp) < 0) {
            do_debug(LOG_FATAL, "fclose error:%s", strerror(errno));
        }
        sprintf(filename, "%s.1", conf.output_file_path);
        fp = fopen(filename, "r");
        if (!fp) {
            do_debug(LOG_FATAL, "unable to open the log file %s\n", filename);
        }
        total_num = 0;
        /* go to the start of the last line at tsar.data.1 */
        if (fseek(fp, -1, SEEK_END) != 0) {
            do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
        }
        while (1) {
            if (fgetc(fp) == '\n') {
                ++total_num;
            }
            /* find the sencond \n from the end, read fp point to the last line */
            if (total_num == 2) {
                break;
            }
            if (fseek(fp, -2, SEEK_CUR) != 0) {
                if (fseek(fp, 0, SEEK_SET) != 0) {
                    do_debug(LOG_FATAL, "fseek error:%s", strerror(errno));
                }
                break;
            }
        }

        if (total_num < 1) {
            do_debug(LOG_FATAL, "not enough lines at log file %s\n", filename);
        }
        memset(&line[0], 0, LEN_40960);
        if (!fgets(line[0], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }

    } else {
        memset(&line[0], 0, LEN_40960);
        if (!fgets(line[0], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }
        memset(&line[1], 0, LEN_40960);
        if (!fgets(line[1], LEN_40960, fp)) {
            do_debug(LOG_FATAL, "fgets error:%s", strerror(errno));
        }
    }
    /* set struct module fields */
    init_module_fields();

    /* read one line to init module parameter */
    read_line_to_module_record(line[0]);
    collect_record_stat();

    read_line_to_module_record(line[1]);
    collect_record_stat();
    /*display check detail*/
    /* ---------------------------RUN_CHECK_NEW--------------------------------------- */
    if (check_type == RUN_CHECK_NEW) {
        printf("%s\ttsar\t", host_name);
        for (i = 0; i < statis.total_mod_num; i++) {
            mod = &mods[i];
            if (!mod->enable) {
                continue;
            }
            struct mod_info *info = mod->info;
            /* get mod name */
            char *mod_name = strstr(mod->opt_line, "--");
            if (mod_name) {
                mod_name += 2;
            }

            char opt[LEN_128] = {0};
            char *n_record = strdup(mod->record);
            char *token = strtok(n_record, ITEM_SPLIT);
            char *s_token;

            for (j = 0; j < mod->n_item; j++) {
                memset(opt, 0, sizeof(opt));
                if (token) {
                    s_token = strstr(token, ITEM_SPSTART);
                    if (s_token) {
                        strncat(opt, token, s_token - token);
                        strcat(opt, ":");
                    }
                }
                st_array = &mod->st_array[j * mod->n_col];
                for (k=0; k < mod->n_col; k++) {
                    if (mod->spec) {
                        if (!st_array || !mod->st_flag) {
                            if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[k].summary_bit))
                                    || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[k].summary_bit)))
                            {
                                printf("%s:%s%s=-%s", mod_name, opt, trim(info[k].hdr, LEN_128), " ");
                            }

                        } else {
                            if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[k].summary_bit))
                                    || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[k].summary_bit)))
                            {
                                printf("%s:%s%s=", mod_name, opt, trim(info[k].hdr, LEN_128));
                                printf("%0.1f ", st_array[k]);
                            }
                        }

                    } else {
                        if (!st_array || !mod->st_flag) {
                            if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[k].summary_bit))
                                    || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[k].summary_bit)))
                            {
                                printf("%s:%s%s=-%s", mod_name, opt, trim(info[k].hdr, LEN_128), " ");
                            }

                        } else {
                            if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[k].summary_bit))
                                    || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[k].summary_bit)))
                            {
                                printf("%s:%s%s=", mod_name, opt, trim(info[k].hdr, LEN_128));
                                printf("%0.1f ", st_array[k]);
                            }
                        }

                    }
                }
                if (token) {
                    token = strtok(NULL, ITEM_SPLIT);
                }
            }
            if (n_record) {
                free(n_record);
                n_record = NULL;
            }
        }
        printf("\n");
        if (fclose(fp) < 0) {
            do_debug(LOG_FATAL, "fclose error:%s", strerror(errno));
        }
        fp = NULL;
        return;
    }
#ifdef OLDTSAR
    /*tsar -check output similar as:
      v014119.cm3   tsar   apache/qps=5.35 apache/rt=165.89 apache/busy=2 apache/idle=148 cpu=3.58 mem=74.93% load1=0.22 load5=0.27 load15=0.20 xvda=0.15 ifin=131.82 ifout=108.86 TCPretr=0.12 df/=4.04% df/home=10.00% df/opt=71.22% df/tmp=2.07% df/usr=21.27% df/var=5.19%
     */
    /* ------------------------------RUN_CHECK------------------------------------------- */
    if (check_type == RUN_CHECK) {
        for (i = 0; i < statis.total_mod_num; i++) {
            mod = &mods[i];
            if (!mod->enable){
                continue;
            }
            if (!strcmp(mod->name, "mod_apache")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[0], " apache/qps=- apache/rt=- apache/busy=- apache/idle=-");

                    } else {
                        sprintf(tmp[0], " apache/qps=%0.2f apache/rt=%0.2f apache/busy=%0.0f apache/idle=%0.0f", st_array[0], st_array[1], st_array[3], st_array[4]);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_cpu")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[1], " cpu=-");

                    } else {
                        sprintf(tmp[1], " cpu=%0.2f", st_array[5]);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_mem")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[2], " mem=-");

                    } else {
                        sprintf(tmp[2], " mem=%0.2f%%", st_array[5]);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_load")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[3], " load1=- load5=- load15=-");

                    } else {
                        sprintf(tmp[3], " load1=%0.2f load5=%0.2f load15=%0.2f", st_array[0], st_array[1], st_array[2]);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_io")) {
                char    opt[LEN_128] = {0};
                char    item[LEN_128] = {0};
                char   *n_record = strdup(mod->record);
                char   *token = strtok(n_record, ITEM_SPLIT);
                char   *s_token;
                for (j = 0; j < mod->n_item; j++) {
                    s_token = strstr(token, ITEM_SPSTART);
                    if (s_token) {
                        memset(opt, 0, sizeof(opt));
                        strncat(opt, token, s_token - token);
                        st_array = &mod->st_array[j * mod->n_col];
                        if (!st_array || !mod->st_flag) {
                            sprintf(item, " %s=-", opt);

                        } else {
                            sprintf(item, " %s=%0.2f", opt, st_array[10]);
                        }
                        strcat(tmp[4], item);
                    }
                    token = strtok(NULL, ITEM_SPLIT);
                }
                if (n_record) {
                    free(n_record);
                    n_record = NULL;
                }
            }
            if (!strcmp(mod->name, "mod_traffic")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[5], " ifin=- ifout=-");

                    } else {
                        sprintf(tmp[5], " ifin=%0.2f ifout=%0.2f", st_array[0] / 1000, st_array[1] / 1000);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_tcp")) {
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[6], " TCPretr=-");

                    } else {
                        sprintf(tmp[6], " TCPretr=%0.2f", st_array[7]);
                    }
                }
            }
            if (!strcmp(mod->name, "mod_partition")) {
                char    opt[LEN_128] = {0};
                char    item[LEN_128] = {0};
                char   *n_record = strdup(mod->record);
                char   *token = strtok(n_record, ITEM_SPLIT);
                char   *s_token;
                for (j = 0; j < mod->n_item; j++) {
                    s_token = strstr(token, ITEM_SPSTART);
                    if (s_token) {
                        memset(opt, 0, sizeof(opt));
                        strncat(opt, token, s_token - token);
                        st_array = &mod->st_array[j * mod->n_col];
                        if (!st_array || !mod->st_flag) {
                            sprintf(item, " df%s=-", opt);

                        } else {
                            sprintf(item, " df%s=%0.2f%%", opt, st_array[3]);
                        }
                        strcat(tmp[7], item);
                    }
                    token = strtok(NULL, ITEM_SPLIT);
                }
                if (n_record) {
                    free(n_record);
                    n_record = NULL;
                }
            }
            if (!strcmp(mod->name, "mod_nginx")){
                for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[8], " nginx/qps=- nginx/rt=-");

                    } else {
                        sprintf(tmp[8], " nginx/qps=%0.2f nginx/rt=%0.2f", st_array[7], st_array[8]);
                    }
                }
            }
	    if (!strcmp(mod->name, "mod_swap")) {
	        for (j = 0; j < mod->n_item; j++) {
                    st_array = &mod->st_array[j * mod->n_col];
                    if (!st_array || !mod->st_flag) {
                        sprintf(tmp[9], " swap/total=- swap/util=-");

                    } else {
                        sprintf(tmp[9], " swap/total=%0.2f swap/util=%0.2f%%", st_array[2] / 1024 / 1024, st_array[3]);
                    }
                }
	    }
        }
        for (j = 0; j < 10; j++) {
            strcat(check, tmp[j]);
        }
        printf("%s\n", check);
        if (fclose(fp) < 0) {
            do_debug(LOG_FATAL, "fclose error:%s", strerror(errno));
        }
        fp = NULL;
    }
#endif
}
Exemplo n.º 15
0
 bool Util::fileExists(std::string filename)
 {
     struct stat file_info;
     return (stat(filename.c_str(), &file_info) == 0);
 }
Exemplo n.º 16
0
/** 
  * Write udhcpd.conf
  * @ipforward : NULL if we want a simple config, otherwise include dns info etc...
  */
static int write_udhcpd_conf(struct ipforward_data *ipforward, struct mode_list_elem *data)
{
  FILE *conffile;
  char *ip, *interface;
  char *ipstart, *ipend;
  int dot = 0, i = 0, test;
  struct stat st;

  /* /tmp is often tmpfs, so we avoid writing to flash */
  conffile = fopen("/tmp/udhcpd.conf", "w");
  if(conffile == NULL)
  {
	log_debug("Error creating /etc/udhcpd.conf!\n");
	return(1);
  }

  /* generate start and end ip based on the setting */
  ip = get_network_ip();
  if(ip == NULL)
  {
	ip = strdup("192.168.2.15");
  }
  ipstart = malloc(sizeof(char)*15);
  ipend = malloc(sizeof(char)*15);
  while(i < 15)
  {
        if(dot < 3)
        {
                if(ip[i] == '.')
                        dot ++;
                ipstart[i] = ip[i];
                ipend[i] = ip[i];
        }
        else
        {
                ipstart[i] = '\0';
                ipend[i] = '\0';
                break;
        }
        i++;
  }
  strcat(ipstart,"1");
  strcat(ipend, "10");

  interface = get_interface(data);
  /* print all data in the file */
  fprintf(conffile, "start\t%s\n", ipstart);
  fprintf(conffile, "end\t%s\n", ipend);
  fprintf(conffile, "interface\t%s\n", interface);
  fprintf(conffile, "option\tsubnet\t255.255.255.0\n");
  if(ipforward != NULL)
  {
	if(!ipforward->dns1 || !ipforward->dns2)
	{
		log_debug("No dns info!");
	}
	else
		fprintf(conffile, "opt\tdns\t%s %s\n", ipforward->dns1, ipforward->dns2);
	fprintf(conffile, "opt\trouter\t%s\n", ip);
  }

  free(ipstart);
  free(ipend);
  free(ip);
  free(interface);
  fclose(conffile);
  log_debug("/etc/udhcpd.conf written.\n");

  /* check if it is a symlink, if not remove and link, create the link if missing */
  test = stat("/etc/udhcpd.conf", &st);
  /* if stat fails there is no file or link */
  if(test == -1)
	goto link;
  /* if it is not a link we remove it, else we expect the right link to be there */
  if((st.st_mode & S_IFMT) != S_IFLNK)
  {
	unlink("/etc/udhcpd.conf");
  }
  else
	goto end;

link:
  symlink("/tmp/udhcpd.conf", "/etc/udhcpd.conf");

end:

  return(0);
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
	if (argc != 4)
	{
		fprintf (stdout, "usage: %s reserved_words_file source_file output_dir\n", argv[0]);
		exit(1);
	}

	fprintf(stdout, "-- Lexer begin --\n");

	FILE *f;

	ParserData *parser_data = (ParserData *)malloc(sizeof(ParserData));

	/* tokenize reserved words file */

	char line[200];
	ReservedWord *head, *curr;
	head = NULL;

	f = fopen (argv[1], "r");

	if (f == NULL)
	{
		fprintf (stderr, "Can't open reserved words file!\n");
		exit(1);
	}

	fprintf(stdout, "Parsing reserved words file.. ");

	while (fgets (line, 200, f) != NULL)
	{
		curr = tokenize_reserved_word_str (line);
		curr->next = head;
		head = curr;
	}

	parser_data->reserved_words = head;
	fclose(f);

	fprintf(stdout,"ok\n");

	/* tokenize input source file */

	parser_data->source = fopen (argv[2], "r");

	if (parser_data->source == NULL)
	{
		fprintf (stderr, "Can't open source file!\n");
		exit(1);
	}

	char *output_dir = malloc(strlen(argv[3]));
	strcpy (output_dir, argv[3]);

	// ensure the output directory is present  
	struct stat fileStat;
	if (stat(output_dir, &fileStat) < 0)
	{
		mode_t process_mask = umask(0);
		mkdir(output_dir, S_IRWXU | S_IRWXG | S_IRWXO);
		umask(process_mask);

		if (stat(output_dir, &fileStat) < 0)
		{
			fprintf (stderr, "Output directory does not exist!\n");
			exit(1);
		}
	}

	// strip trailing "/" from output dir
	if (strcmp (&output_dir[strlen(output_dir)-1], "\\") == 0)
		output_dir[strlen(output_dir)-1] = 0;

	// open listing file for writing
	char *listing_filename = malloc(strlen(output_dir) + 9);
	sprintf(listing_filename, "%s/listing", output_dir);
	parser_data->listing = fopen (listing_filename, "w");

	if (parser_data->listing == NULL)
	{
		fprintf (stderr, "Can't create listing file at %s!\n", listing_filename);
		exit(1);
	}

	// open tokens file for writing
	char *tokens_filename = malloc(strlen(output_dir) + 9);
	sprintf(tokens_filename, "%s/tokens", output_dir);
	parser_data->tokens = fopen (tokens_filename, "w");

	if (parser_data->tokens == NULL)
	{
		fprintf (stderr, "Can't create tokens file at %s!\n", tokens_filename);
		exit(1);
	}

	// token file header
	fprintf (parser_data->tokens, "%-10s%-20s%-20s%s\n", "Line No.", "Lexeme", "TOKEN-TYPE", "ATTRIBUTE");

	// initalize symbol table
	parser_data->symbol_table = (SymbolTable *)malloc(sizeof(SymbolTable));
	parser_data->symbol_table->symbol = NULL;
	parser_data->symbol_table->next = NULL;

	fprintf(stdout, "Parsing source file..\n");

	parse(parser_data);

	if (parser_data->result > 0)
		fprintf(stderr, "Parsing was unsuccessful.\n");
	else
		fprintf(stdout, "Success\n");

	fclose(parser_data->source);
	fclose(parser_data->listing);
	fclose(parser_data->tokens);

	// open symbol table file for writing
	char *symtable_filename = malloc(strlen(output_dir) + 9);
	sprintf(symtable_filename, "%s/symtable", output_dir);
	f = fopen (symtable_filename, "w");

	if (f == NULL)
	{
		fprintf (stderr, "Can't create symbol table file at %s!\n", symtable_filename);
		exit(1);
	}

	// symbol table file header
	fprintf (f, "%-5s%s\n", "Loc.", "ID");

	// write ids to symbol table
	SymbolTable *s = parser_data->symbol_table;
	int i = 0;
	while (s != NULL && s->symbol != NULL)
	{
		fprintf (f, "%-5d%s\n", i, s->symbol);

		i++;
		s = s->next;
	}

	fclose(f);

	return(parser_data->result);
}
Exemplo n.º 18
0
int tagpopen() {

    dev_t devt;
	struct stat     st;
    int    rc = 0;

    devt = makedev(TAGP_MAJOR, 0);

    if (rc) {
        if (errno == ENOENT) {
            /* dev node does not exist. */
            rc = mkdir(DEVICE_NAME, (S_IFDIR | S_IRWXU |
                                                S_IRGRP | S_IXGRP |
                                                S_IROTH | S_IXOTH));
        } else {
            printf("ERROR: Problem with Base dev directory.  Error code from stat() is %d\n\n", errno);
        }

    } else {
        if (!(st.st_mode & S_IFDIR)) {
            rc = unlink(DEVICE_NAME);
            if (!rc) {
                rc = mkdir(DEVICE_NAME, (S_IFDIR | S_IRWXU |
                                                S_IRGRP | S_IXGRP |
                                                S_IROTH | S_IXOTH));
            }
        }
    }

    /*
     * Check for the /dev/tbase node, and create if it does not
     * exist.
     */
    rc = stat(DEVICE_NAME, &st);
    if (rc) {
        if (errno == ENOENT) {
            /* dev node does not exist */
            rc = mknod(DEVICE_NAME, (S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP), devt);
        } else {
            printf("ERROR:Problem with tbase device node directory.  Error code form stat() is %d\n\n", errno);
        }

    } else {
        /*
         * /dev/tbase CHR device exists.  Check to make sure it is for a
         * block device and that it has the right major and minor.
         */
        if ((!(st.st_mode & S_IFCHR)) ||
             (st.st_rdev != devt)) {

            /* Recreate the dev node. */
            rc = unlink(DEVICE_NAME);
            if (!rc) {
                rc = mknod(DEVICE_NAME, (S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP), devt);
            }
        }
    }

    tagp_fd = open(DEVICE_NAME, O_RDWR);

    if (tagp_fd < 0) {
        printf("ERROR: Open of device %s failed %d errno = %d\n", DEVICE_NAME,tagp_fd, errno);
        return errno;
    }
    else {
        printf("Device opened successfully \n");
      return 0;
    }

}
bool is_exist(string filename) {
	struct stat buf;
	int result = stat(filename.c_str(), &buf);
	return (result==0);
}
Exemplo n.º 20
0
int
main(int argc, char **argv)
{
    char *path;
    struct stat st;
    char *buffer;
    FILE *fp;
    int i, k;
    int rewrites_count = sizeof (rewrites) / sizeof (struct rewrite);

    if (argc != 2) {
        printf("usage: %s <libvirtmod.pyd>", argv[0]);
        return 1;
    }

    path = argv[1];

    if (stat(path, &st) < 0) {
        printf("error: could not stat '%s'\n", path);
        return 1;
    }

    buffer = malloc(st.st_size + 1024);
    fp = fopen(path, "rb");

    if (fp == NULL) {
        printf("error: could not open '%s' for reading\n", path);
        return 1;
    }

    if (fread(buffer, 1, st.st_size, fp) != st.st_size) {
        fclose(fp);
        free(buffer);
        printf("error: could not read from '%s'\n", path);
        return 1;
    }

    fclose(fp);

    for (i = 0; i < st.st_size - 100; ++i) {
        for (k = 0; k < rewrites_count; ++k) {
            if (memcmp(buffer + i, rewrites[k].from, rewrites[k].length) == 0) {
                printf("rewriting '%s' at 0x%08x\n", rewrites[k].from, i);

                memcpy(buffer + i, rewrites[k].to, rewrites[k].length);
                i += rewrites[k].length;
            }
        }
    }

    fp = fopen(path, "wb");

    if (fp == NULL) {
        free(buffer);
        printf("error: could not open '%s' for writing\n", path);
        return 1;
    }

    if (fwrite(buffer, 1, st.st_size, fp) != st.st_size) {
        fclose(fp);
        free(buffer);
        printf("error: could not write to '%s'\n", path);
        return 1;
    }

    fclose(fp);
    free(buffer);

    return 0;
}
int main(int argc, char **argv)
{
	idevice_t phone = NULL;
	lockdownd_client_t client = NULL;
	instproxy_client_t ipc = NULL;
	instproxy_error_t err;
	np_client_t np = NULL;
	afc_client_t afc = NULL;
#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
	lockdownd_service_descriptor_t service = NULL;
#else
	uint16_t service = 0;
#endif
	int res = 0;
	char *bundleidentifier = NULL;

	parse_opts(argc, argv);

	argc -= optind;
	argv += optind;

	if (IDEVICE_E_SUCCESS != idevice_new(&phone, udid)) {
		fprintf(stderr, "No iOS device found, is it plugged in?\n");
		return -1;
	}

	if (LOCKDOWN_E_SUCCESS != lockdownd_client_new_with_handshake(phone, &client, "ideviceinstaller")) {
		fprintf(stderr, "Could not connect to lockdownd. Exiting.\n");
		goto leave_cleanup;
	}

	if ((lockdownd_start_service
		 (client, "com.apple.mobile.notification_proxy",
		  &service) != LOCKDOWN_E_SUCCESS) || !service) {
		fprintf(stderr,
				"Could not start com.apple.mobile.notification_proxy!\n");
		goto leave_cleanup;
	}

	np_error_t nperr = np_client_new(phone, service, &np);
#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
	if (service) {
		lockdownd_service_descriptor_free(service);
	}
	service = NULL;
#else
	service = 0;
#endif
	if (nperr != NP_E_SUCCESS) {
		fprintf(stderr, "Could not connect to notification_proxy!\n");
		goto leave_cleanup;
	}

#ifdef HAVE_LIBIMOBILEDEVICE_1_1
	np_set_notify_callback(np, notifier, NULL);
#else
	np_set_notify_callback(np, notifier);
#endif

	const char *noties[3] = { NP_APP_INSTALLED, NP_APP_UNINSTALLED, NULL };

	np_observe_notifications(np, noties);

run_again:
#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
	if (service) {
		lockdownd_service_descriptor_free(service);
	}
	service = NULL;
#else
	service = 0;
#endif
	if ((lockdownd_start_service(client, "com.apple.mobile.installation_proxy",
		  &service) != LOCKDOWN_E_SUCCESS) || !service) {
		fprintf(stderr,
				"Could not start com.apple.mobile.installation_proxy!\n");
		goto leave_cleanup;
	}

	err = instproxy_client_new(phone, service, &ipc);
#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
	if (service) {
		lockdownd_service_descriptor_free(service);
	}
	service = NULL;
#else
	service = 0;
#endif
	if (err != INSTPROXY_E_SUCCESS) {
		fprintf(stderr, "Could not connect to installation_proxy!\n");
		goto leave_cleanup;
	}

	setbuf(stdout, NULL);

	if (last_status) {
		free(last_status);
		last_status = NULL;
	}
	notification_expected = 0;

	if (cmd == CMD_LIST_APPS) {
		int xml_mode = 0;
		plist_t client_opts = instproxy_client_options_new();
		instproxy_client_options_add(client_opts, "ApplicationType", "User", NULL);
		plist_t apps = NULL;

		/* look for options */
		if (options) {
			char *opts = strdup(options);
			char *elem = strtok(opts, ",");
			while (elem) {
				if (!strcmp(elem, "list_system")) {
					if (!client_opts) {
						client_opts = instproxy_client_options_new();
					}
					instproxy_client_options_add(client_opts, "ApplicationType", "System", NULL);
				} else if (!strcmp(elem, "list_all")) {
					instproxy_client_options_free(client_opts);
					client_opts = NULL;
				} else if (!strcmp(elem, "list_user")) {
					/* do nothing, we're already set */
				} else if (!strcmp(elem, "xml")) {
					xml_mode = 1;
				}
				elem = strtok(NULL, ",");
			}
			free(opts);
		}

		err = instproxy_browse(ipc, client_opts, &apps);
		instproxy_client_options_free(client_opts);
		if (err != INSTPROXY_E_SUCCESS) {
			fprintf(stderr, "ERROR: instproxy_browse returned %d\n", err);
			goto leave_cleanup;
		}
		if (!apps || (plist_get_node_type(apps) != PLIST_ARRAY)) {
			fprintf(stderr,
					"ERROR: instproxy_browse returnd an invalid plist!\n");
			goto leave_cleanup;
		}
		if (xml_mode) {
			char *xml = NULL;
			uint32_t len = 0;

			plist_to_xml(apps, &xml, &len);
			if (xml) {
				puts(xml);
				free(xml);
			}
			plist_free(apps);
			goto leave_cleanup;
		}
		printf("Total: %d apps\n", plist_array_get_size(apps));
		uint32_t i = 0;
		for (i = 0; i < plist_array_get_size(apps); i++) {
			plist_t app = plist_array_get_item(apps, i);
			plist_t p_appid =
				plist_dict_get_item(app, "CFBundleIdentifier");
			char *s_appid = NULL;
			char *s_dispName = NULL;
			char *s_version = NULL;
			plist_t dispName =
				plist_dict_get_item(app, "CFBundleDisplayName");
			plist_t version = plist_dict_get_item(app, "CFBundleVersion");

			if (p_appid) {
				plist_get_string_val(p_appid, &s_appid);
			}
			if (!s_appid) {
				fprintf(stderr, "ERROR: Failed to get APPID!\n");
				break;
			}

			if (dispName) {
				plist_get_string_val(dispName, &s_dispName);
			}
			if (version) {
				plist_get_string_val(version, &s_version);
			}

			if (!s_dispName) {
				s_dispName = strdup(s_appid);
			}
			if (s_version) {
				printf("%s - %s %s\n", s_appid, s_dispName, s_version);
				free(s_version);
			} else {
				printf("%s - %s\n", s_appid, s_dispName);
			}
			free(s_dispName);
			free(s_appid);
		}
		plist_free(apps);
	} else if (cmd == CMD_INSTALL || cmd == CMD_UPGRADE) {
		plist_t sinf = NULL;
		plist_t meta = NULL;
		char *pkgname = NULL;
		struct stat fst;
		uint64_t af = 0;
		char buf[8192];

#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
		if (service) {
			lockdownd_service_descriptor_free(service);
		}
		service = NULL;
#else
		service = 0;
#endif
		if ((lockdownd_start_service(client, "com.apple.afc", &service) !=
			 LOCKDOWN_E_SUCCESS) || !service) {
			fprintf(stderr, "Could not start com.apple.afc!\n");
			goto leave_cleanup;
		}

		lockdownd_client_free(client);
		client = NULL;

		if (afc_client_new(phone, service, &afc) != INSTPROXY_E_SUCCESS) {
			fprintf(stderr, "Could not connect to AFC!\n");
			goto leave_cleanup;
		}

		if (stat(appid, &fst) != 0) {
			fprintf(stderr, "ERROR: stat: %s: %s\n", appid, strerror(errno));
			goto leave_cleanup;
		}

		char **strs = NULL;
		if (afc_get_file_info(afc, PKG_PATH, &strs) != AFC_E_SUCCESS) {
			if (afc_make_directory(afc, PKG_PATH) != AFC_E_SUCCESS) {
				fprintf(stderr, "WARNING: Could not create directory '%s' on device!\n", PKG_PATH);
			}
		}
		if (strs) {
			int i = 0;
			while (strs[i]) {
				free(strs[i]);
				i++;
			}
			free(strs);
		}

		plist_t client_opts = instproxy_client_options_new();

		/* open install package */
		int errp = 0;
		struct zip *zf = NULL;
		
		if ((strlen(appid) > 5) && (strcmp(&appid[strlen(appid)-5], ".ipcc") == 0)) {
			zf = zip_open(appid, 0, &errp);
			if (!zf) {
				fprintf(stderr, "ERROR: zip_open: %s: %d\n", appid, errp);
				goto leave_cleanup;
			}

			char* ipcc = strdup(appid);
			if ((asprintf(&pkgname, "%s/%s", PKG_PATH, basename(ipcc)) > 0) && pkgname) {
				afc_make_directory(afc, pkgname);
			}

			printf("Uploading %s package contents... ", basename(ipcc));

			/* extract the contents of the .ipcc file to PublicStaging/<name>.ipcc directory */
			zip_uint64_t numzf = zip_get_num_entries(zf, 0);
			zip_uint64_t i = 0;
			for (i = 0; numzf > 0 && i < numzf; i++) {
				const char* zname = zip_get_name(zf, i, 0);
				char* dstpath = NULL;
				if (!zname) continue;
				if (zname[strlen(zname)-1] == '/') {
					// directory
					if ((asprintf(&dstpath, "%s/%s/%s", PKG_PATH, basename(ipcc), zname) > 0) && dstpath) {
						afc_make_directory(afc, dstpath);						}
					free(dstpath);
					dstpath = NULL;
				} else {
					// file
					struct zip_file* zfile = zip_fopen_index(zf, i, 0);
					if (!zfile) continue;

					if ((asprintf(&dstpath, "%s/%s/%s", PKG_PATH, basename(ipcc), zname) <= 0) || !dstpath || (afc_file_open(afc, dstpath, AFC_FOPEN_WRONLY, &af) != AFC_E_SUCCESS)) {
						fprintf(stderr, "ERROR: can't open afc://%s for writing\n", dstpath);
						free(dstpath);
						dstpath = NULL;
						zip_fclose(zfile);
						continue;
					}

					struct zip_stat zs;
					zip_stat_init(&zs);
					if (zip_stat_index(zf, i, 0, &zs) != 0) {
						fprintf(stderr, "ERROR: zip_stat_index %" PRIu64 " failed!\n", i);
						free(dstpath);
						dstpath = NULL;
						zip_fclose(zfile);
						continue;
					}

					free(dstpath);
					dstpath = NULL;

					zip_uint64_t zfsize = 0;
					while (zfsize < zs.size) {
						zip_int64_t amount = zip_fread(zfile, buf, sizeof(buf));
						if (amount == 0) {
							break;
						}

						if (amount > 0) {
							uint32_t written, total = 0;
							while (total < amount) {
								written = 0;
								if (afc_file_write(afc, af, buf, amount, &written) !=
									AFC_E_SUCCESS) {
									fprintf(stderr, "AFC Write error!\n");
									break;
								}
								total += written;
							}
							if (total != amount) {
								fprintf(stderr, "Error: wrote only %d of %" PRIi64 "\n", total, amount);
								afc_file_close(afc, af);
								zip_fclose(zfile);
								free(dstpath);
								goto leave_cleanup;
							}
						}

						zfsize += amount;
					}

					afc_file_close(afc, af);
					af = 0;

					zip_fclose(zfile);
				}
			}
			free(ipcc);
			printf("DONE.\n");

			instproxy_client_options_add(client_opts, "PackageType", "CarrierBundle", NULL);
		} else if (S_ISDIR(fst.st_mode)) {
			/* upload developer app directory */
			instproxy_client_options_add(client_opts, "PackageType", "Developer", NULL);

			if (asprintf(&pkgname, "%s/%s", PKG_PATH, basename(appid)) < 0) {
				fprintf(stderr, "ERROR: Out of memory allocating pkgname!?\n");
				goto leave_cleanup;
			}

			printf("Uploading %s package contents... ", basename(appid));
			afc_upload_dir(afc, appid, pkgname);
			printf("DONE.\n");
		} else {
			zf = zip_open(appid, 0, &errp);
			if (!zf) {
				fprintf(stderr, "ERROR: zip_open: %s: %d\n", appid, errp);
				goto leave_cleanup;
			}

			/* extract iTunesMetadata.plist from package */
			char *zbuf = NULL;
			uint32_t len = 0;
			plist_t meta_dict = NULL;
			if (zip_get_contents(zf, ITUNES_METADATA_PLIST_FILENAME, 0, &zbuf, &len) == 0) {
				meta = plist_new_data(zbuf, len);
				if (memcmp(zbuf, "bplist00", 8) == 0) {
					plist_from_bin(zbuf, len, &meta_dict);
				} else {
					plist_from_xml(zbuf, len, &meta_dict);
				}
			} else {
				fprintf(stderr, "WARNING: could not locate %s in archive!\n", ITUNES_METADATA_PLIST_FILENAME);
			}
			if (zbuf) {
				free(zbuf);
			}

			/* determine .app directory in archive */
			zbuf = NULL;
			len = 0;
			plist_t info = NULL;
			char* filename = NULL;
			char* app_directory_name = NULL;

			if (zip_get_app_directory(zf, &app_directory_name)) {
				fprintf(stderr, "Unable to locate app directory in archive!\n");
				goto leave_cleanup;
			}

			/* construct full filename to Info.plist */
			filename = (char*)malloc(strlen(app_directory_name)+10+1);
			strcpy(filename, app_directory_name);
			free(app_directory_name);
			app_directory_name = NULL;
			strcat(filename, "Info.plist");

			if (zip_get_contents(zf, filename, 0, &zbuf, &len) < 0) {
				fprintf(stderr, "WARNING: could not locate %s in archive!\n", filename);
				free(filename);
				zip_unchange_all(zf);
				zip_close(zf);
				goto leave_cleanup;
			}
			free(filename);
			if (memcmp(zbuf, "bplist00", 8) == 0) {
				plist_from_bin(zbuf, len, &info);
			} else {
				plist_from_xml(zbuf, len, &info);
			}
			free(zbuf);

			if (!info) {
				fprintf(stderr, "Could not parse Info.plist!\n");
				zip_unchange_all(zf);
				zip_close(zf);
				goto leave_cleanup;
			}

			char *bundleexecutable = NULL;

			plist_t bname = plist_dict_get_item(info, "CFBundleExecutable");
			if (bname) {
				plist_get_string_val(bname, &bundleexecutable);
			}

			bname = plist_dict_get_item(info, "CFBundleIdentifier");
			if (bname) {
				plist_get_string_val(bname, &bundleidentifier);
			}
			plist_free(info);
			info = NULL;

			if (!bundleexecutable) {
				fprintf(stderr, "Could not determine value for CFBundleExecutable!\n");
				zip_unchange_all(zf);
				zip_close(zf);
				goto leave_cleanup;
			}

			char *sinfname = NULL;
			if (asprintf(&sinfname, "Payload/%s.app/SC_Info/%s.sinf", bundleexecutable, bundleexecutable) < 0) {
				fprintf(stderr, "Out of memory!?\n");
				goto leave_cleanup;
			}
			free(bundleexecutable);

			/* extract .sinf from package */
			zbuf = NULL;
			len = 0;
			if (zip_get_contents(zf, sinfname, 0, &zbuf, &len) == 0) {
				sinf = plist_new_data(zbuf, len);
			} else {
				fprintf(stderr, "WARNING: could not locate %s in archive!\n", sinfname);
			}
			free(sinfname);
			if (zbuf) {
				free(zbuf);
			}

			/* copy archive to device */
			pkgname = NULL;
			if (asprintf(&pkgname, "%s/%s", PKG_PATH, bundleidentifier) < 0) {
				fprintf(stderr, "Out of memory!?\n");
				goto leave_cleanup;
			}

			printf("Copying '%s' to device... ", appid);

			if (afc_upload_file(afc, appid, pkgname) < 0) {
				free(pkgname);
				goto leave_cleanup;
			}

			printf("DONE.\n");

			if (bundleidentifier) {
				instproxy_client_options_add(client_opts, "CFBundleIdentifier", bundleidentifier, NULL);
			}
			if (sinf) {
				instproxy_client_options_add(client_opts, "ApplicationSINF", sinf, NULL);
			}
			if (meta) {
				instproxy_client_options_add(client_opts, "iTunesMetadata", meta, NULL);
			}
		}
		if (zf) {
			zip_unchange_all(zf);
			zip_close(zf);
		}

		/* perform installation or upgrade */
		if (cmd == CMD_INSTALL) {
			printf("Installing '%s'\n", bundleidentifier);
#ifdef HAVE_LIBIMOBILEDEVICE_1_1
			instproxy_install(ipc, pkgname, client_opts, status_cb, NULL);
#else
			instproxy_install(ipc, pkgname, client_opts, status_cb);
#endif
		} else {
			printf("Upgrading '%s'\n", bundleidentifier);
#ifdef HAVE_LIBIMOBILEDEVICE_1_1
			instproxy_upgrade(ipc, pkgname, client_opts, status_cb, NULL);
#else
			instproxy_upgrade(ipc, pkgname, client_opts, status_cb);
#endif
		}
		instproxy_client_options_free(client_opts);
		free(pkgname);
		wait_for_op_complete = 1;
		notification_expected = 1;
	} else if (cmd == CMD_UNINSTALL) {
		printf("Uninstalling '%s'\n", appid);
#ifdef HAVE_LIBIMOBILEDEVICE_1_1
		instproxy_uninstall(ipc, appid, NULL, status_cb, NULL);
#else
		instproxy_uninstall(ipc, appid, NULL, status_cb);
#endif
		wait_for_op_complete = 1;
		notification_expected = 0;
	} else if (cmd == CMD_LIST_ARCHIVES) {
		int xml_mode = 0;
		plist_t dict = NULL;
		plist_t lres = NULL;

		/* look for options */
		if (options) {
			char *opts = strdup(options);
			char *elem = strtok(opts, ",");
			while (elem) {
				if (!strcmp(elem, "xml")) {
					xml_mode = 1;
				}
				elem = strtok(NULL, ",");
			}
		}

		err = instproxy_lookup_archives(ipc, NULL, &dict);
		if (err != INSTPROXY_E_SUCCESS) {
			fprintf(stderr, "ERROR: lookup_archives returned %d\n", err);
			goto leave_cleanup;
		}
		if (!dict) {
			fprintf(stderr,
					"ERROR: lookup_archives did not return a plist!?\n");
			goto leave_cleanup;
		}

		lres = plist_dict_get_item(dict, "LookupResult");
		if (!lres || (plist_get_node_type(lres) != PLIST_DICT)) {
			plist_free(dict);
			fprintf(stderr, "ERROR: Could not get dict 'LookupResult'\n");
			goto leave_cleanup;
		}

		if (xml_mode) {
			char *xml = NULL;
			uint32_t len = 0;

			plist_to_xml(lres, &xml, &len);
			if (xml) {
				puts(xml);
				free(xml);
			}
			plist_free(dict);
			goto leave_cleanup;
		}
		plist_dict_iter iter = NULL;
		plist_t node = NULL;
		char *key = NULL;

		printf("Total: %d archived apps\n", plist_dict_get_size(lres));
		plist_dict_new_iter(lres, &iter);
		if (!iter) {
			plist_free(dict);
			fprintf(stderr, "ERROR: Could not create plist_dict_iter!\n");
			goto leave_cleanup;
		}
		do {
			key = NULL;
			node = NULL;
			plist_dict_next_item(lres, iter, &key, &node);
			if (key && (plist_get_node_type(node) == PLIST_DICT)) {
				char *s_dispName = NULL;
				char *s_version = NULL;
				plist_t dispName =
					plist_dict_get_item(node, "CFBundleDisplayName");
				plist_t version =
					plist_dict_get_item(node, "CFBundleVersion");
				if (dispName) {
					plist_get_string_val(dispName, &s_dispName);
				}
				if (version) {
					plist_get_string_val(version, &s_version);
				}
				if (!s_dispName) {
					s_dispName = strdup(key);
				}
				if (s_version) {
					printf("%s - %s %s\n", key, s_dispName, s_version);
					free(s_version);
				} else {
					printf("%s - %s\n", key, s_dispName);
				}
				free(s_dispName);
				free(key);
			}
		}
		while (node);
		plist_free(dict);
	} else if (cmd == CMD_ARCHIVE) {
		char *copy_path = NULL;
		int remove_after_copy = 0;
		int skip_uninstall = 1;
		int app_only = 0;
		int docs_only = 0;
		plist_t client_opts = NULL;

		/* look for options */
		if (options) {
			char *opts = strdup(options);
			char *elem = strtok(opts, ",");
			while (elem) {
				if (!strcmp(elem, "uninstall")) {
					skip_uninstall = 0;
				} else if (!strcmp(elem, "app_only")) {
					app_only = 1;
					docs_only = 0;
				} else if (!strcmp(elem, "docs_only")) {
					docs_only = 1;
					app_only = 0;
				} else if ((strlen(elem) > 5) && !strncmp(elem, "copy=", 5)) {
					copy_path = strdup(elem+5);
				} else if (!strcmp(elem, "remove")) {
					remove_after_copy = 1;
				}
				elem = strtok(NULL, ",");
			}
		}

		if (skip_uninstall || app_only || docs_only) {
			client_opts = instproxy_client_options_new();
			if (skip_uninstall) {
				instproxy_client_options_add(client_opts, "SkipUninstall", 1, NULL);
			}
			if (app_only) {
				instproxy_client_options_add(client_opts, "ArchiveType", "ApplicationOnly", NULL);
			} else if (docs_only) {
				instproxy_client_options_add(client_opts, "ArchiveType", "DocumentsOnly", NULL);
			}
		}

		if (copy_path) {
			struct stat fst;
			if (stat(copy_path, &fst) != 0) {
				fprintf(stderr, "ERROR: stat: %s: %s\n", copy_path, strerror(errno));
				free(copy_path);
				goto leave_cleanup;
			}

			if (!S_ISDIR(fst.st_mode)) {
				fprintf(stderr, "ERROR: '%s' is not a directory as expected.\n", copy_path);
				free(copy_path);
				goto leave_cleanup;
			}

#ifdef HAVE_LIBIMOBILEDEVICE_1_1_5
			if (service) {
				lockdownd_service_descriptor_free(service);
			}
			service = NULL;
#else
			service = 0;
#endif
			if ((lockdownd_start_service(client, "com.apple.afc", &service) != LOCKDOWN_E_SUCCESS) || !service) {
				fprintf(stderr, "Could not start com.apple.afc!\n");
				free(copy_path);
				goto leave_cleanup;
			}

			lockdownd_client_free(client);
			client = NULL;

			if (afc_client_new(phone, service, &afc) != INSTPROXY_E_SUCCESS) {
				fprintf(stderr, "Could not connect to AFC!\n");
				goto leave_cleanup;
			}
		}

#ifdef HAVE_LIBIMOBILEDEVICE_1_1
		instproxy_archive(ipc, appid, client_opts, status_cb, NULL);
#else
		instproxy_archive(ipc, appid, client_opts, status_cb);
#endif
		instproxy_client_options_free(client_opts);
		wait_for_op_complete = 1;
		if (skip_uninstall) {
			notification_expected = 0;
		} else {
			notification_expected = 1;
		}

		idevice_wait_for_operation_to_complete();

		if (copy_path) {
			if (err_occured) {
				afc_client_free(afc);
				afc = NULL;
				goto leave_cleanup;
			}
			FILE *f = NULL;
			uint64_t af = 0;
			/* local filename */
			char *localfile = NULL;
			if (asprintf(&localfile, "%s/%s.ipa", copy_path, appid) < 0) {
				fprintf(stderr, "Out of memory!?\n");
				goto leave_cleanup;
			}
			free(copy_path);

			f = fopen(localfile, "wb");
			if (!f) {
				fprintf(stderr, "ERROR: fopen: %s: %s\n", localfile, strerror(errno));
				free(localfile);
				goto leave_cleanup;
			}

			/* remote filename */
			char *remotefile = NULL;
			if (asprintf(&remotefile, "%s/%s.zip", APPARCH_PATH, appid) < 0) {
				fprintf(stderr, "Out of memory!?\n");
				goto leave_cleanup;
			}

			uint32_t fsize = 0;
			char **fileinfo = NULL;
			if ((afc_get_file_info(afc, remotefile, &fileinfo) != AFC_E_SUCCESS) || !fileinfo) {
				fprintf(stderr, "ERROR getting AFC file info for '%s' on device!\n", remotefile);
				fclose(f);
				free(remotefile);
				free(localfile);
				goto leave_cleanup;
			}

			int i;
			for (i = 0; fileinfo[i]; i+=2) {
				if (!strcmp(fileinfo[i], "st_size")) {
					fsize = atoi(fileinfo[i+1]);
					break;
				}
			}
			i = 0;
			while (fileinfo[i]) {
				free(fileinfo[i]);
				i++;
			}
			free(fileinfo);

			if (fsize == 0) {
				fprintf(stderr, "Hm... remote file length could not be determined. Cannot copy.\n");
				fclose(f);
				free(remotefile);
				free(localfile);
				goto leave_cleanup;
			}

			if ((afc_file_open(afc, remotefile, AFC_FOPEN_RDONLY, &af) != AFC_E_SUCCESS) || !af) {
				fclose(f);
				fprintf(stderr, "ERROR: could not open '%s' on device for reading!\n", remotefile);
				free(remotefile);
				free(localfile);
				goto leave_cleanup;
			}

			/* copy file over */
			printf("Copying '%s' --> '%s'... ", remotefile, localfile);
			free(remotefile);
			free(localfile);

			uint32_t amount = 0;
			uint32_t total = 0;
			char buf[8192];

			do {
				if (afc_file_read(afc, af, buf, sizeof(buf), &amount) != AFC_E_SUCCESS) {
					fprintf(stderr, "AFC Read error!\n");
					break;
				}

				if (amount > 0) {
					size_t written = fwrite(buf, 1, amount, f);
					if (written != amount) {
						fprintf(stderr, "Error when writing %d bytes to local file!\n", amount);
						break;
					}
					total += written;
				}
			} while (amount > 0);

			afc_file_close(afc, af);
			fclose(f);

			printf("DONE.\n");

			if (total != fsize) {
				fprintf(stderr, "WARNING: remote and local file sizes don't match (%d != %d)\n", fsize, total);
				if (remove_after_copy) {
					fprintf(stderr, "NOTE: archive file will NOT be removed from device\n");
					remove_after_copy = 0;
				}
			}

			if (remove_after_copy) {
				/* remove archive if requested */
				printf("Removing '%s'\n", appid);
				cmd = CMD_REMOVE_ARCHIVE;
				free(options);
				options = NULL;
				if (LOCKDOWN_E_SUCCESS != lockdownd_client_new_with_handshake(phone, &client, "ideviceinstaller")) {
					fprintf(stderr, "Could not connect to lockdownd. Exiting.\n");
					goto leave_cleanup;
				}
				goto run_again;
			}
		}
		goto leave_cleanup;
	} else if (cmd == CMD_RESTORE) {
#ifdef HAVE_LIBIMOBILEDEVICE_1_1
		instproxy_restore(ipc, appid, NULL, status_cb, NULL);
#else
		instproxy_restore(ipc, appid, NULL, status_cb);
#endif
		wait_for_op_complete = 1;
		notification_expected = 1;
	} else if (cmd == CMD_REMOVE_ARCHIVE) {
#ifdef HAVE_LIBIMOBILEDEVICE_1_1
		instproxy_remove_archive(ipc, appid, NULL, status_cb, NULL);
#else
		instproxy_remove_archive(ipc, appid, NULL, status_cb);
#endif
		wait_for_op_complete = 1;
	} else {
		printf
			("ERROR: no operation selected?! This should not be reached!\n");
		res = -2;
		goto leave_cleanup;
	}

	if (client) {
		/* not needed anymore */
		lockdownd_client_free(client);
		client = NULL;
	}

	idevice_wait_for_operation_to_complete();

leave_cleanup:
	if (bundleidentifier) {
		free(bundleidentifier);
	}
	if (np) {
		np_client_free(np);
	}
	if (ipc) {
		instproxy_client_free(ipc);
	}
	if (afc) {
		afc_client_free(afc);
	}
	if (client) {
		lockdownd_client_free(client);
	}
	idevice_free(phone);

	if (udid) {
		free(udid);
	}
	if (appid) {
		free(appid);
	}
	if (options) {
		free(options);
	}

	return res;
}
Exemplo n.º 22
0
isc_result_t
isc_entropy_createfilesource(isc_entropy_t *ent, const char *fname) {
	int fd;
	struct stat _stat;
	isc_boolean_t is_usocket = ISC_FALSE;
	isc_boolean_t is_connected = ISC_FALSE;
	isc_result_t ret;
	isc_entropysource_t *source;

	REQUIRE(VALID_ENTROPY(ent));
	REQUIRE(fname != NULL);

	LOCK(&ent->lock);

	source = NULL;

	if (stat(fname, &_stat) < 0) {
		ret = isc__errno2result(errno);
		goto errout;
	}
	/* 
	 * Solaris 2.5.1 does not have support for sockets (S_IFSOCK),
	 * but it does return type S_IFIFO (the OS believes that
	 * the socket is a fifo).  This may be an issue if we tell
	 * the program to look at an actual FIFO as its source of
	 * entropy.
	 */
#if defined(S_ISSOCK)
	if (S_ISSOCK(_stat.st_mode))
		is_usocket = ISC_TRUE;
#endif
#if defined(S_ISFIFO)
	if (S_ISFIFO(_stat.st_mode))
		is_usocket = ISC_TRUE;
#endif
	if (is_usocket)
		fd = socket(PF_UNIX, SOCK_STREAM, 0);
	else
		fd = open(fname, O_RDONLY | PORT_NONBLOCK, 0);

	if (fd < 0) {
		ret = isc__errno2result(errno);
		goto errout;
	}

	ret = make_nonblock(fd);
	if (ret != ISC_R_SUCCESS)
		goto closefd;

	if (is_usocket) {
		struct sockaddr_un sname;

		memset(&sname, 0, sizeof(sname));
		sname.sun_family = AF_UNIX;
		strncpy(sname.sun_path, fname, sizeof(sname.sun_path));
		sname.sun_path[sizeof(sname.sun_path)-1] = '0';
#ifdef ISC_PLATFORM_HAVESALEN
#if !defined(SUN_LEN)
#define SUN_LEN(su) \
	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
#endif
		sname.sun_len = SUN_LEN(&sname);
#endif

		if (connect(fd, (struct sockaddr *) &sname,
			    sizeof(struct sockaddr_un)) < 0) {
			if (errno != EINPROGRESS) {
				ret = isc__errno2result(errno);
				goto closefd;
			}
		} else
			is_connected = ISC_TRUE;
	}

	source = isc_mem_get(ent->mctx, sizeof(isc_entropysource_t));
	if (source == NULL) {
		ret = ISC_R_NOMEMORY;
		goto closefd;
	}

	/*
	 * From here down, no failures can occur.
	 */
	source->magic = SOURCE_MAGIC;
	source->ent = ent;
	source->total = 0;
	source->bad = ISC_FALSE;
	memset(source->name, 0, sizeof(source->name));
	ISC_LINK_INIT(source, link);
	if (is_usocket) {
		source->sources.usocket.handle = fd;
		if (is_connected)
			source->sources.usocket.status =
					isc_usocketsource_connected;
		else
			source->sources.usocket.status =
					isc_usocketsource_connecting;
		source->sources.usocket.sz_to_recv = 0;
		source->type = ENTROPY_SOURCETYPE_USOCKET;
	} else {
		source->sources.file.handle = fd;
		source->type = ENTROPY_SOURCETYPE_FILE;
	}

	/*
	 * Hook it into the entropy system.
	 */
	ISC_LIST_APPEND(ent->sources, source, link);
	ent->nsources++;

	UNLOCK(&ent->lock);
	return (ISC_R_SUCCESS);

 closefd:
	(void)close(fd);

 errout:
	if (source != NULL)
		isc_mem_put(ent->mctx, source, sizeof(isc_entropysource_t));

	UNLOCK(&ent->lock);

	return (ret);
}
Exemplo n.º 23
0
/***********************************************************************
 * Main
 ***********************************************************************/
int main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */
	char *fname;
	char *desc;
	int ind;
	struct stat *stbuf;
	struct sigaction sa, osa;

    /***************************************************************
     * parse standard options
     ***************************************************************/
	if ((msg = parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *)NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
		tst_exit();
	}

    /***************************************************************
     * perform global setup for test
     ***************************************************************/
	setup();

	/* set the expected errnos... */
	TEST_EXP_ENOS(exp_enos);

    /***************************************************************
     * check looping state if -c option given
     ***************************************************************/
	for (lc = 0; TEST_LOOPING(lc); lc++) {

		/* reset Tst_count in case we are looping. */
		Tst_count = 0;

		for (ind = 0; Test_cases[ind].desc != NULL; ind++) {

			fname = Test_cases[ind].pathname;
			desc = Test_cases[ind].desc;
			stbuf = Test_cases[ind].stbuf;

			if (stbuf == (struct stat *)-1) {
				/* special sig11 case */
				sa.sa_handler = &sig11_handler;
				sigemptyset(&sa.sa_mask);
				sa.sa_flags = 0;

				sigaction(SIGSEGV, NULL, &osa);
				sigaction(SIGSEGV, &sa, NULL);

				if (setjmp(sig11_recover)) {
					TEST_RETURN = -1;
					TEST_ERRNO = EFAULT;
				} else {
					TEST(stat(fname, stbuf));
				}
				sigaction(SIGSEGV, &osa, NULL);
			} else {
				/*
				 *  Call stat(2)
				 */

				TEST(stat(fname, stbuf));
			}

			/* check return code */
			if (TEST_RETURN == -1) {
				if (STD_FUNCTIONAL_TEST) {
					if (TEST_ERRNO ==
					    Test_cases[ind].exp_errno)
						tst_resm(TPASS,
							 "stat(<%s>, &stbuf) Failed, errno=%d",
							 desc, TEST_ERRNO);
					else
						tst_resm(TFAIL,
							 "stat(<%s>, &stbuf) Failed, errno=%d, expected errno:%d",
							 desc, TEST_ERRNO,
							 Test_cases[ind].
							 exp_errno);
				} else
					Tst_count++;
			} else {
				tst_resm(TFAIL,
					 "stat(<%s>, &stbuf) returned %ld, expected -1, errno:%d",
					 desc, TEST_RETURN,
					 Test_cases[ind].exp_errno);
			}
		}

	}			/* End for TEST_LOOPING */

    /***************************************************************
     * cleanup and exit
     ***************************************************************/
	cleanup();

	return 0;
}				/* End main */
Exemplo n.º 24
0
int myls(int argc, char *argv[])
{	
	DIR *directory; //Stores a pointer to the directory
	struct dirent *file;
	int i;
	struct stat sb;
	struct passwd *pwd;
	struct group *grp;
	if(!strcmp(argv[1], "-l"))
	{
		for(i=2; i<argc; i++)
		{
			if(!access(argv[i],F_OK)) //Check if the directory specified by argv[i] exists.
			{
				directory=opendir(argv[i]); //If it exists, then open the directory.

				if(directory!=NULL)
				{
					while((file=readdir(directory))!=NULL) //Read each entry in the directory.
					{
	
						if (stat(file->d_name, &sb) == -1) 
						{
							perror("stat");
						}
						//Display the type of file.
						switch (sb.st_mode & S_IFMT) 
						{
							case S_IFBLK:  printf("b");            
								       break;
							case S_IFCHR:  printf("c");        
								       break;
							case S_IFDIR:  printf("d");               
								       break;
							case S_IFIFO:  printf("p");               
								       break;
							case S_IFLNK:  printf("l");                 
								       break;
							case S_IFREG:  printf("-");            
								       break;
							case S_IFSOCK: printf("s");                  
								       break;
							default:       printf("u");                
								       break;
						}
						//Display the permissions for user, group and others.
						(sb.st_mode & S_IRUSR)? printf("r"):printf("-");
						(sb.st_mode & S_IWUSR)? printf("w"):printf("-");
						(sb.st_mode & S_IXUSR)? printf("x"):printf("-");
						(sb.st_mode & S_IRGRP)? printf("r"):printf("-");
						(sb.st_mode & S_IWGRP)? printf("w"):printf("-");
						(sb.st_mode & S_IXGRP)? printf("x"):printf("-");
						(sb.st_mode & S_IROTH)? printf("r"):printf("-");
						(sb.st_mode & S_IWOTH)? printf("w"):printf("-");
						(sb.st_mode & S_IXOTH)? printf("x"):printf("-");
	
						printf("%3ld ", (long) sb.st_nlink);//Display the number of links.
						grp = getgrgid(sb.st_gid);
						pwd = getpwuid(sb.st_uid);
						printf("%11s %11s ", pwd->pw_name,grp->gr_name);//Display the username and group name.
						printf("%4lld ",(long long) sb.st_size);//Display the size of the file.
						printf("%s ",file->d_name);//Display the file name.
						printf("%s",ctime(&sb.st_atime)); //Display the last access time of the file.
					}
				}
			}
		}	
	}
	else if(!strcmp(argv[1], "-li"))
	{
		for(i=2; i<argc; i++)
		{
			if(!access(argv[i],F_OK)) //Check if the directory specified by argv[i] exists.
			{
				directory=opendir(argv[i]); //If it exists, then open the directory.

				if(directory!=NULL)
				{
					while((file=readdir(directory))!=NULL) //Read each entry in the directory.
					{
	
						if (lstat(file->d_name, &sb) == -1) 
						{
							perror("stat");
						}
						
						 printf("%6ld ", (long) sb.st_ino);
						//Display the type of file.
						switch (sb.st_mode & S_IFMT) 
						{
							case S_IFBLK:  printf("b");            
								       break;
							case S_IFCHR:  printf("c");        
								       break;
							case S_IFDIR:  printf("d");               
								       break;
							case S_IFIFO:  printf("p");               
								       break;
							case S_IFLNK:  printf("l");                 
								       break;
							case S_IFREG:  printf("-");            
								       break;
							case S_IFSOCK: printf("s");                  
								       break;
							default:       printf("u");                
								       break;
						}
						//Display the permissions for user, group and others.
						(sb.st_mode & S_IRUSR)? printf("r"):printf("-");
						(sb.st_mode & S_IWUSR)? printf("w"):printf("-");
						(sb.st_mode & S_IXUSR)? printf("x"):printf("-");
						(sb.st_mode & S_IRGRP)? printf("r"):printf("-");
						(sb.st_mode & S_IWGRP)? printf("w"):printf("-");
						(sb.st_mode & S_IXGRP)? printf("x"):printf("-");
						(sb.st_mode & S_IROTH)? printf("r"):printf("-");
						(sb.st_mode & S_IWOTH)? printf("w"):printf("-");
						(sb.st_mode & S_IXOTH)? printf("x"):printf("-");
	
						printf("%3ld ", (long) sb.st_nlink);//Display the number of links.
						grp = getgrgid(sb.st_gid);
						pwd = getpwuid(sb.st_uid);
						printf("%11s %11s ", pwd->pw_name,grp->gr_name);//Display the username and group name.
						printf("%4lld ",(long long) sb.st_size);//Display the size of the file.
						printf("%s ",file->d_name);//Display the file name.
						printf("%s",ctime(&sb.st_atime)); //Display the last access time of the file.
					}
				}
			}
		}	
	}
	else
	{
		for(i=1;i<=argc-1;i++)
		{
			if(!access(argv[i],F_OK)) //Check if the directory specified by argv[i] exists.
			{
				directory=opendir(argv[i]); //If it exists, then open the directory.

				if(directory!=NULL)
				{
					while((file=readdir(directory))!=NULL) //Read each entry in the directory.
						printf("%-5s\t",file->d_name);
					printf("\n");
				}
				else
					perror("opendir"); //Display the error occurred while opening the directory.
			}
			else
					perror("access"); //Display an error if the directory does not exists.
		}

	}	
	return 0;
}
Exemplo n.º 25
0
void
parseDomainFile(AtomPtr file,
                DomainPtr **domains_return, regex_t **regex_return)
{
    struct stat ss;
    int rc;

    if(*domains_return) {
        DomainPtr *domain = *domains_return;
        while(*domain) {
            free(*domain);
            domain++;
        }
        free(*domains_return);
        *domains_return = NULL;
    }

    if(*regex_return) {
        regfree(*regex_return);
        *regex_return = NULL;
    }

    if(!file || file->length == 0)
        return;

    domains = malloc(64 * sizeof(DomainPtr));
    if(domains == NULL) {
        do_log(L_ERROR, "Couldn't allocate domain list.\n");
        return;
    }
    dlen = 0;
    dsize = 64;

    regexbuf = malloc(512);
    if(regexbuf == NULL) {
        do_log(L_ERROR, "Couldn't allocate regex.\n");
        free(domains);
        return;
    }
    rlen = 0;
    rsize = 512;

    rc = stat(file->string, &ss);
    if(rc < 0) {
        if(errno != ENOENT)
            do_log_error(L_WARN, errno, "Couldn't stat file %s", file->string);
    } else {
        if(!S_ISDIR(ss.st_mode))
            readDomainFile(file->string);
        else {
            char *fts_argv[2];
            FTS *fts;
            FTSENT *fe;
            fts_argv[0] = file->string;
            fts_argv[1] = NULL;
            fts = fts_open(fts_argv, FTS_LOGICAL, NULL);
            if(fts) {
                while(1) {
                    fe = fts_read(fts);
                    if(!fe) break;
                    if(fe->fts_info != FTS_D && fe->fts_info != FTS_DP &&
                       fe->fts_info != FTS_DC && fe->fts_info != FTS_DNR)
                        readDomainFile(fe->fts_accpath);
                }
                fts_close(fts);
            } else {
                do_log_error(L_ERROR, errno,
                             "Couldn't scan directory %s", file->string);
            }
        }
    }

    if(dlen > 0) {
        domains[dlen] = NULL;
    } else {
        free(domains);
        domains = NULL;
    }

    regex_t *regex;

    if(rlen > 0) {
        regex = malloc(sizeof(regex_t));
        rc = regcomp(regex, regexbuf, REG_EXTENDED | REG_NOSUB);
        if(rc != 0) {
            char errbuf[100];
            regerror(rc, regex, errbuf, 100);
            do_log(L_ERROR, "Couldn't compile regex: %s.\n", errbuf);
            free(regex);
            regex = NULL;
        }
    } else {
        regex = NULL;
    }
    free(regexbuf);

    *domains_return = domains;
    *regex_return = regex;

    return;
}
Exemplo n.º 26
0
int main(int argc, char *argv[]) {
	FILE *fp_infile = NULL, *fp_outfile = NULL, *fp_xmloutfile = NULL, *devnull;
#ifdef __MINGW32__
	HANDLE fh_infile = NULL;
#endif
	int c, lastsecond = 0, lastkeyframe = 0, unlink_infile = 0;
	char *flv, *infile, *outfile, *xmloutfile, *tempfile, *creator;
	unsigned int i;
	size_t filesize = 0, streampos, metadatasize;
	struct stat sb;
	FLVFileHeader_t *flvfileheader;

	opterr = 0;

	infile = NULL;
	outfile = NULL;
	xmloutfile = NULL;
	tempfile = NULL;
	creator = NULL;

	while((c = getopt(argc, argv, "i:o:x:t:c:lkh")) != -1) {
		switch(c) {
			case 'i':
				infile = optarg;
				break;
			case 'o':
				outfile = optarg;
				break;
			case 'x':
				xmloutfile = optarg;
				break;
			case 't':
				tempfile = optarg;
				break;
			case 'c':
				creator = optarg;
				break;
			case 'l':
				lastsecond = 1;
				break;
			case 'k':
				lastkeyframe = 1;
				break;
			case 'h':
				print_usage();
				exit(1);
				break;
			case ':':
				fprintf(stderr, "The option -%c expects a parameter. -h for help.\n", optopt);
				exit(1);
				break;
			case '?':
				fprintf(stderr, "Unknown option: -%c. -h for help.\n", optopt);
				exit(1);
				break;
			default:
				print_usage();
				exit(1);
				break;
		}
	}

	if(infile == NULL) {
		fprintf(stderr, "Please provide an input file. -h for help.\n");
		exit(1);
	}

	if(outfile == NULL && xmloutfile == NULL) {
		fprintf(stderr, "Please provide at least one output file. -h for help.\n");
		exit(1);
	}

	if(tempfile == NULL && !strcmp(infile, "-")) {
		fprintf(stderr, "Please specify a temporary file. -h for help.\n");
		exit(1);
	}

	// Check input file
	if(!strcmp(infile, "-")) {		// Read from stdin
		// Check the temporary file
		if(outfile != NULL) {
			if(!strcmp(tempfile, outfile)) {
				fprintf(stderr, "The temporary file and the output file must not be the same.\n");
				exit(1);
			}
		}

		if(xmloutfile != NULL) {
			if(!strcmp(tempfile, xmloutfile)) {
				fprintf(stderr, "The temporary file and the XML output file must not be the same.\n");
				exit(1);
			}
		}

		// Open the temporary file
		fp_infile = fopen(tempfile, "wb");
		if(fp_infile == NULL) {
			fprintf(stderr, "Couldn't open the tempfile %s.\n", tempfile);
			exit(1);
		}

		// Store stdin to temporary file
		storeFLVFromStdin(fp_infile);

		// Close temporary file
		fclose(fp_infile);

		// Mimic normal input file, but don't forget to remove the temporary file
		infile = tempfile;
		unlink_infile = 1;
	}
	else {
		if(outfile != NULL) {
			if(!strcmp(infile, outfile)) {
				fprintf(stderr, "The input file and the output file must not be the same.\n");
				exit(1);
			}
		}

		if(xmloutfile != NULL) {
			if(!strcmp(infile, xmloutfile)) {
				fprintf(stderr, "The input file and the XML output file must not be the same.\n");
				exit(1);
			}
		}
	}

	// Get size of input file
	if(stat(infile, &sb) == -1) {
		fprintf(stderr, "Couldn't stat on %s.\n", infile);
		exit(1);
	}

	filesize = sb.st_size;

	// Open input file
#ifndef __MINGW32__
	fp_infile = fopen(infile, "rb");
#else
	// Open infile with CreateFile() API
	fh_infile = CreateFile(infile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	// Meaningless type casting here. It is just used to pass the error checking codes.
	fp_infile = (FILE *)fh_infile;
#endif
	if(fp_infile == NULL) {
		fprintf(stderr, "Couldn't open %s.\n", infile);
		exit(1);
	}

	// Check output file
	if(outfile != NULL) {
		if(!strcmp(infile, outfile)) {
			fprintf(stderr, "The input file and the output file must not be the same.\n");
			exit(1);
		}

		if(strcmp(outfile, "-")) {
			fp_outfile = fopen(outfile, "wb");
			if(fp_outfile == NULL) {
				fprintf(stderr, "Couldn't open %s.\n", outfile);
				exit(1);
			}
		}
		else
			fp_outfile = stdout;
	}

	// Check XML output file
	if(xmloutfile != NULL) {
		if(!strcmp(infile, xmloutfile)) {
			fprintf(stderr, "The input file and the XML output file must not be the same.\n");
			exit(1);
		}

		if(!strcmp(outfile, xmloutfile)) {
			fprintf(stderr, "The output file and the XML output file must not be the same.\n");
			exit(1);
		}

		if(strcmp(xmloutfile, "-")) {
			fp_xmloutfile = fopen(xmloutfile, "wb");
			if(fp_xmloutfile == NULL) {
				fprintf(stderr, "Couldn't open %s.\n", xmloutfile);
				exit(1);
			}
		}
		else
			fp_xmloutfile = stdout;
	}

	// create mmap of input file
#ifndef __MINGW32__
	flv = mmap(NULL, filesize, PROT_READ, MAP_NOCORE | MAP_PRIVATE, fileno(fp_infile), 0);
	if(flv == MAP_FAILED) {
		fprintf(stderr, "Couldn't load %s (%s).\n", infile, strerror(errno));
		exit(1);
	}

#else
	HANDLE h = NULL;
	h = CreateFileMapping(fh_infile, NULL, PAGE_READONLY | SEC_COMMIT, 0, filesize,  NULL);
	if(h == NULL) {
		fprintf(stderr, "Couldn't create file mapping object %s. Error code: %d\n", infile, (int)GetLastError());
		exit(1);
	}
	flv = MapViewOfFile(h, FILE_MAP_READ, 0, 0, filesize);
	if(flv == NULL) {
		fprintf(stderr, "Couldn't load %s.\n", infile);
		exit(1);
	}
#endif

	// Simple check if the filee is a flv file
	if(strncmp(flv, "FLV", 3)) {
		fprintf(stderr, "The input file is not a FLV.\n");
		exit(1);
	}

	// Metadata initialisieren
	initFLVMetaData(creator, lastsecond, lastkeyframe);

	flvfileheader = (FLVFileHeader_t *)flv;

	// Die Position des 1. Tags im FLV bestimmen (Header + PrevTagSize0)
	streampos = FLV_UI32(flvfileheader->headersize) + 4;

	// Das FLV einlesen und Informationen fuer die Metatags extrahieren
	readFLVFirstPass(flv, streampos, filesize);

#ifndef __MINGW32__
	devnull = fopen("/dev/null", "wb");
#else
	devnull = fopen("nul", "wb");
#endif

	if(devnull == NULL) {
		fprintf(stderr, "Couldn't open NULL device.\n");
		exit(1);
	}

	// Die Groessen berechnen
	metadatasize = writeFLVMetaData(devnull);
	flvmetadata.lastsecondsize = writeFLVLastSecond(devnull, 0.0);
	flvmetadata.lastkeyframesize = writeFLVLastKeyframe(devnull);	// Not fully implemented, i.e. has no effect

	fclose(devnull);

	// Falls es Keyframes hat, muss ein 2. Durchgang fuer den Keyframeindex gemacht werden
	if(flvmetadata.hasKeyframes == 1) {
		readFLVSecondPass(flv, streampos, filesize);

		// Die Filepositions korrigieren
		for(i = 0; i < flvmetadata.keyframes; i++)
			flvmetadata.filepositions[i] += (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize);

		flvmetadata.lastkeyframelocation = flvmetadata.filepositions[flvmetadata.keyframes - 1];
	}

	// filesize = FLVFileHeader + PreviousTagSize0 + MetadataSize + DataSize
	flvmetadata.filesize = (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize + flvmetadata.datasize);
	if(flvmetadata.hasLastSecond == 1)
		flvmetadata.filesize += (double)flvmetadata.lastsecondsize;

	if(outfile != NULL)
		writeFLV(fp_outfile, flv, streampos, filesize);

	if(xmloutfile != NULL)
		writeXMLMetadata(fp_xmloutfile, infile, outfile);

	// Some cleanup
#ifndef __MINGW32__
	munmap(flv, filesize);
	fclose(fp_infile);
#else
	UnmapViewOfFile(flv);
	CloseHandle(h);
	CloseHandle(fh_infile);
#endif

	// Remove the input file if it is the temporary file
	if(unlink_infile == 1)
		unlink(infile);

	if(fp_outfile != NULL && fp_outfile != stdout)
		fclose(fp_outfile);

	if(fp_xmloutfile != NULL && fp_xmloutfile != stdout)
		fclose(fp_xmloutfile);

	return 0;
}
Exemplo n.º 27
0
static int command_remove(args_t * args)
{
	assert(args != NULL);

	struct stat st;
	if (stat(args->path, &st) != 0) {
		ERRNO(errno);
		return -1;
	}

	if (!S_ISREG(st.st_mode)) {
		ERRNO(errno);
		return -1;
	}

	FILE *i = fopen(args->path, "r");
	if (i == NULL) {
		ERRNO(errno);
		return -1;
	}

	FILE *o = fopen(args->file, "w");
	if (o == NULL) {
		ERRNO(errno);
		return -1;
	}

#define INPUT_SIZE		4086
	char input[INPUT_SIZE];	// multiple of 9-bytes
#undef INPUT_SIZE

	size_t count = 0;
	while (count < st.st_size) {
		clearerr(i);

		size_t rc = fread(input, 1, sizeof input, i);
		if (rc == 0) {
			int err = ferror(i);
			if (err) {
				ERRNO(errno);
				return -1;
			} else
				break;
		}

		count += rc;

    char output[(((sizeof input)/(ECC_SIZE+1))*ECC_SIZE) ];

		ssize_t removed_size;
		if (args->p8 == f_P8)
			removed_size =
			    p8_ecc_remove_size(output, sizeof output, input, rc);
		else
			removed_size =
			    sfc_ecc_remove(output, sizeof output, input, rc);
		if (removed_size < 0) {
			ERRNO(errno);
			return -1;
		}

		clearerr(o);
		rc = fwrite(output, 1, removed_size, o);
		if (rc == 0) {
			int err = ferror(o);
			if (err) {
				ERRNO(errno);
				return -1;
			}
		}
	}

	if (fclose(i) == EOF) {
		ERRNO(errno);
		return -1;
	}

	if (fclose(o) == EOF) {
		ERRNO(errno);
		return -1;
	}

	return 0;
}
Exemplo n.º 28
0
/* mounts, creating the device if needed+possible */
int my_mount(const char *dev, const char *location, const char *fs, int force_rw)
{
    unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY);
    char * opts = NULL;
    struct stat buf;
    int rc;

    if (strcmp(fs, "nfs")) {
        rc = ensure_dev_exists(dev);
        if (rc != 0) {
            log_message("could not create required device file");
            return -1;
        }
    }

    log_message("mounting %s on %s as type %s", dev, location, fs);

    if (stat(location, &buf)) {
        if (mkdir(location, 0755)) {
            log_perror("could not create location dir");
            return -1;
        }
    } else if (!S_ISDIR(buf.st_mode)) {
        log_message("not a dir %s, will unlink and mkdir", location);
        if (unlink(location)) {
            log_perror("could not unlink");
            return -1;
        }
        if (mkdir(location, 0755)) {
            log_perror("could not create location dir");
            return -1;
        }
    }

#ifndef DISABLE_MEDIAS
    if (!strcmp(fs, "vfat")) {
        my_modprobe("nls_cp437", ANY_DRIVER_TYPE, NULL);
        my_modprobe("nls_iso8859_1", ANY_DRIVER_TYPE, NULL);
        my_modprobe("vfat", ANY_DRIVER_TYPE, NULL);
        opts = (char*)"check=relaxed";
    }

    if (!strcmp(fs, "ntfs")) {
        my_modprobe("ntfs", ANY_DRIVER_TYPE, NULL);
    }

    if (!strcmp(fs, "reiserfs"))
        my_modprobe("reiserfs", ANY_DRIVER_TYPE, NULL);

    if (!strcmp(fs, "reiser4"))
        my_modprobe("reiser4", ANY_DRIVER_TYPE, NULL);

    if (!strcmp(fs, "jfs"))
        my_modprobe("jfs", ANY_DRIVER_TYPE, NULL);

    if (!strcmp(fs, "xfs"))
        my_modprobe("xfs", ANY_DRIVER_TYPE, NULL);

    if (!strcmp(fs, "ext4"))
        my_modprobe("ext4", ANY_DRIVER_TYPE, NULL);

    if (!strcmp(fs, "btrfs"))
        my_modprobe("btrfs", ANY_DRIVER_TYPE, NULL);

#endif
    if (!strcmp(fs, "iso9660"))
        my_modprobe("isofs", ANY_DRIVER_TYPE, NULL);

#ifndef DISABLE_NETWORK
    if (!strcmp(fs, "nfs")) {
        my_modprobe("nfs", ANY_DRIVER_TYPE, NULL);
        log_message("preparing nfsmount for %s", dev);
        rc = nfsmount_prepare(dev, &opts);
        if (rc != 0)
            return rc;
    }
#endif

    rc = mount(dev, location, fs, flags, opts);
    if (rc != 0) {
        log_perror("mount failed");
        rmdir(location);
    }

    return rc;
}
Exemplo n.º 29
0
static int do_daemon_work(const char *channel, const char *sync_shutdown_file,
		   unsigned long timeout, unsigned long min_delta,
		   int *restartp)
{
    int r = 0;
    time_t session_start;
    time_t single_start;
    int    delta;
    struct stat sbuf;
    sync_log_reader_t *slr;

    *restartp = RESTART_NONE;
    slr = sync_log_reader_create_with_channel(channel);

    session_start = time(NULL);

    while (1) {
	single_start = time(NULL);

	signals_poll();

	/* Check for shutdown file */
	if (sync_shutdown_file && !stat(sync_shutdown_file, &sbuf)) {
	    unlink(sync_shutdown_file);
	    break;
	}

	/* See if its time to RESTART */
	if ((timeout > 0) &&
	    ((single_start - session_start) > (time_t) timeout)) {
	    *restartp = RESTART_NORMAL;
	    break;
	}

	r = sync_log_reader_begin(slr);
	if (r) {
	    /* including specifically r == IMAP_AGAIN */
	    if (min_delta > 0) {
		sleep(min_delta);
	    } else {
		usleep(100000);    /* 1/10th second */
	    }
	    continue;
	}

	/* Process the work log */
	if ((r=do_sync(slr))) {
	    syslog(LOG_ERR,
		   "Processing sync log file %s failed: %s",
		   sync_log_reader_get_file_name(slr), error_message(r));
	    break;
	}

	r = sync_log_reader_end(slr);
	if (r) break;

	delta = time(NULL) - single_start;

	if (((unsigned) delta < min_delta) && ((min_delta-delta) > 0))
	    sleep(min_delta-delta);
    }
    sync_log_reader_free(slr);

    if (*restartp == RESTART_NORMAL) {
	r = do_restart();
	if (r) {
	    syslog(LOG_ERR, "sync_client RESTART failed: %s",
		   error_message(r));
	} else {
	    syslog(LOG_INFO, "sync_client RESTART succeeded");
	}
	r = 0;
    }

    return(r);
}
Exemplo n.º 30
0
/*
 * parse a file or directory of files
 * const char *fn: name of magic file or directory
 */
static int apprentice_load(RMagic *ms, struct r_magic **magicp, ut32 *nmagicp, const char *fn, int action) {
	ut32 marraycount, i, mentrycount = 0, starttest;
	struct r_magic_entry *marray;
	char subfn[MAXPATHLEN];
	struct dirent *d;
	struct stat st;
	int errs = 0;
	DIR *dir;

	ms->flags |= R_MAGIC_CHECK;	/* Enable checks for parsed files */

        maxmagic = MAXMAGIS;
	if ((marray = calloc (maxmagic, sizeof(*marray))) == NULL) {
		file_oomem (ms, maxmagic * sizeof(*marray));
		return -1;
	}
	marraycount = 0;

	/* print silly verbose header for USG compat. */
	if (action == FILE_CHECK)
		eprintf ("%s\n", usg_hdr);

	/* load directory or file */
	if (stat (fn, &st) == 0 && S_ISDIR (st.st_mode)) {
		if (r_sandbox_enable (0) && !r_sandbox_check_path (fn)) {
			free (marray);
			return  -1;
		}
		dir = opendir (fn);
		if (dir) {
			while ((d = readdir (dir))) {
				if (*d->d_name=='.') continue;
				snprintf (subfn, sizeof (subfn), "%s/%s", fn, d->d_name);
				if (stat (subfn, &st) == 0 && S_ISREG (st.st_mode))
					load_1 (ms, action, subfn, &errs, &marray, &marraycount);
				//else perror (subfn);
			}
			closedir (dir);
		} else errs++;
	} else load_1 (ms, action, fn, &errs, &marray, &marraycount);
	if (errs)
		goto out;

	/* Set types of tests */
	for (i = 0; i < marraycount; ) {
		if (marray[i].mp->cont_level != 0) {
			i++;
			continue;
		}

		starttest = i;
		do {
			set_test_type(marray[starttest].mp, marray[i].mp);
			if (ms->flags & R_MAGIC_DEBUG) {
				(void)fprintf(stderr, "%s%s%s: %s\n",
					marray[i].mp->mimetype,
					marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
					marray[i].mp->desc[0] ? marray[i].mp->desc : "(no description)",
					marray[i].mp->flag & BINTEST ? "binary" : "text");
				if (marray[i].mp->flag & BINTEST) {
#define SYMBOL "text"
#define SYMLEN sizeof(SYMBOL)
					char *p = strstr(marray[i].mp->desc, "text");
					if (p && (p == marray[i].mp->desc || isspace((unsigned char)p[-1])) &&
					    (p + SYMLEN - marray[i].mp->desc == MAXstring ||
					     (p[SYMLEN] == '\0' || isspace((unsigned char)p[SYMLEN])))) {
						(void)fprintf(stderr,
							      "*** Possible binary test for text type\n");
					}
#undef SYMBOL
#undef SYMLEN
				}
			}
		} while (++i < marraycount && marray[i].mp->cont_level != 0);
	}

	qsort (marray, marraycount, sizeof(*marray), apprentice_sort);

	/*
	 * Make sure that any level 0 "default" line is last (if one exists).
	 */
	for (i = 0; i < marraycount; i++) {
		if (marray[i].mp->cont_level == 0 &&
		    marray[i].mp->type == FILE_DEFAULT) {
			while (++i < marraycount)
				if (marray[i].mp->cont_level == 0)
					break;
			if (i != marraycount) {
				ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
				file_magwarn (ms, "level 0 \"default\" did not sort last");
			}
			break;
		}
	}

	for (i = 0; i < marraycount; i++)
		mentrycount += marray[i].cont_count;

	if ((*magicp = malloc (1+(sizeof(**magicp) * mentrycount))) == NULL) {
		file_oomem (ms, sizeof(**magicp) * mentrycount);
		errs++;
		goto out;
	}

	mentrycount = 0;
	for (i = 0; i < marraycount; i++) {
		(void)memcpy (*magicp + mentrycount, marray[i].mp,
		    marray[i].cont_count * sizeof (**magicp));
		mentrycount += marray[i].cont_count;
	}
out:
	for (i = 0; i < marraycount; i++)
		free(marray[i].mp);
	free (marray);
	if (errs) {
		*magicp = NULL;
		*nmagicp = 0;
		return errs;
	}
	*nmagicp = mentrycount;
	return 0;
}