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(), legacyRetrofit() */
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)
146 rpmtd td = rpmtdNew();
148 list = PyList_New(0);
150 hi = headerInitIterator(s->h);
151 while (headerNext(hi, td)) {
152 rpmTag tag = rpmtdTag(td);
153 if (tag == HEADER_I18NTABLE) continue;
155 switch (rpmtdType(td)) {
161 case RPM_STRING_ARRAY_TYPE:
162 case RPM_STRING_TYPE:
163 PyList_Append(list, o=PyInt_FromLong(tag));
166 case RPM_I18NSTRING_TYPE: /* hum.. ?`*/
173 headerFreeIterator(hi);
181 static PyObject * hdrUnload(hdrObject * s, PyObject * args, PyObject *keywords)
187 static char *kwlist[] = { "legacyHeader", NULL};
189 if (!PyArg_ParseTupleAndKeywords(args, keywords, "|i", kwlist, &legacy))
192 h = headerLink(s->h);
193 /* XXX this legacy switch is a hack, needs to be removed. */
195 h = headerCopy(s->h); /* XXX strip region tags, etc */
198 len = headerSizeof(h, 0);
199 buf = headerUnload(h);
202 if (buf == NULL || len == 0) {
203 PyErr_SetString(pyrpmError, "can't unload bad header\n");
207 rc = PyString_FromStringAndSize(buf, len);
215 static PyObject * hdrExpandFilelist(hdrObject * s)
217 expandFilelist (s->h);
225 static PyObject * hdrCompressFilelist(hdrObject * s)
227 compressFilelist (s->h);
233 /* make a header with _all_ the tags we need */
236 static void mungeFilelist(Header h)
238 const char ** fileNames = NULL;
239 rpm_count_t count = 0;
241 if (!headerIsEntry (h, RPMTAG_BASENAMES)
242 || !headerIsEntry (h, RPMTAG_DIRNAMES)
243 || !headerIsEntry (h, RPMTAG_DIRINDEXES))
246 rpmfiBuildFNames(h, RPMTAG_BASENAMES, &fileNames, &count);
248 if (fileNames == NULL || count <= 0)
251 /* XXX Legacy tag needs to go away. */
252 headerAddEntry(h, RPMTAG_OLDFILENAMES, RPM_STRING_ARRAY_TYPE,
255 fileNames = _free(fileNames);
260 static PyObject * hdrFullFilelist(hdrObject * s)
262 mungeFilelist (s->h);
270 static PyObject * hdrSprintf(hdrObject * s, PyObject * args, PyObject * kwds)
276 char * kwlist[] = {"format", NULL};
278 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &fmt))
281 r = headerFormat(s->h, fmt, &err);
283 PyErr_SetString(pyrpmError, err);
287 result = Py_BuildValue("s", r);
295 static int hdr_compare(hdrObject * a, hdrObject * b)
297 return rpmVersionCompare(a->h, b->h);
300 static long hdr_hash(PyObject * h)
307 static struct PyMethodDef hdr_methods[] = {
308 {"keys", (PyCFunction) hdrKeyList, METH_NOARGS,
310 {"unload", (PyCFunction) hdrUnload, METH_VARARGS|METH_KEYWORDS,
312 {"expandFilelist", (PyCFunction) hdrExpandFilelist,METH_NOARGS,
314 {"compressFilelist",(PyCFunction) hdrCompressFilelist,METH_NOARGS,
316 {"fullFilelist", (PyCFunction) hdrFullFilelist, METH_NOARGS,
318 {"sprintf", (PyCFunction) hdrSprintf, METH_VARARGS|METH_KEYWORDS,
321 {"dsOfHeader", (PyCFunction)hdr_dsOfHeader, METH_NOARGS,
323 {"dsFromHeader", (PyCFunction)hdr_dsFromHeader, METH_VARARGS|METH_KEYWORDS,
325 {"fiFromHeader", (PyCFunction)hdr_fiFromHeader, METH_VARARGS|METH_KEYWORDS,
328 {NULL, NULL} /* sentinel */
333 static void hdr_dealloc(hdrObject * s)
335 if (s->h) headerFree(s->h);
341 rpmTag tagNumFromPyObject (PyObject *item)
345 if (PyInt_Check(item)) {
346 return PyInt_AsLong(item);
347 } else if (PyString_Check(item)) {
348 str = PyString_AsString(item);
349 return rpmTagGetValue(str);
351 return RPMTAG_NOT_FOUND;
356 static PyObject * hdr_subscript(hdrObject * s, PyObject * item)
358 rpmTagType tagtype, type;
359 rpmTag tag = RPMTAG_NOT_FOUND;
360 rpm_count_t count, i;
362 PyObject * o, * metao;
367 tag = tagNumFromPyObject (item);
368 if (tag == RPMTAG_NOT_FOUND) {
369 PyErr_SetString(PyExc_KeyError, "unknown header tag");
373 /* Retrieve data from extension or header. */
374 if (!headerGet(s->h, tag, &td, HEADERGET_EXT)) {
386 return PyList_New(0);
394 tagtype = rpmTagGetType(tag);
395 forceArray = (tagtype & RPM_MASK_RETURN_TYPE) == RPM_ARRAY_RETURN_TYPE;
399 o = PyString_FromStringAndSize(data, count);
403 if (count != 1 || forceArray) {
404 metao = PyList_New(0);
405 for (i = 0; i < count; i++) {
406 o = PyInt_FromLong(((int *) data)[i]);
407 PyList_Append(metao, o);
412 o = PyInt_FromLong(*((int *) data));
418 if (count != 1 || forceArray) {
419 metao = PyList_New(0);
420 for (i = 0; i < count; i++) {
421 o = PyInt_FromLong(((char *) data)[i]);
422 PyList_Append(metao, o);
427 o = PyInt_FromLong(*((char *) data));
432 if (count != 1 || forceArray) {
433 metao = PyList_New(0);
434 for (i = 0; i < count; i++) {
435 o = PyInt_FromLong(((short *) data)[i]);
436 PyList_Append(metao, o);
441 o = PyInt_FromLong(*((short *) data));
445 case RPM_STRING_ARRAY_TYPE:
448 metao = PyList_New(0);
449 for (i = 0; i < count; i++) {
450 o = PyString_FromString(stringArray[i]);
451 PyList_Append(metao, o);
457 case RPM_STRING_TYPE:
458 case RPM_I18NSTRING_TYPE:
459 if (count != 1 || forceArray) {
462 metao = PyList_New(0);
463 for (i=0; i < count; i++) {
464 o = PyString_FromString(stringArray[i]);
465 PyList_Append(metao, o);
470 o = PyString_FromString(data);
475 PyErr_SetString(PyExc_TypeError, "unsupported type in header");
483 static PyObject * hdr_getattro(PyObject * o, PyObject * n)
486 res = PyObject_GenericGetAttr(o, n);
488 res = hdr_subscript((hdrObject *)o, n);
492 static int hdr_setattro(PyObject * o, PyObject * n, PyObject * v)
494 return PyObject_GenericSetAttr(o, n, v);
499 static PyMappingMethods hdr_as_mapping = {
500 (lenfunc) 0, /* mp_length */
501 (binaryfunc) hdr_subscript, /* mp_subscript */
502 (objobjargproc)0, /* mp_ass_subscript */
507 static char hdr_doc[] =
512 PyTypeObject hdr_Type = {
513 PyObject_HEAD_INIT(&PyType_Type)
515 "rpm.hdr", /* tp_name */
516 sizeof(hdrObject), /* tp_size */
518 (destructor) hdr_dealloc, /* tp_dealloc */
520 (getattrfunc) 0, /* tp_getattr */
522 (cmpfunc) hdr_compare, /* tp_compare */
524 0, /* tp_as_number */
525 0, /* tp_as_sequence */
526 &hdr_as_mapping, /* tp_as_mapping */
527 hdr_hash, /* tp_hash */
530 (getattrofunc) hdr_getattro, /* tp_getattro */
531 (setattrofunc) hdr_setattro, /* tp_setattro */
532 0, /* tp_as_buffer */
533 Py_TPFLAGS_DEFAULT, /* tp_flags */
534 hdr_doc, /* tp_doc */
535 #if Py_TPFLAGS_HAVE_ITER
538 0, /* tp_richcompare */
539 0, /* tp_weaklistoffset */
542 hdr_methods, /* tp_methods */
547 0, /* tp_descr_get */
548 0, /* tp_descr_set */
549 0, /* tp_dictoffset */
558 hdrObject * hdr_Wrap(Header h)
560 hdrObject * hdr = PyObject_New(hdrObject, &hdr_Type);
561 hdr->h = headerLink(h);
565 Header hdrGetHeader(hdrObject * s)
572 PyObject * hdrLoad(PyObject * self, PyObject * args, PyObject * kwds)
578 char * kwlist[] = {"headers", NULL};
580 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s#", kwlist, &obj, &len))
583 /* copy is needed to avoid surprises from data swab in headerLoad(). */
584 h = headerCopyLoad(obj);
586 if (errno == ENOMEM) {
587 PyErr_SetString(pyrpmError, "out of memory");
589 PyErr_SetString(pyrpmError, "bad header");
596 h = headerFree(h); /* XXX ref held by hdr */
598 return (PyObject *) hdr;
603 PyObject * rpmReadHeaders (FD_t fd)
610 PyErr_SetFromErrno(pyrpmError);
614 list = PyList_New(0);
615 Py_BEGIN_ALLOW_THREADS
616 h = headerRead(fd, HEADER_MAGIC_YES);
622 if (PyList_Append(list, (PyObject *) hdr)) {
629 h = headerFree(h); /* XXX ref held by hdr */
631 Py_BEGIN_ALLOW_THREADS
632 h = headerRead(fd, HEADER_MAGIC_YES);
641 PyObject * rpmHeaderFromFD(PyObject * self, PyObject * args, PyObject * kwds)
646 char * kwlist[] = {"fd", NULL};
648 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i", kwlist, &fileno))
653 list = rpmReadHeaders (fd);
661 PyObject * rpmHeaderFromFile(PyObject * self, PyObject * args, PyObject *kwds)
666 char * kwlist[] = {"file", NULL};
668 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &filespec))
671 fd = Fopen(filespec, "r.fdio");
674 PyErr_SetFromErrno(pyrpmError);
678 list = rpmReadHeaders (fd);
685 * This assumes the order of list matches the order of the new headers, and
686 * throws an exception if that isn't true.
688 int rpmMergeHeaders(PyObject * list, FD_t fd, int matchTag)
692 rpmTag newMatch, oldMatch;
694 rpm_count_t count = 0;
695 int rc = 1; /* assume failure */
696 rpmtd td = rpmtdNew();
698 Py_BEGIN_ALLOW_THREADS
699 h = headerRead(fd, HEADER_MAGIC_YES);
703 if (!headerGet(h, matchTag, td, HEADERGET_MINMEM)) {
704 PyErr_SetString(pyrpmError, "match tag missing in new header");
707 newMatch = rpmtdTag(td);
710 hdr = (hdrObject *) PyList_GetItem(list, count++);
713 if (!headerGet(hdr->h, matchTag, td, HEADERGET_MINMEM)) {
714 PyErr_SetString(pyrpmError, "match tag missing in new header");
717 oldMatch = rpmtdTag(td);
720 if (newMatch != oldMatch) {
721 PyErr_SetString(pyrpmError, "match tag mismatch");
725 for (hi = headerInitIterator(h); headerNext(hi, td); rpmtdFreeData(td))
728 headerRemoveEntry(hdr->h, rpmtdTag(td));
729 headerPut(hdr->h, td, HEADERPUT_DEFAULT);
732 headerFreeIterator(hi);
735 Py_BEGIN_ALLOW_THREADS
736 h = headerRead(fd, HEADER_MAGIC_YES);
747 rpmMergeHeadersFromFD(PyObject * self, PyObject * args, PyObject * kwds)
754 char * kwlist[] = {"list", "fd", "matchTag", NULL};
756 if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oii", kwlist, &list,
760 if (!PyList_Check(list)) {
761 PyErr_SetString(PyExc_TypeError, "first parameter must be a list");
767 rc = rpmMergeHeaders (list, fd, matchTag);
781 rpmSingleHeaderFromFD(PyObject * self, PyObject * args, PyObject * kwds)
788 char * kwlist[] = {"fd", NULL};
790 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i", kwlist, &fileno))
793 offset = lseek(fileno, 0, SEEK_CUR);
798 PyErr_SetFromErrno(pyrpmError);
802 Py_BEGIN_ALLOW_THREADS
803 h = headerRead(fd, HEADER_MAGIC_YES);
808 tuple = PyTuple_New(2);
811 PyTuple_SET_ITEM(tuple, 0, (PyObject *) hdr_Wrap(h));
812 PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong(offset));
817 PyTuple_SET_ITEM(tuple, 0, Py_None);
818 PyTuple_SET_ITEM(tuple, 1, Py_None);
826 PyObject * versionCompare (PyObject * self, PyObject * args, PyObject * kwds)
828 hdrObject * h1, * h2;
829 char * kwlist[] = {"version0", "version1", NULL};
831 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!", kwlist, &hdr_Type,
832 &h1, &hdr_Type, &h2))
835 return Py_BuildValue("i", hdr_compare(h1, h2));
840 static int compare_values(const char *str1, const char *str2)
844 else if (str1 && !str2)
846 else if (!str1 && str2)
848 return rpmvercmp(str1, str2);
851 PyObject * labelCompare (PyObject * self, PyObject * args)
853 char *v1, *r1, *v2, *r2;
857 if (!PyArg_ParseTuple(args, "(zzz)(zzz)",
858 &e1, &v1, &r1, &e2, &v2, &r2))
861 if (e1 == NULL) e1 = "0";
862 if (e2 == NULL) e2 = "0";
864 rc = compare_values(e1, e2);
866 rc = compare_values(v1, v2);
868 rc = compare_values(r1, r2);
870 return Py_BuildValue("i", rc);