Beispiel #1
0
/**
 * virPidFileReadPathIfAlive:
 * @path: path to pidfile
 * @pid: variable to return pid in
 * @binpath: path of executable associated with the pidfile
 *
 * This will attempt to read a pid from @path, and store it
 * in @pid. The @pid will only be set, however, if the
 * pid in @path is running, and its executable path
 * resolves to @binpath. This adds protection against
 * recycling of previously reaped pids.
 *
 * If @binpath is NULL the check for the executable path
 * is skipped.
 *
 * Returns -errno upon error, or zero on successful
 * reading of the pidfile. If the PID was not still
 * alive, zero will be returned, but @pid will be
 * set to -1.
 */
int virPidFileReadPathIfAlive(const char *path,
                              pid_t *pid,
                              const char *binPath)
{
    int ret;
    bool isLink;
    char *procPath = NULL;
    char *procLink = NULL;
    size_t procLinkLen;
    char *resolvedBinPath = NULL;
    char *resolvedProcLink = NULL;
    const char deletedText[] = " (deleted)";
    size_t deletedTextLen = strlen(deletedText);
    pid_t retPid;

    /* only set this at the very end on success */
    *pid = -1;

    if ((ret = virPidFileReadPath(path, &retPid)) < 0)
        goto cleanup;

#ifndef WIN32
    /* Check that it's still alive.  Safe to skip this sanity check on
     * mingw, which lacks kill().  */
    if (kill(retPid, 0) < 0) {
        ret = 0;
        retPid = -1;
        goto cleanup;
    }
#endif

    if (!binPath) {
        /* we only knew the pid, and that pid is alive, so we can
         * return it.
         */
        ret = 0;
        goto cleanup;
    }

    if (virAsprintf(&procPath, "/proc/%lld/exe", (long long)retPid) < 0) {
        ret = -ENOMEM;
        goto cleanup;
    }

    if ((ret = virFileIsLink(procPath)) < 0)
        goto cleanup;
    isLink = ret;

    if (isLink && virFileLinkPointsTo(procPath, binPath)) {
        /* the link in /proc/$pid/exe is a symlink to a file
         * that has the same inode as the file at binpath.
         */
        ret = 0;
        goto cleanup;
    }

    /* Even if virFileLinkPointsTo returns a mismatch, it could be
     * that the binary was deleted/replaced after it was executed. In
     * that case the link in /proc/$pid/exe will contain
     * "$procpath (deleted)".  Read that link, remove the " (deleted)"
     * part, and see if it has the same canonicalized name as binpath.
     */
    if (!(procLink = areadlink(procPath))) {
        ret = -errno;
        goto cleanup;
    }
    procLinkLen = strlen(procLink);
    if (procLinkLen > deletedTextLen)
        procLink[procLinkLen - deletedTextLen] = 0;

    if ((ret = virFileResolveAllLinks(binPath, &resolvedBinPath)) < 0)
        goto cleanup;
    if ((ret = virFileResolveAllLinks(procLink, &resolvedProcLink)) < 0)
        goto cleanup;

    ret = STREQ(resolvedBinPath, resolvedProcLink) ? 0 : -1;

cleanup:
    VIR_FREE(procPath);
    VIR_FREE(procLink);
    VIR_FREE(resolvedProcLink);
    VIR_FREE(resolvedBinPath);

    /* return the originally set pid of -1 unless we proclaim success */
    if (ret == 0)
        *pid = retPid;
    return ret;
}
Beispiel #2
0
int main(
  int argc,
  char **argv
)
{
    register int c;
    bool showusage = FALSE;                     /* usage error? */
    int rc = 0;
    FILE *outfp, *infp;

    /*
     * figure out invocation leaf-name
     */

    if ((progname = strrchr(argv[0], '/')) == (char *) NULL)
        progname = argv[0];
    else
        progname++;

    argv[0] = progname;                         /* for getopt err reporting */

    /*
     *  Check options and arguments.
     */

    progname = argv[0];
    while ((c = getopt(argc, argv, "F:a:o:vl")) != EOF)
        switch (c)
        {
            case 'a':                           /* base address */
                base = stol(optarg);
                break;

            case 'l':                           /* linear output */
                linear = TRUE;
                break;

            case 'v':                           /* toggle verbose */
                verbose = ! verbose;
                break;

            case 'o':                           /* output file */
                outfilename = optarg;
                break;

            case 'F':                           /* 0xFF fill amount (bytes) */
                FFfill = stol(optarg) * 1024L / 8L;
                break;

            case '?':
                showusage = TRUE;
        }

    if (showusage)
    {
        (void) fprintf(stderr, "%s", USAGE);
        exit(1);
    }

    if (linear && (base != 0))
    {
        error(0, "-l and -a may not be specified in combination");
        exit(1);
    }

    if (STREQ(outfilename, "-"))
    {
        outfp = stdout;
        outfilename = "stdout";
    }
    else
        if ((outfp = fopen(outfilename, "w")) == (FILE *) NULL)
        {
            error(-1, "couldn't open '%s' for output", outfilename);
            exit(1);
        }

    /*
     * Now process the input files (or stdin, if none specified)
     */

    if (argv[optind] == (char *) NULL)          /* just stdin */
        exit(unhex(stdin, "stdin", outfp, outfilename));
    else
        for (; (optarg = argv[optind]); optind++)
        {
            if (STREQ(optarg, "-"))
                rc += unhex(stdin, "stdin", outfp, outfilename);
            else
            {
                if ((infp = fopen(optarg, "r")) == (FILE *) NULL)
                {
                    error(-1, "couldn't open '%s' for input", optarg);
                    exit(1);
                }
                rc += unhex(infp, optarg, outfp, outfilename);
            }
        }

    return(rc);
}
Beispiel #3
0
/**
 * virCapabilitiesFormatXML:
 * @caps: capabilities to format
 *
 * Convert the capabilities object into an XML representation
 *
 * Returns the XML document as a string
 */
char *
virCapabilitiesFormatXML(virCapsPtr caps)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    size_t i, j, k;
    char host_uuid[VIR_UUID_STRING_BUFLEN];

    virBufferAddLit(&buf, "<capabilities>\n\n");
    virBufferAdjustIndent(&buf, 2);
    virBufferAddLit(&buf, "<host>\n");
    virBufferAdjustIndent(&buf, 2);
    if (virUUIDIsValid(caps->host.host_uuid)) {
        virUUIDFormat(caps->host.host_uuid, host_uuid);
        virBufferAsprintf(&buf, "<uuid>%s</uuid>\n", host_uuid);
    }
    virBufferAddLit(&buf, "<cpu>\n");
    virBufferAdjustIndent(&buf, 2);

    if (caps->host.arch)
        virBufferAsprintf(&buf, "<arch>%s</arch>\n",
                          virArchToString(caps->host.arch));
    if (caps->host.nfeatures) {
        virBufferAddLit(&buf, "<features>\n");
        virBufferAdjustIndent(&buf, 2);
        for (i = 0; i < caps->host.nfeatures; i++) {
            virBufferAsprintf(&buf, "<%s/>\n",
                              caps->host.features[i]);
        }
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</features>\n");
    }
    virCPUDefFormatBuf(&buf, caps->host.cpu, false);

    for (i = 0; i < caps->host.nPagesSize; i++) {
        virBufferAsprintf(&buf, "<pages unit='KiB' size='%u'/>\n",
                          caps->host.pagesSize[i]);
    }

    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</cpu>\n");

    /* The PM query was successful. */
    if (caps->host.powerMgmt) {
        /* The host supports some PM features. */
        unsigned int pm = caps->host.powerMgmt;
        virBufferAddLit(&buf, "<power_management>\n");
        virBufferAdjustIndent(&buf, 2);
        while (pm) {
            int bit = ffs(pm) - 1;
            virBufferAsprintf(&buf, "<%s/>\n",
                              virCapsHostPMTargetTypeToString(bit));
            pm &= ~(1U << bit);
        }
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</power_management>\n");
    } else {
        /* The host does not support any PM feature. */
        virBufferAddLit(&buf, "<power_management/>\n");
    }

    if (caps->host.offlineMigrate) {
        virBufferAddLit(&buf, "<migration_features>\n");
        virBufferAdjustIndent(&buf, 2);
        if (caps->host.liveMigrate)
            virBufferAddLit(&buf, "<live/>\n");
        if (caps->host.nmigrateTrans) {
            virBufferAddLit(&buf, "<uri_transports>\n");
            virBufferAdjustIndent(&buf, 2);
            for (i = 0; i < caps->host.nmigrateTrans; i++) {
                virBufferAsprintf(&buf, "<uri_transport>%s</uri_transport>\n",
                                  caps->host.migrateTrans[i]);
            }
            virBufferAdjustIndent(&buf, -2);
            virBufferAddLit(&buf, "</uri_transports>\n");
        }
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</migration_features>\n");
    }

    if (caps->host.nnumaCell &&
        virCapabilitiesFormatNUMATopology(&buf, caps->host.nnumaCell,
                                          caps->host.numaCell) < 0)
        return NULL;

    for (i = 0; i < caps->host.nsecModels; i++) {
        virBufferAddLit(&buf, "<secmodel>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<model>%s</model>\n",
                          caps->host.secModels[i].model);
        virBufferAsprintf(&buf, "<doi>%s</doi>\n",
                          caps->host.secModels[i].doi);
        for (j = 0; j < caps->host.secModels[i].nlabels; j++) {
            virBufferAsprintf(&buf, "<baselabel type='%s'>%s</baselabel>\n",
                              caps->host.secModels[i].labels[j].type,
                              caps->host.secModels[i].labels[j].label);
        }
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</secmodel>\n");
    }

    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</host>\n\n");


    for (i = 0; i < caps->nguests; i++) {
        virBufferAddLit(&buf, "<guest>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<os_type>%s</os_type>\n",
                          virDomainOSTypeToString(caps->guests[i]->ostype));
        if (caps->guests[i]->arch.id)
            virBufferAsprintf(&buf, "<arch name='%s'>\n",
                              virArchToString(caps->guests[i]->arch.id));
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<wordsize>%d</wordsize>\n",
                          caps->guests[i]->arch.wordsize);
        if (caps->guests[i]->arch.defaultInfo.emulator)
            virBufferAsprintf(&buf, "<emulator>%s</emulator>\n",
                              caps->guests[i]->arch.defaultInfo.emulator);
        if (caps->guests[i]->arch.defaultInfo.loader)
            virBufferAsprintf(&buf, "<loader>%s</loader>\n",
                              caps->guests[i]->arch.defaultInfo.loader);

        for (j = 0; j < caps->guests[i]->arch.defaultInfo.nmachines; j++) {
            virCapsGuestMachinePtr machine = caps->guests[i]->arch.defaultInfo.machines[j];
            virBufferAddLit(&buf, "<machine");
            if (machine->canonical)
                virBufferAsprintf(&buf, " canonical='%s'", machine->canonical);
            if (machine->maxCpus > 0)
                virBufferAsprintf(&buf, " maxCpus='%d'", machine->maxCpus);
            virBufferAsprintf(&buf, ">%s</machine>\n", machine->name);
        }

        for (j = 0; j < caps->guests[i]->arch.ndomains; j++) {
            virBufferAsprintf(&buf, "<domain type='%s'",
                virDomainVirtTypeToString(caps->guests[i]->arch.domains[j]->type));
            if (!caps->guests[i]->arch.domains[j]->info.emulator &&
                !caps->guests[i]->arch.domains[j]->info.loader &&
                !caps->guests[i]->arch.domains[j]->info.nmachines) {
                virBufferAddLit(&buf, "/>\n");
                continue;
            }
            virBufferAddLit(&buf, ">\n");
            virBufferAdjustIndent(&buf, 2);
            if (caps->guests[i]->arch.domains[j]->info.emulator)
                virBufferAsprintf(&buf, "<emulator>%s</emulator>\n",
                                  caps->guests[i]->arch.domains[j]->info.emulator);
            if (caps->guests[i]->arch.domains[j]->info.loader)
                virBufferAsprintf(&buf, "<loader>%s</loader>\n",
                                  caps->guests[i]->arch.domains[j]->info.loader);

            for (k = 0; k < caps->guests[i]->arch.domains[j]->info.nmachines; k++) {
                virCapsGuestMachinePtr machine = caps->guests[i]->arch.domains[j]->info.machines[k];
                virBufferAddLit(&buf, "<machine");
                if (machine->canonical)
                    virBufferAsprintf(&buf, " canonical='%s'", machine->canonical);
                if (machine->maxCpus > 0)
                    virBufferAsprintf(&buf, " maxCpus='%d'", machine->maxCpus);
                virBufferAsprintf(&buf, ">%s</machine>\n", machine->name);
            }
            virBufferAdjustIndent(&buf, -2);
            virBufferAddLit(&buf, "</domain>\n");
        }

        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</arch>\n");

        if (caps->guests[i]->nfeatures) {
            virBufferAddLit(&buf, "<features>\n");
            virBufferAdjustIndent(&buf, 2);

            for (j = 0; j < caps->guests[i]->nfeatures; j++) {
                if (STREQ(caps->guests[i]->features[j]->name, "pae") ||
                    STREQ(caps->guests[i]->features[j]->name, "nonpae") ||
                    STREQ(caps->guests[i]->features[j]->name, "ia64_be") ||
                    STREQ(caps->guests[i]->features[j]->name, "cpuselection") ||
                    STREQ(caps->guests[i]->features[j]->name, "deviceboot")) {
                    virBufferAsprintf(&buf, "<%s/>\n",
                                      caps->guests[i]->features[j]->name);
                } else {
                    virBufferAsprintf(&buf, "<%s default='%s' toggle='%s'/>\n",
                                      caps->guests[i]->features[j]->name,
                                      caps->guests[i]->features[j]->defaultOn ? "on" : "off",
                                      caps->guests[i]->features[j]->toggle ? "yes" : "no");
                }
            }

            virBufferAdjustIndent(&buf, -2);
            virBufferAddLit(&buf, "</features>\n");
        }
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</guest>\n\n");
    }
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</capabilities>\n");

    if (virBufferCheckError(&buf) < 0)
        return NULL;

    return virBufferContentAndReset(&buf);
}
Beispiel #4
0
static Pf *
orbconnections2pf( Pf *pfanalyze )
{
	Pf	*pf;
	Pf	*pfserver;
	Pf	*pfconnections;
	Pf	*pfclients;
	Pf	*pfclient;
	Pf	*pfconnection;
	Tbl	*client_keys;
	int	ikey;
	char	*client_key;
	char	*clientid;
	char	*what;
	char	*perm;
	char	*clientaddress;
	char	*serveraddress;
	char	clientaddress_ipc[STRSZ];
	char	serveraddress_ipc[STRSZ];
	int	serverport;
	double	atime;
	regex_t	preg_findclient;
	char	closeorb[STRSZ];
	char	o2omachine[STRSZ];
	char	farorb[STRSZ];
	int	closeport;
	int	farport;
	char	orbstat_machine_hostname[STRSZ];
	char	orbstat_machine_ipc[STRSZ];
	int	orbstat_machine_ip;
	char	cmdline_fromorb[STRSZ];
	char	cmdline_toorb[STRSZ];
	char	cmdline_fromip[STRSZ];
	char	cmdline_fromipc[STRSZ];
	char	cmdline_toip[STRSZ];
	char	cmdline_toipc[STRSZ];
	char	formal_name[STRSZ];
	int	formal_count = 0;
	int	cmdline_fromport;
	int	cmdline_toport;
	struct in_addr addr;
	
	regcomp( &preg_findclient, "^orb2orb ", 0 );

	pf = pfnew( PFFILE );

	atime = pfget_time( pfanalyze, "client_when" );
	pfput_time( pf, "connections_when", atime );

	my_ip( orbstat_machine_hostname, 
	       orbstat_machine_ipc, 
	       &orbstat_machine_ip );

	if( is_localhost( orbstat_machine_ipc ) ) {
		
		elog_complain( 0, "libpforbstat: orbstat machine is localhost; giving up on connection analysis\n" );
		regfree( &preg_findclient );
		return pf;

	} else {

		pfput_string( pf, "orbstat_machine", orbstat_machine_ipc );
	}

	pfget( pfanalyze, "server", (void **) &pfserver );
	serveraddress = pfget_string( pfserver, "address" );
	serverport = pfget_int( pfserver, "port" );

	if( is_nonroutable( serveraddress ) && 
	    report_nonroutable( serveraddress ) ) {

		elog_complain( 0, "libpforbstat: warning: monitored server %s is nonroutable\n", serveraddress );
	}
	
	if( name2ip( serveraddress, &addr, serveraddress_ipc ) < 0 ) {
		
		elog_complain( 0, "libpforbstat: warning: name translation failed for %s\n", serveraddress );
		strcpy( serveraddress_ipc, serveraddress );
	}

	if( is_localhost( serveraddress ) ) {

		strcpy( closeorb, orbstat_machine_ipc );

	} else {

		strcpy( closeorb, serveraddress_ipc );
	}

	closeport = serverport;

	/* SCAFFOLD: this causes memory problems. Leave untranslated for now:
	pfput_string( pfserver, "address", closeorb ); Record the translated server address */

	pfget( pfanalyze, "clients", (void **) &pfclients );

	client_keys = pfkeys( pfclients );

	pfconnections = pfnew( PFTBL );

	for( ikey = 0; ikey < maxtbl( client_keys ); ikey++ ) {

		client_key = gettbl( client_keys, ikey );
		pfget( pfclients, client_key, (void **) &pfclient );

		what = pfget_string( pfclient, "what" );

		if( ! regexec( &preg_findclient, what, 0, 0, 0 ) ) {

			pfconnection = pfnew( PFARR );

			/* Easy things: */

			pfput_string( pfconnection, "what", what );

			if( ( clientid = pfget_string( pfclient, "clientid") ) != NULL ) {

				pfput_string( pfconnection, "clientid", clientid );
			}
			
			/* Preparatory raw-information acquisition: */

			extract_orb2orb_orbargs( what, 
						 cmdline_fromorb, 
						 cmdline_toorb );

			parse_orbname( cmdline_fromorb, 
				       cmdline_fromip, 
				       &cmdline_fromport );

			if( name2ip( cmdline_fromip, &addr, cmdline_fromipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", cmdline_fromipc );
				strcpy( cmdline_fromipc, cmdline_fromip );
			}

			parse_orbname( cmdline_toorb, 
				       cmdline_toip, 
				       &cmdline_toport );

			if( name2ip( cmdline_toip, &addr, cmdline_toipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", cmdline_toipc );
				strcpy( cmdline_toipc, cmdline_toip );
			}

			perm = pfget_string( pfclient, "perm" );

			clientaddress = pfget_string( pfclient, "address" );

			if( name2ip( clientaddress, &addr, clientaddress_ipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", clientaddress );
				strcpy( clientaddress_ipc, clientaddress );
			}

			/* Analysis */

			if( is_nonroutable( clientaddress ) &&
			    report_nonroutable( clientaddress ) ) { 
				
				elog_complain( 0, "libpforbstat: warning: clientaddress %s is nonroutable\n", 
						clientaddress );
			} 
			
			if( is_localhost( clientaddress ) ) {
			
				strcpy( o2omachine, serveraddress_ipc );

			} else {
				
				strcpy( o2omachine, clientaddress_ipc );
			}

			pfput_string( pfconnection, "o2omachine", o2omachine );

			if( STREQ( perm, "w" ) ) {

				strcpy( farorb, cmdline_fromipc );
				farport = cmdline_fromport;

			} else if( STREQ( perm, "r" ) ) {		

				strcpy( farorb, cmdline_toipc );
				farport = cmdline_toport;

			} else {
				elog_complain( 0, 
						"libpforbstat: unexpected perm '%s' in client info; giving up on client\n", 
						perm );
				pffree( pfconnection );
				continue;
			}

			if(is_localhost(farorb)) {

				strcpy( farorb, o2omachine );
			}

			if( STREQ( perm, "w" ) ) {
			
				pfput_string( pfconnection, "fromaddress", farorb );
				pfput_int( pfconnection, "fromport", farport );

				pfput_string( pfconnection, "toaddress", closeorb );
				pfput_int( pfconnection, "toport", closeport );

				pfput_string( pfconnection, "closeorb", "toaddress" );

			} else {	/* perm == "r" */

				pfput_string( pfconnection, "fromaddress", closeorb );
				pfput_int( pfconnection, "fromport", closeport );

				pfput_string( pfconnection, "toaddress", farorb );
				pfput_int( pfconnection, "toport", farport );

				pfput_string( pfconnection, "closeorb", "fromaddress" );
			} 	

			sprintf( formal_name, "client%03d", ++formal_count );
			pfput( pfconnections, formal_name, pfconnection, PFPF );
		}
	}

	freetbl( client_keys, 0 );

	pfput( pf, "connections", pfconnections, PFPF );

	regfree( &preg_findclient );

	return pf;
}
Beispiel #5
0
/* Prepare the input source.  If the input is a regular tar file, this
 * just sets ifile = input.  However normally the input will be either
 * a directory or a compressed tarball.  In that case we set up an
 * external command to do the tar/uncompression to a temporary pipe,
 * and set ifile to the name of the pipe.  If there is a subprocess,
 * the PID is returned so that callers can wait on it.
 */
static int
prepare_input (const char *input, const char *ifmt,
               char **ifile_rtn, int *fd_rtn, pid_t *pid_rtn)
{
  const char *argv[7];

  *pid_rtn = 0;
  *fd_rtn = -1;

  if (STREQ (ifmt, "directory")) {
    argv[0] = "tar";
    argv[1] = "-C";
    argv[2] = input;
    argv[3] = "-cf";
    argv[4] = "-";
    argv[5] = ".";
    argv[6] = NULL;

    if (bg_command ((char **) argv, fd_rtn, pid_rtn) == -1)
      return -1;

    if (asprintf (ifile_rtn, "/dev/fd/%d", *fd_rtn) == -1) {
      perror ("asprintf");
      return -1;
    }
  }
  else {
    if (strstr (ifmt, "compress")) {
      if (strstr (ifmt, "compress'd")) {
        argv[0] = "uncompress";
        argv[1] = "-c";
        argv[2] = input;
        argv[3] = NULL;
      }
      else if (strstr (ifmt, "gzip compressed")) {
        argv[0] = "gzip";
        argv[1] = "-cd";
        argv[2] = input;
        argv[3] = NULL;
      }
      else if (strstr (ifmt, "bzip2 compressed")) {
        argv[0] = "bzip2";
        argv[1] = "-cd";
        argv[2] = input;
        argv[3] = NULL;
      }
      else if (strstr (ifmt, "xz compressed")) {
        argv[0] = "xz";
        argv[1] = "-cd";
        argv[2] = input;
        argv[3] = NULL;
      }
      else
        /* Shouldn't happen - see estimate_input above. */
        abort ();

      if (bg_command ((char **) argv, fd_rtn, pid_rtn) == -1)
        return -1;

      if (asprintf (ifile_rtn, "/dev/fd/%d", *fd_rtn) == -1) {
        perror ("asprintf");
        return -1;
      }
    }
    else {
      /* Plain tar file, read directly from the file. */
      *ifile_rtn = strdup (input);
      if (*ifile_rtn == NULL) {
        perror ("strdup");
        return -1;
      }
    }
  }

  return 0;
}
Beispiel #6
0
int
main (int argc, char *argv[])
{
  /* Set global program name that is not polluted with libtool artifacts.  */
  set_program_name (argv[0]);

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  enum { HELP_OPTION = CHAR_MAX + 1 };

  static const char *options = "a:c:d:qvVx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "filesystem", 1, 0, 0 },
    { "format", 2, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "lvm", 2, 0, 0 },
    { "partition", 2, 0, 0 },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { "wipe", 0, 0, 0 },
    { 0, 0, 0, 0 }
  };
  struct drv *drvs = NULL;
  struct drv *drv;
  const char *format = NULL;
  int c;
  int option_index;
  int retry, retries;

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  argv[0] = bad_cast (program_name);

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "format")) {
        if (!optarg || STREQ (optarg, ""))
          format = NULL;
        else
          format = optarg;
      } else if (STREQ (long_options[option_index].name, "filesystem")) {
        if (STREQ (optarg, "none"))
          filesystem = NULL;
        else if (optarg[0] == '-') { /* eg: --filesystem --lvm */
          fprintf (stderr, _("%s: no filesystem was specified\n"),
                   program_name);
          exit (EXIT_FAILURE);
        } else
          filesystem = optarg;
      } else if (STREQ (long_options[option_index].name, "lvm")) {
        if (vg || lv) {
          fprintf (stderr,
                   _("%s: --lvm option cannot be given multiple times\n"),
                   program_name);
          exit (EXIT_FAILURE);
        }
        if (optarg == NULL) {
          vg = strdup ("VG");
          lv = strdup ("LV");
          if (!vg || !lv) { perror ("strdup"); exit (EXIT_FAILURE); }
        }
        else if (STREQ (optarg, "none"))
          vg = lv = NULL;
        else
          parse_vg_lv (optarg);
      } else if (STREQ (long_options[option_index].name, "partition")) {
        if (optarg == NULL)
          partition = "DEFAULT";
        else if (STREQ (optarg, "none"))
          partition = NULL;
        else
          partition = optarg;
      } else if (STREQ (long_options[option_index].name, "wipe")) {
        wipe = 1;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'x':
      OPTION_x;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* These are really constants, but they have to be variables for the
   * options parsing code.  Assert here that they have known-good
   * values.
   */
  assert (read_only == 0);
  assert (inspector == 0);
  assert (live == 0);

  /* Must be no extra arguments on the command line. */
  if (optind != argc)
    usage (EXIT_FAILURE);

  /* The user didn't specify any drives to format. */
  if (drvs == NULL)
    usage (EXIT_FAILURE);

  /* Because the libguestfs kernel can get stuck rereading the
   * partition table after things have been erased, we sometimes need
   * to completely restart the guest.  Hence this complex retry logic.
   */
  for (retries = 0; retries <= 1; ++retries) {
    /* Add domains/drives from the command line (for a single guest). */
    add_drives (drvs, 'a');

    if (guestfs_launch (g) == -1)
      exit (EXIT_FAILURE);

    /* Test if the wipefs API is available. */
    have_wipefs = feature_available (g, "wipefs");

    /* Perform the format. */
    retry = do_format ();
    if (!retry)
      break;

    if (retries == 0) {
      /* We're going to silently retry, after reopening the connection. */
      guestfs_h *g2;

      g2 = guestfs_create ();
      guestfs_set_verbose (g2, guestfs_get_verbose (g));
      guestfs_set_trace (g2, guestfs_get_trace (g));

      if (guestfs_shutdown (g) == -1)
        exit (EXIT_FAILURE);
      guestfs_close (g);
      g = g2;
    }
    else {
      /* Failed. */
      fprintf (stderr,
               _("%s: failed to rescan the disks after two attempts.  This\n"
                 "may mean there is some sort of partition table or disk\n"
                 "data which we are unable to remove.  If you think this\n"
                 "is a bug, please file a bug at http://libguestfs.org/\n"),
               program_name);
      exit (EXIT_FAILURE);
    }
  }

  /* Free up data structures. */
  free_drives (drvs);

  if (guestfs_shutdown (g) == -1)
    exit (EXIT_FAILURE);
  guestfs_close (g);

  exit (EXIT_SUCCESS);
}
Beispiel #7
0
/* returns 1 if its OK */
static int node_group_ungroup(bNodeTree *ntree, bNode *gnode)
{
    bNodeLink *link, *linkn, *tlink;
    bNode *node, *nextnode;
    bNodeTree *ngroup, *wgroup;
    ListBase anim_basepaths = {NULL, NULL};

    ngroup = (bNodeTree *)gnode->id;

    /* clear new pointers, set in copytree */
    for (node = ntree->nodes.first; node; node = node->next)
        node->new_node = NULL;

    /* wgroup is a temporary copy of the NodeTree we're merging in
     * - all of wgroup's nodes are transferred across to their new home
     * - ngroup (i.e. the source NodeTree) is left unscathed
     * - temp copy. don't change ID usercount
     */
    wgroup = ntreeCopyTree_ex(ngroup, G.main, false);

    /* Add the nodes into the ntree */
    for (node = wgroup->nodes.first; node; node = nextnode) {
        nextnode = node->next;

        /* Remove interface nodes.
         * This also removes remaining links to and from interface nodes.
         */
        if (ELEM(node->type, NODE_GROUP_INPUT, NODE_GROUP_OUTPUT)) {
            nodeFreeNode(wgroup, node);
            continue;
        }

        /* keep track of this node's RNA "base" path (the part of the path identifying the node)
         * if the old nodetree has animation data which potentially covers this node
         */
        if (wgroup->adt) {
            PointerRNA ptr;
            char *path;

            RNA_pointer_create(&wgroup->id, &RNA_Node, node, &ptr);
            path = RNA_path_from_ID_to_struct(&ptr);

            if (path)
                BLI_addtail(&anim_basepaths, BLI_genericNodeN(path));
        }

        /* migrate node */
        BLI_remlink(&wgroup->nodes, node);
        BLI_addtail(&ntree->nodes, node);

        /* ensure unique node name in the node tree */
        nodeUniqueName(ntree, node);

        if (!node->parent) {
            node->locx += gnode->locx;
            node->locy += gnode->locy;
        }

        node->flag |= NODE_SELECT;
    }

    /* Add internal links to the ntree */
    for (link = wgroup->links.first; link; link = linkn) {
        linkn = link->next;
        BLI_remlink(&wgroup->links, link);
        BLI_addtail(&ntree->links, link);
    }

    /* and copy across the animation,
     * note that the animation data's action can be NULL here */
    if (wgroup->adt) {
        LinkData *ld, *ldn = NULL;
        bAction *waction;

        /* firstly, wgroup needs to temporary dummy action that can be destroyed, as it shares copies */
        waction = wgroup->adt->action = BKE_action_copy(wgroup->adt->action);

        /* now perform the moving */
        BKE_animdata_separate_by_basepath(&wgroup->id, &ntree->id, &anim_basepaths);

        /* paths + their wrappers need to be freed */
        for (ld = anim_basepaths.first; ld; ld = ldn) {
            ldn = ld->next;

            MEM_freeN(ld->data);
            BLI_freelinkN(&anim_basepaths, ld);
        }

        /* free temp action too */
        if (waction) {
            BKE_libblock_free(G.main, waction);
        }
    }

    /* free the group tree (takes care of user count) */
    BKE_libblock_free(G.main, wgroup);

    /* restore external links to and from the gnode */
    /* note: the nodes have been copied to intermediate wgroup first (so need to use new_node),
     *       then transferred to ntree (new_node pointers remain valid).
     */

    /* input links */
    for (link = ngroup->links.first; link; link = link->next) {
        if (link->fromnode->type == NODE_GROUP_INPUT) {
            const char *identifier = link->fromsock->identifier;
            int num_external_links = 0;

            /* find external links to this input */
            for (tlink = ntree->links.first; tlink; tlink = tlink->next) {
                if (tlink->tonode == gnode && STREQ(tlink->tosock->identifier, identifier)) {
                    nodeAddLink(ntree, tlink->fromnode, tlink->fromsock, link->tonode->new_node, link->tosock->new_sock);
                    ++num_external_links;
                }
            }

            /* if group output is not externally linked,
             * convert the constant input value to ensure somewhat consistent behavior */
            if (num_external_links == 0) {
                /* XXX TODO bNodeSocket *sock = node_group_find_input_socket(gnode, identifier);
                BLI_assert(sock);*/

                /* XXX TODO nodeSocketCopy(ntree, link->tosock->new_sock, link->tonode->new_node, ntree, sock, gnode);*/
            }
        }
    }

    /* output links */
    for (link = ntree->links.first; link; link = link->next) {
        if (link->fromnode == gnode) {
            const char *identifier = link->fromsock->identifier;
            int num_internal_links = 0;

            /* find internal links to this output */
            for (tlink = ngroup->links.first; tlink; tlink = tlink->next) {
                /* only use active output node */
                if (tlink->tonode->type == NODE_GROUP_OUTPUT && (tlink->tonode->flag & NODE_DO_OUTPUT)) {
                    if (STREQ(tlink->tosock->identifier, identifier)) {
                        nodeAddLink(ntree, tlink->fromnode->new_node, tlink->fromsock->new_sock, link->tonode, link->tosock);
                        ++num_internal_links;
                    }
                }
            }

            /* if group output is not internally linked,
             * convert the constant output value to ensure somewhat consistent behavior */
            if (num_internal_links == 0) {
                /* XXX TODO bNodeSocket *sock = node_group_find_output_socket(gnode, identifier);
                BLI_assert(sock);*/

                /* XXX TODO nodeSocketCopy(ntree, link->tosock, link->tonode, ntree, sock, gnode); */
            }
        }
    }

    /* delete the group instance */
    nodeFreeNode(ntree, gnode);

    ntree->update |= NTREE_UPDATE_NODES | NTREE_UPDATE_LINKS;

    return 1;
}
Beispiel #8
0
/* Extract the next token from raw characters. */
static bool parse_next_token(ExprParseState *state)
{
  /* Skip whitespace. */
  while (isspace(*state->cur)) {
    state->cur++;
  }

  /* End of string. */
  if (*state->cur == 0) {
    state->token = 0;
    return true;
  }

  /* Floating point numbers. */
  if (isdigit(*state->cur) || (state->cur[0] == '.' && isdigit(state->cur[1]))) {
    char *end, *out = state->tokenbuf;
    bool is_float = false;

    while (isdigit(*state->cur)) {
      *out++ = *state->cur++;
    }

    if (*state->cur == '.') {
      is_float = true;
      *out++ = *state->cur++;

      while (isdigit(*state->cur)) {
        *out++ = *state->cur++;
      }
    }

    if (ELEM(*state->cur, 'e', 'E')) {
      is_float = true;
      *out++ = *state->cur++;

      if (ELEM(*state->cur, '+', '-')) {
        *out++ = *state->cur++;
      }

      CHECK_ERROR(isdigit(*state->cur));

      while (isdigit(*state->cur)) {
        *out++ = *state->cur++;
      }
    }

    *out = 0;

    /* Forbid C-style octal constants. */
    if (!is_float && state->tokenbuf[0] == '0') {
      for (char *p = state->tokenbuf + 1; *p; p++) {
        if (*p != '0') {
          return false;
        }
      }
    }

    state->token = TOKEN_NUMBER;
    state->tokenval = strtod(state->tokenbuf, &end);
    return (end == out);
  }

  /* ?= tokens */
  if (state->cur[1] == '=' && strchr(token_eq_characters, state->cur[0])) {
    state->token = MAKE_CHAR2(state->cur[0], state->cur[1]);
    state->cur += 2;
    return true;
  }

  /* Special characters (single character tokens) */
  if (strchr(token_characters, *state->cur)) {
    state->token = *state->cur++;
    return true;
  }

  /* Identifiers */
  if (isalpha(*state->cur) || ELEM(*state->cur, '_')) {
    char *out = state->tokenbuf;

    while (isalnum(*state->cur) || ELEM(*state->cur, '_')) {
      *out++ = *state->cur++;
    }

    *out = 0;

    for (int i = 0; keyword_list[i].name; i++) {
      if (STREQ(state->tokenbuf, keyword_list[i].name)) {
        state->token = keyword_list[i].token;
        return true;
      }
    }

    state->token = TOKEN_ID;
    return true;
  }

  return false;
}
Beispiel #9
0
static bool parse_unary(ExprParseState *state)
{
  int i;

  switch (state->token) {
    case '+':
      return parse_next_token(state) && parse_unary(state);

    case '-':
      CHECK_ERROR(parse_next_token(state) && parse_unary(state));
      parse_add_func(state, OPCODE_FUNC1, 1, op_negate);
      return true;

    case '(':
      return parse_next_token(state) && parse_expr(state) && state->token == ')' &&
             parse_next_token(state);

    case TOKEN_NUMBER:
      parse_add_op(state, OPCODE_CONST, 1)->arg.dval = state->tokenval;
      return parse_next_token(state);

    case TOKEN_ID:
      /* Parameters: search in reverse order in case of duplicate names -
       * the last one should win. */
      for (i = state->param_names_len - 1; i >= 0; i--) {
        if (STREQ(state->tokenbuf, state->param_names[i])) {
          parse_add_op(state, OPCODE_PARAMETER, 1)->arg.ival = i;
          return parse_next_token(state);
        }
      }

      /* Ordinary builtin constants. */
      for (i = 0; builtin_consts[i].name; i++) {
        if (STREQ(state->tokenbuf, builtin_consts[i].name)) {
          parse_add_op(state, OPCODE_CONST, 1)->arg.dval = builtin_consts[i].value;
          return parse_next_token(state);
        }
      }

      /* Ordinary builtin functions. */
      for (i = 0; builtin_ops[i].name; i++) {
        if (STREQ(state->tokenbuf, builtin_ops[i].name)) {
          int args = parse_function_args(state);

          return parse_add_func(state, builtin_ops[i].op, args, builtin_ops[i].funcptr);
        }
      }

      /* Specially supported functions. */
      if (STREQ(state->tokenbuf, "min")) {
        int cnt = parse_function_args(state);
        CHECK_ERROR(cnt > 0);

        parse_add_op(state, OPCODE_MIN, 1 - cnt)->arg.ival = cnt;
        return true;
      }

      if (STREQ(state->tokenbuf, "max")) {
        int cnt = parse_function_args(state);
        CHECK_ERROR(cnt > 0);

        parse_add_op(state, OPCODE_MAX, 1 - cnt)->arg.ival = cnt;
        return true;
      }

      return false;

    default:
      return false;
  }
}
Beispiel #10
0
/* patching UserDef struct and Themes */
void BLO_version_defaults_userpref_blend(Main *bmain, UserDef *userdef)
{

#define USER_VERSION_ATLEAST(ver, subver) MAIN_VERSION_ATLEAST(bmain, ver, subver)

  /* the UserDef struct is not corrected with do_versions() .... ugh! */
  if (userdef->wheellinescroll == 0) {
    userdef->wheellinescroll = 3;
  }
  if (userdef->menuthreshold1 == 0) {
    userdef->menuthreshold1 = 5;
    userdef->menuthreshold2 = 2;
  }
  if (userdef->mixbufsize == 0) {
    userdef->mixbufsize = 2048;
  }
  if (userdef->autokey_mode == 0) {
    /* 'add/replace' but not on */
    userdef->autokey_mode = 2;
  }
  if (userdef->savetime <= 0) {
    userdef->savetime = 1;
    // XXX      error(STRINGIFY(BLENDER_STARTUP_FILE)" is buggy, please consider removing it.\n");
  }
  if (userdef->gizmo_size == 0) {
    userdef->gizmo_size = 75;
    userdef->gizmo_flag |= USER_GIZMO_DRAW;
  }
  if (userdef->pad_rot_angle == 0.0f) {
    userdef->pad_rot_angle = 15.0f;
  }

  /* graph editor - unselected F-Curve visibility */
  if (userdef->fcu_inactive_alpha == 0) {
    userdef->fcu_inactive_alpha = 0.25f;
  }

  if (!USER_VERSION_ATLEAST(192, 0)) {
    strcpy(userdef->sounddir, "/");
  }

  /* patch to set Dupli Armature */
  if (!USER_VERSION_ATLEAST(220, 0)) {
    userdef->dupflag |= USER_DUP_ARM;
  }

  /* added seam, normal color, undo */
  if (!USER_VERSION_ATLEAST(235, 0)) {
    userdef->uiflag |= USER_GLOBALUNDO;
    if (userdef->undosteps == 0) {
      userdef->undosteps = 32;
    }
  }
  if (!USER_VERSION_ATLEAST(236, 0)) {
    /* illegal combo... */
    if (userdef->flag & USER_LMOUSESELECT) {
      userdef->flag &= ~USER_TWOBUTTONMOUSE;
    }
  }
  if (!USER_VERSION_ATLEAST(240, 0)) {
    userdef->uiflag |= USER_PLAINMENUS;
  }
  if (!USER_VERSION_ATLEAST(242, 0)) {
    /* set defaults for 3D View rotating axis indicator */
    /* since size can't be set to 0, this indicates it's not saved in startup.blend */
    if (userdef->rvisize == 0) {
      userdef->rvisize = 15;
      userdef->rvibright = 8;
      userdef->uiflag |= USER_SHOW_GIZMO_AXIS;
    }
  }
  if (!USER_VERSION_ATLEAST(244, 0)) {
    /* set default number of recently-used files (if not set) */
    if (userdef->recent_files == 0) {
      userdef->recent_files = 10;
    }
  }
  if (!USER_VERSION_ATLEAST(245, 3)) {
    if (userdef->coba_weight.tot == 0) {
      BKE_colorband_init(&userdef->coba_weight, true);
    }
  }
  if (!USER_VERSION_ATLEAST(245, 3)) {
    userdef->flag |= USER_ADD_VIEWALIGNED | USER_ADD_EDITMODE;
  }
  if (!USER_VERSION_ATLEAST(250, 0)) {
    /* adjust grease-pencil distances */
    userdef->gp_manhattendist = 1;
    userdef->gp_euclideandist = 2;

    /* adjust default interpolation for new IPO-curves */
    userdef->ipo_new = BEZT_IPO_BEZ;
  }

  if (!USER_VERSION_ATLEAST(250, 3)) {
    /* new audio system */
    if (userdef->audiochannels == 0) {
      userdef->audiochannels = 2;
    }
    if (userdef->audioformat == 0) {
      userdef->audioformat = 0x24;
    }
    if (userdef->audiorate == 0) {
      userdef->audiorate = 48000;
    }
  }

  if (!USER_VERSION_ATLEAST(250, 8)) {
    wmKeyMap *km;

    for (km = userdef->user_keymaps.first; km; km = km->next) {
      if (STREQ(km->idname, "Armature_Sketch")) {
        strcpy(km->idname, "Armature Sketch");
      }
      else if (STREQ(km->idname, "View3D")) {
        strcpy(km->idname, "3D View");
      }
      else if (STREQ(km->idname, "View3D Generic")) {
        strcpy(km->idname, "3D View Generic");
      }
      else if (STREQ(km->idname, "EditMesh")) {
        strcpy(km->idname, "Mesh");
      }
      else if (STREQ(km->idname, "UVEdit")) {
        strcpy(km->idname, "UV Editor");
      }
      else if (STREQ(km->idname, "Animation_Channels")) {
        strcpy(km->idname, "Animation Channels");
      }
      else if (STREQ(km->idname, "GraphEdit Keys")) {
        strcpy(km->idname, "Graph Editor");
      }
      else if (STREQ(km->idname, "GraphEdit Generic")) {
        strcpy(km->idname, "Graph Editor Generic");
      }
      else if (STREQ(km->idname, "Action_Keys")) {
        strcpy(km->idname, "Dopesheet");
      }
      else if (STREQ(km->idname, "NLA Data")) {
        strcpy(km->idname, "NLA Editor");
      }
      else if (STREQ(km->idname, "Node Generic")) {
        strcpy(km->idname, "Node Editor");
      }
      else if (STREQ(km->idname, "Logic Generic")) {
        strcpy(km->idname, "Logic Editor");
      }
      else if (STREQ(km->idname, "File")) {
        strcpy(km->idname, "File Browser");
      }
      else if (STREQ(km->idname, "FileMain")) {
        strcpy(km->idname, "File Browser Main");
      }
      else if (STREQ(km->idname, "FileButtons")) {
        strcpy(km->idname, "File Browser Buttons");
      }
      else if (STREQ(km->idname, "Buttons Generic")) {
        strcpy(km->idname, "Property Editor");
      }
    }
  }

  if (!USER_VERSION_ATLEAST(252, 3)) {
    if (userdef->flag & USER_LMOUSESELECT) {
      userdef->flag &= ~USER_TWOBUTTONMOUSE;
    }
  }
  if (!USER_VERSION_ATLEAST(252, 4)) {
    /* default new handle type is auto handles */
    userdef->keyhandles_new = HD_AUTO;
  }

  if (!USER_VERSION_ATLEAST(257, 0)) {
    /* clear "AUTOKEY_FLAG_ONLYKEYINGSET" flag from userprefs,
     * so that it doesn't linger around from old configs like a ghost */
    userdef->autokey_flag &= ~AUTOKEY_FLAG_ONLYKEYINGSET;
  }

  if (!USER_VERSION_ATLEAST(260, 3)) {
    /* if new keyframes handle default is stuff "auto", make it "auto-clamped" instead
     * was changed in 260 as part of GSoC11, but version patch was wrong
     */
    if (userdef->keyhandles_new == HD_AUTO) {
      userdef->keyhandles_new = HD_AUTO_ANIM;
    }

    /* enable (Cycles) addon by default */
    BKE_addon_ensure(&userdef->addons, "cycles");
  }

  if (!USER_VERSION_ATLEAST(267, 0)) {

    /* GL Texture Garbage Collection */
    if (userdef->textimeout == 0) {
      userdef->texcollectrate = 60;
      userdef->textimeout = 120;
    }
    if (userdef->memcachelimit <= 0) {
      userdef->memcachelimit = 32;
    }
    if (userdef->dbl_click_time == 0) {
      userdef->dbl_click_time = 350;
    }
    if (userdef->v2d_min_gridsize == 0) {
      userdef->v2d_min_gridsize = 35;
    }
    if (userdef->widget_unit == 0) {
      userdef->widget_unit = 20;
    }
    if (userdef->anisotropic_filter <= 0) {
      userdef->anisotropic_filter = 1;
    }

    if (userdef->ndof_sensitivity == 0.0f) {
      userdef->ndof_sensitivity = 1.0f;
      userdef->ndof_flag = (NDOF_LOCK_HORIZON | NDOF_SHOULD_PAN | NDOF_SHOULD_ZOOM |
                            NDOF_SHOULD_ROTATE);
    }

    if (userdef->ndof_orbit_sensitivity == 0.0f) {
      userdef->ndof_orbit_sensitivity = userdef->ndof_sensitivity;

      if (!(userdef->flag & USER_TRACKBALL)) {
        userdef->ndof_flag |= NDOF_TURNTABLE;
      }
    }
  }

  /* NOTE!! from now on use userdef->versionfile and userdef->subversionfile */
#undef USER_VERSION_ATLEAST
#define USER_VERSION_ATLEAST(ver, subver) MAIN_VERSION_ATLEAST(userdef, ver, subver)

  if (!USER_VERSION_ATLEAST(271, 5)) {
    userdef->pie_menu_radius = 100;
    userdef->pie_menu_threshold = 12;
    userdef->pie_animation_timeout = 6;
  }

  if (!USER_VERSION_ATLEAST(275, 2)) {
    userdef->ndof_deadzone = 0.1;
  }

  if (!USER_VERSION_ATLEAST(275, 4)) {
    userdef->node_margin = 80;
  }

  if (!USER_VERSION_ATLEAST(278, 6)) {
    /* Clear preference flags for re-use. */
    userdef->flag &= ~(USER_FLAG_NUMINPUT_ADVANCED | USER_FLAG_UNUSED_2 | USER_FLAG_UNUSED_3 |
                       USER_FLAG_UNUSED_6 | USER_FLAG_UNUSED_7 | USER_FLAG_UNUSED_9 |
                       USER_DEVELOPER_UI);
    userdef->uiflag &= ~(USER_HEADER_BOTTOM);
    userdef->transopts &= ~(USER_TR_UNUSED_2 | USER_TR_UNUSED_3 | USER_TR_UNUSED_4 |
                            USER_TR_UNUSED_6 | USER_TR_UNUSED_7);

    userdef->uiflag |= USER_LOCK_CURSOR_ADJUST;
  }

  if (!USER_VERSION_ATLEAST(280, 20)) {
    userdef->gpu_viewport_quality = 0.6f;

    /* Reset theme, old themes will not be compatible with minor version updates from now on. */
    for (bTheme *btheme = userdef->themes.first; btheme; btheme = btheme->next) {
      memcpy(btheme, &U_theme_default, sizeof(*btheme));
    }

    /* Annotations - new layer color
     * Replace anything that used to be set if it looks like was left
     * on the old default (i.e. black), which most users used
     */
    if ((userdef->gpencil_new_layer_col[3] < 0.1f) || (userdef->gpencil_new_layer_col[0] < 0.1f)) {
      /* - New color matches the annotation pencil icon
       * - Non-full alpha looks better!
       */
      ARRAY_SET_ITEMS(userdef->gpencil_new_layer_col, 0.38f, 0.61f, 0.78f, 0.9f);
    }
  }

  if (!USER_VERSION_ATLEAST(280, 31)) {
    /* Remove select/action mouse from user defined keymaps. */
    for (wmKeyMap *keymap = userdef->user_keymaps.first; keymap; keymap = keymap->next) {
      for (wmKeyMapDiffItem *kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
        if (kmdi->remove_item) {
          do_version_select_mouse(userdef, kmdi->remove_item);
        }
        if (kmdi->add_item) {
          do_version_select_mouse(userdef, kmdi->add_item);
        }
      }

      for (wmKeyMapItem *kmi = keymap->items.first; kmi; kmi = kmi->next) {
        do_version_select_mouse(userdef, kmi);
      }
    }
  }

  if (!USER_VERSION_ATLEAST(280, 33)) {
    /* Enable GLTF addon by default. */
    BKE_addon_ensure(&userdef->addons, "io_scene_gltf2");
  }

  if (!USER_VERSION_ATLEAST(280, 35)) {
    /* Preserve RMB select setting after moving to Python and changing default value. */
    if (USER_VERSION_ATLEAST(280, 32) || !(userdef->flag & USER_LMOUSESELECT)) {
      BKE_keyconfig_pref_set_select_mouse(userdef, 1, false);
    }

    userdef->flag &= ~USER_LMOUSESELECT;
  }

  if (!USER_VERSION_ATLEAST(280, 38)) {

    /* (keep this block even if it becomes empty). */
    copy_v4_fl4(userdef->light_param[0].vec, -0.580952, 0.228571, 0.781185, 0.0);
    copy_v4_fl4(userdef->light_param[0].col, 0.900000, 0.900000, 0.900000, 1.000000);
    copy_v4_fl4(userdef->light_param[0].spec, 0.318547, 0.318547, 0.318547, 1.000000);
    userdef->light_param[0].flag = 1;
    userdef->light_param[0].smooth = 0.1;

    copy_v4_fl4(userdef->light_param[1].vec, 0.788218, 0.593482, -0.162765, 0.0);
    copy_v4_fl4(userdef->light_param[1].col, 0.267115, 0.269928, 0.358840, 1.000000);
    copy_v4_fl4(userdef->light_param[1].spec, 0.090838, 0.090838, 0.090838, 1.000000);
    userdef->light_param[1].flag = 1;
    userdef->light_param[1].smooth = 0.25;

    copy_v4_fl4(userdef->light_param[2].vec, 0.696472, -0.696472, -0.172785, 0.0);
    copy_v4_fl4(userdef->light_param[2].col, 0.293216, 0.304662, 0.401968, 1.000000);
    copy_v4_fl4(userdef->light_param[2].spec, 0.069399, 0.020331, 0.020331, 1.000000);
    userdef->light_param[2].flag = 1;
    userdef->light_param[2].smooth = 0.4;

    copy_v4_fl4(userdef->light_param[3].vec, 0.021053, -0.989474, 0.143173, 0.0);
    copy_v4_fl4(userdef->light_param[3].col, 0.0, 0.0, 0.0, 1.0);
    copy_v4_fl4(userdef->light_param[3].spec, 0.072234, 0.082253, 0.162642, 1.000000);
    userdef->light_param[3].flag = 1;
    userdef->light_param[3].smooth = 0.7;

    copy_v3_fl3(userdef->light_ambient, 0.025000, 0.025000, 0.025000);

    userdef->flag &= ~(USER_FLAG_UNUSED_4);

    userdef->uiflag &= ~(USER_HEADER_FROM_PREF | USER_UIFLAG_UNUSED_12 | USER_UIFLAG_UNUSED_22);
  }

  if (!USER_VERSION_ATLEAST(280, 41)) {
    /* (keep this block even if it becomes empty). */

    if (userdef->pie_tap_timeout == 0) {
      userdef->pie_tap_timeout = 20;
    }
  }

  if (!USER_VERSION_ATLEAST(280, 44)) {
    userdef->uiflag &= ~(USER_UIFLAG_UNUSED_0 | USER_UIFLAG_UNUSED_1);
    userdef->uiflag2 &= ~(USER_UIFLAG2_UNUSED_0);
    userdef->gp_settings &= ~(GP_PAINT_UNUSED_0);
  }

  if (!USER_VERSION_ATLEAST(280, 50)) {
    /* 3ds is no longer enabled by default and not ported yet. */
    BKE_addon_remove_safe(&userdef->addons, "io_scene_3ds");
  }

  if (!USER_VERSION_ATLEAST(280, 51)) {
    userdef->move_threshold = 2;
  }

  if (!USER_VERSION_ATLEAST(280, 58)) {
    if (userdef->image_draw_method != IMAGE_DRAW_METHOD_GLSL) {
      userdef->image_draw_method = IMAGE_DRAW_METHOD_AUTO;
    }
  }

  /* patch to set Dupli Lightprobes and Grease Pencil */
  if (!USER_VERSION_ATLEAST(280, 58)) {
    userdef->dupflag |= USER_DUP_LIGHTPROBE;
    userdef->dupflag |= USER_DUP_GPENCIL;
  }

  if (!USER_VERSION_ATLEAST(280, 60)) {
    const float GPU_VIEWPORT_QUALITY_FXAA = 0.10f;
    const float GPU_VIEWPORT_QUALITY_TAA8 = 0.25f;
    const float GPU_VIEWPORT_QUALITY_TAA16 = 0.6f;
    const float GPU_VIEWPORT_QUALITY_TAA32 = 0.8f;

    if (userdef->gpu_viewport_quality <= GPU_VIEWPORT_QUALITY_FXAA) {
      userdef->viewport_aa = SCE_DISPLAY_AA_OFF;
    }
    else if (userdef->gpu_viewport_quality <= GPU_VIEWPORT_QUALITY_TAA8) {
      userdef->viewport_aa = SCE_DISPLAY_AA_FXAA;
    }
    else if (userdef->gpu_viewport_quality <= GPU_VIEWPORT_QUALITY_TAA16) {
      userdef->viewport_aa = SCE_DISPLAY_AA_SAMPLES_8;
    }
    else if (userdef->gpu_viewport_quality <= GPU_VIEWPORT_QUALITY_TAA32) {
      userdef->viewport_aa = SCE_DISPLAY_AA_SAMPLES_16;
    }
    else {
      userdef->viewport_aa = SCE_DISPLAY_AA_SAMPLES_32;
    }
  }

  if (!USER_VERSION_ATLEAST(280, 62)) {
    /* (keep this block even if it becomes empty). */
    if (userdef->vbotimeout == 0) {
      userdef->vbocollectrate = 60;
      userdef->vbotimeout = 120;
    }

    if (userdef->lookdev_sphere_size == 0) {
      userdef->lookdev_sphere_size = 150;
    }

    userdef->pref_flag |= USER_PREF_FLAG_SAVE;
  }

  if (!USER_VERSION_ATLEAST(280, 73)) {
    userdef->drag_threshold = 30;
    userdef->drag_threshold_mouse = 3;
    userdef->drag_threshold_tablet = 10;
  }

  /**
   * Include next version bump.
   */
  {
    /* pass */
  }

  if (userdef->pixelsize == 0.0f) {
    userdef->pixelsize = 1.0f;
  }

  for (bTheme *btheme = userdef->themes.first; btheme; btheme = btheme->next) {
    do_versions_theme(userdef, btheme);
  }
#undef USER_VERSION_ATLEAST
}
Beispiel #11
0
static void
ParseConfigurationFile( FILE *file )
{
    char line[LINE_BUFFER_LEN];
    char *token;
    bool protocol_found = false;
    bool server_found = false;
    bool username_found = false;
    bool password_found = false;
    const char *err_string = NULL;

    /* Default values for optional parameters. */
    strcpy( wmnotify_infos.imap_folder, "INBOX"); /* Default IMAP folder. */
    wmnotify_infos.port = 110;
    wmnotify_infos.mail_check_interval = 60; /* 1 minute interval. */
    wmnotify_infos.audible_notification = false; /* Disabled. */
    wmnotify_infos.use_ssl = false; /* Disabled. */
    wmnotify_infos.mail_client_argv[0] = NULL; /* No default command. */
    wmnotify_infos.audiofile[0] = '\0'; /* No default audio file. */
    wmnotify_infos.volume = 100; /* 100% volume. */

    /* Reading one line of data from the configuration file. */
    /* char *fgets(char *s, int size, FILE *stream);
       Reading stops after an EOF or a newline.  If a newline is read, it is
       stored into the buffer.  A '\0'  is  stored after the last character in
       the buffer. */
    while( fgets( line, LINE_BUFFER_LEN, file ) != NULL ) {
        token = strtok( line, delimiter_single_arg );

        if( ( token == NULL ) || ( token[0] == '#' ) ) {
            continue; /* Next iteration of the while() loop (next line). */
        }

        if( STREQ( token, "protocol" ) ) {
            token = GetArguments( "protocol", true );
            if( STREQ( token, "POP3" ) == true ) {
                wmnotify_infos.protocol = POP3_PROTOCOL;
            }
            else if( STREQ( token, "IMAP4" ) == true ) {
                wmnotify_infos.protocol = IMAP4_PROTOCOL;
            }
            else {
                fprintf( stderr, "%s: protocol must be POP3 or IMAP4.\n", PACKAGE );
                exit( EXIT_FAILURE );
            }

            protocol_found = true;
        }
        else if( STREQ( token, "imap_folder" ) ) {
            token = GetArguments( "imap_folder", true );
            /* Should check size before using strcpy(), or use strncopy() instead. */
            strcpy( wmnotify_infos.imap_folder, token );
        }
        else if( STREQ( token, "use_ssl" ) ) {
            int number;

            token = GetArguments( "use_ssl", true );
            number = GetNumber( token, "use_ssl" );
            if( number == 0 ) {
                wmnotify_infos.use_ssl = false;
            }
            else if( number == 1 ) {
#if HAVE_SSL
                wmnotify_infos.use_ssl = true;
#else
                fprintf( stderr, "%s error: You must compile %s with SSL support to\n" \
                         "set parameter 'use_ssl' to true in configuration file\n", PACKAGE, PACKAGE );
                exit( EXIT_FAILURE );
#endif
            }
            else {
                fprintf( stderr, "%s: Invalid value for parameter 'use_ssl' in\n" \
                         "configuration file (must be 0 or 1): %d\n", PACKAGE, number );
                exit( EXIT_FAILURE );
            }
        }
        else if( STREQ( token, "server" ) ) {
            token = GetArguments( "server", true );
            strncpy( wmnotify_infos.server_name, token, MAX_STR_LEN );
            server_found = true;
        }
        else if( STREQ( token, "port" ) ) {
            token = GetArguments( "port", true );
            wmnotify_infos.port = (u_int16_t) GetNumber( token, "port" );
        }

        else if( STREQ( token, "username" ) ) {
            token = GetArguments( "username", true );
            strncpy( wmnotify_infos.username, token, MAX_STR_LEN );
            username_found = true;
        }
        else if( STREQ( token, "password" ) ) {
            token = GetArguments( "password", true );
            strncpy( wmnotify_infos.password, token, MAX_STR_LEN );
            password_found = true;
        }
        else if( STREQ( token, "mailcheckdelay" ) ) {
            int delay; /* delay in minutes. */

            token = GetArguments( "mailcheckdelay", true );
            /* GetNumber() will exit if a negative number is entered. */
            delay = GetNumber( token, "mailcheckdelay" );
            if( delay == 0 ) {
                fprintf( stderr, "%s: Mail check interval must be greater than '0'\n",
                         PACKAGE );
                exit( EXIT_FAILURE );
            }
            wmnotify_infos.mail_check_interval = (unsigned int) delay * 60;
        }
        else if( STREQ( token, "mailclient" ) ) {
            token = GetArguments( "mailclient", false ); /* Multiple arguments */
            strcpy( wmnotify_infos.mail_client_command, token );
            ParseCommand( wmnotify_infos.mail_client_command,
                          wmnotify_infos.mail_client_argv );
        }
        else if( STREQ( token, "enablebeep" ) ) {
            int number;

            token = GetArguments( "enablebeep", true );
            number = GetNumber( token, "enablebeep" );
            if( number == 0 ) {
                wmnotify_infos.audible_notification = false;
            }
            else if( number == 1 ) {
                wmnotify_infos.audible_notification = true;
            }
            else {
                fprintf( stderr, "%s: Invalid value for for parameter 'enablebeep' in\n" \
                         "configuration file (must be 0 or 1): %d\n", PACKAGE, number );
                exit( EXIT_FAILURE );
            }
        }
        else if( STREQ( token, "audiofile" ) ) {
            token = GetArguments( "audiofile", true );
            /* Should check size before using strcpy(), or use strncopy() instead. */
            strcpy( wmnotify_infos.audiofile, token );
        }
        else if( STREQ( token, "volume" ) ) {
            token = GetArguments( "volume", true );
            wmnotify_infos.volume = GetNumber( token, "volume" );
        }
        else {
            fprintf( stderr, "%s: invalid parameter in configuration file: %s\n", PACKAGE,
                     token );
            exit( EXIT_FAILURE );
        }

        token = strtok( NULL, delimiter_single_arg );
        if( ( token != NULL ) && ( token[0] != '#' ) ) {
            fprintf( stderr, "%s: Garbage at end of line in configuration file: %s\n", PACKAGE,
                     token );
            exit( EXIT_FAILURE );
        }
    }

    if( protocol_found == false ) {
        err_string = "protocol";
    }
    else if( server_found == false ) {
        err_string = "server";
    }
    else if( username_found == false ) {
        err_string = "username";
    }
    else if( password_found == false ) {
        err_string = "password";
    }
    else {
        return; /* success */
    }

    /* Failure. */
    fprintf( stderr, "%s: Mandatory parameter \"%s\" missing from configuration "
             "file.\n", PACKAGE, err_string );
    exit( EXIT_FAILURE );
}
Beispiel #12
0
hive_h *
hivex_open (const char *filename, int flags)
{
  hive_h *h = NULL;

  assert (sizeof (struct ntreg_header) == 0x1000);
  assert (offsetof (struct ntreg_header, csum) == 0x1fc);

  h = calloc (1, sizeof *h);
  if (h == NULL)
    goto error;

  h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;

  const char *debug = getenv ("HIVEX_DEBUG");
  if (debug && STREQ (debug, "1"))
    h->msglvl = 2;

  DEBUG (2, "created handle %p", h);

  h->writable = !!(flags & HIVEX_OPEN_WRITE);
  h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE);
  h->filename = strdup (filename);
  if (h->filename == NULL)
    goto error;

#ifdef O_CLOEXEC
  h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);
#else
  h->fd = open (filename, O_RDONLY | O_BINARY);
#endif
  if (h->fd == -1)
    goto error;
#ifndef O_CLOEXEC
  fcntl (h->fd, F_SETFD, FD_CLOEXEC);
#endif

  struct stat statbuf;
  if (fstat (h->fd, &statbuf) == -1)
    goto error;

  h->size = statbuf.st_size;

  if (h->size < 0x2000) {
    SET_ERRNO (EINVAL,
               "%s: file is too small to be a Windows NT Registry hive file",
               filename);
    goto error;
  }

  if (!h->writable) {
    h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
    if (h->addr == MAP_FAILED)
      goto error;

    DEBUG (2, "mapped file at %p", h->addr);
  } else {
    h->addr = malloc (h->size);
    if (h->addr == NULL)
      goto error;

    if (full_read (h->fd, h->addr, h->size) < h->size)
      goto error;

    /* We don't need the file descriptor along this path, since we
     * have read all the data.
     */
    if (close (h->fd) == -1)
      goto error;
    h->fd = -1;
  }

  /* Check header. */
  if (h->hdr->magic[0] != 'r' ||
      h->hdr->magic[1] != 'e' ||
      h->hdr->magic[2] != 'g' ||
      h->hdr->magic[3] != 'f') {
    SET_ERRNO (ENOTSUP,
               "%s: not a Windows NT Registry hive file", filename);
    goto error;
  }

  /* Check major version. */
  uint32_t major_ver = le32toh (h->hdr->major_ver);
  if (major_ver != 1) {
    SET_ERRNO (ENOTSUP,
               "%s: hive file major version %" PRIu32 " (expected 1)",
               filename, major_ver);
    goto error;
  }

  h->bitmap = calloc (1 + h->size / 32, 1);
  if (h->bitmap == NULL)
    goto error;

  /* Header checksum. */
  uint32_t sum = header_checksum (h);
  if (sum != le32toh (h->hdr->csum)) {
    SET_ERRNO (EINVAL, "%s: bad checksum in hive header", filename);
    goto error;
  }

  for (int t=0; t<nr_recode_types; t++) {
    gl_lock_init (h->iconv_cache[t].mutex);
    h->iconv_cache[t].handle = NULL;
  }

  /* Last modified time. */
  h->last_modified = le64toh ((int64_t) h->hdr->last_modified);

  if (h->msglvl >= 2) {
    char *name = _hivex_recode (h, utf16le_to_utf8,
                                h->hdr->name, 64, NULL);

    fprintf (stderr,
             "hivex_open: header fields:\n"
             "  file version             %" PRIu32 ".%" PRIu32 "\n"
             "  sequence nos             %" PRIu32 " %" PRIu32 "\n"
             "    (sequences nos should match if hive was synched at shutdown)\n"
             "  last modified            %" PRIi64 "\n"
             "    (Windows filetime, x 100 ns since 1601-01-01)\n"
             "  original file name       %s\n"
             "    (only 32 chars are stored, name is probably truncated)\n"
             "  root offset              0x%x + 0x1000\n"
             "  end of last page         0x%x + 0x1000 (total file size 0x%zx)\n"
             "  checksum                 0x%x (calculated 0x%x)\n",
             major_ver, le32toh (h->hdr->minor_ver),
             le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
             h->last_modified,
             name ? name : "(conversion failed)",
             le32toh (h->hdr->offset),
             le32toh (h->hdr->blocks), h->size,
             le32toh (h->hdr->csum), sum);
    free (name);
  }

  h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
  h->endpages = le32toh (h->hdr->blocks) + 0x1000;

  DEBUG (2, "root offset = 0x%zx", h->rootoffs);

  /* We'll set this flag when we see a block with the root offset (ie.
   * the root block).
   */
  int seen_root_block = 0, bad_root_block = 0;

  /* Collect some stats. */
  size_t pages = 0;           /* Number of hbin pages read. */
  size_t smallest_page = SIZE_MAX, largest_page = 0;
  size_t blocks = 0;          /* Total number of blocks found. */
  size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
  size_t used_blocks = 0;     /* Total number of used blocks found. */
  size_t used_size = 0;       /* Total size (bytes) of used blocks. */

  /* Read the pages and blocks.  The aim here is to be robust against
   * corrupt or malicious registries.  So we make sure the loops
   * always make forward progress.  We add the address of each block
   * we read to a hash table so pointers will only reference the start
   * of valid blocks.
   */
  size_t off;
  struct ntreg_hbin_page *page;
  for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
    if (off >= h->endpages)
      break;

    page = (struct ntreg_hbin_page *) ((char *) h->addr + off);
    if (page->magic[0] != 'h' ||
        page->magic[1] != 'b' ||
        page->magic[2] != 'i' ||
        page->magic[3] != 'n') {

      if (!h->unsafe) {
        SET_ERRNO (ENOTSUP,
                   "%s: trailing garbage at end of file "
                   "(at 0x%zx, after %zu pages)",
                   filename, off, pages);
        goto error;
      }

      DEBUG (2,
             "page not found at expected offset 0x%zx, "
             "seeking until one is found or EOF is reached",
             off);

      int found = 0;
      while (off < h->size) {
        off += 0x1000;

        if (off >= h->endpages)
          break;

        page = (struct ntreg_hbin_page *) ((char *) h->addr + off);
        if (page->magic[0] == 'h' &&
            page->magic[1] == 'b' &&
            page->magic[2] == 'i' &&
            page->magic[3] == 'n') {
          DEBUG (2, "found next page by seeking at 0x%zx", off);
          found = 1;
          break;
        }
      }

      if (!found) {
        DEBUG (2, "page not found and end of pages section reached");
        break;
      }
    }

    size_t page_size = le32toh (page->page_size);
    DEBUG (2, "page at 0x%zx, size %zu", off, page_size);
    pages++;
    if (page_size < smallest_page) smallest_page = page_size;
    if (page_size > largest_page) largest_page = page_size;

    if (page_size <= sizeof (struct ntreg_hbin_page) ||
        (page_size & 0x0fff) != 0) {
      SET_ERRNO (ENOTSUP,
                 "%s: page size %zu at 0x%zx, bad registry",
                 filename, page_size, off);
      goto error;
    }

    if (off + page_size > h->size) {
      SET_ERRNO (ENOTSUP,
                 "%s: page size %zu at 0x%zx extends beyond end of file, bad registry",
                 filename, page_size, off);
      goto error;
    }

    size_t page_offset = le32toh(page->offset_first) + 0x1000;

    if (page_offset != off) {
      SET_ERRNO (ENOTSUP,
                 "%s: declared page offset (0x%zx) does not match computed "
                 "offset (0x%zx), bad registry",
                 filename, page_offset, off);
      goto error;
    }

    /* Read the blocks in this page. */
    size_t blkoff;
    struct ntreg_hbin_block *block;
    size_t seg_len;
    for (blkoff = off + 0x20;
         blkoff < off + page_size;
         blkoff += seg_len) {
      blocks++;

      int is_root = blkoff == h->rootoffs;
      if (is_root)
        seen_root_block = 1;

      block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);
      int used;
      seg_len = block_len (h, blkoff, &used);
/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-overflow"
      if (seg_len <= 4 || (seg_len & 3) != 0) {
#pragma GCC diagnostic pop
        if (is_root || !h->unsafe) {
          SET_ERRNO (ENOTSUP,
                     "%s, the block at 0x%zx has invalid size %" PRIu32
                     ", bad registry",
                     filename, blkoff, le32toh (block->seg_len));
          goto error;
        } else {
          DEBUG (2,
                 "%s: block at 0x%zx has invalid size %" PRIu32 ", skipping",
                 filename, blkoff, le32toh (block->seg_len));
          break;
        }
      }

      if (h->msglvl >= 2) {
        unsigned char *id = (unsigned char *) block->id;
        int id0 = id[0], id1 = id[1];

        fprintf (stderr, "%s: %s: "
                 "%s block id %d,%d (%c%c) at 0x%zx size %zu%s\n",
                 "hivex", __func__,
                 used ? "used" : "free",
                 id0, id1,
                 c_isprint (id0) ? id0 : '.',
                 c_isprint (id1) ? id1 : '.',
                 blkoff,
                 seg_len, is_root ? " (root)" : "");
      }

      blocks_bytes += seg_len;
      if (seg_len < smallest_block) smallest_block = seg_len;
      if (seg_len > largest_block) largest_block = seg_len;

      if (is_root && !used)
        bad_root_block = 1;

      if (used) {
        used_blocks++;
        used_size += seg_len;

        /* Root block must be an nk-block. */
        if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
          bad_root_block = 1;

        /* Note this blkoff is a valid address. */
        BITMAP_SET (h->bitmap, blkoff);
      }
    }
  }

  if (!seen_root_block) {
    SET_ERRNO (ENOTSUP, "%s: no root block found", filename);
    goto error;
  }

  if (bad_root_block) {
    SET_ERRNO (ENOTSUP, "%s: bad root block (free or not nk)", filename);
    goto error;
  }

  DEBUG (1, "successfully read Windows Registry hive file:\n"
         "  pages:          %zu [sml: %zu, lge: %zu]\n"
         "  blocks:         %zu [sml: %zu, avg: %zu, lge: %zu]\n"
         "  blocks used:    %zu\n"
         "  bytes used:     %zu",
         pages, smallest_page, largest_page,
         blocks, smallest_block, blocks_bytes / blocks, largest_block,
         used_blocks, used_size);

  return h;

 error:;
  int err = errno;
  if (h) {
    free (h->bitmap);
    if (h->addr && h->size && h->addr != MAP_FAILED) {
      if (!h->writable)
        munmap (h->addr, h->size);
      else
        free (h->addr);
    }
    if (h->fd >= 0)
      close (h->fd);
    free (h->filename);
    free (h);
  }
  errno = err;
  return NULL;
}
Beispiel #13
0
void
kernel_configuration (struct config *config, char **cmdline, int cmdline_source)
{
  const char *p;

  p = get_cmdline_key (cmdline, "p2v.pre");
  if (p)
    run_command (config->verbose, "p2v.pre", p);

  p = get_cmdline_key (cmdline, "p2v.server");
  assert (p); /* checked by caller */
  free (config->server);
  config->server = strdup (p);

  p = get_cmdline_key (cmdline, "p2v.port");
  if (p) {
    if (sscanf (p, "%d", &config->port) != 1) {
      fprintf (stderr, "%s: cannot parse p2v.port from kernel command line",
               guestfs_int_program_name);
      exit (EXIT_FAILURE);
    }
  }

  p = get_cmdline_key (cmdline, "p2v.username");
  if (p) {
    free (config->username);
    config->username = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.password");
  if (p) {
    free (config->password);
    config->password = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.identity");
  if (p) {
    free (config->identity_url);
    config->identity_url = strdup (p);
    config->identity_file_needs_update = 1;
  }

  p = get_cmdline_key (cmdline, "p2v.sudo");
  if (p)
    config->sudo = 1;

  /* We should now be able to connect and interrogate virt-v2v
   * on the conversion server.
   */
  p = get_cmdline_key (cmdline, "p2v.skip_test_connection");
  if (!p) {
    wait_network_online (config);
    if (test_connection (config) == -1) {
      const char *err = get_ssh_error ();

      fprintf (stderr, "%s: error opening control connection to %s:%d: %s\n",
               guestfs_int_program_name, config->server, config->port, err);
      exit (EXIT_FAILURE);
    }
  }

  p = get_cmdline_key (cmdline, "p2v.name");
  if (p) {
    free (config->guestname);
    config->guestname = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.vcpus");
  if (p) {
    if (sscanf (p, "%d", &config->vcpus) != 1) {
      fprintf (stderr, "%s: cannot parse p2v.vcpus from kernel command line\n",
               guestfs_int_program_name);
      exit (EXIT_FAILURE);
    }
  }

  p = get_cmdline_key (cmdline, "p2v.memory");
  if (p) {
    char mem_code;

    if (sscanf (p, "%" SCNu64 "%c", &config->memory, &mem_code) != 2) {
      fprintf (stderr, "%s: cannot parse p2v.memory from kernel command line\n",
               guestfs_int_program_name);
      exit (EXIT_FAILURE);
    }
    config->memory *= 1024;
    if (mem_code == 'M' || mem_code == 'm'
        || mem_code == 'G' || mem_code == 'g')
      config->memory *= 1024;
    if (mem_code == 'G' || mem_code == 'g')
      config->memory *= 1024;
    if (mem_code != 'M' && mem_code != 'm'
        && mem_code != 'G' && mem_code != 'g') {
      fprintf (stderr, "%s: p2v.memory on kernel command line must be followed by 'G' or 'M'\n",
               guestfs_int_program_name);
      exit (EXIT_FAILURE);
    }
  }

  p = get_cmdline_key (cmdline, "p2v.disks");
  if (p) {
    CLEANUP_FREE char *t;

    t = strdup (p);
    guestfs_int_free_string_list (config->disks);
    config->disks = guestfs_int_split_string (',', t);
  }

  p = get_cmdline_key (cmdline, "p2v.removable");
  if (p) {
    CLEANUP_FREE char *t;

    t = strdup (p);
    guestfs_int_free_string_list (config->removable);
    config->removable = guestfs_int_split_string (',', t);
  }

  p = get_cmdline_key (cmdline, "p2v.interfaces");
  if (p) {
    CLEANUP_FREE char *t;

    t = strdup (p);
    guestfs_int_free_string_list (config->interfaces);
    config->interfaces = guestfs_int_split_string (',', t);
  }

  p = get_cmdline_key (cmdline, "p2v.network");
  if (p) {
    CLEANUP_FREE char *t;

    t = strdup (p);
    guestfs_int_free_string_list (config->network_map);
    config->network_map = guestfs_int_split_string (',', t);
  }

  p = get_cmdline_key (cmdline, "p2v.o");
  if (p) {
    free (config->output);
    config->output = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.oa");
  if (p) {
    if (STREQ (p, "sparse"))
      config->output_allocation = OUTPUT_ALLOCATION_SPARSE;
    else if (STREQ (p, "preallocated"))
      config->output_allocation = OUTPUT_ALLOCATION_PREALLOCATED;
    else
      fprintf (stderr, "%s: warning: don't know what p2v.oa=%s means\n",
               guestfs_int_program_name, p);
  }

  p = get_cmdline_key (cmdline, "p2v.oc");
  if (p) {
    free (config->output_connection);
    config->output_connection = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.of");
  if (p) {
    free (config->output_format);
    config->output_format = strdup (p);
  }

  p = get_cmdline_key (cmdline, "p2v.os");
  if (p) {
    free (config->output_storage);
    config->output_storage = strdup (p);
  }

  /* Undocumented command line tool used for testing command line parsing. */
  p = get_cmdline_key (cmdline, "p2v.dump_config_and_exit");
  if (p) {
    print_config (config, stdout);
    exit (EXIT_SUCCESS);
  }

  /* Some disks must have been specified for conversion. */
  if (config->disks == NULL || guestfs_int_count_strings (config->disks) == 0) {
    fprintf (stderr, "%s: error: no non-removable disks were discovered on this machine.\n",
             guestfs_int_program_name);
    fprintf (stderr, "virt-p2v looked in /sys/block and in p2v.disks on the kernel command line.\n");
    fprintf (stderr, "This is a fatal error and virt-p2v cannot continue.\n");
    exit (EXIT_FAILURE);
  }

  /* Perform the conversion in text mode. */
  if (start_conversion (config, notify_ui_callback) == -1) {
    const char *err = get_conversion_error ();

    fprintf (stderr, "%s: error during conversion: %s\n",
             guestfs_int_program_name, err);

    p = get_cmdline_key (cmdline, "p2v.fail");
    if (p)
      run_command (config->verbose, "p2v.fail", p);

    exit (EXIT_FAILURE);
  }

  p = get_cmdline_key (cmdline, "p2v.post");
  if (!p) {
    if (geteuid () == 0 && cmdline_source == CMDLINE_SOURCE_PROC_CMDLINE)
      p = "poweroff";
  }
  if (p)
    run_command (config->verbose, "p2v.post", p);
}
Beispiel #14
0
int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  parse_config ();

  enum { HELP_OPTION = CHAR_MAX + 1 };

  /* The command line arguments are broadly compatible with (a subset
   * of) guestfish.  Thus we have to deal mainly with -a, -m and --ro.
   */
  static const char *options = "a:c:d:im:no:rv?Vwx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "connect", 1, 0, 'c' },
    { "dir-cache-timeout", 1, 0, 0 },
    { "domain", 1, 0, 'd' },
    { "echo-keys", 0, 0, 0 },
    { "format", 2, 0, 0 },
    { "fuse-help", 0, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "inspector", 0, 0, 'i' },
    { "keys-from-stdin", 0, 0, 0 },
    { "live", 0, 0, 0 },
    { "mount", 1, 0, 'm' },
    { "no-sync", 0, 0, 'n' },
    { "option", 1, 0, 'o' },
    { "ro", 0, 0, 'r' },
    { "rw", 0, 0, 'w' },
    { "selinux", 0, 0, 0 },
    { "trace", 0, 0, 'x' },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { 0, 0, 0, 0 }
  };

  struct drv *drvs = NULL;
  struct drv *drv;
  struct mp *mps = NULL;
  struct mp *mp;
  char *p;
  const char *format = NULL;
  int c, r;
  int option_index;
  struct sigaction sa;

  int fuse_argc = 0;
  const char **fuse_argv = NULL;

#define ADD_FUSE_ARG(str)                                               \
  do {                                                                  \
    fuse_argc ++;                                                       \
    fuse_argv = realloc (fuse_argv, (1+fuse_argc) * sizeof (char *));   \
    if (!fuse_argv) {                                                   \
      perror ("realloc");                                               \
      exit (EXIT_FAILURE);                                                         \
    }                                                                   \
    fuse_argv[fuse_argc-1] = (str);                                     \
    fuse_argv[fuse_argc] = NULL;                                        \
  } while (0)

  /* LC_ALL=C is required so we can parse error messages. */
  setenv ("LC_ALL", "C", 1);

  /* Set global program name that is not polluted with libtool artifacts.  */
  set_program_name (argv[0]);

  memset (&sa, 0, sizeof sa);
  sa.sa_handler = SIG_IGN;
  sa.sa_flags = SA_RESTART;
  sigaction (SIGPIPE, &sa, NULL);

  /* Various initialization. */
  init_dir_caches ();

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  guestfs_set_recovery_proc (g, 0);

  ADD_FUSE_ARG (program_name);
  /* MUST be single-threaded.  You cannot have two threads accessing the
   * same libguestfs handle, and opening more than one handle is likely
   * to be very expensive.
   */
  ADD_FUSE_ARG ("-s");

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "dir-cache-timeout"))
        dir_cache_timeout = atoi (optarg);
      else if (STREQ (long_options[option_index].name, "fuse-help"))
        fuse_help ();
      else if (STREQ (long_options[option_index].name, "selinux"))
        guestfs_set_selinux (g, 1);
      else if (STREQ (long_options[option_index].name, "format")) {
        if (!optarg || STREQ (optarg, ""))
          format = NULL;
        else
          format = optarg;
      } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
        keys_from_stdin = 1;
      } else if (STREQ (long_options[option_index].name, "echo-keys")) {
        echo_keys = 1;
      } else if (STREQ (long_options[option_index].name, "live")) {
        live = 1;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'c':
      OPTION_c;
      break;

    case 'd':
      OPTION_d;
      break;

    case 'i':
      OPTION_i;
      break;

    case 'm':
      OPTION_m;
      break;

    case 'n':
      OPTION_n;
      break;

    case 'o':
      ADD_FUSE_ARG ("-o");
      ADD_FUSE_ARG (optarg);
      break;

    case 'r':
      OPTION_r;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'w':
      OPTION_w;
      break;

    case 'x':
      OPTION_x;
      ADD_FUSE_ARG ("-f");
      guestfs_set_recovery_proc (g, 1);
      trace_calls = 1;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* Check we have the right options. */
  if (!live) {
    if (!drvs || !(mps || inspector)) {
      fprintf (stderr,
               _("%s: must have at least one -a/-d and at least one -m/-i option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }
  } else {
    size_t count_d = 0, count_other = 0;
    struct drv *drv;

    if (read_only) {
      fprintf (stderr,
               _("%s: --live is not compatible with --ro option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    if (inspector) {
      fprintf (stderr,
               _("%s: --live is not compatible with -i option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    /* --live: make sure there was one -d option and no -a options */
    for (drv = drvs; drv; drv = drv->next) {
      if (drv->type == drv_d)
        count_d++;
      else
        count_other++;
    }

    if (count_d != 1) {
      fprintf (stderr,
               _("%s: with --live, you must use exactly one -d option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    if (count_other != 0) {
      fprintf (stderr,
               _("%s: --live is not compatible with -a option\n"),
               program_name);
      exit (EXIT_FAILURE);
    }
  }

  /* We'd better have a mountpoint. */
  if (optind+1 != argc) {
    fprintf (stderr,
             _("%s: you must specify a mountpoint in the host filesystem\n"),
             program_name);
    exit (EXIT_FAILURE);
  }

  /* Do the guest drives and mountpoints. */
  add_drives (drvs, 'a');
  if (guestfs_launch (g) == -1)
    exit (EXIT_FAILURE);
  if (inspector)
    inspect_mount ();
  mount_mps (mps);

  free_drives (drvs);
  free_mps (mps);

  /* FUSE example does this, not clear if it's necessary, but ... */
  if (guestfs_umask (g, 0) == -1)
    exit (EXIT_FAILURE);

  /* At the last minute, remove the libguestfs error handler.  In code
   * above this point, the default error handler has been used which
   * sends all errors to stderr.  Now before entering FUSE itself we
   * want to silence errors so we can convert them (see error()
   * function above).
   */
  guestfs_set_error_handler (g, NULL, NULL);

  /* Finish off FUSE args. */
  ADD_FUSE_ARG (argv[optind]);

  /*
    It says about the line containing the for-statement:
    error: assuming signed overflow does not occur when simplifying conditional to constant [-Wstrict-overflow]

  if (verbose) {
    fprintf (stderr, "guestmount: invoking FUSE with args [");
    for (i = 0; i < fuse_argc; ++i) {
      if (i > 0) fprintf (stderr, ", ");
      fprintf (stderr, "%s", fuse_argv[i]);
    }
    fprintf (stderr, "]\n");
  }
  */

  r = fuse_main (fuse_argc, (char **) fuse_argv, &fg_operations, NULL);

  /* Cleanup. */
  guestfs_close (g);
  free_dir_caches ();

  exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
Beispiel #15
0
/*
 * read a packet from the wire, and decrypt it.  Increment the global
 * seq_no return NULL on failure
 */
u_char *
read_packet(void)
{
    HDR		hdr;
    u_char	*pkt, *data;
    int		len;
    char	*tkey;

    if (debug & DEBUG_PACKET_FLAG)
	report(LOG_DEBUG, "Waiting for packet");

    /* read a packet header */
    len = sockread(session.sock, (u_char *)&hdr,
		   TAC_PLUS_HDR_SIZE, cfg_get_readtimeout());
    if (len != TAC_PLUS_HDR_SIZE) {
	report(LOG_DEBUG, "Read %d bytes from %s %s, expecting %d",
	       len, session.peer, session.port, TAC_PLUS_HDR_SIZE);
	return(NULL);
    }
    session.peerflags = hdr.flags;

    if ((hdr.version & TAC_PLUS_MAJOR_VER_MASK) != TAC_PLUS_MAJOR_VER) {
	report(LOG_ERR, "%s: Illegal major version specified: found %d wanted "
	       "%d\n", session.peer, hdr.version, TAC_PLUS_MAJOR_VER);
	return(NULL);
    }

    /* get memory for the packet */
    len = TAC_PLUS_HDR_SIZE + ntohl(hdr.datalength);
    if ((ntohl(hdr.datalength) & ~0xffffUL) ||
	(len < TAC_PLUS_HDR_SIZE) || (len > 0x10000)) {
	report(LOG_ERR, "%s: Illegal data size: %lu\n", session.peer,
	       ntohl(hdr.datalength));
	return(NULL);
    }
    pkt = (u_char *)tac_malloc(len);

    /* initialise the packet */
    memcpy(pkt, &hdr, TAC_PLUS_HDR_SIZE);

    /* the data start here */
    data = pkt + TAC_PLUS_HDR_SIZE;

    /* read the rest of the packet data */
    if (sockread(session.sock, data, ntohl(hdr.datalength),
		 cfg_get_readtimeout()) != ntohl(hdr.datalength)) {
	report(LOG_ERR, "%s: start_session: bad socket read", session.peer);
	free(pkt);
	return(NULL);
    }
    session.seq_no++;		/* should now equal that of incoming packet */
    session.last_exch = time(NULL);

    if (session.seq_no != hdr.seq_no) {
	report(LOG_ERR, "%s: Illegal session seq # %d != packet seq # %d",
	       session.peer, session.seq_no, hdr.seq_no);
	free(pkt);
	return(NULL);
    }

    /* decrypt the data portion */
    tkey = cfg_get_host_key(session.peerip);
    if (tkey == NULL && !STREQ(session.peer, session.peerip)) {
	tkey = cfg_get_host_prompt(session.peer);
    }
    if (tkey == NULL)
	tkey = session.key;
    if (md5_xor((HDR *)pkt, data, tkey)) {
	report(LOG_ERR, "%s: start_session error decrypting data",
	       session.peer);
	free(pkt);
	return(NULL);
    }

    if (debug & DEBUG_PACKET_FLAG)
	report(LOG_DEBUG, "Read %s size=%d",
	       summarise_incoming_packet_type(pkt), len);

    session.version = hdr.version;

    return(pkt);
}
Beispiel #16
0
void parse_args(int argc, char** argv, struct prefs* v) {
	gboolean in_loop = TRUE;

	struct option long_options[] = {
		{ "font-size-modifier", 1, NULL, 'z' },
		{ "black", 1, NULL, '1' },
		{ "red", 1, NULL, '2' },
		{ "green", 1, NULL, '3' },
		{ "yellow", 1, NULL, '4' },
		{ "blue", 1, NULL, '5' },
		{ "magenta", 1, NULL, '6' },
		{ "cyan", 1, NULL, '7' },
		{ "white", 1, NULL, '8' },
		{ "jump-resize", 2, NULL, 'j' },
		{ "file-icons", 2, NULL, 'i' },
		{ "version", 0, NULL, 'V' },
	};

	GdkColor color_temp;

	optind = 0;
	while (in_loop) {
		switch (fgetopt_long(argc, argv, "j::z:i::vV", long_options, NULL)) {

			case -1:
				in_loop = FALSE;
				break;

			/* Font size modifier */
			case 'z':
				v->font_size_modifier = CLAMP(atoi(optarg), -10, 10);
				break;

			/* Enable or disable icons */
			case 'i':
				if (!optarg || STREQ(optarg, "on"))
					v->show_icons = TRUE;
				else if (STREQ(optarg, "off"))
					v->show_icons = FALSE;
				break;

			/* Enable or disable jump-resize */
			case 'j':
				if (!optarg || STREQ(optarg, "on"))
					v->jump_resize = TRUE;
				else if (STREQ(optarg, "off"))
					v->jump_resize = FALSE;
				break;

			/* Colours */
			case '1':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_BLACK, &color_temp);
				break;
			case '2':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_RED, &color_temp);
				break;
			case '3':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_GREEN, &color_temp);
				break;
			case '4':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_YELLOW, &color_temp);
				break;
			case '5':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_BLUE, &color_temp);
				break;
			case '6':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_MAGENTA, &color_temp);
				break;
			case '7':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_CYAN, &color_temp);
				break;
			case '8':
				if (gdk_color_parse(optarg, &color_temp))
					set_color(TCC_WHITE, &color_temp);
				break;

			case 'v':
			case 'V':
				report_version();
				break;
	
			case ':':
				g_warning("Option missing argument");
				/*exit(EXIT_FAILURE);*/
				break;

			case '?':
			default:
				g_warning("Unknown option provided");
				/*exit(EXIT_FAILURE);*/
				break;
		}
	}
}
/* seems messy, but thats what you get with not using pointers but channel names :) */
void ED_armature_bone_rename(bArmature *arm, const char *oldnamep, const char *newnamep)
{
	Object *ob;
	char newname[MAXBONENAME];
	char oldname[MAXBONENAME];
	
	/* names better differ! */
	if (strncmp(oldnamep, newnamep, MAXBONENAME)) {
		
		/* we alter newname string... so make copy */
		BLI_strncpy(newname, newnamep, MAXBONENAME);
		/* we use oldname for search... so make copy */
		BLI_strncpy(oldname, oldnamep, MAXBONENAME);
		
		/* now check if we're in editmode, we need to find the unique name */
		if (arm->edbo) {
			EditBone *eBone = ED_armature_bone_find_name(arm->edbo, oldname);
			
			if (eBone) {
				unique_editbone_name(arm->edbo, newname, NULL);
				BLI_strncpy(eBone->name, newname, MAXBONENAME);
			}
			else {
				return;
			}
		}
		else {
			Bone *bone = BKE_armature_find_bone_name(arm, oldname);
			
			if (bone) {
				unique_bone_name(arm, newname);
				BLI_strncpy(bone->name, newname, MAXBONENAME);
			}
			else {
				return;
			}
		}
		
		/* do entire dbase - objects */
		for (ob = G.main->object.first; ob; ob = ob->id.next) {
			ModifierData *md;
			
			/* we have the object using the armature */
			if (arm == ob->data) {
				Object *cob;
				
				/* Rename the pose channel, if it exists */
				if (ob->pose) {
					bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, oldname);
					if (pchan) {
						GHash *gh = ob->pose->chanhash;

						/* remove the old hash entry, and replace with the new name */
						if (gh) {
							BLI_assert(BLI_ghash_haskey(gh, pchan->name));
							BLI_ghash_remove(gh, pchan->name, NULL, NULL);
						}

						BLI_strncpy(pchan->name, newname, MAXBONENAME);

						if (gh) {
							BLI_ghash_insert(gh, pchan->name, pchan);
						}
					}

					BLI_assert(BKE_pose_channels_is_valid(ob->pose) == true);
				}
				
				/* Update any object constraints to use the new bone name */
				for (cob = G.main->object.first; cob; cob = cob->id.next) {
					if (cob->constraints.first)
						constraint_bone_name_fix(ob, &cob->constraints, oldname, newname);
					if (cob->pose) {
						bPoseChannel *pchan;
						for (pchan = cob->pose->chanbase.first; pchan; pchan = pchan->next) {
							constraint_bone_name_fix(ob, &pchan->constraints, oldname, newname);
						}
					}
				}
			}
			
			/* See if an object is parented to this armature */
			if (ob->parent && (ob->parent->data == arm)) {
				if (ob->partype == PARBONE) {
					/* bone name in object */
					if (!strcmp(ob->parsubstr, oldname))
						BLI_strncpy(ob->parsubstr, newname, MAXBONENAME);
				}
			}
			
			if (modifiers_usesArmature(ob, arm)) {
				bDeformGroup *dg = defgroup_find_name(ob, oldname);
				if (dg) {
					BLI_strncpy(dg->name, newname, MAXBONENAME);
				}
			}
			
			/* fix modifiers that might be using this name */
			for (md = ob->modifiers.first; md; md = md->next) {
				switch (md->type) {
					case eModifierType_Hook:
					{
						HookModifierData *hmd = (HookModifierData *)md;

						if (hmd->object && (hmd->object->data == arm)) {
							if (STREQ(hmd->subtarget, oldname))
								BLI_strncpy(hmd->subtarget, newname, MAXBONENAME);
						}
						break;
					}
					case eModifierType_UVWarp:
					{
						UVWarpModifierData *umd = (UVWarpModifierData *)md;

						if (umd->object_src && (umd->object_src->data == arm)) {
							if (STREQ(umd->bone_src, oldname))
								BLI_strncpy(umd->bone_src, newname, MAXBONENAME);
						}
						if (umd->object_dst && (umd->object_dst->data == arm)) {
							if (STREQ(umd->bone_dst, oldname))
								BLI_strncpy(umd->bone_dst, newname, MAXBONENAME);
						}
						break;
					}
					default:
						break;
				}
			}
		}
		
		/* Fix all animdata that may refer to this bone - we can't just do the ones attached to objects, since
		 * other ID-blocks may have drivers referring to this bone [#29822]
		 */
		{
			
			BKE_all_animdata_fix_paths_rename(&arm->id, "pose.bones", oldname, newname);
		}
		
		/* correct view locking */
		{
			bScreen *screen;
			for (screen = G.main->screen.first; screen; screen = screen->id.next) {
				ScrArea *sa;
				/* add regions */
				for (sa = screen->areabase.first; sa; sa = sa->next) {
					SpaceLink *sl;
					for (sl = sa->spacedata.first; sl; sl = sl->next) {
						if (sl->spacetype == SPACE_VIEW3D) {
							View3D *v3d = (View3D *)sl;
							if (v3d->ob_centre && v3d->ob_centre->data == arm) {
								if (!strcmp(v3d->ob_centre_bone, oldname)) {
									BLI_strncpy(v3d->ob_centre_bone, newname, MAXBONENAME);
								}
							}
						}
					}
				}
			}
		}
	}
}
Beispiel #18
0
int
main (int argc, char *argv[])
{
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  (void) bindtextdomain (PACKAGE, LOCALEDIR);
  (void) bindtextdomain ("bison-runtime", LOCALEDIR);
  (void) textdomain (PACKAGE);

  {
    char const *cp = getenv ("LC_CTYPE");
    if (cp && STREQ (cp, "C"))
      set_custom_quoting (&quote_quoting_options, "'", "'");
    else
      set_quoting_style (&quote_quoting_options, locale_quoting_style);
  }

  atexit (close_stdout);

  uniqstrs_new ();
  muscle_init ();
  complain_init ();

  getargs (argc, argv);

  timevar_report = trace_flag & trace_time;
  init_timevar ();
  timevar_start (TV_TOTAL);

  if (trace_flag & trace_bitsets)
    bitset_stats_enable ();

  /* Read the input.  Copy some parts of it to FGUARD, FACTION, FTABLE
     and FATTRS.  In file reader.c.  The other parts are recorded in
     the grammar; see gram.h.  */

  timevar_push (TV_READER);
  reader ();
  timevar_pop (TV_READER);

  if (complaint_status == status_complaint)
    goto finish;

  /* Find useless nonterminals and productions and reduce the grammar. */
  timevar_push (TV_REDUCE);
  reduce_grammar ();
  timevar_pop (TV_REDUCE);

  /* Record other info about the grammar.  In files derives and
     nullable.  */
  timevar_push (TV_SETS);
  derives_compute ();
  nullable_compute ();
  timevar_pop (TV_SETS);

  /* Compute LR(0) parser states.  See state.h for more info.  */
  timevar_push (TV_LR0);
  generate_states ();
  timevar_pop (TV_LR0);

  /* Add lookahead sets to parser states.  Except when LALR(1) is
     requested, split states to eliminate LR(1)-relative
     inadequacies.  */
  ielr ();

  /* Find and record any conflicts: places where one token of
     lookahead is not enough to disambiguate the parsing.  In file
     conflicts.  Also resolve s/r conflicts based on precedence
     declarations.  */
  timevar_push (TV_CONFLICTS);
  conflicts_solve ();
  if (!muscle_percent_define_flag_if ("lr.keep-unreachable-state"))
    {
      state_number *old_to_new = xnmalloc (nstates, sizeof *old_to_new);
      state_number nstates_old = nstates;
      state_remove_unreachable_states (old_to_new);
      lalr_update_state_numbers (old_to_new, nstates_old);
      conflicts_update_state_numbers (old_to_new, nstates_old);
      free (old_to_new);
    }
  conflicts_print ();
  timevar_pop (TV_CONFLICTS);

  /* Compute the parser tables.  */
  timevar_push (TV_ACTIONS);
  tables_generate ();
  timevar_pop (TV_ACTIONS);

  grammar_rules_useless_report (_("rule useless in parser due to conflicts"));

  print_precedence_warnings ();

  /* Output file names. */
  compute_output_file_names ();

  /* Output the detailed report on the grammar.  */
  if (report_flag)
    {
      timevar_push (TV_REPORT);
      print_results ();
      timevar_pop (TV_REPORT);
    }

  /* Output the graph.  */
  if (graph_flag)
    {
      timevar_push (TV_GRAPH);
      print_graph ();
      timevar_pop (TV_GRAPH);
    }

  /* Output xml.  */
  if (xml_flag)
    {
      timevar_push (TV_XML);
      print_xml ();
      timevar_pop (TV_XML);
    }

  /* Stop if there were errors, to avoid trashing previous output
     files.  */
  if (complaint_status == status_complaint)
    goto finish;

  /* Lookahead tokens are no longer needed. */
  timevar_push (TV_FREE);
  lalr_free ();
  timevar_pop (TV_FREE);

  /* Output the tables and the parser to ftable.  In file output.  */
  timevar_push (TV_PARSER);
  output ();
  timevar_pop (TV_PARSER);

  timevar_push (TV_FREE);
  nullable_free ();
  derives_free ();
  tables_free ();
  states_free ();
  reduce_free ();
  conflicts_free ();
  grammar_free ();
  output_file_names_free ();

  /* The scanner memory cannot be released right after parsing, as it
     contains things such as user actions, prologue, epilogue etc.  */
  gram_scanner_free ();
  muscle_free ();
  uniqstrs_free ();
  code_scanner_free ();
  skel_scanner_free ();
  quotearg_free ();
  timevar_pop (TV_FREE);

  if (trace_flag & trace_bitsets)
    bitset_stats_dump (stderr);

 finish:

  /* Stop timing and print the times.  */
  timevar_stop (TV_TOTAL);
  timevar_print (stderr);

  cleanup_caret ();

  return complaint_status ? EXIT_FAILURE : EXIT_SUCCESS;
}
Beispiel #19
0
/* Returns 0 on success, 1 if we need to retry. */
static int
do_format (void)
{
  char **devices;
  size_t i;
  int ret;

  devices = guestfs_list_devices (g);
  if (devices == NULL)
    exit (EXIT_FAILURE);

  /* Erase the disks. */
  if (!wipe) {
    for (i = 0; devices[i] != NULL; ++i) {
      /* erase the filesystem signatures on each device */
      if (have_wipefs && guestfs_wipefs (g, devices[i]) == -1)
        exit (EXIT_FAILURE);
      /* Then erase the partition table on each device. */
      if (guestfs_zero (g, devices[i]) == -1)
        exit (EXIT_FAILURE);
    }
  }
  else /* wipe */ {
    for (i = 0; devices[i] != NULL; ++i) {
      if (guestfs_zero_device (g, devices[i]) == -1)
        exit (EXIT_FAILURE);
    }
  }

  if (do_rescan (devices)) {
    ret = 1; /* which means, reopen the handle and retry */
    goto out;
  }

  /* Format each disk. */
  for (i = 0; devices[i] != NULL; ++i) {
    char *dev = devices[i];
    int free_dev = 0;

    if (partition) {
      const char *ptype = partition;
      int64_t dev_size;

      /* If partition has the magic value "DEFAULT", choose either MBR or GPT.*/
      if (STREQ (partition, "DEFAULT")) {
        dev_size = guestfs_blockdev_getsize64 (g, devices[i]);
        if (dev_size == -1)
          exit (EXIT_FAILURE);
        ptype = dev_size < INT64_C(2)*1024*1024*1024*1024 ? "mbr" : "gpt";
      }

      if (guestfs_part_disk (g, devices[i], ptype) == -1)
        exit (EXIT_FAILURE);
      if (asprintf (&dev, "%s1", devices[i]) == -1) {
        perror ("asprintf");
        exit (EXIT_FAILURE);
      }
      free_dev = 1;
    }

    if (vg && lv) {
      char *devs[2] = { dev, NULL };

      if (guestfs_pvcreate (g, dev) == -1)
        exit (EXIT_FAILURE);

      if (guestfs_vgcreate (g, vg, devs) == -1)
        exit (EXIT_FAILURE);

      if (guestfs_lvcreate_free (g, lv, vg, 100) == -1)
        exit (EXIT_FAILURE);

      if (free_dev)
        free (dev);
      if (asprintf (&dev, "/dev/%s/%s", vg, lv) == -1) {
        perror ("asprintf");
        exit (EXIT_FAILURE);
      }
      free_dev = 1;
    }

    if (filesystem) {
      if (guestfs_mkfs_opts (g, filesystem, dev, -1) == -1)
        exit (EXIT_FAILURE);
    }

    if (free_dev)
      free (dev);
  }

  if (guestfs_sync (g) == -1)
    exit (EXIT_FAILURE);

  ret = 0;

 out:
  /* Free device list. */
  for (i = 0; devices[i] != NULL; ++i)
    free (devices[i]);
  free (devices);

  return ret;
}
Beispiel #20
0
int
main (int argc, string *argv)
{
  const_string coerce;
  unsigned coerce_len;
  int option;

#ifdef WIN32
  setmode(fileno(stdout), _O_BINARY);
#endif

  while ((option = getopt(argc, argv, "il:")) != -1) {
    switch (option) {
    case 'i':
      do_ini = true;
      break;
    case 'l':
      max_lines = atoi(optarg);
      if (max_lines <= 0)
        FATAL("[-i] [-l lines] name");
      break;
    default:
      FATAL("[-i] [-l lines] name");
      break;
    }
  }
  if (optind + 1 != argc)
    FATAL("[-i] [-l lines] name");
  output_name = argv[optind];

  sprintf (filename, "%sd.h", output_name);
  sprintf (tempfile, "%s.tmp", output_name);
  out = xfopen (filename, FOPEN_W_MODE);
  fputs ("#undef TRIP\n#undef TRAP\n", out);
  /* We have only one binary that can do both ini stuff and vir stuff.  */
  fputs ("#define STAT\n#define INI\n", out);
  
  if (STREQ (output_name, "mf")) {
    fputs ("#define INIMF\n#define MF\n", out);
    coerce = "mfcoerce.h";
  } else if (STREQ (output_name, "tex")) {
    fputs ("#define INITEX\n#define TeX\n#define onlyTeX\n", out);
    coerce = "texcoerce.h";
  } else if (STREQ (output_name, "aleph")) {
    fputs ("#define INITEX\n#define TeX\n#define Aleph\n", out);
    coerce = "alephcoerce.h";
  } else if (STREQ (output_name, "etex")) {
    fputs ("#define INITEX\n#define TeX\n#define eTeX\n", out);
    coerce = "etexcoerce.h";
  } else if (STREQ (output_name, "pdftex")) {
    fputs ("#define INITEX\n#define TeX\n#define pdfTeX\n", out);
    coerce = "pdftexcoerce.h";
  } else if (STREQ (output_name, "ptex")) {
    fputs ("#define INITEX\n#define TeX\n#define pTeX\n", out);
    coerce = "ptexcoerce.h";
  } else if (STREQ (output_name, "eptex")) {
    fputs ("#define INITEX\n#define TeX\n#define epTeX\n", out);
    coerce = "eptexcoerce.h";
  } else if (STREQ (output_name, "euptex")) {
    fputs ("#define INITEX\n#define TeX\n#define eupTeX\n", out);
    coerce = "euptexcoerce.h";
  } else if (STREQ (output_name, "uptex")) {
    fputs ("#define INITEX\n#define TeX\n#define upTeX\n", out);
    coerce = "uptexcoerce.h";
  } else if (STREQ (output_name, "xetex")) {
    fputs ("#define INITEX\n#define TeX\n#define XeTeX\n", out);
    coerce = "xetexcoerce.h";
  } else
    FATAL1 ("Can only split mf, tex, aleph, eptex, euptex, etex, pdftex, ptex, uptex, or xetex,\n not %s", output_name);
  
  coerce_len = strlen (coerce);
  
  /* Read everything up to coerce.h.  */
  while (fgets (buffer, sizeof (buffer), stdin))
    {
      if (strncmp (&buffer[10], coerce, coerce_len) == 0)
	break;

      if (buffer[0] == '#' || buffer[0] == '\n' || buffer[0] == '}'
	  || buffer[0] == '/' || buffer[0] == ' '
	  || strncmp (buffer, "typedef", 7) == 0)
	/*nothing */ ;
      else
	fputs ("EXTERN ", out);

      fputs (buffer, out);
    }

  if (strncmp (&buffer[10], coerce, coerce_len) != 0)
    FATAL1 ("No #include %s line", coerce);

  fputs (buffer, out);
  xfclose (out, filename);

  if (do_ini) {
    sprintf (ini_name, "%sini.c", output_name);
    ini = xfopen (ini_name, FOPEN_W_MODE);
    fputs ("#define EXTERN extern\n", ini);
    fprintf (ini, "#include \"%sd.h\"\n\n", output_name);
  }

  sprintf (filename, "%s0.c", output_name);
  out = xfopen (filename, FOPEN_W_MODE);
  fputs ("#define EXTERN extern\n", out);
  fprintf (out, "#include \"%sd.h\"\n\n", output_name);

  do
    {
      /* Read one routine into a temp file */
      has_ini = false;
      temp = xfopen (tempfile, "wb+");

      while (read_line ())
	{
	  fputs (buffer, temp);
	  if (buffer[0] == '}')
	    break;		/* End of procedure */
	}
      while (ifdef_nesting > 0 && read_line ())
	fputs (buffer, temp);
      rewind (temp);

      if (do_ini && has_ini)
	{			/* Contained "#ifdef INI..." */
	  while (fgets (buffer, sizeof (buffer), temp))
	    fputs (buffer, ini);
	}
      else
	{			/* Doesn't contain "#ifdef INI..." */
	  while (fgets (buffer, sizeof (buffer), temp))
	    {
	      fputs (buffer, out);
	      lines_in_file++;
	    }
	}
      xfclose (temp, tempfile);

      /* Switch to new output file.  */
      if (max_lines && lines_in_file > max_lines)
	{
	  xfclose (out, filename);
	  sprintf (filename, "%s%d.c", output_name, ++filenumber);
	  out = xfopen (filename, FOPEN_W_MODE);
	  fputs ("#define EXTERN extern\n", out);
	  fprintf (out, "#include \"%sd.h\"\n\n", output_name);
	  lines_in_file = 0;
	}
    }
  while (!feof (stdin));

  xfclose (out, filename);
  if (lines_in_file == 0)
    unlink (filename);

  if (do_ini)
    xfclose (ini, ini_name);

  if (unlink (tempfile)) {
      perror (tempfile);
      exit (EXIT_FAILURE);
  }

  return EXIT_SUCCESS;
}
Beispiel #21
0
static void
parse_orbname( char *orbname, char *orb_address, int *orb_port )
{
	char	*split_orbname;
	Tbl	*orbname_parts;
	char	orbname_port[STRSZ];
	Hook	*hook = 0;
	static Pf *pfnames = 0;
	int	len = 0;
		
	if( STREQ( orbname, ":" ) ) {
		
		strcpy( orb_address, "127.0.0.1" );
		strcpy( orbname_port, "" );

	} else {
		
		split_orbname = strdup( orbname );
		orbname_parts = split( split_orbname, ':' );

		if( maxtbl( orbname_parts ) == 1 && orbname[0] == ':' ) {

			strcpy( orb_address, "127.0.0.1" );
			strcpy( orbname_port, poptbl( orbname_parts ) );

		} else if( maxtbl( orbname_parts ) == 1 ) {

			strcpy( orb_address, shifttbl( orbname_parts ) );
			strcpy( orbname_port, "" );

		} else if( maxtbl( orbname_parts ) == 2 ) {

			strcpy( orb_address, shifttbl( orbname_parts ) );
			strcpy( orbname_port, poptbl( orbname_parts ) );

		} else {

			elog_complain( 0, "pforbstat: unexpected error translating orb2orb argument <%s>\n",
				  orbname );
			strcpy( orb_address, "" );
			strcpy( orbname_port, "" );
		}

		free( split_orbname );
		freetbl( orbname_parts, 0 );
	}

	if( ( len = strlen( orbname_port ) ) > 0 ) {

		if( orbname_port[len-1] == '@' ) {
			
			orbname_port[len-1] = '\0';
		}
	}

	if( STREQ( orbname_port, "" ) ) {
		
		*orb_port = ORB_TCP_PORT;

	} else if( strmatches( orbname_port, "^[0-9]+$", &hook ) ) {
		
		*orb_port = atoi( orbname_port );

	} else {

		if( pfnames == 0 ) {

			pfread( "orbserver_names", &pfnames );
		}

		if( pfget_string( pfnames, orbname_port ) == 0 ) {

			elog_complain( 0, "pforbstat: couldn't translate orb port \":%s\"\n", orbname_port );

			*orb_port = 0;

		} else {
		
			*orb_port = pfget_int( pfnames, orbname_port );
		}
	}

	if( hook != (Hook *) NULL ) {

		free_hook( &hook );
	}

	return;
}
Beispiel #22
0
int main(int argc, char **argv) {
    int i, n;
    char **origenv;
    char **newenv;
    char *cwd;
    FILE *log = fopen(abs_builddir "/commandhelper.log", "w");

    if (!log)
        goto error;

    for (i = 1 ; i < argc ; i++) {
        fprintf(log, "ARG:%s\n", argv[i]);
    }

    origenv = environ;
    n = 0;
    while (*origenv != NULL) {
        n++;
        origenv++;
    }

    if (VIR_ALLOC_N(newenv, n) < 0) {
        exit(EXIT_FAILURE);
    }

    origenv = environ;
    n = i = 0;
    while (*origenv != NULL) {
        newenv[i++] = *origenv;
        n++;
        origenv++;
    }
    qsort(newenv, n, sizeof(newenv[0]), envsort);

    for (i = 0 ; i < n ; i++) {
        /* Ignore the variables used to instruct the loader into
         * behaving differently, as they could throw the tests off. */
        if (!STRPREFIX(newenv[i], "LD_"))
            fprintf(log, "ENV:%s\n", newenv[i]);
    }

    for (i = 0 ; i < sysconf(_SC_OPEN_MAX) ; i++) {
        int f;
        int closed;
        if (i == fileno(log))
            continue;
        closed = fcntl(i, F_GETFD, &f) == -1 &&
            errno == EBADF;
        if (!closed)
            fprintf(log, "FD:%d\n", i);
    }

    fprintf(log, "DAEMON:%s\n", getpgrp() == getsid(0) ? "yes" : "no");
    if (!(cwd = getcwd(NULL, 0)))
        return EXIT_FAILURE;
    if (strlen(cwd) > strlen(".../commanddata") &&
        STREQ(cwd + strlen(cwd) - strlen("/commanddata"), "/commanddata"))
        strcpy(cwd, ".../commanddata");
    fprintf(log, "CWD:%s\n", cwd);
    VIR_FREE(cwd);

    VIR_FORCE_FCLOSE(log);

    char buf[1024];
    ssize_t got;

    fprintf(stdout, "BEGIN STDOUT\n");
    fflush(stdout);
    fprintf(stderr, "BEGIN STDERR\n");
    fflush(stderr);

    for (;;) {
        got = read(STDIN_FILENO, buf, sizeof(buf));
        if (got < 0)
            goto error;
        if (got == 0)
            break;
        if (safewrite(STDOUT_FILENO, buf, got) != got)
            goto error;
        if (safewrite(STDERR_FILENO, buf, got) != got)
            goto error;
    }

    fprintf(stdout, "END STDOUT\n");
    fflush(stdout);
    fprintf(stderr, "END STDERR\n");
    fflush(stderr);

    return EXIT_SUCCESS;

error:
    return EXIT_FAILURE;
}
Beispiel #23
0
int
main (int argc, char *argv[])
{
  int c;
  int option_index;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "long-options")) {
        display_long_options (long_options);
      }
      else if (STREQ (long_options[option_index].name, "short-options")) {
        display_short_options (options);
      }
      else if (STREQ (long_options[option_index].name, "floppy")) {
        size_str = "1440K";
        partition = "mbr";
        type = "vfat";
      }
      else if (STREQ (long_options[option_index].name, "label")) {
        label = optarg;
      }
      else if (STREQ (long_options[option_index].name, "partition")) {
        if (optarg == NULL)
          partition = "mbr";
        else
          partition = optarg;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 guestfs_int_program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'F':
      format = optarg;
      break;

    case 's':
      size_str = optarg;
      break;

    case 't':
      type = optarg;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'x':
      OPTION_x;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  if (optind + 2 != argc) {
    fprintf (stderr, _("%s: missing input and output arguments on the command line\n"),
             guestfs_int_program_name);
    usage (EXIT_FAILURE);
  }

  if (do_make_fs (argv[optind], argv[optind+1]) == -1)
    exit (EXIT_FAILURE);

  exit (EXIT_SUCCESS);
}
static int
udevConnectListAllInterfaces(virConnectPtr conn,
                             virInterfacePtr **ifaces,
                             unsigned int flags)
{
    struct udev_iface_driver *driverState = conn->interfacePrivateData;
    struct udev *udev;
    struct udev_enumerate *enumerate = NULL;
    struct udev_list_entry *devices;
    struct udev_list_entry *dev_entry;
    virInterfacePtr *ifaces_list = NULL;
    virInterfacePtr iface_obj;
    int tmp_count;
    int count = 0;
    int status = 0;
    int ret;

    virCheckFlags(VIR_CONNECT_LIST_INTERFACES_FILTERS_ACTIVE, -1);

    if (virConnectListAllInterfacesEnsureACL(conn) < 0)
        return -1;

    /* Grab a udev reference */
    udev = udev_ref(driverState->udev);

    /* List all interfaces in case we support more filter flags in the future */
    enumerate = udevGetDevices(udev, VIR_UDEV_IFACE_ALL);

    if (!enumerate) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to get list of %s interfaces on host"),
                       virUdevStatusString(status));
        ret = -1;
        goto cleanup;
    }

    /* Do the scan to load up the enumeration */
    udev_enumerate_scan_devices(enumerate);

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* For each item so we can count */
    udev_list_entry_foreach(dev_entry, devices) {
        count++;
    }

    /* If we've got nothing, exit out */
    if (count == 0) {
        ret = 0;
        goto cleanup;
    }

    /* If we're asked for the ifaces then alloc up memory */
    if (ifaces && VIR_ALLOC_N(ifaces_list, count + 1) < 0) {
        ret = -1;
        goto cleanup;
    }

    /* Get a list we can walk */
    devices = udev_enumerate_get_list_entry(enumerate);

    /* reset our iterator */
    count = 0;

    /* Walk through each device */
    udev_list_entry_foreach(dev_entry, devices) {
        struct udev_device *dev;
        const char *path;
        const char *name;
        const char *macaddr;
        virInterfaceDefPtr def;

        path = udev_list_entry_get_name(dev_entry);
        dev = udev_device_new_from_syspath(udev, path);
        name = udev_device_get_sysname(dev);
        macaddr = udev_device_get_sysattr_value(dev, "address");
        status = STREQ(udev_device_get_sysattr_value(dev, "operstate"), "up");

        def = udevGetMinimalDefForDevice(dev);
        if (!virConnectListAllInterfacesCheckACL(conn, def)) {
            udev_device_unref(dev);
            virInterfaceDefFree(def);
            continue;
        }
        virInterfaceDefFree(def);

        /* Filter the results */
        if (MATCH(VIR_CONNECT_LIST_INTERFACES_FILTERS_ACTIVE) &&
            !((MATCH(VIR_CONNECT_LIST_INTERFACES_ACTIVE) && status) ||
              (MATCH(VIR_CONNECT_LIST_INTERFACES_INACTIVE) && !status))) {
            udev_device_unref(dev);
            continue;
        }

        /* If we matched a filter, then add it */
        if (ifaces) {
            iface_obj = virGetInterface(conn, name, macaddr);
            ifaces_list[count++] = iface_obj;
        }
        udev_device_unref(dev);
    }

    /* Drop our refcounts */
    udev_enumerate_unref(enumerate);
    udev_unref(udev);

    /* Trim the array to its final size */
    if (ifaces) {
        ignore_value(VIR_REALLOC_N(ifaces_list, count + 1));
        *ifaces = ifaces_list;
        ifaces_list = NULL;
    }

    return count;

 cleanup:
    if (enumerate)
        udev_enumerate_unref(enumerate);
    udev_unref(udev);

    if (ifaces) {
        for (tmp_count = 0; tmp_count < count; tmp_count++)
            virInterfaceFree(ifaces_list[tmp_count]);
    }

    VIR_FREE(ifaces_list);

    return ret;

}
Beispiel #25
0
static int
do_make_fs (const char *input, const char *output_str)
{
  const char *dev, *options;
  CLEANUP_UNLINK_FREE char *output = NULL;
  uint64_t estimate, size;
  struct guestfs_disk_create_argv optargs;
  CLEANUP_FREE char *ifmt = NULL;
  CLEANUP_FREE char *ifile = NULL;
  pid_t pid;
  int status, fd;

  /* Use of CLEANUP_UNLINK_FREE *output ensures the output file is
   * deleted unless we successfully reach the end of this function.
   */
  output = strdup (output_str);
  if (output == NULL) {
    perror ("strdup");
    return -1;
  }

  /* Input.  What is it?  Estimate how much space it will need. */
  if (estimate_input (input, &estimate, &ifmt) == -1)
    return -1;

  if (verbose) {
    fprintf (stderr, "input format = %s\n", ifmt);
    fprintf (stderr, "estimate = %" PRIu64 " bytes "
             "(%" PRIu64 " 1K blocks, %" PRIu64 " 4K blocks)\n",
             estimate, estimate / 1024, estimate / 4096);
  }

  estimate += 256 * 1024;       /* For superblocks &c. */

  if (STRPREFIX (type, "ext") && type[3] >= '3') {
    /* For ext3+, add some more for the journal. */
    estimate += 1024 * 1024;
  }

  else if (STREQ (type, "ntfs")) {
    estimate += 4 * 1024 * 1024; /* NTFS journal. */
  }

  else if (STREQ (type, "btrfs")) {
    /* For BTRFS, the minimum metadata allocation is 256MB, with data
     * additional to that.  Note that we disable data and metadata
     * duplication below.
     */
    estimate += 256 * 1024 * 1024;
  }

  /* Add 10%, see above. */
  estimate *= 1.10;

  /* Calculate the output size. */
  if (size_str == NULL)
    size = estimate;
  else
    if (parse_size (size_str, estimate, &size) == -1)
      return -1;

  /* Create the output disk. */
  optargs.bitmask = 0;
  if (STREQ (format, "qcow2")) {
    optargs.bitmask |= GUESTFS_DISK_CREATE_PREALLOCATION_BITMASK;
    optargs.preallocation = "metadata";
  }
  if (guestfs_disk_create_argv (g, output, format, size, &optargs) == -1)
    return -1;

  if (guestfs_add_drive_opts (g, output,
                              GUESTFS_ADD_DRIVE_OPTS_FORMAT, format,
                              -1) == -1)
    return -1;

  if (guestfs_launch (g) == -1)
    return -1;

  if (check_ntfs_available () == -1)
    return -1;

  /* Partition the disk. */
  dev = "/dev/sda";
  if (partition) {
    int mbr_id = 0;

    if (STREQ (partition, ""))
      partition = "mbr";

    if (guestfs_part_disk (g, dev, partition) == -1)
      return -1;

    dev = "/dev/sda1";

    /* Set the partition type byte if it's MBR and the filesystem type
     * is one that we know about.
     */
    if (STREQ (partition, "mbr") || STREQ (partition, "msdos")) {
      if (STREQ (type, "msdos"))
        /* According to Wikipedia.  However I have not actually tried this. */
        mbr_id = 0x1;
      else if (STREQ (type, "vfat") || STREQ (type, "fat"))
        mbr_id = 0xb;
      else if (STREQ (type, "ntfs"))
        mbr_id = 0x7;
      else if (STRPREFIX (type, "ext"))
        mbr_id = 0x83;
      else if (STREQ (type, "minix"))
        mbr_id = 0x81;
    }
    if (mbr_id != 0) {
      if (guestfs_part_set_mbr_id (g, "/dev/sda", 1, mbr_id) == -1)
        return -1;
    }
  }

  if (verbose)
    fprintf (stderr, "creating %s filesystem on %s ...\n", type, dev);

  /* Create the filesystem. */
  if (STRNEQ (type, "btrfs")) {
    int r;
    struct guestfs_mkfs_opts_argv optargs = { .bitmask = 0 };

    if (label) {
      optargs.label = label;
      optargs.bitmask |= GUESTFS_MKFS_OPTS_LABEL_BITMASK;
    }

    guestfs_push_error_handler (g, NULL, NULL);
    r = guestfs_mkfs_opts_argv (g, type, dev, &optargs);
    guestfs_pop_error_handler (g);

    if (r == -1) {
      /* Provide more guidance in the error message (RHBZ#823883). */
      fprintf (stderr, "%s: 'mkfs' (create filesystem) operation failed.\n",
               guestfs_int_program_name);
      if (STREQ (type, "fat"))
        fprintf (stderr, "Instead of 'fat', try 'vfat' (long filenames) or 'msdos' (short filenames).\n");
      else
        fprintf (stderr, "Is '%s' a correct filesystem type?\n", type);

      return -1;
    }
  }
  else {
Beispiel #26
0
static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int codec_id, AVFormatContext *of,
                                    int rectx, int recty, char *error, int error_size)
{
	AVStream *st;
	AVCodecContext *c;
	AVCodec *codec;
	AVDictionary *opts = NULL;

	error[0] = '\0';

	st = avformat_new_stream(of, NULL);
	if (!st) return NULL;
	st->id = 0;

	/* Set up the codec context */
	
	c = st->codec;
	c->codec_id = codec_id;
	c->codec_type = AVMEDIA_TYPE_VIDEO;

	/* Get some values from the current render settings */
	
	c->width = rectx;
	c->height = recty;

	/* FIXME: Really bad hack (tm) for NTSC support */
	if (context->ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
		c->time_base.den = 2997;
		c->time_base.num = 100;
	}
	else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) {
		c->time_base.den = rd->frs_sec;
		c->time_base.num = (int) rd->frs_sec_base;
	}
	else {
		c->time_base.den = rd->frs_sec * 100000;
		c->time_base.num = ((double) rd->frs_sec_base) * 100000;
	}
	
	c->gop_size = context->ffmpeg_gop_size;
	c->bit_rate = context->ffmpeg_video_bitrate * 1000;
	c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
	c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
	c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;

#if 0
	/* this options are not set in ffmpeg.c and leads to artifacts with MPEG-4
	 * see #33586: Encoding to mpeg4 makes first frame(s) blocky
	 */
	c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
	c->rc_buffer_aggressivity = 1.0;
#endif

	c->me_method = ME_EPZS;
	
	codec = avcodec_find_encoder(c->codec_id);
	if (!codec)
		return NULL;
	
	/* Be sure to use the correct pixel format(e.g. RGB, YUV) */

	if (codec->pix_fmts) {
		c->pix_fmt = codec->pix_fmts[0];
	}
	else {
		/* makes HuffYUV happy ... */
		c->pix_fmt = PIX_FMT_YUV422P;
	}

	if (context->ffmpeg_type == FFMPEG_XVID) {
		/* arghhhh ... */
		c->pix_fmt = PIX_FMT_YUV420P;
		c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
	}

	if (codec_id == AV_CODEC_ID_H264) {
		/* correct wrong default ffmpeg param which crash x264 */
		c->qmin = 10;
		c->qmax = 51;
	}
	
	/* Keep lossless encodes in the RGB domain. */
	if (codec_id == AV_CODEC_ID_HUFFYUV) {
		if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
			c->pix_fmt = PIX_FMT_BGRA;
		}
		else {
			c->pix_fmt = PIX_FMT_RGB32;
		}
	}

	if (codec_id == AV_CODEC_ID_FFV1) {
		c->pix_fmt = PIX_FMT_RGB32;
	}

	if (codec_id == AV_CODEC_ID_QTRLE) {
		if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
			c->pix_fmt = PIX_FMT_ARGB;
		}
	}

	if (codec_id == AV_CODEC_ID_PNG) {
		if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
			c->pix_fmt = PIX_FMT_RGBA;
		}
	}

	if ((of->oformat->flags & AVFMT_GLOBALHEADER)
#if 0
	    || STREQ(of->oformat->name, "mp4")
	    || STREQ(of->oformat->name, "mov")
	    || STREQ(of->oformat->name, "3gp")
#endif
	    )
	{
		PRINT("Using global header\n");
		c->flags |= CODEC_FLAG_GLOBAL_HEADER;
	}
	
	/* Determine whether we are encoding interlaced material or not */
	if (rd->mode & R_FIELDS) {
		PRINT("Encoding interlaced video\n");
		c->flags |= CODEC_FLAG_INTERLACED_DCT;
		c->flags |= CODEC_FLAG_INTERLACED_ME;
	}

	/* xasp & yasp got float lately... */

	st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);

	set_ffmpeg_properties(rd, c, "video", &opts);

	if (avcodec_open2(c, codec, &opts) < 0) {
		BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
		av_dict_free(&opts);
		return NULL;
	}
	av_dict_free(&opts);

	context->current_frame = alloc_picture(c->pix_fmt, c->width, c->height);

	context->img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
	                                 NULL, NULL, NULL);
	return st;
}
Beispiel #27
0
static virSecretDefPtr
secretXMLParseNode(xmlDocPtr xml, xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virSecretDefPtr def = NULL, ret = NULL;
    char *prop = NULL;
    char *uuidstr = NULL;

    if (!virXMLNodeNameEqual(root, "secret")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <secret>"),
                       root->name);
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError();
        goto cleanup;
    }
    ctxt->node = root;

    if (VIR_ALLOC(def) < 0)
        goto cleanup;

    prop = virXPathString("string(./@ephemeral)", ctxt);
    if (prop != NULL) {
        if (STREQ(prop, "yes")) {
            def->isephemeral = true;
        } else if (STREQ(prop, "no")) {
            def->isephemeral = false;
        } else {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid value of 'ephemeral'"));
            goto cleanup;
        }
        VIR_FREE(prop);
    }

    prop = virXPathString("string(./@private)", ctxt);
    if (prop != NULL) {
        if (STREQ(prop, "yes")) {
            def->isprivate = true;
        } else if (STREQ(prop, "no")) {
            def->isprivate = false;
        } else {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid value of 'private'"));
            goto cleanup;
        }
        VIR_FREE(prop);
    }

    uuidstr = virXPathString("string(./uuid)", ctxt);
    if (!uuidstr) {
        if (virUUIDGenerate(def->uuid)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to generate UUID"));
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuidstr, def->uuid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("malformed uuid element"));
            goto cleanup;
        }
        VIR_FREE(uuidstr);
    }

    def->description = virXPathString("string(./description)", ctxt);
    if (virXPathNode("./usage", ctxt) != NULL
        && virSecretDefParseUsage(ctxt, def) < 0)
        goto cleanup;
    ret = def;
    def = NULL;

 cleanup:
    VIR_FREE(prop);
    VIR_FREE(uuidstr);
    virSecretDefFree(def);
    xmlXPathFreeContext(ctxt);
    return ret;
}
Beispiel #28
0
/*
 * Mount a sub-mount
 */
static int
amfs_auto_mount(am_node *mp, mntfs *mf)
{
  /*
   * Pseudo-directories are used to provide some structure
   * to the automounted directories instead
   * of putting them all in the top-level automount directory.
   *
   * Here, just increment the parent's link count.
   */
  mp->am_parent->am_fattr.na_nlink++;

  /*
   * Info field of . means use parent's info field.
   * Historical - not documented.
   */
  if (mf->mf_info[0] == '.' && mf->mf_info[1] == '\0')
    mf->mf_info = strealloc(mf->mf_info, mp->am_parent->am_mnt->mf_info);

  /*
   * Compute prefix:
   *
   * If there is an option prefix then use that else
   * If the parent had a prefix then use that with name
   *      of this node appended else
   * Use the name of this node.
   *
   * That means if you want no prefix you must say so
   * in the map.
   */
  if (mf->mf_fo->opt_pref) {
    /* allow pref:=null to set a real null prefix */
    if (STREQ(mf->mf_fo->opt_pref, "null")) {
      mp->am_pref = strdup("");
    } else {
      /*
       * the prefix specified as an option
       */
      mp->am_pref = strdup(mf->mf_fo->opt_pref);
    }
  } else {
    /*
     * else the parent's prefix
     * followed by the name
     * followed by /
     */
    char *ppref = mp->am_parent->am_pref;
    if (ppref == 0)
      ppref = "";
    mp->am_pref = str3cat((char *) 0, ppref, mp->am_name, "/");
  }

#ifdef HAVE_FS_AUTOFS
  if (mf->mf_flags & MFF_IS_AUTOFS) {
    char opts[SIZEOF_OPTS];
    int error;

    autofs_get_opts(opts, sizeof(opts), mp->am_autofs_fh);

    /* now do the mount */
    error = amfs_mount(mp, mf, opts);
    if (error) {
      errno = error;
      plog(XLOG_FATAL, "amfs_auto_mount: amfs_mount failed: %m");
      return error;
    }
  }
#endif /* HAVE_FS_AUTOFS */

  /*
   * Attach a map cache
   */
  amfs_mkcacheref(mf);

  return 0;
}
Beispiel #29
0
static char*
virBhyveTapGetRealDeviceName(char *name)
{
    /* This is an ugly hack, because if we rename
     * tap device to vnet%d, its device name will be
     * still /dev/tap%d, and bhyve tries to open /dev/tap%d,
     * so we have to find the real name
     */
    char *ret = NULL;
    struct dirent *dp;
    char *devpath = NULL;
    int fd;

    DIR *dirp = opendir("/dev");
    if (dirp == NULL) {
        virReportSystemError(errno,
                             _("Failed to opendir path '%s'"),
                             "/dev");
        return NULL;
    }

    while ((dp = readdir(dirp)) != NULL) {
        if (STRPREFIX(dp->d_name, "tap")) {
            struct ifreq ifr;
            if (virAsprintf(&devpath, "/dev/%s", dp->d_name) < 0) {
                goto cleanup;
            }
            if ((fd = open(devpath, O_RDWR)) < 0) {
                virReportSystemError(errno, _("Unable to open '%s'"), devpath);
                goto cleanup;
            }

            if (ioctl(fd, TAPGIFNAME, (void *)&ifr) < 0) {
                virReportSystemError(errno, "%s",
                                     _("Unable to query tap interface name"));
                goto cleanup;
            }

            if (STREQ(name, ifr.ifr_name)) {
                /* we can ignore the return value
                 * because we still have nothing
                 * to do but return;
                 */
                ignore_value(VIR_STRDUP(ret, dp->d_name));
                goto cleanup;
            }

            VIR_FREE(devpath);
            VIR_FORCE_CLOSE(fd);
        }

        errno = 0;
    }

    if (errno != 0)
        virReportSystemError(errno, "%s",
                             _("Unable to iterate over TAP devices"));

cleanup:
    VIR_FREE(devpath);
    VIR_FORCE_CLOSE(fd);
    closedir(dirp);
    return ret;
}
Beispiel #30
0
const char *
virNWFilterVarCombIterGetVarValue(virNWFilterVarCombIterPtr ci,
                                  const virNWFilterVarAccess *vap)
{
    size_t i;
    unsigned int iterId;
    bool found = false;
    const char *res = NULL;
    virNWFilterVarValuePtr value;
    int iterIndex = -1;
    const char *varName = virNWFilterVarAccessGetVarName(vap);

    switch (virNWFilterVarAccessGetType(vap)) {
    case VIR_NWFILTER_VAR_ACCESS_ITERATOR:
        iterId = virNWFilterVarAccessGetIterId(vap);
        iterIndex = virNWFilterVarCombIterGetIndexByIterId(ci, iterId);
        if (iterIndex < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get iterator index for "
                             "iterator ID %u"), iterId);
            return NULL;
        }
        break;
    case VIR_NWFILTER_VAR_ACCESS_ELEMENT:
        iterId = virNWFilterVarAccessGetIntIterId(vap);
        iterIndex = virNWFilterVarCombIterGetIndexByIterId(ci, iterId);
        if (iterIndex < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not get iterator index for "
                             "(internal) iterator ID %u"), iterId);
            return NULL;
        }
        break;
    case VIR_NWFILTER_VAR_ACCESS_LAST:
        return NULL;
    }

    for (i = 0; i < ci->iter[iterIndex].nVarNames; i++) {
        if (STREQ(ci->iter[iterIndex].varNames[i], varName)) {
            found = true;
            break;
        }
    }

    if (!found) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find variable '%s' in iterator"),
                       varName);
        return NULL;
    }

    value = virHashLookup(ci->hashTable->hashTable, varName);
    if (!value) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find value for variable '%s'"),
                       varName);
        return NULL;
    }

    res = virNWFilterVarValueGetNthValue(value, ci->iter[iterIndex].curValue);
    if (!res) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get nth (%u) value of "
                         "variable '%s'"),
                       ci->iter[iterIndex].curValue, varName);
        return NULL;
    }

    return res;
}