2 * \file python/header-py.c
7 #include <rpm/rpmlib.h> /* rpmvercmp */
8 #include <rpm/rpmtag.h>
9 #include <rpm/rpmstring.h>
10 #include <rpm/rpmts.h> /* XXX rpmtsCreate/rpmtsFree */
12 #include "lib/legacy.h" /* XXX expand/compressFilelist(), providePackageNVR() */
14 #include "header-py.h"
22 * \brief START HERE / RPM base module for the Python API
24 * The rpm base module provides the main starting point for
25 * accessing RPM from Python. For most usage, call
26 * the TransactionSet method to get a transaction set (rpmts).
32 * ts = rpm.TransactionSet()
35 * The transaction set will open the RPM database as needed, so
36 * in most cases, you do not need to explicitly open the
37 * database. The transaction set is the workhorse of RPM.
39 * You can open another RPM database, such as one that holds
40 * all packages for a given Linux distribution, to provide
41 * packages used to solve dependencies. To do this, use
45 * rpm.addMacro('_dbpath', '/path/to/alternate/database')
46 * solvets = rpm.TransactionSet()
48 * rpm.delMacro('_dbpath')
50 * # Open default database
51 * ts = rpm.TransactionSet()
54 * This code gives you access to two RPM databases through
55 * two transaction sets (rpmts): ts is a transaction set
56 * associated with the default RPM database and solvets
57 * is a transaction set tied to an alternate database, which
58 * is very useful for resolving dependencies.
60 * The rpm methods used here are:
62 * - addMacro(macro, value)
63 * @param macro Name of macro to add
64 * @param value Value for the macro
67 * @param macro Name of macro to delete
73 * \brief A python header object represents an RPM package header.
75 * All RPM packages have headers that provide metadata for the package.
76 * Header objects can be returned by database queries or loaded from a
77 * binary package on disk.
79 * The ts.hdrFromFdno() function returns the package header from a
80 * package on disk, verifying package signatures and digests of the
81 * package while reading.
83 * Note: The older method rpm.headerFromPackage() which has been replaced
84 * by ts.hdrFromFdno() used to return a (hdr, isSource) tuple.
86 * If you need to distinguish source/binary headers, do:
90 * ts = rpm.TranssactionSet()
91 * fdno = os.open("/tmp/foo-1.0-1.i386.rpm", os.O_RDONLY)
92 * hdr = ts.hdrFromFdno(fdno)
94 * if hdr[rpm.RPMTAG_SOURCEPACKAGE]:
95 * print "header is from a source package"
97 * print "header is from a binary package"
100 * The Python interface to the header data is quite elegant. It
101 * presents the data in a dictionary form. We'll take the header we
102 * just loaded and access the data within it:
104 * print hdr[rpm.RPMTAG_NAME]
105 * print hdr[rpm.RPMTAG_VERSION]
106 * print hdr[rpm.RPMTAG_RELEASE]
108 * in the case of our "foo-1.0-1.i386.rpm" package, this code would
116 * You make also access the header data by string name:
119 * print hdr['version']
120 * print hdr['release']
123 * This method of access is a teensy bit slower because the name must be
124 * translated into the tag number dynamically. You also must make sure
125 * the strings in header lookups don't get translated, or the lookups
130 * \name Class: rpm.hdr
142 static PyObject * hdrKeyList(hdrObject * s)
149 list = PyList_New(0);
151 hi = headerInitIterator(s->h);
152 while (headerNextIterator(hi, &tag, &type, NULL, NULL)) {
153 if (tag == HEADER_I18NTABLE) continue;
161 case RPM_STRING_ARRAY_TYPE:
162 case RPM_STRING_TYPE:
163 PyList_Append(list, o=PyInt_FromLong(tag));
167 headerFreeIterator(hi);
174 static PyObject * hdrUnload(hdrObject * s, PyObject * args, PyObject *keywords)
180 static char *kwlist[] = { "legacyHeader", NULL};
182 if (!PyArg_ParseTupleAndKeywords(args, keywords, "|i", kwlist, &legacy))
185 h = headerLink(s->h);
186 /* XXX this legacy switch is a hack, needs to be removed. */
188 h = headerCopy(s->h); /* XXX strip region tags, etc */
191 len = headerSizeof(h, 0);
192 buf = headerUnload(h);
195 if (buf == NULL || len == 0) {
196 PyErr_SetString(pyrpmError, "can't unload bad header\n");
200 rc = PyString_FromStringAndSize(buf, len);
208 static PyObject * hdrExpandFilelist(hdrObject * s)
210 expandFilelist (s->h);
218 static PyObject * hdrCompressFilelist(hdrObject * s)
220 compressFilelist (s->h);
226 /* make a header with _all_ the tags we need */
229 static void mungeFilelist(Header h)
231 const char ** fileNames = NULL;
232 rpm_count_t count = 0;
234 if (!headerIsEntry (h, RPMTAG_BASENAMES)
235 || !headerIsEntry (h, RPMTAG_DIRNAMES)
236 || !headerIsEntry (h, RPMTAG_DIRINDEXES))
239 rpmfiBuildFNames(h, RPMTAG_BASENAMES, &fileNames, &count);
241 if (fileNames == NULL || count <= 0)
244 /* XXX Legacy tag needs to go away. */
245 headerAddEntry(h, RPMTAG_OLDFILENAMES, RPM_STRING_ARRAY_TYPE,
248 fileNames = _free(fileNames);
253 static PyObject * hdrFullFilelist(hdrObject * s)
255 mungeFilelist (s->h);
263 static PyObject * hdrSprintf(hdrObject * s, PyObject * args, PyObject * kwds)
269 char * kwlist[] = {"format", NULL};
271 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &fmt))
274 r = headerSprintf(s->h, fmt, rpmTagTable, rpmHeaderFormats, &err);
276 PyErr_SetString(pyrpmError, err);
280 result = Py_BuildValue("s", r);
288 static int hdr_compare(hdrObject * a, hdrObject * b)
290 return rpmVersionCompare(a->h, b->h);
293 static long hdr_hash(PyObject * h)
300 static struct PyMethodDef hdr_methods[] = {
301 {"keys", (PyCFunction) hdrKeyList, METH_NOARGS,
303 {"unload", (PyCFunction) hdrUnload, METH_VARARGS|METH_KEYWORDS,
305 {"expandFilelist", (PyCFunction) hdrExpandFilelist,METH_NOARGS,
307 {"compressFilelist",(PyCFunction) hdrCompressFilelist,METH_NOARGS,
309 {"fullFilelist", (PyCFunction) hdrFullFilelist, METH_NOARGS,
311 {"sprintf", (PyCFunction) hdrSprintf, METH_VARARGS|METH_KEYWORDS,
314 {"dsOfHeader", (PyCFunction)hdr_dsOfHeader, METH_NOARGS,
316 {"dsFromHeader", (PyCFunction)hdr_dsFromHeader, METH_VARARGS|METH_KEYWORDS,
318 {"fiFromHeader", (PyCFunction)hdr_fiFromHeader, METH_VARARGS|METH_KEYWORDS,
321 {NULL, NULL} /* sentinel */
326 static void hdr_dealloc(hdrObject * s)
328 if (s->h) headerFree(s->h);
334 rpm_tag_t tagNumFromPyObject (PyObject *item)
338 if (PyInt_Check(item)) {
339 return PyInt_AsLong(item);
340 } else if (PyString_Check(item)) {
341 str = PyString_AsString(item);
342 return rpmTagGetValue(str);
344 return RPMTAG_NOT_FOUND;
348 * Retrieve tag info from header.
349 * This is a "dressed" entry to headerGetEntry to do:
350 * 1) DIRNAME/BASENAME/DIRINDICES -> FILENAMES tag conversions.
351 * 2) i18n lookaside (if enabled).
355 * @retval type address of tag value data type
356 * @retval p address of pointer to tag value(s)
357 * @retval c address of number of values
358 * @return 0 on success, 1 on bad magic, 2 on error
360 static int dressedHeaderGetEntry(Header h, rpm_tag_t tag, rpm_tagtype_t *type,
361 void **p, rpm_count_t *c)
364 case RPMTAG_OLDFILENAMES:
365 { const char ** fl = NULL;
367 rpmfiBuildFNames(h, RPMTAG_BASENAMES, &fl, &count);
371 if (type) *type = RPM_STRING_ARRAY_TYPE;
379 case RPMTAG_DESCRIPTION:
386 (void) stpcpy( stpcpy( stpcpy( fmt, "%{"), rpmTagGetName(tag)), "}\n");
388 /* XXX FIXME: memory leak. */
389 msgstr = headerSprintf(h, fmt, rpmTagTable, rpmHeaderFormats, &errstr);
391 *p = (void *) msgstr;
392 if (type) *type = RPM_STRING_TYPE;
402 return headerGetEntry(h, tag, type, p, c);
409 static PyObject * hdr_subscript(hdrObject * s, PyObject * item)
411 rpm_tagtype_t tagtype, type;
412 rpm_tag_t tag = RPMTAG_NOT_FOUND;
413 rpm_count_t count, i;
415 PyObject * o, * metao;
420 const struct headerSprintfExtension_s * ext = NULL;
421 const struct headerSprintfExtension_s * extensions = rpmHeaderFormats;
423 if (PyCObject_Check (item))
424 ext = PyCObject_AsVoidPtr(item);
426 tag = tagNumFromPyObject (item);
427 if (tag == RPMTAG_NOT_FOUND && PyString_Check(item)) {
428 /* if we still don't have the tag, go looking for the header
430 str = PyString_AsString(item);
431 while (extensions->name) {
432 if (extensions->type == HEADER_EXT_TAG
433 && !xstrcasecmp(extensions->name + 7, str)) {
440 /* Retrieve data from extension or header. */
442 ext->u.tagFunction(s->h, &type, &data, &count, &freeData);
444 if (tag == RPMTAG_NOT_FOUND) {
445 PyErr_SetString(PyExc_KeyError, "unknown header tag");
449 if (!dressedHeaderGetEntry(s->h, tag, &type, &data, &count)) {
461 return PyList_New(0);
467 tagtype = rpmTagGetType(tag);
469 /* this blows up with header extension types */
470 type = tagtype & RPM_MASK_TYPE;
472 forceArray = (tagtype & RPM_MASK_RETURN_TYPE) == RPM_ARRAY_RETURN_TYPE;
473 freeData = (tagtype & RPM_MASK_TYPE) == RPM_I18NSTRING_TYPE;
477 o = PyString_FromStringAndSize(data, count);
481 if (count != 1 || forceArray) {
482 metao = PyList_New(0);
483 for (i = 0; i < count; i++) {
484 o = PyInt_FromLong(((int *) data)[i]);
485 PyList_Append(metao, o);
490 o = PyInt_FromLong(*((int *) data));
496 if (count != 1 || forceArray) {
497 metao = PyList_New(0);
498 for (i = 0; i < count; i++) {
499 o = PyInt_FromLong(((char *) data)[i]);
500 PyList_Append(metao, o);
505 o = PyInt_FromLong(*((char *) data));
510 if (count != 1 || forceArray) {
511 metao = PyList_New(0);
512 for (i = 0; i < count; i++) {
513 o = PyInt_FromLong(((short *) data)[i]);
514 PyList_Append(metao, o);
519 o = PyInt_FromLong(*((short *) data));
523 case RPM_STRING_ARRAY_TYPE:
526 metao = PyList_New(0);
527 for (i = 0; i < count; i++) {
528 o = PyString_FromString(stringArray[i]);
529 PyList_Append(metao, o);
536 case RPM_STRING_TYPE:
537 case RPM_I18NSTRING_TYPE:
538 if (count != 1 || forceArray) {
541 metao = PyList_New(0);
542 for (i=0; i < count; i++) {
543 o = PyString_FromString(stringArray[i]);
544 PyList_Append(metao, o);
549 o = PyString_FromString(data);
556 PyErr_SetString(PyExc_TypeError, "unsupported type in header");
563 static PyObject * hdr_getattro(PyObject * o, PyObject * n)
566 res = PyObject_GenericGetAttr(o, n);
568 res = hdr_subscript(o, n);
572 static int hdr_setattro(PyObject * o, PyObject * n, PyObject * v)
574 return PyObject_GenericSetAttr(o, n, v);
579 static PyMappingMethods hdr_as_mapping = {
580 (lenfunc) 0, /* mp_length */
581 (binaryfunc) hdr_subscript, /* mp_subscript */
582 (objobjargproc)0, /* mp_ass_subscript */
587 static char hdr_doc[] =
592 PyTypeObject hdr_Type = {
593 PyObject_HEAD_INIT(&PyType_Type)
595 "rpm.hdr", /* tp_name */
596 sizeof(hdrObject), /* tp_size */
598 (destructor) hdr_dealloc, /* tp_dealloc */
600 (getattrfunc) 0, /* tp_getattr */
602 (cmpfunc) hdr_compare, /* tp_compare */
604 0, /* tp_as_number */
605 0, /* tp_as_sequence */
606 &hdr_as_mapping, /* tp_as_mapping */
607 hdr_hash, /* tp_hash */
610 (getattrofunc) hdr_getattro, /* tp_getattro */
611 (setattrofunc) hdr_setattro, /* tp_setattro */
612 0, /* tp_as_buffer */
613 Py_TPFLAGS_DEFAULT, /* tp_flags */
614 hdr_doc, /* tp_doc */
615 #if Py_TPFLAGS_HAVE_ITER
618 0, /* tp_richcompare */
619 0, /* tp_weaklistoffset */
622 hdr_methods, /* tp_methods */
627 0, /* tp_descr_get */
628 0, /* tp_descr_set */
629 0, /* tp_dictoffset */
638 hdrObject * hdr_Wrap(Header h)
640 hdrObject * hdr = PyObject_New(hdrObject, &hdr_Type);
641 hdr->h = headerLink(h);
645 Header hdrGetHeader(hdrObject * s)
652 PyObject * hdrLoad(PyObject * self, PyObject * args, PyObject * kwds)
658 char * kwlist[] = {"headers", NULL};
660 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s#", kwlist, &obj, &len))
663 /* copy is needed to avoid surprises from data swab in headerLoad(). */
664 h = headerCopyLoad(obj);
666 if (errno == ENOMEM) {
667 PyErr_SetString(pyrpmError, "out of memory");
669 PyErr_SetString(pyrpmError, "bad header");
673 compressFilelist (h);
674 providePackageNVR (h);
677 h = headerFree(h); /* XXX ref held by hdr */
679 return (PyObject *) hdr;
684 PyObject * rpmReadHeaders (FD_t fd)
691 PyErr_SetFromErrno(pyrpmError);
695 list = PyList_New(0);
696 Py_BEGIN_ALLOW_THREADS
697 h = headerRead(fd, HEADER_MAGIC_YES);
702 providePackageNVR(h);
704 if (PyList_Append(list, (PyObject *) hdr)) {
711 h = headerFree(h); /* XXX ref held by hdr */
713 Py_BEGIN_ALLOW_THREADS
714 h = headerRead(fd, HEADER_MAGIC_YES);
723 PyObject * rpmHeaderFromFD(PyObject * self, PyObject * args, PyObject * kwds)
728 char * kwlist[] = {"fd", NULL};
730 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i", kwlist, &fileno))
735 list = rpmReadHeaders (fd);
743 PyObject * rpmHeaderFromFile(PyObject * self, PyObject * args, PyObject *kwds)
748 char * kwlist[] = {"file", NULL};
750 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &filespec))
753 fd = Fopen(filespec, "r.fdio");
756 PyErr_SetFromErrno(pyrpmError);
760 list = rpmReadHeaders (fd);
767 * This assumes the order of list matches the order of the new headers, and
768 * throws an exception if that isn't true.
770 int rpmMergeHeaders(PyObject * list, FD_t fd, int matchTag)
777 rpm_count_t c, count = 0;
782 Py_BEGIN_ALLOW_THREADS
783 h = headerRead(fd, HEADER_MAGIC_YES);
787 if (!headerGetEntry(h, matchTag, NULL, (void **) &newMatch, NULL)) {
788 PyErr_SetString(pyrpmError, "match tag missing in new header");
792 hdr = (hdrObject *) PyList_GetItem(list, count++);
795 if (!headerGetEntry(hdr->h, matchTag, NULL, (void **) &oldMatch, NULL)) {
796 PyErr_SetString(pyrpmError, "match tag missing in new header");
800 if (*newMatch != *oldMatch) {
801 PyErr_SetString(pyrpmError, "match tag mismatch");
805 for (hi = headerInitIterator(h);
806 headerNextIterator(hi, &tag, &type, (void *) &p, &c);
807 p = headerFreeData(p, type))
810 headerRemoveEntry(hdr->h, tag);
811 headerAddEntry(hdr->h, tag, type, p, c);
814 headerFreeIterator(hi);
817 Py_BEGIN_ALLOW_THREADS
818 h = headerRead(fd, HEADER_MAGIC_YES);
826 rpmMergeHeadersFromFD(PyObject * self, PyObject * args, PyObject * kwds)
833 char * kwlist[] = {"list", "fd", "matchTag", NULL};
835 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oii", kwlist, &list,
839 if (!PyList_Check(list)) {
840 PyErr_SetString(PyExc_TypeError, "first parameter must be a list");
846 rc = rpmMergeHeaders (list, fd, matchTag);
860 rpmSingleHeaderFromFD(PyObject * self, PyObject * args, PyObject * kwds)
867 char * kwlist[] = {"fd", NULL};
869 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i", kwlist, &fileno))
872 offset = lseek(fileno, 0, SEEK_CUR);
877 PyErr_SetFromErrno(pyrpmError);
881 Py_BEGIN_ALLOW_THREADS
882 h = headerRead(fd, HEADER_MAGIC_YES);
887 tuple = PyTuple_New(2);
890 PyTuple_SET_ITEM(tuple, 0, (PyObject *) hdr_Wrap(h));
891 PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong(offset));
896 PyTuple_SET_ITEM(tuple, 0, Py_None);
897 PyTuple_SET_ITEM(tuple, 1, Py_None);
905 PyObject * versionCompare (PyObject * self, PyObject * args, PyObject * kwds)
907 hdrObject * h1, * h2;
908 char * kwlist[] = {"version0", "version1", NULL};
910 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!", kwlist, &hdr_Type,
911 &h1, &hdr_Type, &h2))
914 return Py_BuildValue("i", hdr_compare(h1, h2));
919 static int compare_values(const char *str1, const char *str2)
923 else if (str1 && !str2)
925 else if (!str1 && str2)
927 return rpmvercmp(str1, str2);
930 PyObject * labelCompare (PyObject * self, PyObject * args)
932 char *v1, *r1, *v2, *r2;
936 if (!PyArg_ParseTuple(args, "(zzz)(zzz)",
937 &e1, &v1, &r1, &e2, &v2, &r2))
940 if (e1 == NULL) e1 = "0";
941 if (e2 == NULL) e2 = "0";
943 rc = compare_values(e1, e2);
945 rc = compare_values(v1, v2);
947 rc = compare_values(r1, r2);
949 return Py_BuildValue("i", rc);