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