Exemplo n.º 1
0
/*
 * Builds the spec file
 * @param [Number] flags bits to enable stages of build
 * @param [Boolean] test When true, don't execute scripts or package
 * @return [Number] exit code
 *
 * @example
 *   spec = RPM::Spec.open("foo.spec")
 *   spec.build(RPM::BUILD__UNTIL_BUILD)
 */
VALUE
rpm_spec_build(int argc, VALUE* argv, VALUE spec)
{
	int flags, test;
	rpmRC rc;

	switch (argc) {
	case 0:
		rb_raise(rb_eArgError, "argument too few(1..2)");

	case 1:
		flags = NUM2INT(argv[0]);
		test = 0;
		break;

	case 2:
		flags = NUM2INT(argv[0]);
		test = RTEST(argv[1]);
		break;

	default:
		rb_raise(rb_eArgError, "argument too many(0..1)");
	}

#if RPM_VERSION_CODE < RPM_VERSION(4,1,0)
	rc = buildSpec(RPM_SPEC(spec), flags,test);
#else
	rpmts ts = NULL;
	ts = rpmtsCreate();
	rc = buildSpec(ts, RPM_SPEC(spec), flags,test);
	ts_free(ts);
#endif

	return INT2NUM(rc);
}
Exemplo n.º 2
0
static rpmRC inst(const char *fn)
{
    rpmRC rc = RPMRC_FAIL;
    rpmts ts = rpmtsCreate();
    FD_t fd = Fopen(fn, "r");
    Header h = NULL;
    int upgrade = 1;
    rpmRelocation relocs = NULL;
    rpmps ps = NULL;
    rpmprobFilterFlags probFilter = 0;

assert(ts);
    (void) rpmtsSetNotifyCallback(ts, rpmShowProgress,  (void *) ((long)0));
    if (fd == NULL || Ferror(fd))
	goto exit;
     (void) rpmReadPackageFile(ts, fd, fn, &h);

    if ((rc = rpmtsAddInstallElement(ts, h, fn, upgrade, relocs)) != 0
     || (rc = rpmcliInstallCheck(ts)) != 0
     || (rc = rpmcliInstallOrder(ts)) != 0
     || (rc = rpmcliInstallRun(ts, ps, probFilter)) != 0)
	goto exit;

exit:
    h = headerFree(h);
    if (fd) (void) Fclose(fd);
    fd = NULL;
    ts = rpmtsFree(ts);
    if (rc)
fprintf(stderr, "<== %s(%s) rc %d\n", __FUNCTION__, fn, rc);
    return rc;
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
    int rc;
    
    xsetprogname(argv[0]);	/* Portability call -- see system.h */
    rpmReadConfigFiles(NULL, NULL);
    char * filename;
    if (argc == 1)
	filename = "-";
    else {
	if (rstreq(argv[1], "-h") || rstreq(argv[1], "--help")) {
	    fprintf(stderr, "Usage: rpm2archive file.rpm\n");
	    exit(EXIT_FAILURE);
	} else {
	    filename = argv[1];
	}
    }

    rpmts ts = rpmtsCreate();
    rpmVSFlags vsflags = 0;

    /* XXX retain the ageless behavior of rpm2cpio */
    vsflags |= _RPMVSF_NODIGESTS;
    vsflags |= _RPMVSF_NOSIGNATURES;
    vsflags |= RPMVSF_NOHDRCHK;
    (void) rpmtsSetVSFlags(ts, vsflags);

    rc = process_package(ts, filename);

    ts = rpmtsFree(ts);

    return rc;
}
Exemplo n.º 4
0
Arquivo: rpm.c Projeto: wlindauer/abrt
static int rpm_query_file(rpmts *ts, rpmdbMatchIterator *iter, Header *header,
        const char *filename, const char *rootdir_or_NULL)
{
    const char *queryname = filename;

    *ts = rpmtsCreate();
    if (rootdir_or_NULL)
    {
        if (rpmtsSetRootDir(*ts, rootdir_or_NULL) != 0)
        {
            rpmtsFree(*ts);
            return -1;
        }

        unsigned len = strlen(rootdir_or_NULL);
        /* remove 'chroot' prefix */
        if (strncmp(filename, rootdir_or_NULL, len) == 0 && filename[len] == '/')
            queryname += len;
    }

    *iter = rpmtsInitIterator(*ts, RPMTAG_BASENAMES, queryname, 0);
    *header = rpmdbNextIterator(*iter);

    if (!(*header) && rootdir_or_NULL)
    {
        rpmdbFreeIterator(*iter);
        rpmtsFree(*ts);

        return rpm_query_file(ts, iter, header, filename, NULL);
    }

    return 0;
}
Exemplo n.º 5
0
static char *rpm_get_nvr_by_pkg_name(const char *pkg_name)
{
    int status = rpmReadConfigFiles((const char *) NULL, (const char *) NULL);
    if (status)
        error_msg_and_die("error reading RPM rc files");

    char *nvr = NULL;

    rpmts ts = rpmtsCreate();
    rpmdbMatchIterator iter = rpmtsInitIterator(ts, RPMTAG_NAME, pkg_name, 0);
    Header header = rpmdbNextIterator(iter);

    if (!header)
        goto error;

    const char *errmsg = NULL;
    nvr = headerFormat(header, "%{name}-%{version}-%{release}", &errmsg);

    if (!nvr && errmsg)
        error_msg("cannot get nvr. reason: %s", errmsg);

error:
    rpmdbFreeIterator(iter);
    rpmtsFree(ts);

    rpmFreeRpmrc();
    rpmFreeCrypto();
    rpmFreeMacros(NULL);

    return nvr;
}
Exemplo n.º 6
0
Arquivo: rpm.c Projeto: wlindauer/abrt
char *rpm_get_fingerprint(const char *pkg)
{
#ifdef HAVE_LIBRPM
    char *fingerprint = NULL;
    char *pgpsig = NULL;
    const char *errmsg = NULL;

    rpmts ts = rpmtsCreate();
    rpmdbMatchIterator iter = rpmtsInitIterator(ts, RPMTAG_NAME, pkg, 0);
    Header header = rpmdbNextIterator(iter);

    if (!header)
        goto error;

    pgpsig = headerFormat(header, "%|SIGGPG?{%{SIGGPG:pgpsig}}:{%{SIGPGP:pgpsig}}|", &errmsg);
    if (!pgpsig && errmsg)
    {
        log_notice("cannot get siggpg:pgpsig. reason: %s", errmsg);
        goto error;
    }

    char *pgpsig_tmp = strstr(pgpsig, " Key ID ");
    if (pgpsig_tmp)
        fingerprint = xstrdup(pgpsig_tmp + sizeof(" Key ID ") - 1);

error:
    free(pgpsig);
    rpmdbFreeIterator(iter);
    rpmtsFree(ts);
    return fingerprint;
#else
    return NULL;
#endif
}
Exemplo n.º 7
0
Arquivo: pack.c Projeto: kaltsi/rpm
/**
 * @todo Create transaction set *much* earlier.
 */
static rpmRC cpio_doio(FD_t fdo, Header h, CSA_t csa,
		const char * fmodeMacro)
{
    rpmts ts = rpmtsCreate();
    rpmfi fi = csa->cpioList;
    rpmte te = NULL;
    rpmfs fs = NULL;
    char *failedFile = NULL;
    FD_t cfd;
    rpmRC rc = RPMRC_OK;
    int xx, i;

    {	char *fmode = rpmExpand(fmodeMacro, NULL);
	if (!(fmode && fmode[0] == 'w'))
	    fmode = xstrdup("w9.gzdio");
	(void) Fflush(fdo);
	cfd = Fdopen(fdDup(Fileno(fdo)), fmode);
	fmode = _free(fmode);
    }
    if (cfd == NULL)
	return RPMRC_FAIL;

    /* make up a transaction element for passing to fsm */
    rpmtsAddInstallElement(ts, h, NULL, 0, NULL);
    te = rpmtsElement(ts, 0);
    fs = rpmteGetFileStates(te);

    fi = rpmfiInit(fi, 0);
    while ((i = rpmfiNext(fi)) >= 0) {
	if (rpmfiFFlags(fi) & RPMFILE_GHOST)
	    rpmfsSetAction(fs, i, FA_SKIP);
	else
	    rpmfsSetAction(fs, i, FA_COPYOUT);
    }

    xx = fsmSetup(rpmfiFSM(fi), FSM_PKGBUILD, ts, te, fi, cfd,
		&csa->cpioArchiveSize, &failedFile);
    if (xx)
	rc = RPMRC_FAIL;
    (void) Fclose(cfd);
    xx = fsmTeardown(rpmfiFSM(fi));
    if (rc == RPMRC_OK && xx) rc = RPMRC_FAIL;

    if (rc) {
	if (failedFile)
	    rpmlog(RPMLOG_ERR, _("create archive failed on file %s: %s\n"),
		failedFile, cpioStrerror(rc));
	else
	    rpmlog(RPMLOG_ERR, _("create archive failed: %s\n"),
		cpioStrerror(rc));
      rc = RPMRC_FAIL;
    }
    rpmtsEmpty(ts);

    failedFile = _free(failedFile);
    ts = rpmtsFree(ts);

    return rc;
}
Exemplo n.º 8
0
int main(int argc, char *argv[]) 
{
    rpmts ts = NULL;
    enum modes bigMode = MODE_INSTALL;
    struct rpmInstallArguments_s *ia = &rpmIArgs;
    poptContext optCon;
    int ec = 0;
    int ret = 0;
    char rpmFile[1][PATH_MAX];
    memset(&rpmFile,0,PATH_MAX);
    snprintf(rpmFile[0],PATH_MAX,"%s",argv[1]);
    char *p[2];
    p[0] = "";
    p[1] = (char *)&rpmFile[0];
    optCon = rpmcliInit(2, p, optionsTable);


    printf("\n argc[%d],bigmode[%s]\n",argc,bigMode == MODE_UNKNOWN?"unknow":"others");
    ia->installInterfaceFlags = INSTALL_INSTALL | INSTALL_LABEL | INSTALL_PERCENT;

    ts = rpmtsCreate();
    rpmtsSetRootDir(ts, rpmcliRootDir);

        if (!ia->incldocs) {
            if (rpmExpandNumeric("%{_excludedocs}"))
                ia->transFlags |= RPMTRANS_FLAG_NODOCS;
        }

        if (ia->noDeps) 
            ia->installInterfaceFlags |= INSTALL_NODEPS;

        if (ia->prefix) {
            ia->relocations = malloc(2 * sizeof(*ia->relocations));
            ia->relocations[0].oldPath = NULL;   /* special case magic */
            ia->relocations[0].newPath = ia->prefix;
            ia->relocations[1].oldPath = NULL;
            ia->relocations[1].newPath = NULL;
        } else if (ia->relocations) {
            ia->relocations = realloc(ia->relocations, 
                sizeof(*ia->relocations) * (ia->numRelocations + 1));
            ia->relocations[ia->numRelocations].oldPath = NULL;
            ia->relocations[ia->numRelocations].newPath = NULL;
        }

    ret= rpmInstall(ts, ia, (ARGV_t) poptGetArgs(optCon));
    printf("\n ret[%d]\n",ret);

    rpmtsFree(ts);
    ts = NULL;

    rpmcliFini(optCon);

    return 0;
}
Exemplo n.º 9
0
rpmRC
rpmReadPackageInfo(FD_t fd, Header * sigp, Header * hdrp)
{
    rpmRC rc;

    rpmts ts = rpmtsCreate();
    rc = rpmReadPackageFile(ts, fd, "readRPM", hdrp);
    ts = rpmtsFree(ts);
    
    if (sigp) *sigp = NULL;                 /* XXX HACK */

    return rc;
}
Exemplo n.º 10
0
QueryData genRpmPackages(QueryContext& context) {
  QueryData results;

  auto dropper = DropPrivileges::get();
  if (!dropper->dropTo("nobody") && isUserAdmin()) {
    LOG(WARNING) << "Cannot drop privileges for rpm_packages";
    return results;
  }

  // Isolate RPM/package inspection to the canonical: /usr/lib/rpm.
  RpmEnvironmentManager env_manager;

  // The following implementation uses http://rpm.org/api/4.11.1/
  rpmInitCrypto();
  if (rpmReadConfigFiles(nullptr, nullptr) != 0) {
    TLOG << "Cannot read RPM configuration files";
    return results;
  }

  rpmts ts = rpmtsCreate();
  rpmdbMatchIterator matches;
  if (context.constraints["name"].exists(EQUALS)) {
    auto name = (*context.constraints["name"].getAll(EQUALS).begin());
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, name.c_str(), name.size());
  } else {
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, nullptr, 0);
  }

  Header header;
  while ((header = rpmdbNextIterator(matches)) != nullptr) {
    Row r;
    rpmtd td = rpmtdNew();
    r["name"] = getRpmAttribute(header, RPMTAG_NAME, td);
    r["version"] = getRpmAttribute(header, RPMTAG_VERSION, td);
    r["release"] = getRpmAttribute(header, RPMTAG_RELEASE, td);
    r["source"] = getRpmAttribute(header, RPMTAG_SOURCERPM, td);
    r["size"] = getRpmAttribute(header, RPMTAG_SIZE, td);
    r["sha1"] = getRpmAttribute(header, RPMTAG_SHA1HEADER, td);
    r["arch"] = getRpmAttribute(header, RPMTAG_ARCH, td);

    rpmtdFree(td);
    results.push_back(r);
  }

  rpmdbFreeIterator(matches);
  rpmtsFree(ts);
  rpmFreeCrypto();
  rpmFreeRpmrc();

  return results;
}
Exemplo n.º 11
0
/* --- Object ctors/dtors */
static rpmts
rpmts_init(JSContext *cx, JSObject *obj)
{
    rpmts ts;

    if ((ts = rpmtsCreate()) == NULL)
	return NULL;
    if (!JS_SetPrivate(cx, obj, (void *)ts)) {
	/* XXX error msg */
	(void) rpmtsFree(ts);
	return NULL;
    }
    return ts;
}
Exemplo n.º 12
0
VALUE
rpm_db_transaction(int argc, VALUE* argv, VALUE db)
{
	VALUE trans;
	rpm_trans_t* ts;
	const char* root = "/";

#if 0
	if (OBJ_FROZEN(db)) {
		rb_error_frozen("RPM::DB");
	}
#endif
	switch (argc) {
	case 0:
		break;

	case 1:
		if (TYPE(argv[0]) != T_STRING) {
			rb_raise(rb_eTypeError, "illegal argument type");
		}
		root = RSTRING_PTR(argv[0]);
		break;

	default:
		rb_raise(rb_eArgError, "argument too many(0..1)");
	}

	ts = ALLOC(rpm_trans_t);
#if RPM_VERSION_CODE < RPM_VERSION(4,1,0)
	ts->ts = rpmtransCreateSet(RPM_DB(db), root);
#else
	ts->ts = rpmtsCreate();
	rpmtsSetRootDir(ts->ts, root);
#endif
	ts->script_fd = 0;
	ts->db = DATA_PTR(db);
	trans = Data_Wrap_Struct(rpm_cTransaction, NULL, transaction_free, ts);
	db_ref(ts->db);
	rb_ivar_set(trans, id_db, db);

	rb_catch("abort", transaction_yield, trans);

	if (rb_ivar_get(trans, id_aborted) == Qtrue) {
		return Qfalse;
	} else if (rb_ivar_get(trans, id_commited) != Qtrue && !OBJ_FROZEN(db)) {
		rb_catch("abort", transaction_commit, trans);
	}

	return rb_ivar_get(trans, id_pl);
}
Exemplo n.º 13
0
int 
verifyRpmPackage(char *filename) 
{
    
    int ret = 0;
    rpmts ts; //rpm transaction
    FD_t fd; //file descriptor
    char error[1024];
    QVA_t ka = malloc(sizeof(rpmQVKArgs));
    memcpy(ka, &rpmQVKArgs, sizeof(rpmQVKArgs));


    rpmcliConfigured();
    //creating query set
    rpmVerifyFlags verifyFlags =
        (VERIFY_MD5|VERIFY_DIGEST);
    verifyFlags &= ~ka->qva_flags;
    ka->qva_flags = (rpmQueryFlags) verifyFlags;

    //error is also used to pass the input file name
    //dangerous
    strcpy(error, filename);

    //trasaction set
    ts = rpmtsCreate();

    //file descriptor
    fd = Fopen(filename, "r.ufdio");
    if (fd == NULL) {
	logmsg("verifyRpmPackage:Error opening file %s\n", filename);
	free(ka);
	return -1;
    }
    ret = rpmVerifySignatures(ka, ts, fd, error);
    if (ret != 0) {
        //package is corrupted
        logmsg("verifyRpmPackage:Package corrupted %s\n", error);
	ts = rpmtsFree(ts);
	Fclose(fd);
	free(ka);
	return -1;
    }
    //package is correct return 0
    ts = rpmtsFree(ts);
    Fclose(fd);
    free(ka);
    return 0;

}
Exemplo n.º 14
0
/*************************************************************************
* FUNCTION      :   RPMTransaction_Set::Create                           *
* ARGUMENTS     :   interp, name                                         *
* RETURNS       :   object created or 0 if error                         *
* EXCEPTIONS    :   none                                                 *
* PURPOSE       :   Set up an empty transaction list                     *
*************************************************************************/
RPMTransaction_Set *RPMTransaction_Set::Create(Tcl_Interp *interp,const char *name)
{
    if (RPMTransaction_Set::Cmd_exists(interp,name))
    {
        RPM_for_TCL::Error(interp, "\"%s\" command already exists",name);
        return 0;
    }
    rpmts ts = rpmtsCreate();
    if (!ts)
    {
        RPM_for_TCL::Error(interp, "cannot create RPM transaction: %s",rpmErrorString());
        return 0;
    }

    return new RPMTransaction_Set(interp,name,ts);
}
Exemplo n.º 15
0
Arquivo: tssl.c Projeto: avokhmin/RPM5
int
main(int argc, char *argv[])
{
    poptContext optCon = rpmcliInit(argc, argv, optionsTable);
    rpmts ts = rpmtsCreate();
    int rc = rpmtsOpenDB(ts, O_RDONLY);

fprintf(stderr, " DSA");
    rc = doit(ts, "DSA");
fprintf(stderr, " RSA");
    rc = doit(ts, "RSA");
fprintf(stderr, "\n");

    (void) rpmtsFree(ts); 
    ts = NULL;

    optCon = rpmcliFini(optCon);

    return rc;
}
Exemplo n.º 16
0
QueryData genRpmPackages(QueryContext& context) {
  QueryData results;
  // The following implementation uses http://rpm.org/api/4.11.1/
  rpmInitCrypto();
  if (rpmReadConfigFiles(nullptr, nullptr) != 0) {
    TLOG << "Cannot read RPM configuration files.";
    return results;
  }

  rpmts ts = rpmtsCreate();
  rpmdbMatchIterator matches;
  if (context.constraints["name"].exists()) {
    auto name = (*context.constraints["name"].getAll(EQUALS).begin());
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, name.c_str(), name.size());
  } else {
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, nullptr, 0);
  }

  Header header;
  while ((header = rpmdbNextIterator(matches)) != nullptr) {
    Row r;
    rpmtd td = rpmtdNew();
    r["name"] = getRpmAttribute(header, RPMTAG_NAME, td);
    r["version"] = getRpmAttribute(header, RPMTAG_VERSION, td);
    r["release"] = getRpmAttribute(header, RPMTAG_RELEASE, td);
    r["source"] = getRpmAttribute(header, RPMTAG_SOURCERPM, td);
    r["size"] = getRpmAttribute(header, RPMTAG_SIZE, td);
    r["sha1"] = getRpmAttribute(header, RPMTAG_SHA1HEADER, td);
    r["arch"] = getRpmAttribute(header, RPMTAG_ARCH, td);

    rpmtdFree(td);
    results.push_back(r);
  }

  rpmdbFreeIterator(matches);
  rpmtsFree(ts);
  rpmFreeCrypto();
  rpmFreeRpmrc();

  return results;
}
Exemplo n.º 17
0
void *probe_init (void)
{
#ifdef RPM46_FOUND
	rpmlogSetCallback(rpmErrorCb, NULL);
#endif
        if (rpmReadConfigFiles ((const char *)NULL, (const char *)NULL) != 0) {
                dI("rpmReadConfigFiles failed: %u, %s.", errno, strerror (errno));
                return (NULL);
        }

        g_rpm.rpmts = rpmtsCreate();

        pthread_mutex_init(&(g_rpm.mutex), NULL);

	if (OSCAP_GSYM(offline_mode) & PROBE_OFFLINE_OWN) {
		const char* root = getenv("OSCAP_PROBE_ROOT");
		rpmtsSetRootDir(g_rpm.rpmts, root);
	}

        return ((void *)&g_rpm);
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    int ec = EXIT_FAILURE;
    poptContext optCon = rpmcliInit(argc, argv, optionsTable);
    rpmts ts = rpmtsCreate();
    ARGV_const_t args = NULL;
    
    if (argc < 2) {
	printUsage(optCon, stderr, 0);
	goto exit;
    }

    args = (ARGV_const_t) poptGetArgs(optCon);

    if (mode != MODE_LISTKEY && args == NULL)
	argerror(_("no arguments given"));

    rpmtsSetRootDir(ts, rpmcliRootDir);

    switch (mode) {
    case MODE_CHECKSIG:
	ec = rpmcliVerifySignatures(ts, args);
	break;
    case MODE_IMPORTKEY:
	ec = rpmcliImportPubkeys(ts, args);
	break;
    /* XXX TODO: actually implement these... */
    case MODE_DELKEY:
    case MODE_LISTKEY:
	break;
    default:
	argerror(_("only one major mode may be specified"));
    }

exit:
    rpmtsFree(ts);
    rpmcliFini(optCon);
    return ec;
}
Exemplo n.º 19
0
string_list *
rpm_file_list(const char * pkg)
{
  rpmReadConfigFiles(NULL, NULL);
  FD_t fd = Fopen(pkg, "r.ufdio");

  rpmts ts = rpmtsCreate();
  Header h;
  rpmReadPackageFile(ts, fd, NULL, &h);
  rpmtsFree(ts);

  string_list * sl = string_list_new();
  rpmfi fi = rpmfiNew(NULL, h, RPMTAG_BASENAMES, RPMFI_KEEPHEADER);

  if (fi) {
    while (rpmfiNext(fi) != -1) {
      string_list_append(sl, rpmfiFN(fi));
    }
    fi = rpmfiFree(fi);
  }

  return sl;
}
Exemplo n.º 20
0
void
Init_HR_SWInst(void)
{
    SWI_t          *swi = &_myswi;      /* XXX static for now */
    swi->swi_index = 0;

#ifdef HAVE_LIBRPM
    if (swi->swi_rpmts != NULL)
        return;
    swi->swi_rpmts = rpmtsCreate();
    rpmtsSetVSFlags( swi->swi_rpmts, (_RPMVSF_NOSIGNATURES|_RPMVSF_NODIGESTS));
    Check_HRSW_cache(swi);
#else
    if (swi->swi_directory != NULL) {
        if (swi->swi_dp != NULL) {
            closedir(swi->swi_dp);
            swi->swi_dp = NULL;
        }
        if ((swi->swi_dp = opendir(swi->swi_directory)) == NULL)
            swi->swi_index = -1;
    } else
        swi->swi_index = -1;
#endif
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    FD_t fdi, fdo;
    Header h;
    char * rpmio_flags = NULL;
    rpmRC rc;
    FD_t gzdi;
    
    setprogname(argv[0]);	/* Retrofit glibc __progname */
    rpmReadConfigFiles(NULL, NULL);
    if (argc == 1)
	fdi = fdDup(STDIN_FILENO);
    else {
	if (rstreq(argv[1], "-h") || rstreq(argv[1], "--help")) {
	    fprintf(stderr, "Usage: rpm2cpio file.rpm\n");
	    exit(EXIT_FAILURE);
	}
	fdi = Fopen(argv[1], "r.ufdio");
    }

    if (Ferror(fdi)) {
	fprintf(stderr, "%s: %s: %s\n", argv[0],
		(argc == 1 ? "<stdin>" : argv[1]), Fstrerror(fdi));
	exit(EXIT_FAILURE);
    }
    fdo = fdDup(STDOUT_FILENO);

    {	rpmts ts = rpmtsCreate();
	rpmVSFlags vsflags = 0;

	/* XXX retain the ageless behavior of rpm2cpio */
        vsflags |= _RPMVSF_NODIGESTS;
        vsflags |= _RPMVSF_NOSIGNATURES;
        vsflags |= RPMVSF_NOHDRCHK;
	(void) rpmtsSetVSFlags(ts, vsflags);

	rc = rpmReadPackageFile(ts, fdi, "rpm2cpio", &h);

	ts = rpmtsFree(ts);
    }

    switch (rc) {
    case RPMRC_OK:
    case RPMRC_NOKEY:
    case RPMRC_NOTTRUSTED:
	break;
    case RPMRC_NOTFOUND:
	fprintf(stderr, _("argument is not an RPM package\n"));
	exit(EXIT_FAILURE);
	break;
    case RPMRC_FAIL:
    default:
	fprintf(stderr, _("error reading header from package\n"));
	exit(EXIT_FAILURE);
	break;
    }

    /* Retrieve type of payload compression. */
    {	const char *compr = headerGetString(h, RPMTAG_PAYLOADCOMPRESSOR);
	rpmio_flags = rstrscat(NULL, "r.", compr ? compr : "gzip", NULL);
    }

    gzdi = Fdopen(fdi, rpmio_flags);	/* XXX gzdi == fdi */
    free(rpmio_flags);

    if (gzdi == NULL) {
	fprintf(stderr, _("cannot re-open payload: %s\n"), Fstrerror(gzdi));
	exit(EXIT_FAILURE);
    }

    rc = ufdCopy(gzdi, fdo);
    rc = (rc <= 0) ? EXIT_FAILURE : EXIT_SUCCESS;
    Fclose(fdo);

    Fclose(gzdi);	/* XXX gzdi == fdi */

    return rc;
}
Exemplo n.º 22
0
uint32_t
VerifyRpmSig(
    rpmKeyring pKeyring,
    const char* pszPkgFile
    )
{
    uint32_t dwError = 0;
    FD_t pFD_t = NULL;
    rpmts pTS = NULL;
    rpmtd pTD = NULL;
    Header pPkgHeader = NULL;
    pgpDig pDigest = NULL;


    if(!pKeyring || IsNullOrEmptyString(pszPkgFile))
    {
        dwError = ERROR_TDNF_INVALID_PARAMETER;
        BAIL_ON_TDNF_ERROR(dwError);
    }

    pFD_t = Fopen(pszPkgFile, "r.fdio");
    if(!pFD_t)
    {
        dwError = errno;
        BAIL_ON_TDNF_SYSTEM_ERROR(dwError);
    }

    pTS = rpmtsCreate();
    if(!pTS)
    {
        dwError = ERROR_TDNF_RPMTS_CREATE_FAILED;
        BAIL_ON_TDNF_RPM_ERROR(dwError);
    }
    rpmtsSetVSFlags (pTS, _RPMVSF_NOSIGNATURES);

    pTD = rpmtdNew();
    if(!pTD)
    {
        dwError = ERROR_TDNF_RPMTD_CREATE_FAILED;
        BAIL_ON_TDNF_RPM_ERROR(dwError);
    }

    dwError = rpmReadPackageFile(pTS, pFD_t, pszPkgFile, &pPkgHeader);
    BAIL_ON_TDNF_RPM_ERROR(dwError);

    if(!headerConvert(pPkgHeader, HEADERCONV_RETROFIT_V3))
    {
        dwError = ERROR_TDNF_RPM_HEADER_CONVERT_FAILED; 
        BAIL_ON_TDNF_RPM_ERROR(dwError);
    }

    if(!headerGet(pPkgHeader, RPMTAG_RSAHEADER, pTD, HEADERGET_MINMEM))
    {
        dwError = ERROR_TDNF_RPM_GET_RSAHEADER_FAILED;
        BAIL_ON_TDNF_ERROR(dwError);
    }

    pDigest = pgpNewDig();
    if(pgpPrtPkts(pTD->data, pTD->count, pDigest, 0))
    {
        dwError = ERROR_TDNF_RPM_GPG_PARSE_FAILED;
        BAIL_ON_TDNF_ERROR(dwError);
    }

    if(rpmKeyringLookup(pKeyring, pDigest) != RPMRC_OK)
    {
        dwError = ERROR_TDNF_RPM_GPG_NO_MATCH;
        BAIL_ON_TDNF_ERROR(dwError);
    }

cleanup:
    if(pFD_t)
    {
        Fclose(pFD_t);
    }
    if(pDigest)
    {
        pgpFreeDig(pDigest);
    }
    if(pPkgHeader)
    {
        headerFree(pPkgHeader);
    }
    if(pTD)
    {
        rpmtdFree(pTD);
    }
    if(pTS)
    {
        rpmtsFree(pTS);
    }
    return dwError;

error:
    goto cleanup;
}
Exemplo n.º 23
0
/* ---------------------------------------------------------------------
 */
int
netsnmp_swinst_arch_load( netsnmp_container *container, u_int flags)
{
    rpmts                 ts;

    rpmdbMatchIterator    mi;
    Header                h;
    char                 *n, *v, *r, *g;
    int32_t              *t;
    time_t                install_time;
    size_t                date_len;
    int                   i = 1;
    netsnmp_swinst_entry *entry;

    ts = rpmtsCreate();
    rpmtsSetVSFlags( ts, (_RPMVSF_NOSIGNATURES|_RPMVSF_NODIGESTS));

    mi = rpmtsInitIterator( ts, RPMDBI_PACKAGES, NULL, 0);
    if (mi == NULL)
	NETSNMP_LOGONCE((LOG_ERR, "rpmdbOpen() failed\n"));

    while (NULL != (h = rpmdbNextIterator( mi )))
    {
        const u_char *dt;
        entry = netsnmp_swinst_entry_create( i++ );
        if (NULL == entry)
            continue;   /* error already logged by function */
        CONTAINER_INSERT(container, entry);

        h = headerLink( h );
        headerGetEntry( h, RPMTAG_NAME,        NULL, (void**)&n, NULL);
        headerGetEntry( h, RPMTAG_VERSION,     NULL, (void**)&v, NULL);
        headerGetEntry( h, RPMTAG_RELEASE,     NULL, (void**)&r, NULL);
        headerGetEntry( h, RPMTAG_GROUP,       NULL, (void**)&g, NULL);
        headerGetEntry( h, RPMTAG_INSTALLTIME, NULL, (void**)&t, NULL);

        entry->swName_len = snprintf( entry->swName, sizeof(entry->swName),
                                      "%s-%s-%s", n, v, r);
        if (entry->swName_len > sizeof(entry->swName))
            entry->swName_len = sizeof(entry->swName);
        entry->swType = (NULL != strstr( g, "System Environment"))
                        ? 2      /* operatingSystem */
                        : 4;     /*  application    */

        install_time = *t;
        dt = date_n_time( &install_time, &date_len );
        if (date_len != 8 && date_len != 11) {
            snmp_log(LOG_ERR, "Bogus length from date_n_time for %s", entry->swName);
            entry->swDate_len = 0;
        }
        else {
            entry->swDate_len = date_len;
            memcpy(entry->swDate, dt, entry->swDate_len);
        }

        headerFree( h );
    }
    rpmdbFreeIterator( mi );
    rpmtsFree( ts );

    DEBUGMSGTL(("swinst:load:arch", "loaded %d entries\n",
                (int)CONTAINER_SIZE(container)));

    return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[]) 
{
    rpmts ts = NULL;
    struct rpmInstallArguments_s *ia = &rpmIArgs;
    poptContext optCon = NULL;
    int ec = 0;
    int ret = 0;
    char **arg = NULL;
    
    arg = malloc(sizeof(char *) * argc);
    memset(arg, 0, sizeof(char *) * argc);
    for (int i = 0; i < argc; i++) {
        arg[i] = malloc(sizeof(char) * PATH_MAX);
        memset(arg[i], 0, sizeof(char) * PATH_MAX);
        snprintf(arg[i], strlen(arg[i]) - 1, argv[i]);
    }
    optCon = rpmcliInit(argc, arg, optionsTable);

    ia->installInterfaceFlags = INSTALL_INSTALL | INSTALL_LABEL | INSTALL_PERCENT;

    ts = rpmtsCreate();
    rpmtsSetRootDir(ts, rpmcliRootDir);

    if (!ia->incldocs) {
        if (rpmExpandNumeric("%{_excludedocs}"))
            ia->transFlags |= RPMTRANS_FLAG_NODOCS;
    }

    if (ia->noDeps) 
        ia->installInterfaceFlags |= INSTALL_NODEPS;

    if (ia->prefix) {
        ia->relocations = malloc(2 * sizeof(*ia->relocations));
        ia->relocations[0].oldPath = NULL;   /* special case magic */
        ia->relocations[0].newPath = ia->prefix;
        ia->relocations[1].oldPath = NULL;
        ia->relocations[1].newPath = NULL;
    } else if (ia->relocations) {
        ia->relocations = realloc(ia->relocations, 
                          sizeof(*ia->relocations) * (ia->numRelocations + 1));
        ia->relocations[ia->numRelocations].oldPath = NULL;
        ia->relocations[ia->numRelocations].newPath = NULL;
    }

    rpmInstallISoftApp(ts, ia, (ARGV_t) poptGetArgs(optCon), NULL);

    rpmtsFree(ts);
    ts = NULL;

    rpmcliFini(optCon);
    optCon = NULL;

    if (arg) {
        for (int i = 0; i < argc; i++) {
            if (arg[i]) {
                free(arg[i]);
                arg[i] = NULL;
            }
        }
        free(arg);
        arg = NULL;
    }

    return 0;
}
Exemplo n.º 25
0
static void integrity_check(const char *progname, enum modes progmode_num)
{
    rpmts ts = NULL;
    rpmlua lua = NULL;
    char *spec_fn = NULL;
    char *proc_fn = NULL;
    char *pkey_fn = NULL;
    char *spec = NULL;
    char *proc = NULL;
    rpmiob spec_iob = NULL;
    rpmiob proc_iob = NULL;
    const char *result = NULL;
    const char *error = NULL;
    int xx;
    const char *progmode;
    int rc = INTEGRITY_ERROR;

    /* determine paths of integrity checking related files */
    spec_fn = rpmExpand("%{?_integrity_spec_cfg}%{!?_integrity_spec_cfg:scripts/integrity.cfg}", NULL);
    if (spec_fn == NULL || spec_fn[0] == '\0') {
        integrity_check_message("ERROR: Integrity Configuration Specification file not configured.\n"
            "rpm: HINT: macro %%{_integrity_spec_cfg} not configured correctly.\n");
        goto failure;
    }
    proc_fn = rpmExpand("%{?_integrity_proc_lua}%{!?_integrity_proc_lua:scripts/integrity.lua}", NULL);
    if (proc_fn == NULL || proc_fn[0] == '\0') {
        integrity_check_message("ERROR: Integrity Validation Processor file not configured.\n"
            "rpm: HINT: macro %%{_integrity_proc_lua} not configured correctly.\n");
        goto failure;
    }
    pkey_fn = rpmExpand("%{?_integrity_pkey_pgp}%{!?_integrity_pkey_pgp:scripts/integrity.pgp}", NULL);
    if (pkey_fn == NULL || pkey_fn[0] == '\0') {
        integrity_check_message("ERROR: Integrity Autority Public-Key file not configured.\n"
            "rpm: HINT: macro %%{_integrity_pkey_pgp} not configured correctly.\n");
        goto failure;
    }

    /* create RPM transaction environment and open RPM database */
    ts = rpmtsCreate();
    (void)rpmtsOpenDB(ts, O_RDONLY);

    /* check signature on integrity configuration specification file */
    if (rpmnsProbeSignature(ts, spec_fn, NULL, pkey_fn, RPM_INTEGRITY_FP, 0) != RPMRC_OK) {
        integrity_check_message("ERROR: Integrity Configuration Specification file contains invalid signature.\n"
            "rpm: HINT: Check file \"%s\".\n", spec_fn);
        goto failure;
    }

    /* check signature on integrity validation processor file */
    if (rpmnsProbeSignature(ts, proc_fn, NULL, pkey_fn, RPM_INTEGRITY_FP, 0) != RPMRC_OK) {
        integrity_check_message("ERROR: Integrity Validation Processor file contains invalid signature.\n"
            "rpm: HINT: Check file \"%s\".\n", proc_fn);
        goto failure;
    }

    /* load integrity configuration specification file */
    xx = rpmiobSlurp(spec_fn, &spec_iob);
    if (!(xx == 0 && spec_iob != NULL)) {
        integrity_check_message("ERROR: Unable to load Integrity Configuration Specification file.\n"
            "rpm: HINT: Check file \"%s\".\n", spec_fn);
        goto failure;
    }
    spec = rpmiobStr(spec_iob);

    /* load integrity validation processor file */
    xx = rpmiobSlurp(proc_fn, &proc_iob);
    if (!(xx == 0 && proc_iob != NULL)) {
        integrity_check_message("ERROR: Unable to load Integrity Validation Processor file.\n"
            "rpm: HINT: Check file \"%s\".\n", proc_fn);
        goto failure;
    }
    proc = rpmiobStr(proc_iob);

    /* provision program name and mode */
    if (progname == NULL || progname[0] == '\0')
        progname = "rpm";
    switch (progmode_num) {
        case MODE_QUERY:     progmode = "query";     break;
        case MODE_VERIFY:    progmode = "verify";    break;
        case MODE_CHECKSIG:  progmode = "checksig";  break;
        case MODE_RESIGN:    progmode = "resign";    break;
        case MODE_INSTALL:   progmode = "install";   break;
        case MODE_ERASE:     progmode = "erase";     break;
        case MODE_BUILD:     progmode = "build";     break;
        case MODE_REBUILD:   progmode = "rebuild";   break;
        case MODE_RECOMPILE: progmode = "recompile"; break;
        case MODE_TARBUILD:  progmode = "tarbuild";  break;
        case MODE_REBUILDDB: progmode = "rebuilddb"; break;
        case MODE_UNKNOWN:   progmode = "unknown";   break;
        default:             progmode = "unknown";   break;
    }

    /* execute Integrity Validation Processor via Lua glue code */
    lua = rpmluaNew();
    rpmluaSetPrintBuffer(lua, 1);
    rpmluaextActivate(lua);
    lua_getfield(lua->L, LUA_GLOBALSINDEX, "integrity");
    lua_getfield(lua->L, -1, "processor");
    lua_remove(lua->L, -2);
    lua_pushstring(lua->L, progname);
    lua_pushstring(lua->L, progmode);
    lua_pushstring(lua->L, spec_fn);
    lua_pushstring(lua->L, spec);
    lua_pushstring(lua->L, proc_fn);
    lua_pushstring(lua->L, proc);
#ifdef RPM_INTEGRITY_MV
    lua_pushstring(lua->L, RPM_INTEGRITY_MV);
#else
    lua_pushstring(lua->L, "0");
#endif
    if (lua_pcall(lua->L, 7, 1, 0) != 0) {
        error = lua_isstring(lua->L, -1) ? lua_tostring(lua->L, -1) : "unknown error";
        lua_pop(lua->L, 1);
        integrity_check_message("ERROR: Failed to execute Integrity Validation Processor.\n"
            "rpm: ERROR: Lua: %s.\n"
            "rpm: HINT: Check file \"%s\".\n", error, proc_fn);
        goto failure;
    }

    /* check Integrity Validation Processor results */
    if (!lua_isstring(lua->L, -1)) {
        integrity_check_message("ERROR: Failed to fetch Integrity Validation Processor results.\n"
            "rpm: HINT: Check file \"%s\".\n", proc_fn);
        goto failure;
    }
    result = lua_tostring(lua->L, -1);
    if (strcmp(result, "OK") == 0)
        rc = INTEGRITY_OK;
    else if (strncmp(result, "WARNING:", 8) == 0) {
        rc = INTEGRITY_WARNING;
        integrity_check_message("%s\n", result);
    }
    else {
        rc = INTEGRITY_ERROR;
        integrity_check_message("%s\n", result);
    }

    /* cleanup processing */
    failure:
    if (lua != NULL)
	rpmluaFree(lua);
    if (ts != NULL)
	(void)rpmtsFree(ts);
    ts = NULL;
    if (spec_iob != NULL)
	spec_iob = rpmiobFree(spec_iob);
    if (proc_iob != NULL)
	proc_iob = rpmiobFree(proc_iob);

    /* final result handling */
    if (rc != INTEGRITY_OK) {
        if (isatty(STDIN_FILENO) || isatty(STDOUT_FILENO))
            sleep(4);
        if (rc == INTEGRITY_ERROR)
            exit(42);
    }
    return;
}
Exemplo n.º 26
0
int main(int argc, const char ** argv)
#endif
	/*@globals rpmEVR, RPMVERSION,
		rpmGlobalMacroContext, rpmCLIMacroContext,
		h_errno, fileSystem, internalState@*/
	/*@modifies fileSystem, internalState@*/
{
    poptContext optCon = rpmcliInit(argc, (char *const *)argv, optionsTable);

    rpmts ts = NULL;
    enum modes bigMode = MODE_UNKNOWN;

#if defined(IAM_RPMQV)
    QVA_t qva = &rpmQVKArgs;
#endif

#ifdef	IAM_RPMBT
    BTA_t ba = &rpmBTArgs;
#endif

#ifdef	IAM_RPMEIU
    QVA_t ia = &rpmIArgs;
#endif

#if defined(IAM_RPMDB)
    QVA_t da = &rpmDBArgs;
#endif

#if defined(IAM_RPMK)
    QVA_t ka = &rpmQVKArgs;
#endif

#if defined(IAM_RPMBT) || defined(IAM_RPMK)
    char * passPhrase = "";
#endif

    pid_t pipeChild = 0;
    int ec = 0;
    int status;
    int p[2];
#ifdef	IAM_RPMEIU
    int xx;
#endif
	
#if !defined(__GLIBC__) && !defined(__LCLINT__)
    environ = envp;
#else
/* XXX limit the fiddle up to linux for now. */
#if !defined(HAVE_SETPROCTITLE) && defined(__linux__)
    (void) initproctitle(argc, (char **)argv, environ);
#endif
#endif  

    /* Set the major mode based on argv[0] */
    /*@-nullpass@*/
#ifdef	IAM_RPMBT
    if (!strcmp(__progname, "rpmb"))	bigMode = MODE_BUILD;
    if (!strcmp(__progname, "lt-rpmb"))	bigMode = MODE_BUILD;
    if (!strcmp(__progname, "rpmt"))	bigMode = MODE_TARBUILD;
    if (!strcmp(__progname, "rpmbuild"))	bigMode = MODE_BUILD;
#endif
#ifdef	IAM_RPMQV
    if (!strcmp(__progname, "rpmq"))	bigMode = MODE_QUERY;
    if (!strcmp(__progname, "lt-rpmq"))	bigMode = MODE_QUERY;
    if (!strcmp(__progname, "rpmv"))	bigMode = MODE_VERIFY;
    if (!strcmp(__progname, "rpmquery"))	bigMode = MODE_QUERY;
    if (!strcmp(__progname, "rpmverify"))	bigMode = MODE_VERIFY;
#endif
#ifdef	RPMEIU
    if (!strcmp(__progname, "rpme"))	bigMode = MODE_ERASE;
    if (!strcmp(__progname, "rpmi"))	bigMode = MODE_INSTALL;
    if (!strcmp(__progname, "lt-rpmi"))	bigMode = MODE_INSTALL;
    if (!strcmp(__progname, "rpmu"))	bigMode = MODE_INSTALL;
#endif
    /*@=nullpass@*/

#if defined(IAM_RPMQV)
    /* Jumpstart option from argv[0] if necessary. */
    switch (bigMode) {
    case MODE_QUERY:	qva->qva_mode = 'q';	break;
    case MODE_VERIFY:	qva->qva_mode = 'V';	break;
    case MODE_CHECKSIG:	qva->qva_mode = 'K';	break;
    case MODE_RESIGN:	qva->qva_mode = 'R';	break;
    case MODE_INSTALL:
    case MODE_ERASE:
    case MODE_BUILD:
    case MODE_REBUILD:
    case MODE_RECOMPILE:
    case MODE_TARBUILD:
    case MODE_REBUILDDB:
    case MODE_UNKNOWN:
    default:
	break;
    }
#endif

    rpmcliConfigured();

#ifdef	IAM_RPMBT
    switch (ba->buildMode) {
    case 'b':	bigMode = MODE_BUILD;		break;
    case 't':	bigMode = MODE_TARBUILD;	break;
    case 'B':	bigMode = MODE_REBUILD;		break;
    case 'C':	bigMode = MODE_RECOMPILE;	break;
    }

    if ((ba->buildAmount & RPMBUILD_RMSOURCE) && bigMode == MODE_UNKNOWN)
	bigMode = MODE_BUILD;

    if ((ba->buildAmount & RPMBUILD_RMSPEC) && bigMode == MODE_UNKNOWN)
	bigMode = MODE_BUILD;
#endif	/* IAM_RPMBT */
    
#ifdef	IAM_RPMDB
  if (bigMode == MODE_UNKNOWN || (bigMode & MODES_DB)) {
    if (da->rebuild) {
	if (bigMode != MODE_UNKNOWN) 
	    argerror(_("only one major mode may be specified"));
	else
	    bigMode = MODE_REBUILDDB;
    }
  }
#endif	/* IAM_RPMDB */

#ifdef	IAM_RPMQV
  if (bigMode == MODE_UNKNOWN || (bigMode & MODES_QV)) {
    switch (qva->qva_mode) {
    case 'q':	bigMode = MODE_QUERY;		break;
    case 'V':	bigMode = MODE_VERIFY;		break;
    }

    if (qva->qva_sourceCount) {
	if (qva->qva_sourceCount > 2)
	    argerror(_("one type of query/verify may be performed at a "
			"time"));
    }
    if (qva->qva_flags && (bigMode & ~MODES_QV)) 
	argerror(_("unexpected query flags"));

    if (qva->qva_queryFormat && (bigMode & ~MODES_QV)) 
	argerror(_("unexpected query format"));

    if (qva->qva_source != RPMQV_PACKAGE && (bigMode & ~MODES_QV)) 
	argerror(_("unexpected query source"));
  }
#endif	/* IAM_RPMQV */

#ifdef	IAM_RPMEIU
  if (bigMode == MODE_UNKNOWN || (bigMode & MODES_IE))
    {	int iflags = (ia->installInterfaceFlags &
		(INSTALL_UPGRADE|INSTALL_FRESHEN|INSTALL_INSTALL));
	int eflags = (ia->installInterfaceFlags & INSTALL_ERASE);

	if (iflags & eflags)
	    argerror(_("only one major mode may be specified"));
	else if (iflags)
	    bigMode = MODE_INSTALL;
	else if (eflags)
	    bigMode = MODE_ERASE;
    }
#endif	/* IAM_RPMEIU */

#ifdef	IAM_RPMK
  if (bigMode == MODE_UNKNOWN || (bigMode & MODES_K)) {
	switch (ka->qva_mode) {
	case RPMSIGN_NONE:
	    ka->sign = 0;
	    break;
	case RPMSIGN_IMPORT_PUBKEY:
	case RPMSIGN_CHK_SIGNATURE:
	    bigMode = MODE_CHECKSIG;
	    ka->sign = 0;
	    break;
	case RPMSIGN_ADD_SIGNATURE:
	case RPMSIGN_NEW_SIGNATURE:
	case RPMSIGN_DEL_SIGNATURE:
	    bigMode = MODE_RESIGN;
	    ka->sign = (ka->qva_mode != RPMSIGN_DEL_SIGNATURE);
	    break;
	}
  }
#endif	/* IAM_RPMK */

#if defined(IAM_RPMEIU)
    if (!( bigMode == MODE_INSTALL ) &&
(ia->probFilter & (RPMPROB_FILTER_REPLACEPKG | RPMPROB_FILTER_OLDPACKAGE)))
	argerror(_("only installation, upgrading, rmsource and rmspec may be forced"));
    if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_FORCERELOCATE))
	argerror(_("files may only be relocated during package installation"));

    if (ia->relocations && ia->qva_prefix)
	argerror(_("cannot use --prefix with --relocate or --excludepath"));

    if (bigMode != MODE_INSTALL && ia->relocations)
	argerror(_("--relocate and --excludepath may only be used when installing new packages"));

    if (bigMode != MODE_INSTALL && ia->qva_prefix)
	argerror(_("--prefix may only be used when installing new packages"));

    if (ia->qva_prefix && ia->qva_prefix[0] != '/') 
	argerror(_("arguments to --prefix must begin with a /"));

    if (bigMode != MODE_INSTALL && (ia->installInterfaceFlags & INSTALL_HASH))
	argerror(_("--hash (-h) may only be specified during package "
			"installation"));

    if (bigMode != MODE_INSTALL && (ia->installInterfaceFlags & INSTALL_PERCENT))
	argerror(_("--percent may only be specified during package "
			"installation"));

    if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_REPLACEPKG))
	argerror(_("--replacepkgs may only be specified during package "
			"installation"));

    if (bigMode != MODE_INSTALL && (ia->transFlags & RPMTRANS_FLAG_NODOCS))
	argerror(_("--excludedocs may only be specified during package "
		   "installation"));

    if (bigMode != MODE_INSTALL && ia->incldocs)
	argerror(_("--includedocs may only be specified during package "
		   "installation"));

    if (ia->incldocs && (ia->transFlags & RPMTRANS_FLAG_NODOCS))
	argerror(_("only one of --excludedocs and --includedocs may be "
		 "specified"));
  
    if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_IGNOREARCH))
	argerror(_("--ignorearch may only be specified during package "
		   "installation"));

    if (bigMode != MODE_INSTALL && (ia->probFilter & RPMPROB_FILTER_IGNOREOS))
	argerror(_("--ignoreos may only be specified during package "
		   "installation"));

    if ((ia->installInterfaceFlags & INSTALL_ALLMATCHES) && bigMode != MODE_ERASE)
	argerror(_("--allmatches may only be specified during package "
		   "erasure"));

    if ((ia->transFlags & RPMTRANS_FLAG_ALLFILES) && bigMode != MODE_INSTALL)
	argerror(_("--allfiles may only be specified during package "
		   "installation"));

    if ((ia->transFlags & RPMTRANS_FLAG_JUSTDB) &&
	bigMode != MODE_INSTALL && bigMode != MODE_ERASE)
	argerror(_("--justdb may only be specified during package "
		   "installation and erasure"));

    if (bigMode != MODE_INSTALL && bigMode != MODE_ERASE &&
	(ia->transFlags & (RPMTRANS_FLAG_NOSCRIPTS | _noTransScripts | _noTransTriggers)))
	argerror(_("script disabling options may only be specified during "
		   "package installation and erasure"));

    if (bigMode != MODE_INSTALL && bigMode != MODE_ERASE &&
	(ia->transFlags & (RPMTRANS_FLAG_NOTRIGGERS | _noTransTriggers)))
	argerror(_("trigger disabling options may only be specified during "
		   "package installation and erasure"));

    if (ia->noDeps & (bigMode & ~MODES_FOR_NODEPS))
	argerror(_("--nodeps may only be specified during package "
		   "building, rebuilding, recompilation, installation, "
		   "erasure, and verification"));

    if ((ia->transFlags & RPMTRANS_FLAG_TEST) && (bigMode & ~MODES_FOR_TEST))
	argerror(_("--test may only be specified during package installation, "
		 "erasure, and building"));
#endif	/* IAM_RPMEIU */

    if (rpmioRootDir && rpmioRootDir[1] && (bigMode & ~MODES_FOR_ROOT))
	argerror(_("--root (-r) may only be specified during "
		 "installation, erasure, querying, and "
		 "database rebuilds"));

    if (rpmioRootDir) {
	switch (urlIsURL(rpmioRootDir)) {
	default:
	    if (bigMode & MODES_FOR_ROOT)
		break;
	    /*@fallthrough@*/
	case URL_IS_UNKNOWN:
	    if (rpmioRootDir[0] != '/')
		argerror(_("arguments to --root (-r) must begin with a /"));
	    break;
	}
    }

#if defined(RPM_VENDOR_OPENPKG) /* integrity-checking */
    integrity_check(__progname, bigMode);
#endif

#if defined(IAM_RPMBT) || defined(IAM_RPMK)
    if (0
#if defined(IAM_RPMBT)
    || ba->sign 
#endif
#if defined(IAM_RPMK)
    || ka->sign
#endif
    )
    /*@-branchstate@*/
    {
        if (bigMode == MODE_REBUILD || bigMode == MODE_BUILD ||
	    bigMode == MODE_RESIGN || bigMode == MODE_TARBUILD)
	{
	    const char ** av;
	    struct stat sb;
	    int errors = 0;

	    if ((av = poptGetArgs(optCon)) == NULL) {
		fprintf(stderr, _("no files to sign\n"));
		errors++;
	    } else
	    while (*av) {
		if (Stat(*av, &sb)) {
		    fprintf(stderr, _("cannot access file %s\n"), *av);
		    errors++;
		}
		av++;
	    }

	    if (errors) {
		ec = errors;
		goto exit;
	    }

	
            if (poptPeekArg(optCon)
#if defined(IAM_RPMBT)
	    && !ba->nopassword 
#endif
#if defined(IAM_RPMK)
	    && !ka->nopassword
#endif
	    )
	    {
		passPhrase = Getpass(_("Enter pass phrase: "));
		if (rpmCheckPassPhrase(passPhrase)) {
		    fprintf(stderr, _("Pass phrase check failed\n"));
		    ec = EXIT_FAILURE;
		    goto exit;
		}
		fprintf(stderr, _("Pass phrase is good.\n"));
		/* XXX Getpass() should realloc instead. */
		passPhrase = xstrdup(passPhrase);
	    }
	}
    }
    /*@=branchstate@*/
#endif	/* IAM_RPMBT || IAM_RPMK */

    if (rpmioPipeOutput) {
	if (pipe(p) < 0) {
	    fprintf(stderr, _("creating a pipe for --pipe failed: %m\n"));
	    goto exit;
	}

	if (!(pipeChild = fork())) {
	    (void) close(p[1]);
	    (void) dup2(p[0], STDIN_FILENO);
	    (void) close(p[0]);
	    (void) execl("/bin/sh", "/bin/sh", "-c", rpmioPipeOutput, NULL);
	    fprintf(stderr, _("exec failed\n"));
	}

	(void) close(p[0]);
	(void) dup2(p[1], STDOUT_FILENO);
	(void) close(p[1]);
    }
	
    ts = rpmtsCreate();
    (void) rpmtsSetRootDir(ts, rpmioRootDir);
    switch (bigMode) {
#ifdef	IAM_RPMDB
    case MODE_REBUILDDB:
    {   rpmVSFlags vsflags = rpmExpandNumeric("%{_vsflags_rebuilddb}");
	rpmVSFlags ovsflags;
	if (rpmcliQueryFlags & VERIFY_DIGEST)
	    vsflags |= _RPMVSF_NODIGESTS;
	if (rpmcliQueryFlags & VERIFY_SIGNATURE)
	    vsflags |= _RPMVSF_NOSIGNATURES;
	ovsflags = rpmtsSetVSFlags(ts, vsflags);
	ec = rpmtsRebuildDB(ts);
	vsflags = rpmtsSetVSFlags(ts, ovsflags);
    }	break;
#endif	/* IAM_RPMDB */

#ifdef	IAM_RPMBT
    case MODE_REBUILD:
    case MODE_RECOMPILE:
    {	const char * pkg;
	int nbuilds = 0;

        while (!rpmIsVerbose())
	    rpmIncreaseVerbosity();

	if (!poptPeekArg(optCon))
	    argerror(_("no packages files given for rebuild"));

	ba->buildAmount =
	    RPMBUILD_PREP | RPMBUILD_BUILD | RPMBUILD_INSTALL | RPMBUILD_CHECK;
	if (bigMode == MODE_REBUILD) {
	    ba->buildAmount |= RPMBUILD_PACKAGEBINARY;
	    ba->buildAmount |= RPMBUILD_RMSOURCE;
	    ba->buildAmount |= RPMBUILD_RMSPEC;
	    ba->buildAmount |= RPMBUILD_CLEAN;
	    ba->buildAmount |= RPMBUILD_RMBUILD;
	}

	while ((pkg = poptGetArg(optCon))) {
	    if (nbuilds++ > 0) {
		rpmFreeMacros(NULL);
		rpmFreeRpmrc();
		(void) rpmReadConfigFiles(NULL, NULL);
	    }
	    ba->specFile = NULL;
	    ba->cookie = NULL;
	    ec = rpmInstallSource(ts, pkg, &ba->specFile, &ba->cookie);
	    if (ec == 0) {
		ba->rootdir = rpmioRootDir;
		ba->passPhrase = passPhrase;
		ec = build(ts, ba, NULL);
	    }
	    ba->cookie = _free(ba->cookie);
	    ba->specFile = _free(ba->specFile);

	    if (ec)
		/*@loopbreak@*/ break;
	}

    }	break;

    case MODE_BUILD:
    case MODE_TARBUILD:
    {	int nbuilds = 0;

#if defined(RPM_VENDOR_OPENPKG) /* no-auto-verbose-increase-for-track-and-fetch */
	if (ba->buildChar != 't' && ba->buildChar != 'f')
#endif
        while (!rpmIsVerbose())
	    rpmIncreaseVerbosity();
       
	switch (ba->buildChar) {
	case 'a':
	    ba->buildAmount |= RPMBUILD_PACKAGESOURCE;
	    /*@fallthrough@*/
	case 'b':
	    ba->buildAmount |= RPMBUILD_PACKAGEBINARY;
	    ba->buildAmount |= RPMBUILD_CLEAN;
#if defined(RPM_VENDOR_MANDRIVA)
	    if ((ba->buildChar == 'a' || ba->buildChar == 'b') && ba->shortCircuit)
#else
	    if ((ba->buildChar == 'b') && ba->shortCircuit)
#endif
		/*@innerbreak@*/ break;
	    /*@fallthrough@*/
	case 'i':
	    ba->buildAmount |= RPMBUILD_INSTALL;
	    ba->buildAmount |= RPMBUILD_CHECK;
	    if ((ba->buildChar == 'i') && ba->shortCircuit)
		/*@innerbreak@*/ break;
	    /*@fallthrough@*/
	case 'c':
	    ba->buildAmount |= RPMBUILD_BUILD;
	    if ((ba->buildChar == 'c') && ba->shortCircuit)
		/*@innerbreak@*/ break;
	    /*@fallthrough@*/
	case 'p':
	    ba->buildAmount |= RPMBUILD_PREP;
	    /*@innerbreak@*/ break;
	    
	case 'l':
	    ba->buildAmount |= RPMBUILD_FILECHECK;
	    /*@innerbreak@*/ break;
	case 's':
	    ba->buildAmount |= RPMBUILD_PACKAGESOURCE;
#if defined(RPM_VENDOR_OPENPKG) || defined(RPM_VENDOR_MANDRIVA) || defined(RPM_VENDOR_ARK) /* no-deps-on-building-srpms */
	    /* enforce no dependency checking when rolling a source RPM */
	    ba->noDeps = 1;
#endif
	    /*@innerbreak@*/ break;
	case 't':	/* support extracting the "%track" script/section */
	    ba->buildAmount |= RPMBUILD_TRACK;
	    /* enforce no dependency checking and expansion of %setup, %patch and %prep macros */
	    ba->noDeps = 1;
	    rpmDefineMacro(NULL, "setup #", RMIL_CMDLINE);
	    rpmDefineMacro(NULL, "patch #", RMIL_CMDLINE);
	    rpmDefineMacro(NULL, "prep %%prep", RMIL_CMDLINE);
	    /*@innerbreak@*/ break;
	case 'f':
	    ba->buildAmount |= RPMBUILD_FETCHSOURCE;
	    ba->noDeps = 1;
	    /*@innerbreak@*/ break;
	}

	if (!poptPeekArg(optCon)) {
	    if (bigMode == MODE_BUILD)
		argerror(_("no spec files given for build"));
	    else
		argerror(_("no tar files given for build"));
	}

	while ((ba->specFile = poptGetArg(optCon))) {
	    if (nbuilds++ > 0) {
		rpmFreeMacros(NULL);
		rpmFreeRpmrc();
		(void) rpmReadConfigFiles(NULL, NULL);
	    }
	    ba->rootdir = rpmioRootDir;
	    ba->passPhrase = passPhrase;
	    ba->cookie = NULL;
	    ec = build(ts, ba, NULL);
	    if (ec)
		/*@loopbreak@*/ break;
	}
    }	break;
#endif	/* IAM_RPMBT */

#ifdef	IAM_RPMEIU
    case MODE_ERASE:
	ia->depFlags = global_depFlags;
	if (ia->noDeps) ia->installInterfaceFlags |= INSTALL_NODEPS;

	if (!poptPeekArg(optCon)) {
	    if (ia->rbtid == 0)
		argerror(_("no packages given for erase"));
ia->transFlags |= RPMTRANS_FLAG_NOFDIGESTS;
ia->probFilter |= RPMPROB_FILTER_OLDPACKAGE;
ia->rbCheck = rpmcliInstallCheck;
ia->rbOrder = rpmcliInstallOrder;
ia->rbRun = rpmcliInstallRun;
	    ec += rpmRollback(ts, ia, NULL);
	} else {
	    ec += rpmErase(ts, ia, (const char **) poptGetArgs(optCon));
	}
	break;

    case MODE_INSTALL:

	/* RPMTRANS_FLAG_KEEPOBSOLETE */

	ia->depFlags = global_depFlags;
	if (!ia->incldocs) {
	    if (ia->transFlags & RPMTRANS_FLAG_NODOCS) {
		;
	    } else if (rpmExpandNumeric("%{_excludedocs}"))
		ia->transFlags |= RPMTRANS_FLAG_NODOCS;
	}

	if (ia->noDeps) ia->installInterfaceFlags |= INSTALL_NODEPS;

	/* we've already ensured !(!ia->prefix && !ia->relocations) */
	/*@-branchstate@*/
	if (ia->qva_prefix) {
	    xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations,
			NULL, ia->qva_prefix);
	    xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations,
			NULL, NULL);
	} else if (ia->relocations) {
	    xx = rpmfiAddRelocation(&ia->relocations, &ia->nrelocations,
			NULL, NULL);
	}
	/*@=branchstate@*/

	if (!poptPeekArg(optCon)) {
	    if (ia->rbtid == 0)
		argerror(_("no packages given for install"));
ia->transFlags |= RPMTRANS_FLAG_NOFDIGESTS;
ia->probFilter |= RPMPROB_FILTER_OLDPACKAGE;
ia->rbCheck = rpmcliInstallCheck;
ia->rbOrder = rpmcliInstallOrder;
ia->rbRun = rpmcliInstallRun;
/*@i@*/	    ec += rpmRollback(ts, ia, NULL);
	} else {
	    /*@-compdef -compmempass@*/ /* FIX: ia->relocations[0].newPath undefined */
	    ec += rpmcliInstall(ts, ia, (const char **)poptGetArgs(optCon));
	    /*@=compdef =compmempass@*/
	}
	break;

#endif	/* IAM_RPMEIU */

#ifdef	IAM_RPMQV
    case MODE_QUERY:
	if (!poptPeekArg(optCon)
	 && !(qva->qva_source == RPMQV_ALL || qva->qva_source == RPMQV_HDLIST))
	    argerror(_("no arguments given for query"));

	qva->depFlags = global_depFlags;
	qva->qva_specQuery = rpmspecQuery;
	ec = rpmcliQuery(ts, qva, (const char **) poptGetArgs(optCon));
	qva->qva_specQuery = NULL;
	break;

    case MODE_VERIFY:
    {	rpmVerifyFlags verifyFlags = VERIFY_ALL;

	qva->depFlags = global_depFlags;
	verifyFlags &= ~qva->qva_flags;
	qva->qva_flags = (rpmQueryFlags) verifyFlags;

	if (!poptPeekArg(optCon)
	 && !(qva->qva_source == RPMQV_ALL || qva->qva_source == RPMQV_HDLIST))
	    argerror(_("no arguments given for verify"));
	ec = rpmcliVerify(ts, qva, (const char **) poptGetArgs(optCon));
    }	break;
#endif	/* IAM_RPMQV */

#ifdef IAM_RPMK
    case MODE_CHECKSIG:
    {	rpmVerifyFlags verifyFlags =
		(VERIFY_FDIGEST|VERIFY_HDRCHK|VERIFY_DIGEST|VERIFY_SIGNATURE);

	verifyFlags &= ~ka->qva_flags;
	ka->qva_flags = (rpmQueryFlags) verifyFlags;
    }   /*@fallthrough@*/
    case MODE_RESIGN:
	if (!poptPeekArg(optCon))
	    argerror(_("no arguments given"));
	ka->passPhrase = passPhrase;
	ec = rpmcliSign(ts, ka, (const char **)poptGetArgs(optCon));
    	break;
#endif	/* IAM_RPMK */
	
#if !defined(IAM_RPMQV)
    case MODE_QUERY:
    case MODE_VERIFY:
#endif
#if !defined(IAM_RPMK)
    case MODE_CHECKSIG:
    case MODE_RESIGN:
#endif
#if !defined(IAM_RPMDB)
    case MODE_REBUILDDB:
#endif
#if !defined(IAM_RPMBT)
    case MODE_BUILD:
    case MODE_REBUILD:
    case MODE_RECOMPILE:
    case MODE_TARBUILD:
#endif
#if !defined(IAM_RPMEIU)
    case MODE_INSTALL:
    case MODE_ERASE:
#endif
    case MODE_UNKNOWN:
#ifdef	DYING /* XXX rpmIsVerbose alone stops usage spewage with every --eval */
	if (poptPeekArg(optCon) != NULL || argc <= 1 || rpmIsVerbose()) {
	    printUsage(optCon, stderr, 0);
	    ec = argc;
	}
#endif
	break;
    }

#if defined(IAM_RPMBT) || defined(IAM_RPMK)
exit:
#endif	/* IAM_RPMBT || IAM_RPMK */

    (void)rpmtsFree(ts); 
    ts = NULL;

    if (pipeChild) {
	(void) fclose(stdout);
	(void) waitpid(pipeChild, &status, 0);
    }

#ifdef	IAM_RPMQV
    qva->qva_queryFormat = _free(qva->qva_queryFormat);
#endif

#ifdef	IAM_RPMBT
    freeNames();
    /* XXX _specPool/_pkgPool teardown should be done somewhere else. */
    {	extern rpmioPool _pkgPool;
	extern rpmioPool _specPool;
	_pkgPool = rpmioFreePool(_pkgPool);
	_specPool = rpmioFreePool(_specPool);
    }
#endif

#ifdef	IAM_RPMEIU
    ia->relocations = rpmfiFreeRelocations(ia->relocations);
#endif

    optCon = rpmcliFini(optCon);

/* XXX limit the fiddle up to linux for now. */
#if !defined(HAVE_SETPROCTITLE) && defined(__linux__)
    (void) finiproctitle();
#endif

    /* XXX don't overflow single byte exit status */
    /* XXX status 255 is special to xargs(1) */
    if (ec > 254) ec = 254;

     rpmlog(RPMLOG_DEBUG, D_("exit code: %d\n"), ec);

    /*@-globstate@*/
    return ec;
    /*@=globstate@*/
}
Exemplo n.º 27
0
/*
 * explode source RPM into the current directory
 * use filters to skip packages and files we do not need
 */
int explodeRPM(const char *source,
        filterfunc filter,
        dependencyfunc provides,
        dependencyfunc deps,
        void* userptr)
{
    char buffer[BUFFERSIZE+1]; /* make space for trailing \0 */
    FD_t fdi;
    Header h;
    char * rpmio_flags = NULL;
    rpmRC rc;
    FD_t gzdi;
    struct archive *cpio;
    struct archive_entry *cpio_entry;
    struct cpio_mydata cpio_mydata;

    rpmts ts;
    rpmVSFlags vsflags;
    const char *compr;

    if (strcmp(source, "-") == 0)
        fdi = fdDup(STDIN_FILENO);
    else
        fdi = Fopen(source, "r.ufdio");

    if (Ferror(fdi)) {
        const char *srcname = (strcmp(source, "-") == 0) ? "<stdin>" : source;
        logMessage(ERROR, "%s: %s\n", srcname, Fstrerror(fdi));
        return EXIT_FAILURE;
    }
    rpmReadConfigFiles(NULL, NULL);

    /* Initialize RPM transaction */
    ts = rpmtsCreate();
    vsflags = 0;

    /* Do not check digests, signatures or headers */
    vsflags |= _RPMVSF_NODIGESTS;
    vsflags |= _RPMVSF_NOSIGNATURES;
    vsflags |= RPMVSF_NOHDRCHK;
    (void) rpmtsSetVSFlags(ts, vsflags);

    rc = rpmReadPackageFile(ts, fdi, "rpm2dir", &h);

    ts = rpmtsFree(ts);

    switch (rc) {
        case RPMRC_OK:
        case RPMRC_NOKEY:
        case RPMRC_NOTTRUSTED:
            break;
        case RPMRC_NOTFOUND:
            logMessage(ERROR, "%s is not an RPM package", source);
            return EXIT_FAILURE;
            break;
        case RPMRC_FAIL:
        default:
            logMessage(ERROR, "error reading header from %s package\n", source);
            return EXIT_FAILURE;
            break;
    }

    /* Retrieve all dependencies and run them through deps function */
    while (deps) {
        struct rpmtd_s td;
        const char *depname;

        if (!headerGet(h, RPMTAG_REQUIRENAME, &td, HEADERGET_MINMEM))
            break;

        /* iterator */
        while ((depname = rpmtdNextString(&td))) {
            if (deps(depname, userptr)) {
                Fclose(fdi);
                return EXIT_BADDEPS;
            }
        }
        rpmtdFreeData(&td);
        break;
    }

    /* Retrieve all provides and run them through provides function */
    while (provides) {
        struct rpmtd_s td;
        const char *depname;
        int found = 0;

        if (!headerGet(h, RPMTAG_PROVIDES, &td, HEADERGET_MINMEM))
            break;

        /* iterator */
        while ((depname = rpmtdNextString(&td))) {
            if (!provides(depname, userptr)) {
                found++;
            }
        }
        rpmtdFreeData(&td);
        if (found<=0)
            return EXIT_BADDEPS;
        break;
    }

    /* Retrieve type of payload compression. */
    compr = headerGetString(h, RPMTAG_PAYLOADCOMPRESSOR);
    if (compr && strcmp(compr, "gzip")) {
        checked_asprintf(&rpmio_flags, "r.%sdio", compr);
    }
    else {
        checked_asprintf(&rpmio_flags, "r.gzdio");
    }

    /* Open uncompressed cpio stream */
    gzdi = Fdopen(fdi, rpmio_flags);
    free(rpmio_flags);

    if (gzdi == NULL) {
        logMessage(ERROR, "cannot re-open payload: %s\n", Fstrerror(gzdi));
        return EXIT_FAILURE;
    }

    /* initialize cpio decompressor */
    cpio = archive_read_new();
    if (cpio==NULL) {
        Fclose(gzdi);
        return -1;
    }

    cpio_mydata.gzdi = gzdi;
    cpio_mydata.buffer = buffer;
    archive_read_support_compression_all(cpio);
    archive_read_support_format_all(cpio);
    rc = archive_read_open(cpio, &cpio_mydata, NULL, rpm_myread, rpm_myclose);

    /* check the status of archive_open */
    if (rc != ARCHIVE_OK){
        Fclose(gzdi);
        return -1;
    }

    /* read all files in cpio archive */
    while ((rc = archive_read_next_header(cpio, &cpio_entry)) == ARCHIVE_OK){
        const struct stat *fstat;
        int64_t fsize;
        const char* filename;
        int needskip = 1; /* do we need to read the data to get to the next header? */
        int offset = 0;
        int towrite = 0;

        filename = archive_entry_pathname(cpio_entry);
        fstat = archive_entry_stat(cpio_entry);
        fsize = archive_entry_size(cpio_entry);

        /* Strip leading slashes */
        while (filename[offset] == '/')
            offset+=1;

        /* Strip leading ./ */
        while (filename[offset] == '.' && filename[offset+1] == '/')
            offset+=2;

        /* Other file type - we do not care except special cases */
        if (!S_ISREG(fstat->st_mode))
            towrite = 1;
        else
            towrite = 2;

        if (filter && filter(filename+offset, fstat, userptr)) {
            /* filter this file */
            towrite = 0;
        }

        /* Create directories */
        char* dirname = strdup(filename+offset);

        /* If the dup fails, let's hope the dirs already exist */
        if (dirname){
            char* dirptr = dirname;
            while (dirptr && *dirptr) {
                dirptr = strchr(dirptr, '/');
                if (dirptr) {
                    *dirptr = 0;
                    mkdir(dirname, 0700);
                    *dirptr = '/';
                    dirptr++;
                }
            }
            free(dirname);
        }

        /* Regular file */
        if (towrite>=2) {
            FILE *fdout = fopen(filename+offset, "w");

            if (fdout==NULL){
                rc = 33;
                break;
            }
            
            rc = archive_read_data_into_fd(cpio, fileno(fdout));
            if (rc!=ARCHIVE_OK) {
                /* XXX We didn't get the file.. well.. */
                needskip = 0;
            } else {
                needskip = 0;
                fclose(fdout);
            }
        }

        /* symlink, we assume that the path contained in symlink
         * is shorter than BUFFERSIZE */
        while (towrite && S_ISLNK(fstat->st_mode)) {
            char symlinkbuffer[BUFFERSIZE-1];

            needskip = 0;
            if ((rc = archive_read_data(cpio, symlinkbuffer, fsize))!=ARCHIVE_OK) {
                /* XXX We didn't get the file.. well.. */
                break;
            }

            if (symlink(buffer, filename+offset)) {
                logMessage(ERROR, "Failed to create symlink %s -> %s", filename+offset, buffer);
            }

            break;
        }

        if(needskip)
            archive_read_data_skip(cpio);
    }

    archive_read_finish(cpio);

    return rc != ARCHIVE_OK;
}
Exemplo n.º 28
0
Arquivo: rpmspec.c Projeto: soig/rpm
int main(int argc, char *argv[])
{
    rpmts ts = NULL;
    QVA_t qva = &rpmQVKArgs;

    poptContext optCon;
    int ec = 0;

    xsetprogname(argv[0]); /* Portability call -- see system.h */

    optCon = rpmcliInit(argc, argv, optionsTable);

    if (rpmcliPipeOutput && initPipe())
	exit(EXIT_FAILURE);

    if (target) {
	rpmFreeMacros(NULL);
	rpmFreeRpmrc();
	rpmReadConfigFiles(rpmcliRcfile, target);
    }
	
    ts = rpmtsCreate();
    switch (mode) {

    case MODE_QUERY:
	if (!poptPeekArg(optCon))
	    argerror(_("no arguments given for query"));

	qva->qva_queryFormat = queryformat;
	qva->qva_source = source;
	qva->qva_specQuery = rpmspecQuery;
	ec = rpmcliQuery(ts, qva, (ARGV_const_t) poptGetArgs(optCon));
	break;

    case MODE_PARSE: {
	const char * spath;
	if (!poptPeekArg(optCon))
	    argerror(_("no arguments given for parse"));

	while ((spath = poptGetArg(optCon)) != NULL) {
	    rpmSpec spec = rpmSpecParse(spath, (RPMSPEC_ANYARCH|RPMSPEC_FORCE), NULL);
	    if (spec == NULL) {
		ec++;
		continue;
	    }
	    fprintf(stdout, "%s", rpmSpecGetSection(spec, RPMBUILD_NONE));
	    rpmSpecFree(spec);
	}
	break;
    }

    case MODE_UNKNOWN:
	if (poptPeekArg(optCon) != NULL || argc <= 1 || rpmIsVerbose()) {
	    printUsage(optCon, stderr, 0);
	    ec = argc;
	}
	break;
    }

    rpmtsFree(ts);
    if (finishPipe())
	ec = EXIT_FAILURE;

    free(qva->qva_queryFormat);

    rpmcliFini(optCon);

    return RETVAL(ec);
}
Exemplo n.º 29
0
int loadTs(rpmts **ts, int *tsct, const char *dblistfn)
{
    int count = 0;
    int sz = 5;
    int rc = 0;
    int listfile = 1;
    struct stat st_buf;

    rc = stat(dblistfn, &st_buf);
    if(rc != 0) {
        perror("stat");
        return 1;
    }
    if(S_ISDIR(st_buf.st_mode))
        listfile = 0;

    if(listfile) {
        if(debugmode)
            printf("DEBUG: reading database list file '%s'\n", dblistfn);
        *ts = malloc(sz * sizeof(rpmts));
        FILE *f = fopen(dblistfn, "r" );
        if(f) {
            char line[2048];
            while(fgets(line, sizeof(line), f)) {
                int len = strlen(line) - 1;
                if(len > 0)
                    // Trim trailing whitespace
                    while(len > 0 && isspace(line[len]))
                        line[len--] = '\0';

                if(len > 0) {
                    // Expand array if needed
                    if(count == sz) {
                        sz += 5;
                        *ts = (rpmts *)realloc(*ts, sz);
                    }

                    if(debugmode)
                        printf("DEBUG: opening database '%s'\n", line);
                    char *dbpathm = malloc(strlen(line) + 10);
                    sprintf(dbpathm, "_dbpath %s", line);
                    rpmDefineMacro(NULL, dbpathm, RMIL_CMDLINE);
                    free(dbpathm);

                    rpmts tsi = rpmtsCreate();
                    (*ts)[count] = tsi;
                    rc = rpmtsOpenDB(tsi, O_RDONLY);
                    if( rc ) {
                        fprintf(stderr, "Failed to open database %s\n", line);
                        rc = -1;
                        break;
                    }

                    count++;
                }
            }
            fclose(f);
            *tsct = count;
        }
        else {
            perror(dblistfn);
            rc = -1;
        }
    }
    else {
        if(debugmode)
            printf("DEBUG: opening database '%s'\n", dblistfn);
        // Load from single database
        *ts = malloc(sizeof(rpmts));
        char *dbpathm = malloc(strlen(dblistfn) + 10);
        sprintf(dbpathm, "_dbpath %s", dblistfn);
        rpmDefineMacro(NULL, dbpathm, RMIL_CMDLINE);
        free(dbpathm);

        rpmts tsi = rpmtsCreate();
        (*ts)[0] = tsi;
        rc = rpmtsOpenDB(tsi, O_RDONLY);
        if( rc ) {
            fprintf(stderr, "Failed to open database %s\n", dblistfn);
            rc = -1;
        }
        *tsct = 1;
    }

    return rc;
}
Exemplo n.º 30
0
QueryData genRpmPackageFiles(QueryContext& context) {
  QueryData results;
  if (rpmReadConfigFiles(nullptr, nullptr) != 0) {
    TLOG << "Cannot read RPM configuration files.";
    return results;
  }

  rpmts ts = rpmtsCreate();
  rpmdbMatchIterator matches;
  if (context.constraints["package"].exists()) {
    auto name = (*context.constraints["package"].getAll(EQUALS).begin());
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, name.c_str(), name.size());
  } else {
    matches = rpmtsInitIterator(ts, RPMTAG_NAME, nullptr, 0);
  }

  Header header;
  while ((header = rpmdbNextIterator(matches)) != nullptr) {
    rpmtd td = rpmtdNew();
    rpmfi fi = rpmfiNew(ts, header, RPMTAG_BASENAMES, RPMFI_NOHEADER);
    auto file_count = rpmfiFC(fi);
    if (file_count <= 0 || file_count > MAX_RPM_FILES) {
      // This package contains no or too many files.
      rpmfiFree(fi);
      continue;
    }

    // Iterate over every file in this package.
    for (size_t i = 0; rpmfiNext(fi) >= 0 && i < file_count; i++) {
      Row r;
      r["package"] = getRpmAttribute(header, RPMTAG_NAME, td);
      auto path = rpmfiFN(fi);
      r["path"] = (path != nullptr) ? path : "";
      auto username = rpmfiFUser(fi);
      r["username"] = (username != nullptr) ? username : "";
      auto groupname = rpmfiFGroup(fi);
      r["groupname"] = (groupname != nullptr) ? groupname : "";
      r["mode"] = lsperms(rpmfiFMode(fi));
      r["size"] = BIGINT(rpmfiFSize(fi));

#ifdef CENTOS_CENTOS6
      // Older versions of rpmlib/rpmip use a hash algorithm enum.
      pgpHashAlgo digest_algo;
#else
      int digest_algo;
#endif
      auto digest = rpmfiFDigestHex(fi, &digest_algo);
      if (digest_algo == PGPHASHALGO_SHA256) {
        r["sha256"] = (digest != nullptr) ? digest : "";
      }

      results.push_back(r);
    }

    rpmfiFree(fi);
    rpmtdFree(td);
  }

  rpmdbFreeIterator(matches);
  rpmtsFree(ts);
  rpmFreeRpmrc();

  return results;
}