Turn hdrGetHeader() into argument parsing converter interface
[platform/upstream/rpm.git] / python / rpmts-py.c
1 #include "rpmsystem-py.h"
2
3 #include <rpm/rpmlib.h> /* rpmReadPackageFile, headerCheck */
4 #include <rpm/rpmtag.h>
5 #include <rpm/rpmpgp.h>
6 #include <rpm/rpmdb.h>
7 #include <rpm/rpmbuild.h>
8
9 #include "header-py.h"
10 #include "rpmds-py.h"   /* XXX for rpmdsNew */
11 #include "rpmfd-py.h"
12 #include "rpmfi-py.h"   /* XXX for rpmfiNew */
13 #include "rpmmi-py.h"
14 #include "rpmps-py.h"
15 #include "rpmte-py.h"
16 #include "spec-py.h"
17
18 #include "rpmts-py.h"
19
20 #include "debug.h"
21
22 /** \ingroup python
23  * \name Class: Rpmts
24  * \class Rpmts
25  * \brief A python rpm.ts object represents an RPM transaction set.
26  *
27  * The transaction set is the workhorse of RPM.  It performs the
28  * installation and upgrade of packages.  The rpm.ts object is
29  * instantiated by the TransactionSet function in the rpm module.
30  *
31  * The TransactionSet function takes two optional arguments. The first
32  * argument is the root path. The second is the verify signature disable flags,
33  * a set of the following bits:
34  *
35  * -    rpm.RPMVSF_NOHDRCHK     if set, don't check rpmdb headers
36  * -    rpm.RPMVSF_NEEDPAYLOAD  if not set, check header+payload (if possible)
37  * -    rpm.RPMVSF_NOSHA1HEADER if set, don't check header SHA1 digest
38  * -    rpm.RPMVSF_NODSAHEADER  if set, don't check header DSA signature
39  * -    rpm.RPMVSF_NOMD5        if set, don't check header+payload MD5 digest
40  * -    rpm.RPMVSF_NODSA        if set, don't check header+payload DSA signature
41  * -    rpm.RPMVSF_NORSA        if set, don't check header+payload RSA signature
42  *
43  * For convenience, there are the following masks:
44  * -    rpm._RPMVSF_NODIGESTS           if set, don't check digest(s).
45  * -    rpm._RPMVSF_NOSIGNATURES        if set, don't check signature(s).
46  *
47  * A rpm.ts object has the following methods:
48  *
49  * - addInstall(hdr,data,mode)  Add an install element to a transaction set.
50  * @param hdr   the header to be added
51  * @param data  user data that will be passed to the transaction callback
52  *              during transaction execution
53  * @param mode  optional argument that specifies if this package should
54  *              be installed ('i'), upgraded ('u').
55  *
56  * - addErase(name) Add an erase element to a transaction set.
57  * @param name  the package name to be erased
58  *
59  * - check()    Perform a dependency check on the transaction set. After
60  *              headers have been added to a transaction set, a dependency
61  *              check can be performed to make sure that all package
62  *              dependencies are satisfied.
63  * @return      None If there are no unresolved dependencies
64  *              Otherwise a list of complex tuples is returned, one tuple per
65  *              unresolved dependency, with
66  * The format of the dependency tuple is:
67  *     ((packageName, packageVersion, packageRelease),
68  *      (reqName, reqVersion),
69  *      needsFlags,
70  *      suggestedPackage,
71  *      sense)
72  *     packageName, packageVersion, packageRelease are the name,
73  *     version, and release of the package that has the unresolved
74  *     dependency or conflict.
75  *     The reqName and reqVersion are the name and version of the
76  *     requirement or conflict.
77  *     The needsFlags is a bitfield that describes the versioned
78  *     nature of a requirement or conflict.  The constants
79  *     rpm.RPMSENSE_LESS, rpm.RPMSENSE_GREATER, and
80  *     rpm.RPMSENSE_EQUAL can be logical ANDed with the needsFlags
81  *     to get versioned dependency information.
82  *     suggestedPackage is a tuple if the dependency check was aware
83  *     of a package that solves this dependency problem when the
84  *     dependency check was run.  Packages that are added to the
85  *     transaction set as "available" are examined during the
86  *     dependency check as possible dependency solvers. The tuple
87  *     contains two values, (header, suggestedName).  These are set to
88  *     the header of the suggested package and its name, respectively.
89  *     If there is no known package to solve the dependency problem,
90  *     suggestedPackage is None.
91  *     The constants rpm.RPMDEP_SENSE_CONFLICTS and
92  *     rpm.RPMDEP_SENSE_REQUIRES are set to show a dependency as a
93  *     requirement or a conflict.
94  *
95  * - ts.order() Do a topological sort of added element relations.
96  * @return      None
97  *
98  * - ts.setFlags(transFlags) Set transaction set flags.
99  * @param transFlags - bit(s) to controll transaction operations. The
100  *              following values can be logically OR'ed together:
101  *      - rpm.RPMTRANS_FLAG_TEST - test mode, do not modify the RPM
102  *              database, change any files, or run any package scripts
103  *      - rpm.RPMTRANS_FLAG_BUILD_PROBS - only build a list of
104  *              problems encountered when attempting to run this transaction
105  *              set
106  *      - rpm.RPMTRANS_FLAG_NOSCRIPTS - do not execute package scripts
107  *      - rpm.RPMTRANS_FLAG_JUSTDB - only make changes to the rpm
108  *              database, do not modify files.
109  *      - rpm.RPMTRANS_FLAG_NOTRIGGERS - do not run trigger scripts
110  *      - rpm.RPMTRANS_FLAG_NODOCS - do not install files marked as %doc
111  *      - rpm.RPMTRANS_FLAG_ALLFILES - create all files, even if a
112  *              file is marked %config(missingok) and an upgrade is
113  *              being performed.
114  *      - rpm.RPMTRANS_FLAG_KEEPOBSOLETE - do not remove obsoleted
115  *              packages.
116  * @return      previous transFlags
117  *
118  * - ts.setProbFilter(ignoreSet) Set transaction set problem filter.
119  * @param problemSetFilter - control bit(s) to ignore classes of problems,
120  *              a logical or of one or more of the following bit(s):
121  *      - rpm.RPMPROB_FILTER_IGNOREOS -
122  *      - rpm.RPMPROB_FILTER_IGNOREARCH -
123  *      - rpm.RPMPROB_FILTER_REPLACEPKG -
124  *      - rpm.RPMPROB_FILTER_FORCERELOCATE -
125  *      - rpm.RPMPROB_FILTER_REPLACENEWFILES -
126  *      - rpm.RPMPROB_FILTER_REPLACEOLDFILES -
127  *      - rpm.RPMPROB_FILTER_OLDPACKAGE -
128  *      - rpm.RPMPROB_FILTER_DISKSPACE -
129  * @return      previous ignoreSet
130  *
131  * - ts.run(callback,data) Attempt to execute a transaction set.
132  *      After the transaction set has been populated with install/upgrade or
133  *      erase actions, the transaction set can be executed by invoking
134  *      the ts.run() method.
135  */
136
137 struct rpmtsObject_s {
138     PyObject_HEAD
139     PyObject *md_dict;          /*!< to look like PyModuleObject */
140     rpmts       ts;
141     PyObject * keyList;         /* keeps reference counts correct */
142     FD_t scriptFd;
143     rpmtsi tsi;
144     rpmElementType tsiFilter;
145     rpmprobFilterFlags ignoreSet;
146 };
147
148 struct rpmtsCallbackType_s {
149     PyObject * cb;
150     PyObject * data;
151     rpmtsObject * tso;
152     PyThreadState *_save;
153 };
154
155 RPM_GNUC_NORETURN
156 static void die(PyObject *cb)
157 {
158     char *pyfn = NULL;
159     PyObject *r;
160
161     if (PyErr_Occurred()) {
162         PyErr_Print();
163     }
164     if ((r = PyObject_Repr(cb)) != NULL) { 
165         pyfn = PyString_AsString(r);
166     }
167     fprintf(stderr, _("error: python callback %s failed, aborting!\n"), 
168                       pyfn ? pyfn : "???");
169     rpmdbCheckTerminate(1);
170     exit(EXIT_FAILURE);
171 }
172
173 static PyObject *
174 rpmts_AddInstall(rpmtsObject * s, PyObject * args, PyObject * kwds)
175 {
176     Header h = NULL;
177     PyObject * key;
178     char * how = "u";   /* XXX default to upgrade element if missing */
179     int isUpgrade = 0;
180     char * kwlist[] = {"header", "key", "how", NULL};
181     int rc = 0;
182
183     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O|s:AddInstall", kwlist,
184             hdrFromPyObject, &h, &key, &how))
185         return NULL;
186
187     if (how && !rstreq(how, "u") && !rstreq(how, "i")) {
188         PyErr_SetString(PyExc_TypeError, "how argument must be \"u\" or \"i\"");
189         return NULL;
190     } else if (how && rstreq(how, "u"))
191         isUpgrade = 1;
192
193     rc = rpmtsAddInstallElement(s->ts, h, key, isUpgrade, NULL);
194     if (rc) {
195         PyErr_SetString(pyrpmError, "adding package to transaction failed");
196         return NULL;
197     }
198         
199
200     /* This should increment the usage count for me */
201     if (key)
202         PyList_Append(s->keyList, key);
203
204     Py_RETURN_NONE;
205 }
206
207 /* TODO Permit finer control (i.e. not just --allmatches) of deleted elments.*/
208 static PyObject *
209 rpmts_AddErase(rpmtsObject * s, PyObject * args, PyObject * kwds)
210 {
211     PyObject * o;
212     int installed = 0;
213     rpmdbMatchIterator mi = NULL;
214     Header h;
215     char * kwlist[] = {"name", NULL};
216
217     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:AddErase", kwlist, &o))
218         return NULL;
219
220     if (PyString_Check(o)) {
221         char * name = PyString_AsString(o);
222         mi = rpmtsInitIterator(s->ts, RPMDBI_LABEL, name, 0);
223     } else if (PyInt_Check(o)) {
224         uint32_t recno = PyInt_AsLong(o);
225         mi = rpmtsInitIterator(s->ts, RPMDBI_PACKAGES, &recno, sizeof(recno));
226     } else {
227         PyErr_SetString(PyExc_TypeError, "string or integer expected");
228         return NULL;
229     }
230
231     while ((h = rpmdbNextIterator(mi)) != NULL) {
232         installed++;
233         rpmtsAddEraseElement(s->ts, h, -1);
234     }
235     rpmdbFreeIterator(mi);
236     
237     if (installed) {
238         Py_RETURN_NONE;
239     } else {
240         PyErr_SetString(pyrpmError, "package not installed");
241         return NULL;
242     }
243 }
244
245 static int
246 rpmts_SolveCallback(rpmts ts, rpmds ds, const void * data)
247 {
248     struct rpmtsCallbackType_s * cbInfo = (struct rpmtsCallbackType_s *) data;
249     PyObject * args, * result;
250     int res = 1;
251
252     if (cbInfo->tso == NULL) return res;
253     if (cbInfo->cb == Py_None) return res;
254
255     PyEval_RestoreThread(cbInfo->_save);
256
257     args = Py_BuildValue("(Oissi)", cbInfo->tso,
258                 rpmdsTagN(ds), rpmdsN(ds), rpmdsEVR(ds), rpmdsFlags(ds));
259     result = PyEval_CallObject(cbInfo->cb, args);
260     Py_DECREF(args);
261
262     if (!result) {
263         die(cbInfo->cb);
264     } else {
265         if (PyInt_Check(result))
266             res = PyInt_AsLong(result);
267         Py_DECREF(result);
268     }
269
270     cbInfo->_save = PyEval_SaveThread();
271
272     return res;
273 }
274
275 static PyObject *
276 rpmts_Check(rpmtsObject * s, PyObject * args, PyObject * kwds)
277 {
278     rpmps ps;
279     rpmProblem p;
280     PyObject * list, * cf;
281     struct rpmtsCallbackType_s cbInfo;
282     int xx;
283     char * kwlist[] = {"callback", NULL};
284
285     memset(&cbInfo, 0, sizeof(cbInfo));
286     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:Check", kwlist,
287             &cbInfo.cb))
288         return NULL;
289
290     if (cbInfo.cb != NULL) {
291         if (!PyCallable_Check(cbInfo.cb)) {
292             PyErr_SetString(PyExc_TypeError, "expected a callable");
293             return NULL;
294         }
295         xx = rpmtsSetSolveCallback(s->ts, rpmts_SolveCallback, (void *)&cbInfo);
296     }
297
298     cbInfo.tso = s;
299     cbInfo._save = PyEval_SaveThread();
300
301     xx = rpmtsCheck(s->ts);
302     ps = rpmtsProblems(s->ts);
303
304     PyEval_RestoreThread(cbInfo._save);
305
306     if (ps != NULL) {
307         list = PyList_New(0);
308         rpmpsi psi = rpmpsInitIterator(ps);
309
310         /* XXX TODO: rpmlib >= 4.0.3 can return multiple suggested keys. */
311         while (rpmpsNextIterator(psi) >= 0) {
312             char * altNEVR, * needsName;
313             char * byName, * byVersion, * byRelease, *byArch;
314             char * needsOP, * needsVersion;
315             rpmsenseFlags needsFlags, sense;
316             fnpyKey key;
317
318             p = rpmpsGetProblem(psi);
319
320             byName = xstrdup(rpmProblemGetPkgNEVR(p));
321             if ((byArch= strrchr(byName, '.')) != NULL)
322                 *byArch++ = '\0';
323             if ((byRelease = strrchr(byName, '-')) != NULL)
324                 *byRelease++ = '\0';
325             if ((byVersion = strrchr(byName, '-')) != NULL)
326                 *byVersion++ = '\0';
327
328             key = rpmProblemGetKey(p);
329
330             altNEVR = needsName = xstrdup(rpmProblemGetAltNEVR(p));
331             if (needsName[1] == ' ') {
332                 sense = (needsName[0] == 'C')
333                         ? RPMDEP_SENSE_CONFLICTS : RPMDEP_SENSE_REQUIRES;
334                 needsName += 2;
335             } else
336                 sense = RPMDEP_SENSE_REQUIRES;
337             if ((needsVersion = strrchr(needsName, ' ')) != NULL)
338                 *needsVersion++ = '\0';
339
340             needsFlags = 0;
341             if ((needsOP = strrchr(needsName, ' ')) != NULL) {
342                 for (*needsOP++ = '\0'; *needsOP != '\0'; needsOP++) {
343                     if (*needsOP == '<')        needsFlags |= RPMSENSE_LESS;
344                     else if (*needsOP == '>')   needsFlags |= RPMSENSE_GREATER;
345                     else if (*needsOP == '=')   needsFlags |= RPMSENSE_EQUAL;
346                 }
347             }
348
349             cf = Py_BuildValue("((sss)(ss)iOi)", byName, byVersion, byRelease,
350                                needsName, needsVersion, needsFlags,
351                                (key != NULL ? key : Py_None),
352                                sense);
353             PyList_Append(list, (PyObject *) cf);
354             Py_DECREF(cf);
355             free(byName);
356             free(altNEVR);
357         }
358
359         psi = rpmpsFreeIterator(psi);
360         ps = rpmpsFree(ps);
361
362         return list;
363     }
364
365     Py_RETURN_NONE;
366 }
367
368 static PyObject *
369 rpmts_Order(rpmtsObject * s)
370 {
371     int rc;
372
373     Py_BEGIN_ALLOW_THREADS
374     rc = rpmtsOrder(s->ts);
375     Py_END_ALLOW_THREADS
376
377     return Py_BuildValue("i", rc);
378 }
379
380 static PyObject *
381 rpmts_Clean(rpmtsObject * s)
382 {
383     rpmtsClean(s->ts);
384
385     Py_RETURN_NONE;
386 }
387
388 static PyObject *
389 rpmts_OpenDB(rpmtsObject * s)
390 {
391     int dbmode;
392
393     dbmode = rpmtsGetDBMode(s->ts);
394     if (dbmode == -1)
395         dbmode = O_RDONLY;
396
397     return Py_BuildValue("i", rpmtsOpenDB(s->ts, dbmode));
398 }
399
400 static PyObject *
401 rpmts_CloseDB(rpmtsObject * s)
402 {
403     int rc;
404
405     rc = rpmtsCloseDB(s->ts);
406     rpmtsSetDBMode(s->ts, -1);  /* XXX disable lazy opens */
407
408     return Py_BuildValue("i", rc);
409 }
410
411 static PyObject *
412 rpmts_InitDB(rpmtsObject * s)
413 {
414     int rc;
415
416     rc = rpmtsInitDB(s->ts, O_RDONLY);
417     if (rc == 0)
418         rc = rpmtsCloseDB(s->ts);
419
420     return Py_BuildValue("i", rc);
421 }
422
423 static PyObject *
424 rpmts_RebuildDB(rpmtsObject * s)
425 {
426     int rc;
427
428     Py_BEGIN_ALLOW_THREADS
429     rc = rpmtsRebuildDB(s->ts);
430     Py_END_ALLOW_THREADS
431
432     return Py_BuildValue("i", rc);
433 }
434
435 static PyObject *
436 rpmts_VerifyDB(rpmtsObject * s)
437 {
438     int rc;
439
440     Py_BEGIN_ALLOW_THREADS
441     rc = rpmtsVerifyDB(s->ts);
442     Py_END_ALLOW_THREADS
443
444     return Py_BuildValue("i", rc);
445 }
446
447 static PyObject *
448 rpmts_HdrFromFdno(rpmtsObject * s, PyObject * args, PyObject * kwds)
449 {
450     PyObject * result = NULL;
451     Header h;
452     FD_t fd;
453     rpmRC rpmrc;
454     char * kwlist[] = {"fd", NULL};
455
456     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&:HdrFromFdno", kwlist,
457                                      rpmFdFromPyObject, &fd))
458         return NULL;
459
460     rpmrc = rpmReadPackageFile(s->ts, fd, "rpmts_HdrFromFdno", &h);
461     Fclose(fd);
462
463     switch (rpmrc) {
464     case RPMRC_OK:
465         if (h)
466             result = Py_BuildValue("N", hdr_Wrap(&hdr_Type, h));
467         h = headerFree(h);      /* XXX ref held by result */
468         break;
469
470     case RPMRC_NOKEY:
471         PyErr_SetString(pyrpmError, "public key not available");
472         break;
473
474     case RPMRC_NOTTRUSTED:
475         PyErr_SetString(pyrpmError, "public key not trusted");
476         break;
477
478     case RPMRC_NOTFOUND:
479     case RPMRC_FAIL:
480     default:
481         PyErr_SetString(pyrpmError, "error reading package header");
482         break;
483     }
484
485     return result;
486 }
487
488 static PyObject *
489 rpmts_HdrCheck(rpmtsObject * s, PyObject * args, PyObject * kwds)
490 {
491     PyObject * blob;
492     PyObject * result = NULL;
493     char * msg = NULL;
494     const void * uh;
495     int uc;
496     rpmRC rpmrc;
497     char * kwlist[] = {"headers", NULL};
498
499     if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:HdrCheck", kwlist, &blob))
500         return NULL;
501
502     uh = PyString_AsString(blob);
503     uc = PyString_Size(blob);
504
505     rpmrc = headerCheck(s->ts, uh, uc, &msg);
506
507     switch (rpmrc) {
508     case RPMRC_OK:
509         Py_INCREF(Py_None);
510         result = Py_None;
511         break;
512
513     case RPMRC_NOKEY:
514         PyErr_SetString(pyrpmError, "public key not availaiable");
515         break;
516
517     case RPMRC_NOTTRUSTED:
518         PyErr_SetString(pyrpmError, "public key not trusted");
519         break;
520
521     case RPMRC_FAIL:
522     default:
523         PyErr_SetString(pyrpmError, msg);
524         break;
525     }
526     msg = _free(msg);
527
528     return result;
529 }
530
531 static PyObject *
532 rpmts_SetVSFlags(rpmtsObject * s, PyObject * args, PyObject * kwds)
533 {
534     rpmVSFlags vsflags;
535     char * kwlist[] = {"flags", NULL};
536
537     if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:SetVSFlags", kwlist,
538             &vsflags))
539         return NULL;
540
541     /* XXX FIXME: value check on vsflags, or build pure python object 
542      * for it, and require an object of that type */
543
544     return Py_BuildValue("i", rpmtsSetVSFlags(s->ts, vsflags));
545 }
546
547 static PyObject *
548 rpmts_GetVSFlags(rpmtsObject * s)
549 {
550     return Py_BuildValue("i", rpmtsVSFlags(s->ts));
551 }
552
553 static PyObject *
554 rpmts_SetColor(rpmtsObject * s, PyObject * args, PyObject * kwds)
555 {
556     rpm_color_t tscolor;
557     char * kwlist[] = {"color", NULL};
558
559     if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:Color", kwlist, &tscolor))
560         return NULL;
561
562     /* XXX FIXME: value check on tscolor, or build pure python object
563      * for it, and require an object of that type */
564
565     return Py_BuildValue("i", rpmtsSetColor(s->ts, tscolor));
566 }
567
568 static PyObject *
569 rpmts_PgpPrtPkts(rpmtsObject * s, PyObject * args, PyObject * kwds)
570 {
571     PyObject * blob;
572     unsigned char * pkt;
573     unsigned int pktlen;
574     int rc;
575     char * kwlist[] = {"octets", NULL};
576
577     if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:PgpPrtPkts", kwlist, &blob))
578         return NULL;
579
580     pkt = (unsigned char *)PyString_AsString(blob);
581     pktlen = PyString_Size(blob);
582
583     rc = pgpPrtPkts(pkt, pktlen, NULL, 1);
584
585     return Py_BuildValue("i", rc);
586 }
587
588 static PyObject *
589 rpmts_PgpImportPubkey(rpmtsObject * s, PyObject * args, PyObject * kwds)
590 {
591     PyObject * blob;
592     unsigned char * pkt;
593     unsigned int pktlen;
594     int rc;
595     char * kwlist[] = {"pubkey", NULL};
596
597     if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:PgpImportPubkey",
598             kwlist, &blob))
599         return NULL;
600
601     pkt = (unsigned char *)PyString_AsString(blob);
602     pktlen = PyString_Size(blob);
603
604     rc = rpmtsImportPubkey(s->ts, pkt, pktlen);
605
606     return Py_BuildValue("i", rc);
607 }
608
609 static PyObject *
610 rpmts_GetKeys(rpmtsObject * s)
611 {
612     const void **data = NULL;
613     int num, i;
614     PyObject *tuple;
615
616     rpmtsGetKeys(s->ts, &data, &num);
617     if (data == NULL || num <= 0) {
618         data = _free(data);
619         Py_RETURN_NONE;
620     }
621
622     tuple = PyTuple_New(num);
623
624     for (i = 0; i < num; i++) {
625         PyObject *obj;
626         obj = (data[i] ? (PyObject *) data[i] : Py_None);
627         Py_INCREF(obj);
628         PyTuple_SetItem(tuple, i, obj);
629     }
630
631     data = _free(data);
632
633     return tuple;
634 }
635
636 static void *
637 rpmtsCallback(const void * hd, const rpmCallbackType what,
638                          const rpm_loff_t amount, const rpm_loff_t total,
639                          const void * pkgKey, rpmCallbackData data)
640 {
641     Header h = (Header) hd;
642     struct rpmtsCallbackType_s * cbInfo = data;
643     PyObject * pkgObj = (PyObject *) pkgKey;
644     PyObject * args, * result;
645     static FD_t fd;
646
647     if (cbInfo->cb == Py_None) return NULL;
648
649     /* Synthesize a python object for callback (if necessary). */
650     if (pkgObj == NULL) {
651         if (h) {
652             pkgObj = Py_BuildValue("s", headerGetString(h, RPMTAG_NAME));
653         } else {
654             pkgObj = Py_None;
655             Py_INCREF(pkgObj);
656         }
657     } else
658         Py_INCREF(pkgObj);
659
660     PyEval_RestoreThread(cbInfo->_save);
661
662     args = Py_BuildValue("(iLLOO)", what, amount, total, pkgObj, cbInfo->data);
663     result = PyEval_CallObject(cbInfo->cb, args);
664     Py_DECREF(args);
665     Py_DECREF(pkgObj);
666
667     if (!result) {
668         die(cbInfo->cb);
669     }
670
671     if (what == RPMCALLBACK_INST_OPEN_FILE) {
672         int fdno;
673
674         if (!PyArg_Parse(result, "i", &fdno)) {
675             die(cbInfo->cb);
676         }
677         Py_DECREF(result);
678         cbInfo->_save = PyEval_SaveThread();
679
680         fd = fdDup(fdno);
681         fcntl(Fileno(fd), F_SETFD, FD_CLOEXEC);
682
683         return fd;
684     } else
685     if (what == RPMCALLBACK_INST_CLOSE_FILE) {
686         Fclose (fd);
687     }
688
689     Py_DECREF(result);
690     cbInfo->_save = PyEval_SaveThread();
691
692     return NULL;
693 }
694
695 static PyObject *
696 rpmts_SetFlags(rpmtsObject * s, PyObject * args, PyObject * kwds)
697 {
698     rpmtransFlags transFlags = 0;
699     char * kwlist[] = {"flags", NULL};
700
701     if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:SetFlags", kwlist,
702             &transFlags))
703         return NULL;
704
705     /* XXX FIXME: value check on flags, or build pure python object 
706      * for it, and require an object of that type */
707
708     return Py_BuildValue("i", rpmtsSetFlags(s->ts, transFlags));
709 }
710
711 static PyObject *
712 rpmts_SetProbFilter(rpmtsObject * s, PyObject * args, PyObject * kwds)
713 {
714     rpmprobFilterFlags ignoreSet = 0;
715     rpmprobFilterFlags oignoreSet;
716     char * kwlist[] = {"ignoreSet", NULL};
717
718     if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:ProbFilter", kwlist,
719             &ignoreSet))
720         return NULL;
721
722     oignoreSet = s->ignoreSet;
723     s->ignoreSet = ignoreSet;
724
725     return Py_BuildValue("i", oignoreSet);
726 }
727
728 static PyObject *
729 rpmts_Problems(rpmtsObject * s)
730 {
731     return rpmps_Wrap(&rpmps_Type, rpmtsProblems(s->ts));
732 }
733
734 static PyObject *
735 rpmts_Run(rpmtsObject * s, PyObject * args, PyObject * kwds)
736 {
737     int rc;
738     PyObject * list;
739     rpmps ps;
740     rpmpsi psi;
741     struct rpmtsCallbackType_s cbInfo;
742     char * kwlist[] = {"callback", "data", NULL};
743
744     if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:Run", kwlist,
745             &cbInfo.cb, &cbInfo.data))
746         return NULL;
747
748     cbInfo.tso = s;
749     cbInfo._save = PyEval_SaveThread();
750
751     if (cbInfo.cb != NULL) {
752         if (!PyCallable_Check(cbInfo.cb)) {
753             PyErr_SetString(PyExc_TypeError, "expected a callable");
754             return NULL;
755         }
756         (void) rpmtsSetNotifyCallback(s->ts, rpmtsCallback, (void *) &cbInfo);
757     }
758
759     rc = rpmtsRun(s->ts, NULL, s->ignoreSet);
760     ps = rpmtsProblems(s->ts);
761
762     if (cbInfo.cb)
763         (void) rpmtsSetNotifyCallback(s->ts, NULL, NULL);
764
765     PyEval_RestoreThread(cbInfo._save);
766
767     if (rc < 0) {
768         list = PyList_New(0);
769         return list;
770     } else if (!rc) {
771         Py_RETURN_NONE;
772     }
773
774     list = PyList_New(0);
775     psi = rpmpsInitIterator(ps);
776     while (rpmpsNextIterator(psi) >= 0) {
777         rpmProblem p = rpmpsGetProblem(psi);
778         char * ps = rpmProblemString(p);
779         PyObject * prob = Py_BuildValue("s(isN)", ps,
780                              rpmProblemGetType(p),
781                              rpmProblemGetStr(p),
782                              PyLong_FromLongLong(rpmProblemGetDiskNeed(p)));
783         PyList_Append(list, prob);
784         free(ps);
785         Py_DECREF(prob);
786     }
787
788     psi = rpmpsFreeIterator(psi);
789     ps = rpmpsFree(ps);
790
791     return list;
792 }
793
794 /* TODO Add TR_ADDED filter to iterator. */
795 static PyObject *
796 rpmts_iternext(rpmtsObject * s)
797 {
798     PyObject * result = NULL;
799     rpmte te;
800
801     /* Reset iterator on 1st entry. */
802     if (s->tsi == NULL) {
803         s->tsi = rpmtsiInit(s->ts);
804         if (s->tsi == NULL)
805             return NULL;
806         s->tsiFilter = 0;
807     }
808
809     te = rpmtsiNext(s->tsi, s->tsiFilter);
810     if (te != NULL) {
811         result = rpmte_Wrap(&rpmte_Type, te);
812     } else {
813         s->tsi = rpmtsiFree(s->tsi);
814         s->tsiFilter = 0;
815     }
816
817     return result;
818 }
819
820 static PyObject *
821 spec_Parse(rpmtsObject * s, PyObject * args, PyObject * kwds)
822 {
823     DEPRECATED_METHOD;
824     /* we could pass in the ts from here but hardly worth the trouble */
825     return PyObject_Call((PyObject *) &spec_Type, args, kwds);
826 }
827
828 static PyObject *
829 rpmts_Match(rpmtsObject * s, PyObject * args, PyObject * kwds)
830 {
831     PyObject *Key = NULL;
832     char *key = NULL;
833 /* XXX lkey *must* be a 32 bit integer, int "works" on all known platforms. */
834     int lkey = 0;
835     int len = 0;
836     rpmTag tag = RPMDBI_PACKAGES;
837     char * kwlist[] = {"tagNumber", "key", NULL};
838
839     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O:Match", kwlist,
840             tagNumFromPyObject, &tag, &Key))
841         return NULL;
842
843     if (Key) {
844         if (PyString_Check(Key)) {
845             key = PyString_AsString(Key);
846             len = PyString_Size(Key);
847         } else if (PyInt_Check(Key)) {
848             lkey = PyInt_AsLong(Key);
849             key = (char *)&lkey;
850             len = sizeof(lkey);
851         } else {
852             PyErr_SetString(PyExc_TypeError, "unknown key type");
853             return NULL;
854         }
855         /* One of the conversions above failed, exception is set already */
856         if (PyErr_Occurred()) {
857             return NULL;
858         }
859     }
860
861     /* XXX If not already opened, open the database O_RDONLY now. */
862     /* XXX FIXME: lazy default rdonly open also done by rpmtsInitIterator(). */
863     if (rpmtsGetRdb(s->ts) == NULL) {
864         int rc = rpmtsOpenDB(s->ts, O_RDONLY);
865         if (rc || rpmtsGetRdb(s->ts) == NULL) {
866             PyErr_SetString(PyExc_TypeError, "rpmdb open failed");
867             return NULL;
868         }
869     }
870
871     return rpmmi_Wrap(&rpmmi_Type, rpmtsInitIterator(s->ts, tag, key, len), (PyObject*)s);
872 }
873
874 static struct PyMethodDef rpmts_methods[] = {
875  {"addInstall", (PyCFunction) rpmts_AddInstall, METH_VARARGS|METH_KEYWORDS,
876         NULL },
877  {"addErase",   (PyCFunction) rpmts_AddErase,   METH_VARARGS|METH_KEYWORDS,
878         NULL },
879  {"check",      (PyCFunction) rpmts_Check,      METH_VARARGS|METH_KEYWORDS,
880         NULL },
881  {"order",      (PyCFunction) rpmts_Order,      METH_NOARGS,
882         NULL },
883  {"setFlags",   (PyCFunction) rpmts_SetFlags,   METH_VARARGS|METH_KEYWORDS,
884 "ts.setFlags(transFlags) -> previous transFlags\n\
885 - Set control bit(s) for executing ts.run().\n\
886   Note: This method replaces the 1st argument to the old ts.run()\n" },
887  {"setProbFilter",      (PyCFunction) rpmts_SetProbFilter,      METH_VARARGS|METH_KEYWORDS,
888 "ts.setProbFilter(ignoreSet) -> previous ignoreSet\n\
889 - Set control bit(s) for ignoring problems found by ts.run().\n\
890   Note: This method replaces the 2nd argument to the old ts.run()\n" },
891  {"problems",   (PyCFunction) rpmts_Problems,   METH_NOARGS,
892 "ts.problems() -> ps\n\
893 - Return current problem set.\n" },
894  {"run",        (PyCFunction) rpmts_Run,        METH_VARARGS|METH_KEYWORDS,
895 "ts.run(callback, data) -> (problems)\n\
896 - Run a transaction set, returning list of problems found.\n\
897   Note: The callback may not be None.\n" },
898  {"clean",      (PyCFunction) rpmts_Clean,      METH_NOARGS,
899         NULL },
900  {"openDB",     (PyCFunction) rpmts_OpenDB,     METH_NOARGS,
901 "ts.openDB() -> None\n\
902 - Open the default transaction rpmdb.\n\
903   Note: The transaction rpmdb is lazily opened, so ts.openDB() is seldom needed.\n" },
904  {"closeDB",    (PyCFunction) rpmts_CloseDB,    METH_NOARGS,
905 "ts.closeDB() -> None\n\
906 - Close the default transaction rpmdb.\n\
907   Note: ts.closeDB() disables lazy opens, and should hardly ever be used.\n" },
908  {"initDB",     (PyCFunction) rpmts_InitDB,     METH_NOARGS,
909 "ts.initDB() -> None\n\
910 - Initialize the default transaction rpmdb.\n\
911  Note: ts.initDB() is seldom needed anymore.\n" },
912  {"rebuildDB",  (PyCFunction) rpmts_RebuildDB,  METH_NOARGS,
913 "ts.rebuildDB() -> None\n\
914 - Rebuild the default transaction rpmdb.\n" },
915  {"verifyDB",   (PyCFunction) rpmts_VerifyDB,   METH_NOARGS,
916 "ts.verifyDB() -> None\n\
917 - Verify the default transaction rpmdb.\n" },
918  {"hdrFromFdno",(PyCFunction) rpmts_HdrFromFdno,METH_VARARGS|METH_KEYWORDS,
919 "ts.hdrFromFdno(fdno) -> hdr\n\
920 - Read a package header from a file descriptor.\n" },
921  {"hdrCheck",   (PyCFunction) rpmts_HdrCheck,   METH_VARARGS|METH_KEYWORDS,
922         NULL },
923  {"setVSFlags",(PyCFunction) rpmts_SetVSFlags,  METH_VARARGS|METH_KEYWORDS,
924 "ts.setVSFlags(vsflags) -> ovsflags\n\
925 - Set signature verification flags. Values for vsflags are:\n\
926     rpm.RPMVSF_NOHDRCHK      if set, don't check rpmdb headers\n\
927     rpm.RPMVSF_NEEDPAYLOAD   if not set, check header+payload (if possible)\n\
928     rpm.RPMVSF_NOSHA1HEADER  if set, don't check header SHA1 digest\n\
929     rpm.RPMVSF_NODSAHEADER   if set, don't check header DSA signature\n\
930     rpm.RPMVSF_NOMD5         if set, don't check header+payload MD5 digest\n\
931     rpm.RPMVSF_NODSA         if set, don't check header+payload DSA signature\n\
932     rpm.RPMVSF_NORSA         if set, don't check header+payload RSA signature\n\
933     rpm._RPMVSF_NODIGESTS    if set, don't check digest(s)\n\
934     rpm._RPMVSF_NOSIGNATURES if set, don't check signature(s)\n" },
935  {"getVSFlags",(PyCFunction) rpmts_GetVSFlags,  METH_NOARGS,
936 "ts.getVSFlags() -> vsflags\n\
937 - Retrieve current signature verification flags from transaction\n" },
938  {"setColor",(PyCFunction) rpmts_SetColor,      METH_VARARGS|METH_KEYWORDS,
939         NULL },
940  {"pgpPrtPkts", (PyCFunction) rpmts_PgpPrtPkts, METH_VARARGS|METH_KEYWORDS,
941         NULL },
942  {"pgpImportPubkey",    (PyCFunction) rpmts_PgpImportPubkey,    METH_VARARGS|METH_KEYWORDS,
943         NULL },
944  {"getKeys",    (PyCFunction) rpmts_GetKeys,    METH_NOARGS,
945         NULL },
946  {"parseSpec",  (PyCFunction) spec_Parse,       METH_VARARGS|METH_KEYWORDS,
947 "ts.parseSpec(\"/path/to/foo.spec\") -> spec\n\
948 - Parse a spec file.\n" },
949  {"dbMatch",    (PyCFunction) rpmts_Match,      METH_VARARGS|METH_KEYWORDS,
950 "ts.dbMatch([TagN, [key, [len]]]) -> mi\n\
951 - Create a match iterator for the default transaction rpmdb.\n" },
952     {NULL,              NULL}           /* sentinel */
953 };
954
955 static void rpmts_dealloc(rpmtsObject * s)
956 {
957
958     s->ts = rpmtsFree(s->ts);
959
960     if (s->scriptFd) Fclose(s->scriptFd);
961     /* this will free the keyList, and decrement the ref count of all
962        the items on the list as well :-) */
963     Py_DECREF(s->keyList);
964     s->ob_type->tp_free((PyObject *)s);
965 }
966
967 static PyObject * rpmts_getattro(PyObject * o, PyObject * n)
968 {
969     return PyObject_GenericGetAttr(o, n);
970 }
971
972 static int rpmts_setattro(PyObject * o, PyObject * n, PyObject * v)
973 {
974     rpmtsObject *s = (rpmtsObject *)o;
975     char * name = PyString_AsString(n);
976     int fdno;
977
978     /* XXX TODO: eliminate this hackery */
979     if (rstreq(name, "scriptFd")) {
980         if (!PyArg_Parse(v, "i", &fdno)) return -1;
981         if (fdno < 0) {
982             PyErr_SetString(PyExc_TypeError, "bad file descriptor");
983             return -1;
984         } else {
985             s->scriptFd = fdDup(fdno);
986             rpmtsSetScriptFd(s->ts, s->scriptFd);
987         }
988     } else {
989         return PyObject_GenericSetAttr(o, n, v);
990     }
991
992     return 0;
993 }
994
995 static PyObject * rpmts_new(PyTypeObject * subtype, PyObject *args, PyObject *kwds)
996 {
997     char * rootDir = "/";
998     rpmVSFlags vsflags = rpmExpandNumeric("%{?__vsflags}");
999     char * kwlist[] = {"rootdir", "vsflags", 0};
1000     rpmts ts = NULL;
1001
1002     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|si:rpmts_new", kwlist,
1003             &rootDir, &vsflags))
1004         return NULL;
1005
1006     ts = rpmtsCreate();
1007     /* XXX: Why is there no rpmts_SetRootDir() ? */
1008     (void) rpmtsSetRootDir(ts, rootDir);
1009     /* XXX: make this use common code with rpmts_SetVSFlags() to check the
1010      *      python objects */
1011     (void) rpmtsSetVSFlags(ts, vsflags);
1012
1013     return rpmts_Wrap(subtype, ts);
1014 }
1015
1016 static char rpmts_doc[] =
1017 "";
1018
1019 PyTypeObject rpmts_Type = {
1020         PyObject_HEAD_INIT(&PyType_Type)
1021         0,                              /* ob_size */
1022         "rpm.ts",                       /* tp_name */
1023         sizeof(rpmtsObject),            /* tp_size */
1024         0,                              /* tp_itemsize */
1025         (destructor) rpmts_dealloc,     /* tp_dealloc */
1026         0,                              /* tp_print */
1027         (getattrfunc)0,                 /* tp_getattr */
1028         (setattrfunc)0,                 /* tp_setattr */
1029         0,                              /* tp_compare */
1030         0,                              /* tp_repr */
1031         0,                              /* tp_as_number */
1032         0,                              /* tp_as_sequence */
1033         0,                              /* tp_as_mapping */
1034         0,                              /* tp_hash */
1035         0,                              /* tp_call */
1036         0,                              /* tp_str */
1037         (getattrofunc) rpmts_getattro,  /* tp_getattro */
1038         (setattrofunc) rpmts_setattro,  /* tp_setattro */
1039         0,                              /* tp_as_buffer */
1040         Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1041         rpmts_doc,                      /* tp_doc */
1042         0,                              /* tp_traverse */
1043         0,                              /* tp_clear */
1044         0,                              /* tp_richcompare */
1045         0,                              /* tp_weaklistoffset */
1046         PyObject_SelfIter,              /* tp_iter */
1047         (iternextfunc) rpmts_iternext,  /* tp_iternext */
1048         rpmts_methods,                  /* tp_methods */
1049         0,                              /* tp_members */
1050         0,                              /* tp_getset */
1051         0,                              /* tp_base */
1052         0,                              /* tp_dict */
1053         0,                              /* tp_descr_get */
1054         0,                              /* tp_descr_set */
1055         0,                              /* tp_dictoffset */
1056         0,                              /* tp_init */
1057         0,                              /* tp_alloc */
1058         (newfunc) rpmts_new,            /* tp_new */
1059         0,                              /* tp_free */
1060         0,                              /* tp_is_gc */
1061 };
1062
1063 PyObject *
1064 rpmts_Create(PyObject * self, PyObject * args, PyObject * kwds)
1065 {
1066     return PyObject_Call((PyObject *) &rpmts_Type, args, kwds);
1067 }
1068
1069 PyObject * rpmts_Wrap(PyTypeObject *subtype, rpmts ts)
1070 {
1071     rpmtsObject * s = (rpmtsObject *)subtype->tp_alloc(subtype, 0);
1072     if (s == NULL) return PyErr_NoMemory();
1073
1074     s->ts = ts;
1075     s->keyList = PyList_New(0);
1076     s->scriptFd = NULL;
1077     s->tsi = NULL;
1078     s->tsiFilter = 0;
1079     return (PyObject *) s;
1080 }