A _count is an unsigned int, not an Id
[platform/upstream/libsolv.git] / tools / repo_rpmdb.c
1 /*
2  * Copyright (c) 2007, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /*
9  * repo_rpmdb
10  *
11  * convert rpm db to repo
12  *
13  */
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <limits.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <assert.h>
24
25 #ifdef FEDORA
26 #include <db4/db.h>
27 #else
28 #include <rpm/db.h>
29 #endif
30
31 #include "pool.h"
32 #include "repo.h"
33 #include "hash.h"
34 #include "util.h"
35 #include "queue.h"
36 #include "repo_rpmdb.h"
37
38 #define RPMDB_COOKIE_VERSION 2
39
40 #define TAG_NAME                1000
41 #define TAG_VERSION             1001
42 #define TAG_RELEASE             1002
43 #define TAG_EPOCH               1003
44 #define TAG_SUMMARY             1004
45 #define TAG_DESCRIPTION         1005
46 #define TAG_BUILDTIME           1006
47 #define TAG_BUILDHOST           1007
48 #define TAG_INSTALLTIME         1008
49 #define TAG_SIZE                1009
50 #define TAG_DISTRIBUTION        1010
51 #define TAG_VENDOR              1011
52 #define TAG_LICENSE             1014
53 #define TAG_PACKAGER            1015
54 #define TAG_GROUP               1016
55 #define TAG_URL                 1020
56 #define TAG_ARCH                1022
57 #define TAG_FILESIZES           1028
58 #define TAG_FILEMODES           1030
59 #define TAG_FILEMD5S            1035
60 #define TAG_FILELINKTOS         1036
61 #define TAG_SOURCERPM           1044
62 #define TAG_PROVIDENAME         1047
63 #define TAG_REQUIREFLAGS        1048
64 #define TAG_REQUIRENAME         1049
65 #define TAG_REQUIREVERSION      1050
66 #define TAG_NOSOURCE            1051
67 #define TAG_NOPATCH             1052
68 #define TAG_CONFLICTFLAGS       1053
69 #define TAG_CONFLICTNAME        1054
70 #define TAG_CONFLICTVERSION     1055
71 #define TAG_OBSOLETENAME        1090
72 #define TAG_FILEDEVICES         1095
73 #define TAG_FILEINODES          1096
74 #define TAG_PROVIDEFLAGS        1112
75 #define TAG_PROVIDEVERSION      1113
76 #define TAG_OBSOLETEFLAGS       1114
77 #define TAG_OBSOLETEVERSION     1115
78 #define TAG_DIRINDEXES          1116
79 #define TAG_BASENAMES           1117
80 #define TAG_DIRNAMES            1118
81 #define TAG_PAYLOADFORMAT       1124
82 #define TAG_PATCHESNAME         1133
83 #define TAG_FILECOLORS          1140
84 #define TAG_SUGGESTSNAME        1156
85 #define TAG_SUGGESTSVERSION     1157
86 #define TAG_SUGGESTSFLAGS       1158
87 #define TAG_ENHANCESNAME        1159
88 #define TAG_ENHANCESVERSION     1160
89 #define TAG_ENHANCESFLAGS       1161
90
91 #define DEP_LESS                (1 << 1)
92 #define DEP_GREATER             (1 << 2)
93 #define DEP_EQUAL               (1 << 3)
94 #define DEP_STRONG              (1 << 27)
95 #define DEP_PRE                 ((1 << 6) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 12))
96
97
98 struct rpmid {
99   unsigned int dbid;
100   char *name;
101 };
102
103 typedef struct rpmhead {
104   int cnt;
105   int dcnt;
106   unsigned char *dp;
107   unsigned char data[1];
108 } RpmHead;
109
110 static int
111 headexists(RpmHead *h, int tag)
112 {
113   unsigned int i;
114   unsigned char *d, taga[4];
115
116   d = h->dp - 16;
117   taga[0] = tag >> 24;
118   taga[1] = tag >> 16;
119   taga[2] = tag >> 8;
120   taga[3] = tag;
121   for (i = 0; i < h->cnt; i++, d -= 16)
122     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
123       return 1;
124   return 0;
125 }
126
127 static unsigned int *
128 headint32array(RpmHead *h, int tag, int *cnt)
129 {
130   unsigned int i, o, *r;
131   unsigned char *d, taga[4];
132
133   d = h->dp - 16;
134   taga[0] = tag >> 24;
135   taga[1] = tag >> 16;
136   taga[2] = tag >> 8;
137   taga[3] = tag;
138   for (i = 0; i < h->cnt; i++, d -= 16)
139     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
140       break;
141   if (i >= h->cnt)
142     return 0;
143   if (d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
144     return 0;
145   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
146   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
147   if (o + 4 * i > h->dcnt)
148     return 0;
149   d = h->dp + o;
150   r = sat_calloc(i ? i : 1, sizeof(unsigned int));
151   if (cnt)
152     *cnt = i;
153   for (o = 0; o < i; o++, d += 4)
154     r[o] = d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
155   return r;
156 }
157
158 static unsigned int
159 headint32(RpmHead *h, int tag)
160 {
161   unsigned int i, o;
162   unsigned char *d, taga[4];
163
164   d = h->dp - 16;
165   taga[0] = tag >> 24;
166   taga[1] = tag >> 16;
167   taga[2] = tag >> 8;
168   taga[3] = tag;
169   for (i = 0; i < h->cnt; i++, d -= 16)
170     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
171       break;
172   if (i >= h->cnt)
173     return 0;
174   if (d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
175     return 0;
176   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
177   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
178   if (i == 0 || o + 4 * i > h->dcnt)
179     return 0;
180   d = h->dp + o;
181   return d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
182 }
183
184 static unsigned int *
185 headint16array(RpmHead *h, int tag, int *cnt)
186 {
187   unsigned int i, o, *r;
188   unsigned char *d, taga[4];
189
190   d = h->dp - 16;
191   taga[0] = tag >> 24;
192   taga[1] = tag >> 16;
193   taga[2] = tag >> 8;
194   taga[3] = tag;
195   for (i = 0; i < h->cnt; i++, d -= 16)
196     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
197       break;
198   if (i >= h->cnt)
199     return 0;
200   if (d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 3)
201     return 0;
202   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
203   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
204   if (o + 4 * i > h->dcnt)
205     return 0;
206   d = h->dp + o;
207   r = sat_calloc(i ? i : 1, sizeof(unsigned int));
208   if (cnt)
209     *cnt = i;
210   for (o = 0; o < i; o++, d += 2)
211     r[o] = d[0] << 8 | d[1];
212   return r;
213 }
214
215 static char *
216 headstring(RpmHead *h, int tag)
217 {
218   unsigned int i, o;
219   unsigned char *d, taga[4];
220   d = h->dp - 16;
221   taga[0] = tag >> 24;
222   taga[1] = tag >> 16;
223   taga[2] = tag >> 8;
224   taga[3] = tag;
225   for (i = 0; i < h->cnt; i++, d -= 16)
226     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
227       break;
228   if (i >= h->cnt)
229     return 0;
230   /* 6: STRING, 9: I18NSTRING */
231   if (d[4] != 0 || d[5] != 0 || d[6] != 0 || (d[7] != 6 && d[7] != 9))
232     return 0;
233   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
234   return (char *)h->dp + o;
235 }
236
237 static char **
238 headstringarray(RpmHead *h, int tag, int *cnt)
239 {
240   unsigned int i, o;
241   unsigned char *d, taga[4];
242   char **r;
243
244   d = h->dp - 16;
245   taga[0] = tag >> 24;
246   taga[1] = tag >> 16;
247   taga[2] = tag >> 8;
248   taga[3] = tag;
249   for (i = 0; i < h->cnt; i++, d -= 16)
250     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
251       break;
252   if (i >= h->cnt)
253     return 0;
254   if (d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 8)
255     return 0;
256   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
257   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
258   r = sat_calloc(i ? i : 1, sizeof(char *));
259   if (cnt)
260     *cnt = i;
261   d = h->dp + o;
262   for (o = 0; o < i; o++)
263     {
264       r[o] = (char *)d;
265       if (o + 1 < i)
266         d += strlen((char *)d) + 1;
267       if (d >= h->dp + h->dcnt)
268         {
269           sat_free(r);
270           return 0;
271         }
272     }
273   return r;
274 }
275
276 static char *headtoevr(RpmHead *h)
277 {
278   unsigned int epoch;
279   char *version, *v;
280   char *release;
281   char *evr;
282
283   version  = headstring(h, TAG_VERSION);
284   release  = headstring(h, TAG_RELEASE);
285   epoch = headint32(h, TAG_EPOCH);
286   if (!version || !release)
287     {
288       fprintf(stderr, "headtoevr: bad rpm header\n");
289       exit(1);
290     }
291   for (v = version; *v >= 0 && *v <= '9'; v++)
292     ;
293   if (epoch || (v != version && *v == ':'))
294     {
295       char epochbuf[11];        /* 32bit decimal will fit in */
296       sprintf(epochbuf, "%u", epoch);
297       evr = sat_malloc(strlen(epochbuf) + 1 + strlen(version) + 1 + strlen(release) + 1);
298       sprintf(evr, "%s:%s-%s", epochbuf, version, release);
299     }
300   else
301     {
302       evr = sat_malloc(strlen(version) + 1 + strlen(release) + 1);
303       sprintf(evr, "%s-%s", version, release);
304     }
305   return evr;
306 }
307
308
309 static void
310 setutf8string(Repodata *repodata, Id handle, Id tag, const char *str)
311 {
312   const unsigned char *cp;
313   int state = 0;
314   int c;
315   unsigned char *buf = 0, *bp;
316
317   /* check if it's already utf8, code taken from screen ;-) */
318   cp = (const unsigned char *)str;
319   while ((c = *cp++) != 0)
320     {
321       if (state)
322         {
323           if ((c & 0xc0) != 0x80)
324             break; /* encoding error */
325           c = (c & 0x3f) | (state << 6);
326           if (!(state & 0x40000000))
327             {
328               /* check for overlong sequences */
329               if ((c & 0x820823e0) == 0x80000000)
330                 c = 0xfdffffff;
331               else if ((c & 0x020821f0) == 0x02000000)
332                 c = 0xfff7ffff;
333               else if ((c & 0x000820f8) == 0x00080000)
334                 c = 0xffffd000;
335               else if ((c & 0x0000207c) == 0x00002000)
336                 c = 0xffffff70;
337             }
338         }
339       else
340         {
341           /* new sequence */
342           if (c >= 0xfe)
343             break;
344           else if (c >= 0xfc)
345             c = (c & 0x01) | 0xbffffffc;    /* 5 bytes to follow */
346           else if (c >= 0xf8)
347             c = (c & 0x03) | 0xbfffff00;    /* 4 */
348           else if (c >= 0xf0)
349             c = (c & 0x07) | 0xbfffc000;    /* 3 */
350           else if (c >= 0xe0)
351             c = (c & 0x0f) | 0xbff00000;    /* 2 */
352           else if (c >= 0xc2)
353             c = (c & 0x1f) | 0xfc000000;    /* 1 */
354           else if (c >= 0x80)
355             break;
356         }
357       state = (c & 0x80000000) ? c : 0;
358     }
359   if (c)
360     {
361       /* not utf8, assume latin1 */
362       buf = sat_malloc(2 * strlen(str) + 1);
363       cp = (const unsigned char *)str;
364       str = (char *)buf;
365       bp = buf;
366       while ((c = *cp++) != 0)
367         {
368           if (c >= 0xc0)
369             {
370               *bp++ = 0xc3;
371               c ^= 0x80;
372             }
373           else if (c >= 0x80)
374             *bp++ = 0xc2;
375           *bp++ = c;
376         }
377       *bp++ = 0;
378     }
379   repodata_set_str(repodata, handle, tag, str);
380   if (buf)
381     sat_free(buf);
382 }
383
384 static unsigned int
385 makedeps(Pool *pool, Repo *repo, RpmHead *rpmhead, int tagn, int tagv, int tagf, int strong)
386 {
387   char **n, **v;
388   unsigned int *f;
389   int i, cc, nc, vc, fc;
390   int haspre = 0;
391   unsigned int olddeps;
392   Id *ida;
393
394   n = headstringarray(rpmhead, tagn, &nc);
395   if (!n)
396     return 0;
397   v = headstringarray(rpmhead, tagv, &vc);
398   if (!v)
399     {
400       sat_free(n);
401       return 0;
402     }
403   f = headint32array(rpmhead, tagf, &fc);
404   if (!f)
405     {
406       sat_free(n);
407       free(v);
408       return 0;
409     }
410   if (nc != vc || nc != fc)
411     {
412       fprintf(stderr, "bad dependency entries\n");
413       exit(1);
414     }
415
416   cc = nc;
417   if (strong)
418     {
419       cc = 0;
420       for (i = 0; i < nc; i++)
421         if ((f[i] & DEP_STRONG) == (strong == 1 ? 0 : DEP_STRONG))
422           {
423             cc++;
424             if ((f[i] & DEP_PRE) != 0)
425               haspre = 1;
426           }
427     }
428   else
429     {
430       for (i = 0; i < nc; i++)
431         if ((f[i] & DEP_PRE) != 0)
432           {
433             haspre = 1;
434             break;
435           }
436     }
437   if (tagn != TAG_REQUIRENAME)
438      haspre = 0;
439   if (cc == 0)
440     {
441       sat_free(n);
442       sat_free(v);
443       sat_free(f);
444       return 0;
445     }
446   cc += haspre;
447   olddeps = repo_reserve_ids(repo, 0, cc);
448   ida = repo->idarraydata + olddeps;
449   for (i = 0; ; i++)
450     {
451       if (i == nc)
452         {
453           if (haspre != 1)
454             break;
455           haspre = 2;
456           i = 0;
457           *ida++ = SOLVABLE_PREREQMARKER;
458         }
459       if (strong && (f[i] & DEP_STRONG) != (strong == 1 ? 0 : DEP_STRONG))
460         continue;
461       if (haspre == 1 && (f[i] & DEP_PRE) != 0)
462         continue;
463       if (haspre == 2 && (f[i] & DEP_PRE) == 0)
464         continue;
465       if (f[i] & (DEP_LESS|DEP_GREATER|DEP_EQUAL))
466         {
467           Id name, evr;
468           int flags = 0;
469           if ((f[i] & DEP_LESS) != 0)
470             flags |= 4;
471           if ((f[i] & DEP_EQUAL) != 0)
472             flags |= 2;
473           if ((f[i] & DEP_GREATER) != 0)
474             flags |= 1;
475           name = str2id(pool, n[i], 1);
476           if (v[i][0] == '0' && v[i][1] == ':' && v[i][2])
477             evr = str2id(pool, v[i] + 2, 1);
478           else
479             evr = str2id(pool, v[i], 1);
480           *ida++ = rel2id(pool, name, evr, flags, 1);
481         }
482       else
483         *ida++ = str2id(pool, n[i], 1);
484     }
485   *ida++ = 0;
486   repo->idarraysize += cc + 1;
487   sat_free(n);
488   sat_free(v);
489   sat_free(f);
490   return olddeps;
491 }
492
493
494 #ifdef USE_FILEFILTER
495
496 #define FILEFILTER_EXACT    0
497 #define FILEFILTER_STARTS   1
498 #define FILEFILTER_CONTAINS 2
499
500 struct filefilter {
501   int dirmatch;
502   char *dir;
503   char *base;
504 };
505
506 static struct filefilter filefilters[] = {
507   { FILEFILTER_CONTAINS, "/bin/", 0},
508   { FILEFILTER_CONTAINS, "/sbin/", 0},
509   { FILEFILTER_CONTAINS, "/lib/", 0},
510   { FILEFILTER_CONTAINS, "/lib64/", 0},
511   { FILEFILTER_CONTAINS, "/etc/", 0},
512   { FILEFILTER_STARTS, "/usr/games/", 0},
513   { FILEFILTER_EXACT, "/usr/share/dict/", "words"},
514   { FILEFILTER_STARTS, "/usr/share/", "magic.mime"},
515   { FILEFILTER_STARTS, "/opt/gnome/games/", 0},
516 };
517
518 #endif
519
520 static void
521 adddudata(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, char **dn, unsigned int *di, int fc, int dic)
522 {
523   Id handle, did;
524   int i, fszc;
525   unsigned int *fkb, *fn, *fsz, *fm, *fino;
526   unsigned int inotest[256], inotestok;
527
528   if (!fc)
529     return;
530   fsz = headint32array(rpmhead, TAG_FILESIZES, &fszc);
531   if (!fsz || fc != fszc)
532     {
533       sat_free(fsz);
534       return;
535     }
536   /* stupid rpm recodrs sizes of directories, so we have to check the mode */
537   fm = headint16array(rpmhead, TAG_FILEMODES, &fszc);
538   if (!fm || fc != fszc)
539     {
540       sat_free(fsz);
541       sat_free(fm);
542       return;
543     }
544   fino = headint32array(rpmhead, TAG_FILEINODES, &fszc);
545   if (!fino || fc != fszc)
546     {
547       sat_free(fsz);
548       sat_free(fm);
549       sat_free(fino);
550       return;
551     }
552   inotestok = 0;
553   if (fc < sizeof(inotest))
554     {
555       memset(inotest, 0, sizeof(inotest));
556       for (i = 0; i < fc; i++)
557         {
558           int off, bit;
559           if (fsz[i] == 0 || !S_ISREG(fm[i]))
560             continue;
561           off = (fino[i] >> 5) & (sizeof(inotest)/sizeof(*inotest) - 1);
562           bit = 1 << (fino[i] & 31);
563           if ((inotest[off] & bit) != 0)
564             break;
565           inotest[off] |= bit;
566         }
567       if (i == fc)
568         inotestok = 1;
569     }
570   if (!inotestok)
571     {
572       unsigned int *fdev = headint32array(rpmhead, TAG_FILEDEVICES, &fszc);
573       unsigned int *fx, j;
574       unsigned int mask, hash, hh;
575       if (!fdev || fc != fszc)
576         {
577           sat_free(fsz);
578           sat_free(fm);
579           sat_free(fdev);
580           sat_free(fino);
581           return;
582         }
583       mask = fc;
584       while ((mask & (mask - 1)) != 0)
585         mask = mask & (mask - 1);
586       mask <<= 2;
587       if (mask > sizeof(inotest)/sizeof(*inotest))
588         fx = sat_calloc(mask, sizeof(unsigned int));
589       else
590         {
591           fx = inotest;
592           memset(fx, 0, mask * sizeof(unsigned int));
593         }
594       mask--;
595       for (i = 0; i < fc; i++)
596         {
597           if (fsz[i] == 0 || !S_ISREG(fm[i]))
598             continue;
599           hash = (fino[i] + fdev[i] * 31) & mask;
600           hh = 7;
601           while ((j = fx[hash]) != 0)
602             {
603               if (fino[j - 1] == fino[i] && fdev[j - 1] == fdev[i])
604                 {
605                   fsz[i] = 0;   /* kill entry */
606                   break;
607                 }
608               hash = (hash + hh++) & mask;
609             }
610           if (!j)
611             fx[hash] = i + 1;
612         }
613       if (fx != inotest)
614         sat_free(fx);
615       sat_free(fdev);
616     }
617   sat_free(fino);
618   fn = sat_calloc(dic, sizeof(unsigned int));
619   fkb = sat_calloc(dic, sizeof(unsigned int));
620   for (i = 0; i < fc; i++)
621     {
622       if (fsz[i] == 0 || !S_ISREG(fm[i]))
623         continue;
624       if (di[i] >= dic)
625         continue;
626       fn[di[i]]++;
627       fkb[di[i]] += fsz[i] / 1024 + 1;
628     }
629   sat_free(fsz);
630   sat_free(fm);
631   /* commit */
632   handle = s - pool->solvables;
633   for (i = 0; i < fc; i++)
634     {
635       if (!fn[i])
636         continue;
637       if (!*dn[i] && (s->arch == ARCH_SRC || s->arch == ARCH_NOSRC))
638         did = repodata_str2dir(data, "/usr/src", 1);
639       else
640         did = repodata_str2dir(data, dn[i], 1);
641       repodata_add_dirnumnum(data, handle, SOLVABLE_DISKUSAGE, did, fkb[i], fn[i]);
642     }
643   sat_free(fn);
644   sat_free(fkb);
645 }
646
647 /* assumes last processed array is provides! */
648 static unsigned int
649 addfileprovides(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, unsigned int olddeps)
650 {
651   char **bn;
652   char **dn;
653   unsigned int *di;
654   int bnc, dnc, dic;
655   int i;
656 #ifdef USE_FILEFILTER
657   int j;
658   struct filefilter *ff;
659 #endif
660 #if 0
661   char *fn = 0;
662   int fna = 0;
663 #endif
664
665   if (!data)
666     return olddeps;
667   bn = headstringarray(rpmhead, TAG_BASENAMES, &bnc);
668   if (!bn)
669     return olddeps;
670   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dnc);
671   if (!dn)
672     {
673       sat_free(bn);
674       return olddeps;
675     }
676   di = headint32array(rpmhead, TAG_DIRINDEXES, &dic);
677   if (!di)
678     {
679       sat_free(bn);
680       sat_free(dn);
681       return olddeps;
682     }
683   if (bnc != dic)
684     {
685       fprintf(stderr, "bad filelist\n");
686       exit(1);
687     }
688
689   if (data)
690     adddudata(pool, repo, data, s, rpmhead, dn, di, bnc, dic);
691
692   for (i = 0; i < bnc; i++)
693     {
694 #ifdef USE_FILEFILTER
695       ff = filefilters;
696       for (j = 0; j < sizeof(filefilters)/sizeof(*filefilters); j++, ff++)
697         {
698           if (ff->dir)
699             {
700               switch (ff->dirmatch)
701                 {
702                 case FILEFILTER_STARTS:
703                   if (strncmp(dn[di[i]], ff->dir, strlen(ff->dir)))
704                     continue;
705                   break;
706                 case FILEFILTER_CONTAINS:
707                   if (!strstr(dn[di[i]], ff->dir))
708                     continue;
709                   break;
710                 case FILEFILTER_EXACT:
711                 default:
712                   if (strcmp(dn[di[i]], ff->dir))
713                     continue;
714                   break;
715                 }
716             }
717           if (ff->base)
718             {
719               if (strcmp(bn[i], ff->base))
720                 continue;
721             }
722           break;
723         }
724       if (j == sizeof(filefilters)/sizeof(*filefilters))
725         continue;
726 #endif
727 #if 0
728       j = strlen(bn[i]) + strlen(dn[di[i]]) + 1;
729       if (j > fna)
730         {
731           fna = j + 256;
732           fn = sat_realloc(fn, fna);
733         }
734       strcpy(fn, dn[di[i]]);
735       strcat(fn, bn[i]);
736       olddeps = repo_addid_dep(repo, olddeps, str2id(pool, fn, 1), SOLVABLE_FILEMARKER);
737 #endif
738       if (data)
739         {
740           Id handle, did;
741           handle = s - pool->solvables;
742           did = repodata_str2dir(data, dn[di[i]], 1);
743           if (!did)
744             did = repodata_str2dir(data, "/", 1);
745           repodata_add_dirstr(data, handle, SOLVABLE_FILELIST, did, bn[i]);
746         }
747     }
748 #if 0
749   if (fn)
750     sat_free(fn);
751 #endif
752   sat_free(bn);
753   sat_free(dn);
754   sat_free(di);
755   return olddeps;
756 }
757
758 static void
759 addsourcerpm(Pool *pool, Repodata *data, Id handle, char *sourcerpm, char *name, char *evr)
760 {
761   const char *p, *sevr, *sarch;
762
763   p = strrchr(sourcerpm, '.');
764   if (!p || strcmp(p, ".rpm") != 0)
765     return;
766   p--;
767   while (p > sourcerpm && *p != '.')
768     p--;
769   if (*p != '.' || p == sourcerpm)
770     return;
771   sarch = p-- + 1;
772   while (p > sourcerpm && *p != '-')
773     p--;
774   if (*p != '-' || p == sourcerpm)
775     return;
776   p--;
777   while (p > sourcerpm && *p != '-')
778     p--;
779   if (*p != '-' || p == sourcerpm)
780     return;
781   sevr = p + 1;
782   if (!strcmp(sarch, "src.rpm"))
783     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, ARCH_SRC);
784   else if (!strcmp(sarch, "nosrc.rpm"))
785     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, ARCH_NOSRC);
786   else
787     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, strn2id(pool, sarch, strlen(sarch) - 4, 1));
788   if (evr && !strncmp(sevr, evr, sarch - sevr - 1) && evr[sarch - sevr - 1] == 0)
789     repodata_set_void(data, handle, SOLVABLE_SOURCEEVR);
790   else
791     repodata_set_id(data, handle, SOLVABLE_SOURCEEVR, strn2id(pool, sevr, sarch - sevr - 1, 1));
792   if (name && !strncmp(sourcerpm, name, sevr - sourcerpm - 1) && name[sevr - sourcerpm - 1] == 0)
793     repodata_set_void(data, handle, SOLVABLE_SOURCENAME);
794   else
795     repodata_set_id(data, handle, SOLVABLE_SOURCENAME, strn2id(pool, sourcerpm, sevr - sourcerpm - 1, 1));
796 }
797
798 static int
799 rpm2solv(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead)
800 {
801   char *name;
802   char *evr;
803   char *sourcerpm;
804
805   name = headstring(rpmhead, TAG_NAME);
806   if (!strcmp(name, "gpg-pubkey"))
807     return 0;
808   s->name = str2id(pool, name, 1);
809   if (!s->name)
810     {
811       fprintf(stderr, "package has no name\n");
812       exit(1);
813     }
814   sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
815   if (sourcerpm)
816     s->arch = str2id(pool, headstring(rpmhead, TAG_ARCH), 1);
817   else
818     {
819       if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
820         s->arch = ARCH_NOSRC;
821       else
822         s->arch = ARCH_SRC;
823     }
824   if (!s->arch)
825     s->arch = ARCH_NOARCH;
826   evr = headtoevr(rpmhead);
827   s->evr = str2id(pool, evr, 1);
828   s->vendor = str2id(pool, headstring(rpmhead, TAG_VENDOR), 1);
829
830   s->provides = makedeps(pool, repo, rpmhead, TAG_PROVIDENAME, TAG_PROVIDEVERSION, TAG_PROVIDEFLAGS, 0);
831   s->provides = addfileprovides(pool, repo, data, s, rpmhead, s->provides);
832   if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
833     s->provides = repo_addid_dep(repo, s->provides, rel2id(pool, s->name, s->evr, REL_EQ, 1), 0);
834   s->requires = makedeps(pool, repo, rpmhead, TAG_REQUIRENAME, TAG_REQUIREVERSION, TAG_REQUIREFLAGS, 0);
835   s->conflicts = makedeps(pool, repo, rpmhead, TAG_CONFLICTNAME, TAG_CONFLICTVERSION, TAG_CONFLICTFLAGS, 0);
836   s->obsoletes = makedeps(pool, repo, rpmhead, TAG_OBSOLETENAME, TAG_OBSOLETEVERSION, TAG_OBSOLETEFLAGS, 0);
837
838   s->recommends = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, 2);
839   s->suggests = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, 1);
840   s->supplements = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, 2);
841   s->enhances  = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, 1);
842   s->supplements = repo_fix_supplements(repo, s->provides, s->supplements, 0);
843   s->conflicts = repo_fix_conflicts(repo, s->conflicts);
844
845   if (data)
846     {
847       Id handle;
848       char *str;
849       unsigned int u32;
850
851       handle = s - pool->solvables;
852       str = headstring(rpmhead, TAG_SUMMARY);
853       if (str)
854         setutf8string(data, handle, SOLVABLE_SUMMARY, str);
855       str = headstring(rpmhead, TAG_DESCRIPTION);
856       if (str)
857         {
858           char *aut, *p;
859           for (aut = str; (aut = strchr(aut, '\n')) != 0; aut++)
860             if (!strncmp(aut, "\nAuthors:\n--------\n", 19))
861               break;
862           if (aut)
863             {
864               /* oh my, found SUSE special author section */
865               int l = aut - str;
866               str = strdup(str);
867               aut = str + l;
868               str[l] = 0;
869               while (l > 0 && str[l - 1] == '\n')
870                 str[--l] = 0;
871               if (l)
872                 setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
873               p = aut + 19;
874               aut = str;        /* copy over */
875               while (*p == ' ' || *p == '\n')
876                 p++;
877               while (*p)
878                 {
879                   if (*p == '\n')
880                     {
881                       *aut++ = *p++;
882                       while (*p == ' ')
883                         p++;
884                       continue;
885                     }
886                   *aut++ = *p++;
887                 }
888               while (aut != str && aut[-1] == '\n')
889                 aut--;
890               *aut = 0;
891               if (*str)
892                 setutf8string(data, handle, SOLVABLE_AUTHORS, str);
893               free(str);
894             }
895           else if (*str)
896             setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
897         }
898       str = headstring(rpmhead, TAG_GROUP);
899       if (str)
900         repodata_set_poolstr(data, handle, SOLVABLE_GROUP, str);
901       str = headstring(rpmhead, TAG_LICENSE);
902       if (str)
903         repodata_set_poolstr(data, handle, SOLVABLE_LICENSE, str);
904       str = headstring(rpmhead, TAG_URL);
905       if (str)
906         repodata_set_str(data, handle, SOLVABLE_URL, str);
907       str = headstring(rpmhead, TAG_DISTRIBUTION);
908       if (str)
909         repodata_set_poolstr(data, handle, SOLVABLE_DISTRIBUTION, str);
910       str = headstring(rpmhead, TAG_PACKAGER);
911       if (str)
912         repodata_set_poolstr(data, handle, SOLVABLE_PACKAGER, str);
913       u32 = headint32(rpmhead, TAG_BUILDTIME);
914       if (u32)
915         repodata_set_num(data, handle, SOLVABLE_BUILDTIME, u32);
916       u32 = headint32(rpmhead, TAG_INSTALLTIME);
917       if (u32)
918         repodata_set_num(data, handle, SOLVABLE_INSTALLTIME, u32);
919       u32 = headint32(rpmhead, TAG_SIZE);
920       if (u32)
921         repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, (u32 + 1023) / 1024);
922       if (sourcerpm)
923         addsourcerpm(pool, data, handle, sourcerpm, name, evr);
924     }
925   sat_free(evr);
926   return 1;
927 }
928
929 static Id
930 copyreldep(Pool *pool, Pool *frompool, Id id)
931 {
932   Reldep *rd = GETRELDEP(frompool, id);
933   Id name = rd->name, evr = rd->evr;
934   if (ISRELDEP(name))
935     name = copyreldep(pool, frompool, name);
936   else
937     name = str2id(pool, id2str(frompool, name), 1);
938   if (ISRELDEP(evr))
939     evr = copyreldep(pool, frompool, evr);
940   else
941     evr = str2id(pool, id2str(frompool, evr), 1);
942   return rel2id(pool, name, evr, rd->flags, 1);
943 }
944
945 static Offset
946 copydeps(Pool *pool, Repo *repo, Offset fromoff, Repo *fromrepo)
947 {
948   int cc;
949   Id id, *ida, *from;
950   Offset ido;
951   Pool *frompool = fromrepo->pool;
952
953   if (!fromoff)
954     return 0;
955   from = fromrepo->idarraydata + fromoff;
956   for (ida = from, cc = 0; *ida; ida++, cc++)
957     ;
958   if (cc == 0)
959     return 0;
960   ido = repo_reserve_ids(repo, 0, cc);
961   ida = repo->idarraydata + ido;
962   if (frompool && pool != frompool)
963     {
964       while (*from)
965         {
966           id = *from++;
967           if (ISRELDEP(id))
968             id = copyreldep(pool, frompool, id);
969           else
970             id = str2id(pool, id2str(frompool, id), 1);
971           *ida++ = id;
972         }
973       *ida = 0;
974     }
975   else
976     memcpy(ida, from, (cc + 1) * sizeof(Id));
977   repo->idarraysize += cc + 1;
978   return ido;
979 }
980
981 #define COPYDIR_DIRCACHE_SIZE 512
982
983 static Id copydir_complex(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache);
984
985 static inline Id
986 copydir(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache)
987 {
988   if (cache && cache[did & 255] == did)
989     return cache[(did & 255) + 256];
990   return copydir_complex(pool, data, fromspool, fromdata, did, cache);
991 }
992
993 static Id
994 copydir_complex(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache)
995 {
996   Id parent = dirpool_parent(&fromdata->dirpool, did);
997   Id compid = dirpool_compid(&fromdata->dirpool, did);
998   if (parent)
999     parent = copydir(pool, data, fromspool, fromdata, parent, cache);
1000   if (fromspool != &pool->ss)
1001     compid = str2id(pool, stringpool_id2str(fromspool, compid), 1);
1002   compid = dirpool_add_dir(&data->dirpool, parent, compid, 1);
1003   if (cache)
1004     {
1005       cache[did & 255] = did;
1006       cache[(did & 255) + 256] = compid;
1007     }
1008   return compid;
1009 }
1010
1011 struct solvable_copy_cbdata {
1012   Repodata *data;
1013   Id handle;
1014   Id *dircache;
1015 };
1016
1017 static int
1018 solvable_copy_cb(void *vcbdata, Solvable *r, Repodata *fromdata, Repokey *key, KeyValue *kv)
1019 {
1020   struct solvable_copy_cbdata *cbdata = vcbdata;
1021   Id id, keyname;
1022   Repodata *data = cbdata->data;
1023   Id handle = cbdata->handle;
1024   Pool *pool = data->repo->pool, *frompool = fromdata->repo->pool;
1025   Stringpool *fromspool = fromdata->localpool ? &fromdata->spool : &frompool->ss;
1026
1027   keyname = key->name;
1028   if (keyname >= ID_NUM_INTERNAL)
1029     keyname = str2id(pool, id2str(frompool, keyname), 1);
1030   switch(key->type)
1031     {
1032     case REPOKEY_TYPE_ID:
1033     case REPOKEY_TYPE_CONSTANTID:
1034       id = kv->id;
1035       assert(!data->localpool); /* implement me! */
1036       if (pool != frompool || fromdata->localpool)
1037         {
1038           if (ISRELDEP(id))
1039             id = copyreldep(pool, frompool, id);
1040           else
1041             id = str2id(pool, stringpool_id2str(fromspool, id), 1);
1042         }
1043       if (key->type == REPOKEY_TYPE_ID)
1044         repodata_set_id(data, handle, keyname, id);
1045       else
1046         repodata_set_constantid(data, handle, keyname, id);
1047       break;
1048     case REPOKEY_TYPE_STR:
1049       repodata_set_str(data, handle, keyname, kv->str);
1050       break;
1051     case REPOKEY_TYPE_VOID:
1052       repodata_set_void(data, handle, keyname);
1053       break;
1054     case REPOKEY_TYPE_NUM:
1055       repodata_set_num(data, handle, keyname, kv->num);
1056       break;
1057     case REPOKEY_TYPE_CONSTANT:
1058       repodata_set_constant(data, handle, keyname, kv->num);
1059       break;
1060     case REPOKEY_TYPE_DIRNUMNUMARRAY:
1061       id = kv->id;
1062       assert(!data->localpool); /* implement me! */
1063       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1064       repodata_add_dirnumnum(data, handle, keyname, id, kv->num, kv->num2);
1065       break;
1066     case REPOKEY_TYPE_DIRSTRARRAY:
1067       id = kv->id;
1068       assert(!data->localpool); /* implement me! */
1069       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1070       repodata_add_dirstr(data, handle, keyname, id, kv->str);
1071       break;
1072     default:
1073       break;
1074     }
1075   return 0;
1076 }
1077
1078 static void
1079 solvable_copy(Solvable *s, Solvable *r, Repodata *data, Id *dircache)
1080 {
1081   Repo *repo = s->repo;
1082   Repo *fromrepo = r->repo;
1083   Pool *pool = repo->pool;
1084   struct solvable_copy_cbdata cbdata;
1085
1086   /* copy solvable data */
1087   if (pool == fromrepo->pool)
1088     {
1089       s->name = r->name;
1090       s->evr = r->evr;
1091       s->arch = r->arch;
1092       s->vendor = r->vendor;
1093     }
1094   else
1095     {
1096       if (r->name)
1097         s->name = str2id(pool, id2str(fromrepo->pool, r->name), 1);
1098       if (r->evr)
1099         s->evr = str2id(pool, id2str(fromrepo->pool, r->evr), 1);
1100       if (r->arch)
1101         s->arch = str2id(pool, id2str(fromrepo->pool, r->arch), 1);
1102       if (r->vendor)
1103         s->vendor = str2id(pool, id2str(fromrepo->pool, r->vendor), 1);
1104     }
1105   s->provides = copydeps(pool, repo, r->provides, fromrepo);
1106   s->requires = copydeps(pool, repo, r->requires, fromrepo);
1107   s->conflicts = copydeps(pool, repo, r->conflicts, fromrepo);
1108   s->obsoletes = copydeps(pool, repo, r->obsoletes, fromrepo);
1109   s->recommends = copydeps(pool, repo, r->recommends, fromrepo);
1110   s->suggests = copydeps(pool, repo, r->suggests, fromrepo);
1111   s->supplements = copydeps(pool, repo, r->supplements, fromrepo);
1112   s->enhances  = copydeps(pool, repo, r->enhances, fromrepo);
1113
1114   /* copy all attributes */
1115   if (!data)
1116     return;
1117   cbdata.data = data;
1118   cbdata.handle = s - pool->solvables;
1119   cbdata.dircache = dircache;
1120   repo_search(fromrepo, (r - fromrepo->pool->solvables), 0, 0, SEARCH_NO_STORAGE_SOLVABLE, solvable_copy_cb, &cbdata);
1121 }
1122
1123 /* used to sort entries returned in some database order */
1124 static int
1125 rpmids_sort_cmp(const void *va, const void *vb, void *dp)
1126 {
1127   struct rpmid const *a = va, *b = vb;
1128   int r;
1129   r = strcmp(a->name, b->name);
1130   if (r)
1131     return r;
1132   return a->dbid - b->dbid;
1133 }
1134
1135 static int
1136 pkgids_sort_cmp(const void *va, const void *vb, void *dp)
1137 {
1138   Repo *repo = dp;
1139   Pool *pool = repo->pool;
1140   Solvable *a = pool->solvables + *(Id *)va;
1141   Solvable *b = pool->solvables + *(Id *)vb;
1142   Id *rpmdbid;
1143
1144   if (a->name != b->name)
1145     return strcmp(id2str(pool, a->name), id2str(pool, b->name));
1146   rpmdbid = repo->rpmdbid;
1147   return rpmdbid[(a - pool->solvables) - repo->start] - rpmdbid[(b - pool->solvables) - repo->start];
1148 }
1149
1150 static void
1151 swap_solvables(Repo *repo, Repodata *data, Id pa, Id pb)
1152 {
1153   Pool *pool = repo->pool;
1154   Solvable tmp;
1155
1156   tmp = pool->solvables[pa];
1157   pool->solvables[pa] = pool->solvables[pb];
1158   pool->solvables[pb] = tmp;
1159   if (repo->rpmdbid)
1160     {
1161       Id tmpid = repo->rpmdbid[pa - repo->start];
1162       repo->rpmdbid[pa - repo->start] = repo->rpmdbid[pb - repo->start];
1163       repo->rpmdbid[pb - repo->start] = tmpid;
1164     }
1165   /* only works if nothing is already internalized! */
1166   if (data && data->attrs)
1167     {
1168       Id *tmpattrs = data->attrs[pa - data->start];
1169       data->attrs[pa - data->start] = data->attrs[pb - data->start];
1170       data->attrs[pb - data->start] = tmpattrs;
1171     }
1172 }
1173
1174 static void
1175 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1176 {
1177   memset(cookie, 0, 32);
1178   cookie[3] = RPMDB_COOKIE_VERSION;
1179   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1180   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1181 }
1182
1183 static int
1184 count_headers(const char *rootdir, DB_ENV *dbenv)
1185 {
1186   char dbpath[PATH_MAX];
1187   struct stat statbuf;
1188   int byteswapped;
1189   DB *db = 0;
1190   DBC *dbc = 0;
1191   int count = 0;
1192   DBT dbkey;
1193   DBT dbdata;
1194
1195   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir);
1196   if (stat(dbpath, &statbuf))
1197     return 0;
1198   memset(&dbkey, 0, sizeof(dbkey));
1199   memset(&dbdata, 0, sizeof(dbdata));
1200   if (db_create(&db, dbenv, 0))
1201     {
1202       perror("db_create");
1203       exit(1);
1204     }
1205   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1206     {
1207       perror("db->open Name index");
1208       exit(1);
1209     }
1210   if (db->get_byteswapped(db, &byteswapped))
1211     {
1212       perror("db->get_byteswapped");
1213       exit(1);
1214     }
1215   if (db->cursor(db, NULL, &dbc, 0))
1216     {
1217       perror("db->cursor");
1218       exit(1);
1219     }
1220   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1221     count += dbdata.size >> 3;
1222   dbc->c_close(dbc);
1223   db->close(db, 0);
1224   return count;
1225 }
1226
1227 /*
1228  * read rpm db as repo
1229  *
1230  */
1231
1232 void
1233 repo_add_rpmdb(Repo *repo, Repo *ref, const char *rootdir, int flags)
1234 {
1235   Pool *pool = repo->pool;
1236   unsigned char buf[16];
1237   DB *db = 0;
1238   DBC *dbc = 0;
1239   int byteswapped;
1240   unsigned int dbid;
1241   unsigned char *dp, *dbidp;
1242   int dl, nrpmids;
1243   struct rpmid *rpmids, *rp;
1244   int i;
1245   int rpmheadsize;
1246   RpmHead *rpmhead;
1247   Solvable *s;
1248   Id id, *refhash;
1249   unsigned int refmask, h;
1250   char dbpath[PATH_MAX];
1251   DB_ENV *dbenv = 0;
1252   DBT dbkey;
1253   DBT dbdata;
1254   struct stat packagesstat;
1255   unsigned char newcookie[32];
1256   const unsigned char *oldcookie = 0;
1257   Id oldcookietype = 0;
1258   Repodata *data;
1259   int count = 0, done = 0;
1260   unsigned int now;
1261
1262   now = sat_timems(0);
1263   memset(&dbkey, 0, sizeof(dbkey));
1264   memset(&dbdata, 0, sizeof(dbdata));
1265
1266   if (!rootdir)
1267     rootdir = "";
1268
1269   if (!(flags & REPO_REUSE_REPODATA))
1270     data = repo_add_repodata(repo, 0);
1271   else
1272     data = repo_last_repodata(repo);
1273
1274   if (ref && !(ref->nsolvables && ref->rpmdbid))
1275     ref = 0;
1276
1277   if (db_env_create(&dbenv, 0))
1278     {
1279       perror("db_env_create");
1280       exit(1);
1281     }
1282   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir);
1283   /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1284 #ifdef FEDORA
1285   if (dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0))
1286 #else
1287   if (dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0))
1288 #endif
1289     {
1290       perror("dbenv open");
1291       exit(1);
1292     }
1293
1294   /* XXX: should get ro lock of Packages database! */
1295   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir);
1296   if (stat(dbpath, &packagesstat))
1297     {
1298       perror(dbpath);
1299       exit(1);
1300     }
1301   mkrpmdbcookie(&packagesstat, newcookie);
1302   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1303
1304   if (ref)
1305     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1306   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1307     {
1308       Id *pkgids;
1309
1310       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1311         count = count_headers(rootdir, dbenv);
1312       if (db_create(&db, dbenv, 0))
1313         {
1314           perror("db_create");
1315           exit(1);
1316         }
1317       if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1318         {
1319           perror("db->open Packages index");
1320           exit(1);
1321         }
1322       if (db->get_byteswapped(db, &byteswapped))
1323         {
1324           perror("db->get_byteswapped");
1325           exit(1);
1326         }
1327       if (db->cursor(db, NULL, &dbc, 0))
1328         {
1329           perror("db->cursor");
1330           exit(1);
1331         }
1332       dbidp = (unsigned char *)&dbid;
1333       rpmheadsize = 0;
1334       rpmhead = 0;
1335       i = 0;
1336       s = 0;
1337       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1338         {
1339           if (!s)
1340             s = pool_id2solvable(pool, repo_add_solvable(repo));
1341           if (!repo->rpmdbid)
1342             repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1343           if (dbkey.size != 4)
1344             {
1345               fprintf(stderr, "corrupt Packages database (key size)\n");
1346               exit(1);
1347             }
1348           dp = dbkey.data;
1349           if (byteswapped)
1350             {
1351               dbidp[0] = dp[3];
1352               dbidp[1] = dp[2];
1353               dbidp[2] = dp[1];
1354               dbidp[3] = dp[0];
1355             }
1356           else
1357             memcpy(dbidp, dp, 4);
1358           if (dbid == 0)                /* the join key */
1359             continue;
1360           if (dbdata.size < 8)
1361             {
1362               fprintf(stderr, "corrupt rpm database (size %u)\n", dbdata.size);
1363               exit(1);
1364             }
1365           if (dbdata.size > rpmheadsize)
1366             {
1367               rpmheadsize = dbdata.size + 128;
1368               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1369             }
1370           memcpy(buf, dbdata.data, 8);
1371           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1372           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1373           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1374             {
1375               fprintf(stderr, "corrupt rpm database (data size)\n");
1376               exit(1);
1377             }
1378           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1379           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1380           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1381           if (rpm2solv(pool, repo, data, s, rpmhead))
1382             {
1383               i++;
1384               s = 0;
1385             }
1386           else
1387             {
1388               /* We can reuse this solvable, but make sure it's still
1389                  associated with this repo.  */
1390               memset(s, 0, sizeof(*s));
1391               s->repo = repo;
1392             }
1393           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1394             {
1395               if (done < count)
1396                 done++;
1397               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1398                 pool_debug(pool, SAT_ERROR, "%%%% %d\n", done * 100 / count);
1399             }
1400         }
1401       if (s)
1402         {
1403           /* oops, could not reuse. free it instead */
1404           repo_free_solvable_block(repo, s - pool->solvables, 1, 1);
1405           s = 0;
1406         }
1407       dbc->c_close(dbc);
1408       db->close(db, 0);
1409       db = 0;
1410       /* now sort all solvables */
1411       if (repo->end - repo->start > 1)
1412         {
1413           pkgids = sat_malloc2(repo->end - repo->start, sizeof(Id));
1414           for (i = repo->start; i < repo->end; i++)
1415             pkgids[i - repo->start] = i;
1416           sat_sort(pkgids, repo->end - repo->start, sizeof(Id), pkgids_sort_cmp, repo);
1417           /* adapt order */
1418           for (i = repo->start; i < repo->end; i++)
1419             {
1420               int j = pkgids[i - repo->start];
1421               while (j < i)
1422                 j = pkgids[i - repo->start] = pkgids[j - repo->start];
1423               if (j != i)
1424                 swap_solvables(repo, data, i, j);
1425             }
1426           sat_free(pkgids);
1427         }
1428     }
1429   else
1430     {
1431       Id dircache[COPYDIR_DIRCACHE_SIZE];               /* see copydir */
1432
1433       memset(dircache, 0, sizeof(dircache));
1434       if (db_create(&db, dbenv, 0))
1435         {
1436           perror("db_create");
1437           exit(1);
1438         }
1439       if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1440         {
1441           perror("db->open Name index");
1442           exit(1);
1443         }
1444       if (db->get_byteswapped(db, &byteswapped))
1445         {
1446           perror("db->get_byteswapped");
1447           exit(1);
1448         }
1449       if (db->cursor(db, NULL, &dbc, 0))
1450         {
1451           perror("db->cursor");
1452           exit(1);
1453         }
1454       dbidp = (unsigned char *)&dbid;
1455       nrpmids = 0;
1456       rpmids = 0;
1457       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1458         {
1459           if (dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1460             continue;
1461           dl = dbdata.size;
1462           dp = dbdata.data;
1463           while(dl >= 8)
1464             {
1465               if (byteswapped)
1466                 {
1467                   dbidp[0] = dp[3];
1468                   dbidp[1] = dp[2];
1469                   dbidp[2] = dp[1];
1470                   dbidp[3] = dp[0];
1471                 }
1472               else
1473                 memcpy(dbidp, dp, 4);
1474               rpmids = sat_extend(rpmids, nrpmids, 1, sizeof(*rpmids), 255);
1475               rpmids[nrpmids].dbid = dbid;
1476               rpmids[nrpmids].name = sat_malloc((int)dbkey.size + 1);
1477               memcpy(rpmids[nrpmids].name, dbkey.data, (int)dbkey.size);
1478               rpmids[nrpmids].name[(int)dbkey.size] = 0;
1479               nrpmids++;
1480               dp += 8;
1481               dl -= 8;
1482             }
1483         }
1484       dbc->c_close(dbc);
1485       db->close(db, 0);
1486       db = 0;
1487
1488       /* sort rpmids */
1489       sat_sort(rpmids, nrpmids, sizeof(*rpmids), rpmids_sort_cmp, 0);
1490
1491       dbidp = (unsigned char *)&dbid;
1492       rpmheadsize = 0;
1493       rpmhead = 0;
1494
1495       /* create hash from dbid to ref */
1496       refmask = mkmask(ref->nsolvables);
1497       refhash = sat_calloc(refmask + 1, sizeof(Id));
1498       for (i = 0; i < ref->end - ref->start; i++)
1499         {
1500           if (!ref->rpmdbid[i])
1501             continue;
1502           h = ref->rpmdbid[i] & refmask;
1503           while (refhash[h])
1504             h = (h + 317) & refmask;
1505           refhash[h] = i + 1;   /* make it non-zero */
1506         }
1507
1508       /* count the misses, they will cost us time */
1509       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1510         {
1511           for (i = 0, rp = rpmids; i < nrpmids; i++, rp++)
1512             {
1513               dbid = rp->dbid;
1514               if (refhash)
1515                 {
1516                   h = dbid & refmask;
1517                   while ((id = refhash[h]))
1518                     {
1519                       if (ref->rpmdbid[id - 1] == dbid)
1520                         break;
1521                       h = (h + 317) & refmask;
1522                     }
1523                   if (id)
1524                     continue;
1525                 }
1526               count++;
1527             }
1528         }
1529
1530       s = pool_id2solvable(pool, repo_add_solvable_block(repo, nrpmids));
1531       if (!repo->rpmdbid)
1532         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1533
1534       for (i = 0, rp = rpmids; i < nrpmids; i++, rp++, s++)
1535         {
1536           dbid = rp->dbid;
1537           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1538           if (refhash)
1539             {
1540               h = dbid & refmask;
1541               while ((id = refhash[h]))
1542                 {
1543                   if (ref->rpmdbid[id - 1] == dbid)
1544                     break;
1545                   h = (h + 317) & refmask;
1546                 }
1547               if (id)
1548                 {
1549                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1550                   if (r->repo == ref)
1551                     {
1552                       solvable_copy(s, r, data, dircache);
1553                       continue;
1554                     }
1555                 }
1556             }
1557           if (!db)
1558             {
1559               if (db_create(&db, dbenv, 0))
1560                 {
1561                   perror("db_create");
1562                   exit(1);
1563                 }
1564               if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1565                 {
1566                   perror("db->open var/lib/rpm/Packages");
1567                   exit(1);
1568                 }
1569               if (db->get_byteswapped(db, &byteswapped))
1570                 {
1571                   perror("db->get_byteswapped");
1572                   exit(1);
1573                 }
1574             }
1575           if (byteswapped)
1576             {
1577               buf[0] = dbidp[3];
1578               buf[1] = dbidp[2];
1579               buf[2] = dbidp[1];
1580               buf[3] = dbidp[0];
1581             }
1582           else
1583             memcpy(buf, dbidp, 4);
1584           dbkey.data = buf;
1585           dbkey.size = 4;
1586           dbdata.data = 0;
1587           dbdata.size = 0;
1588           if (db->get(db, NULL, &dbkey, &dbdata, 0))
1589             {
1590               perror("db->get");
1591               fprintf(stderr, "corrupt rpm database, key %d not found\n", dbid);
1592               fprintf(stderr, "please run 'rpm --rebuilddb' to recreate the database index files\n");
1593               exit(1);
1594             }
1595           if (dbdata.size < 8)
1596             {
1597               fprintf(stderr, "corrupt rpm database (size)\n");
1598               exit(1);
1599             }
1600           if (dbdata.size > rpmheadsize)
1601             {
1602               rpmheadsize = dbdata.size + 128;
1603               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1604             }
1605           memcpy(buf, dbdata.data, 8);
1606           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1607           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1608           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1609             {
1610               fprintf(stderr, "corrupt rpm database (data size)\n");
1611               exit(1);
1612             }
1613           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1614           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1615
1616           rpm2solv(pool, repo, data, s, rpmhead);
1617           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1618             {
1619               if (done < count)
1620                 done++;
1621               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1622                 pool_debug(pool, SAT_ERROR, "%%%% %d\n", done * 100 / count);
1623             }
1624         }
1625
1626       if (refhash)
1627         sat_free(refhash);
1628       if (rpmids)
1629         {
1630           for (i = 0; i < nrpmids; i++)
1631             sat_free(rpmids[i].name);
1632           sat_free(rpmids);
1633         }
1634     }
1635   if (db)
1636     db->close(db, 0);
1637   dbenv->close(dbenv, 0);
1638   if (rpmhead)
1639     sat_free(rpmhead);
1640   if (!(flags & REPO_NO_INTERNALIZE))
1641     repodata_internalize(data);
1642   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1643     pool_debug(pool, SAT_ERROR, "%%%% 100\n");
1644   POOL_DEBUG(SAT_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", sat_timems(now));
1645   POOL_DEBUG(SAT_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1646   POOL_DEBUG(SAT_DEBUG_STATS, "repo memory used: %d K incore, %d K idarray\n", data->incoredatalen/1024, repo->idarraysize / (int)(1024/sizeof(Id)));
1647 }
1648
1649
1650 static inline unsigned int
1651 getu32(unsigned char *dp)
1652 {
1653   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1654 }
1655
1656
1657 void
1658 repo_add_rpms(Repo *repo, const char **rpms, int nrpms, int flags)
1659 {
1660   int i, sigdsize, sigcnt, l;
1661   Pool *pool = repo->pool;
1662   Solvable *s;
1663   RpmHead *rpmhead = 0;
1664   int rpmheadsize = 0;
1665   char *payloadformat;
1666   FILE *fp;
1667   unsigned char lead[4096];
1668   int headerstart, headerend;
1669   struct stat stb;
1670   Repodata *data;
1671
1672   if (!(flags & REPO_REUSE_REPODATA))
1673     data = repo_add_repodata(repo, 0);
1674   else
1675     data = repo_last_repodata(repo);
1676
1677   if (nrpms <= 0)
1678     return;
1679
1680   for (i = 0; i < nrpms; i++)
1681     {
1682       if ((fp = fopen(rpms[i], "r")) == 0)
1683         {
1684           perror(rpms[i]);
1685           continue;
1686         }
1687       if (fstat(fileno(fp), &stb))
1688         {
1689           perror("stat");
1690           continue;
1691         }
1692       if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1693         {
1694           fprintf(stderr, "%s: not a rpm\n", rpms[i]);
1695           fclose(fp);
1696           continue;
1697         }
1698       if (lead[78] != 0 || lead[79] != 5)
1699         {
1700           fprintf(stderr, "%s: not a V5 header\n", rpms[i]);
1701           fclose(fp);
1702           continue;
1703         }
1704       if (getu32(lead + 96) != 0x8eade801)
1705         {
1706           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1707           fclose(fp);
1708           continue;
1709         }
1710       sigcnt = getu32(lead + 96 + 8);
1711       sigdsize = getu32(lead + 96 + 12);
1712       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1713         {
1714           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1715           fclose(fp);
1716           continue;
1717         }
1718       sigdsize += sigcnt * 16;
1719       sigdsize = (sigdsize + 7) & ~7;
1720       headerstart = 96 + 16 + sigdsize;
1721       while (sigdsize)
1722         {
1723           l = sigdsize > 4096 ? 4096 : sigdsize;
1724           if (fread(lead, l, 1, fp) != 1)
1725             {
1726               fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1727               fclose(fp);
1728               continue;
1729             }
1730           sigdsize -= l;
1731         }
1732       if (fread(lead, 16, 1, fp) != 1)
1733         {
1734           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1735           fclose(fp);
1736           continue;
1737         }
1738       if (getu32(lead) != 0x8eade801)
1739         {
1740           fprintf(stderr, "%s: bad header\n", rpms[i]);
1741           fclose(fp);
1742           continue;
1743         }
1744       sigcnt = getu32(lead + 8);
1745       sigdsize = getu32(lead + 12);
1746       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1747         {
1748           fprintf(stderr, "%s: bad header\n", rpms[i]);
1749           fclose(fp);
1750           continue;
1751         }
1752       l = sigdsize + sigcnt * 16;
1753       headerend = headerstart + 16 + l;
1754       if (l > rpmheadsize)
1755         {
1756           rpmheadsize = l + 128;
1757           rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1758         }
1759       if (fread(rpmhead->data, l, 1, fp) != 1)
1760         {
1761           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1762           fclose(fp);
1763           continue;
1764         }
1765       rpmhead->cnt = sigcnt;
1766       rpmhead->dcnt = sigdsize;
1767       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1768       if (headexists(rpmhead, TAG_PATCHESNAME))
1769         {
1770           /* this is a patch rpm, ignore */
1771           fclose(fp);
1772           continue;
1773         }
1774       payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
1775       if (payloadformat && !strcmp(payloadformat, "drpm"))
1776         {
1777           /* this is a delta rpm */
1778           fclose(fp);
1779           continue;
1780         }
1781       fclose(fp);
1782       s = pool_id2solvable(pool, repo_add_solvable(repo));
1783       rpm2solv(pool, repo, data, s, rpmhead);
1784       if (data)
1785         {
1786           Id handle = s - pool->solvables;
1787           repodata_set_location(data, handle, 0, 0, rpms[i]);
1788           repodata_set_num(data, handle, SOLVABLE_DOWNLOADSIZE, (unsigned int)((stb.st_size + 1023) / 1024));
1789           repodata_set_num(data, handle, SOLVABLE_HEADEREND, headerend);
1790         }
1791     }
1792   if (rpmhead)
1793     sat_free(rpmhead);
1794   if (!(flags & REPO_NO_INTERNALIZE))
1795     repodata_internalize(data);
1796 }
1797
1798 static inline void
1799 linkhash(const char *lt, char *hash)
1800 {
1801   unsigned int r = 0;
1802   const unsigned char *str = (const unsigned char *)lt;
1803   int l, c;
1804
1805   l = strlen(lt);
1806   while ((c = *str++) != 0)
1807     r += (r << 3) + c;
1808   sprintf(hash, "%08x", r);
1809   sprintf(hash + 8, "%08x", l);
1810   sprintf(hash + 16, "%08x", 0);
1811   sprintf(hash + 24, "%08x", 0);
1812 }
1813
1814 void
1815 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, int, const char *), void *cbdata)
1816 {
1817   RpmHead *rpmhead = rpmhandle;
1818   char **bn;
1819   char **dn;
1820   char **md = 0;
1821   char **lt = 0;
1822   unsigned int *di, diidx;
1823   unsigned int lastdir;
1824   int lastdirl;
1825   unsigned int *fm;
1826   int cnt, dcnt, cnt2;
1827   int i, l1, l;
1828   char *space = 0;
1829   int spacen = 0;
1830   char md5[33], *md5p = 0;
1831
1832   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
1833   if (!dn)
1834     return;
1835   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
1836     {
1837       for (i = 0; i < dcnt; i++)
1838         (*cb)(cbdata, dn[i], 0, (char *)0);
1839       sat_free(dn);
1840       return;
1841     }
1842   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
1843   if (!bn)
1844     {
1845       sat_free(dn);
1846       return;
1847     }
1848   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
1849   if (!di || cnt != cnt2)
1850     {
1851       sat_free(di);
1852       sat_free(bn);
1853       sat_free(dn);
1854       return;
1855     }
1856   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
1857   if (!fm || cnt != cnt2)
1858     {
1859       sat_free(fm);
1860       sat_free(di);
1861       sat_free(bn);
1862       sat_free(dn);
1863       return;
1864     }
1865   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
1866     {
1867       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
1868       if (!md || cnt != cnt2)
1869         {
1870           sat_free(md);
1871           sat_free(fm);
1872           sat_free(di);
1873           sat_free(bn);
1874           sat_free(dn);
1875           return;
1876         }
1877     }
1878   lastdir = dcnt;
1879   lastdirl = 0;
1880   for (i = 0; i < cnt; i++)
1881     {
1882       diidx = di[i];
1883       if (diidx >= dcnt)
1884         continue;
1885       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
1886       if (l1 == 0)
1887         continue;
1888       l = l1 + strlen(bn[i]) + 1;
1889       if (l > spacen)
1890         {
1891           spacen = l + 16;
1892           space = sat_realloc(space, spacen);
1893         }
1894       if (lastdir != diidx)
1895         {
1896           strcpy(space, dn[diidx]);
1897           lastdir = diidx;
1898           lastdirl = l1;
1899         }
1900       strcpy(space + l1, bn[i]);
1901       if (md)
1902         {
1903           md5p = md[i];
1904           if (S_ISLNK(fm[i]))
1905             {
1906               md5p = 0;
1907               if (!lt)
1908                 {
1909                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
1910                   if (cnt != cnt2)
1911                     lt = sat_free(lt);
1912                 }
1913               if (lt)
1914                 {
1915                   linkhash(lt[i], md5);
1916                   md5p = md5;
1917                 }
1918             }
1919           if (!md5p)
1920             md5p = "";
1921         }
1922       (*cb)(cbdata, space, fm[i], md5p);
1923     }
1924   sat_free(space);
1925   sat_free(lt);
1926   sat_free(md);
1927   sat_free(fm);
1928   sat_free(di);
1929   sat_free(bn);
1930   sat_free(dn);
1931 }
1932
1933
1934 struct rpm_by_state {
1935   RpmHead *rpmhead;
1936   int rpmheadsize;
1937
1938   int dbopened;
1939   DB_ENV *dbenv;
1940   DB *db;
1941   int byteswapped;
1942 };
1943
1944 int
1945 rpm_installedrpmdbids(const char *rootdir, Queue *rpmdbidq)
1946 {
1947   char dbpath[PATH_MAX];
1948   DB_ENV *dbenv = 0;
1949   DB *db = 0;
1950   DBC *dbc = 0;
1951   int byteswapped;
1952   DBT dbkey;
1953   DBT dbdata;
1954   Id rpmdbid;
1955   unsigned char *dp;
1956   int dl, cnt;
1957
1958   if (rpmdbidq)
1959     queue_empty(rpmdbidq);
1960   cnt = 0;
1961
1962   if (db_env_create(&dbenv, 0))
1963     {
1964       perror("db_env_create");
1965       return 0;
1966     }
1967   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1968 #ifdef FEDORA
1969   if (dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0))
1970 #else
1971   if (dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0))
1972 #endif
1973     {
1974       perror("dbenv open");
1975       dbenv->close(dbenv, 0);
1976       return 0;
1977     }
1978   if (db_create(&db, dbenv, 0))
1979     {
1980       perror("db_create");
1981       dbenv->close(dbenv, 0);
1982       return 0;
1983     }
1984   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1985     {
1986       perror("db->open Name index");
1987       db->close(db, 0);
1988       dbenv->close(dbenv, 0);
1989       return 0;
1990     }
1991   if (db->get_byteswapped(db, &byteswapped))
1992     {
1993       perror("db->get_byteswapped");
1994       db->close(db, 0);
1995       dbenv->close(dbenv, 0);
1996       return 0;
1997     }
1998   if (db->cursor(db, NULL, &dbc, 0))
1999     {
2000       perror("db->cursor");
2001       db->close(db, 0);
2002       dbenv->close(dbenv, 0);
2003       return 0;
2004     }
2005   memset(&dbkey, 0, sizeof(dbkey));
2006   memset(&dbdata, 0, sizeof(dbdata));
2007   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
2008     {
2009       if (dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
2010         continue;
2011       dl = dbdata.size;
2012       dp = dbdata.data;
2013       while(dl >= 8)
2014         {
2015           if (byteswapped)
2016             {
2017               ((char *)&rpmdbid)[0] = dp[3];
2018               ((char *)&rpmdbid)[1] = dp[2];
2019               ((char *)&rpmdbid)[2] = dp[1];
2020               ((char *)&rpmdbid)[3] = dp[0];
2021             }
2022           else
2023             memcpy((char *)&rpmdbid, dp, 4);
2024           if (rpmdbidq)
2025             queue_push(rpmdbidq, rpmdbid);
2026           cnt++;
2027           dp += 8;
2028           dl -= 8;
2029         }
2030     }
2031   dbc->c_close(dbc);
2032   db->close(db, 0);
2033   dbenv->close(dbenv, 0);
2034   return cnt;
2035 }
2036
2037 void *
2038 rpm_byrpmdbid(Id rpmdbid, const char *rootdir, void **statep)
2039 {
2040   struct rpm_by_state *state = *statep;
2041   unsigned char buf[16];
2042   DBT dbkey;
2043   DBT dbdata;
2044   RpmHead *rpmhead;
2045
2046   if (!rpmdbid)
2047     {
2048       /* close down */
2049       if (!state)
2050         return 0;
2051       if (state->db)
2052         state->db->close(state->db, 0);
2053       if (state->dbenv)
2054         state->dbenv->close(state->dbenv, 0);
2055       sat_free(state->rpmhead);
2056       sat_free(state);
2057       *statep = (void *)0;
2058       return 0;
2059     }
2060
2061   if (!state)
2062     {
2063       state = sat_calloc(1, sizeof(*state));
2064       *statep = state;
2065     }
2066   if (!state->dbopened)
2067     {
2068       char dbpath[PATH_MAX];
2069       state->dbopened = 1;
2070       if (db_env_create(&state->dbenv, 0))
2071         {
2072           perror("db_env_create");
2073           state->dbenv = 0;
2074           return 0;
2075         }
2076       if (!rootdir)
2077         rootdir = "";
2078       snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir);
2079 #ifdef FEDORA
2080       if (state->dbenv->open(state->dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0))
2081 #else
2082       if (state->dbenv->open(state->dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0))
2083 #endif
2084         {
2085           perror("dbenv open");
2086           state->dbenv->close(state->dbenv, 0);
2087           state->dbenv = 0;
2088           return 0;
2089         }
2090       if (db_create(&state->db, state->dbenv, 0))
2091         {
2092           perror("db_create");
2093           state->db = 0;
2094           state->dbenv->close(state->dbenv, 0);
2095           state->dbenv = 0;
2096           return 0;
2097         }
2098       if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
2099         {
2100           perror("db->open var/lib/rpm/Packages");
2101           state->db->close(state->db, 0);
2102           state->db = 0;
2103           state->dbenv->close(state->dbenv, 0);
2104           state->dbenv = 0;
2105           return 0;
2106         }
2107       if (state->db->get_byteswapped(state->db, &state->byteswapped))
2108         {
2109           perror("db->get_byteswapped");
2110           state->db->close(state->db, 0);
2111           state->db = 0;
2112           state->dbenv->close(state->dbenv, 0);
2113           state->dbenv = 0;
2114           return 0;
2115         }
2116     }
2117   memcpy(buf, &rpmdbid, 4);
2118   if (state->byteswapped)
2119     {
2120       unsigned char bx;
2121       bx = buf[0]; buf[0] = buf[3]; buf[3] = bx;
2122       bx = buf[1]; buf[1] = buf[2]; buf[2] = bx;
2123     }
2124   memset(&dbkey, 0, sizeof(dbkey));
2125   memset(&dbdata, 0, sizeof(dbdata));
2126   dbkey.data = buf;
2127   dbkey.size = 4;
2128   dbdata.data = 0;
2129   dbdata.size = 0;
2130   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
2131     {
2132       perror("db->get");
2133       return 0;
2134     }
2135   if (dbdata.size < 8)
2136     {
2137       fprintf(stderr, "corrupt rpm database (size)\n");
2138       return 0;
2139     }
2140   if (dbdata.size > state->rpmheadsize)
2141     {
2142       state->rpmheadsize = dbdata.size + 128;
2143       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
2144     }
2145   rpmhead = state->rpmhead;
2146   memcpy(buf, dbdata.data, 8);
2147   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
2148   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
2149   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
2150     {
2151       fprintf(stderr, "corrupt rpm database (data size)\n");
2152       return 0;
2153     }
2154   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
2155   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2156   return rpmhead;
2157 }
2158  
2159 void *
2160 rpm_byfp(FILE *fp, const char *name, void **statep)
2161 {
2162   struct rpm_by_state *state = *statep;
2163   int headerstart, headerend;
2164   RpmHead *rpmhead;
2165   int sigdsize, sigcnt, l;
2166   unsigned char lead[4096];
2167
2168   if (!fp)
2169     return rpm_byrpmdbid(0, 0, statep);
2170   if (!state)
2171     {
2172       state = sat_calloc(1, sizeof(*state));
2173       *statep = state;
2174     }
2175   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2176     {
2177       fprintf(stderr, "%s: not a rpm\n", name);
2178       return 0;
2179     }
2180   if (lead[78] != 0 || lead[79] != 5)
2181     {
2182       fprintf(stderr, "%s: not a V5 header\n", name);
2183       return 0;
2184     }
2185   if (getu32(lead + 96) != 0x8eade801)
2186     {
2187       fprintf(stderr, "%s: bad signature header\n", name);
2188       return 0;
2189     }
2190   sigcnt = getu32(lead + 96 + 8);
2191   sigdsize = getu32(lead + 96 + 12);
2192   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2193     {
2194       fprintf(stderr, "%s: bad signature header\n", name);
2195       return 0;
2196     }
2197   sigdsize += sigcnt * 16;
2198   sigdsize = (sigdsize + 7) & ~7;
2199   headerstart = 96 + 16 + sigdsize;
2200   while (sigdsize)
2201     {
2202       l = sigdsize > 4096 ? 4096 : sigdsize;
2203       if (fread(lead, l, 1, fp) != 1)
2204         {
2205           fprintf(stderr, "%s: unexpected EOF\n", name);
2206           return 0;
2207         }
2208       sigdsize -= l;
2209     }
2210   if (fread(lead, 16, 1, fp) != 1)
2211     {
2212       fprintf(stderr, "%s: unexpected EOF\n", name);
2213       return 0;
2214     }
2215   if (getu32(lead) != 0x8eade801)
2216     {
2217       fprintf(stderr, "%s: bad header\n", name);
2218       fclose(fp);
2219       return 0;
2220     }
2221   sigcnt = getu32(lead + 8);
2222   sigdsize = getu32(lead + 12);
2223   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2224     {
2225       fprintf(stderr, "%s: bad header\n", name);
2226       fclose(fp);
2227       return 0;
2228     }
2229   l = sigdsize + sigcnt * 16;
2230   headerend = headerstart + 16 + l;
2231   if (l > state->rpmheadsize)
2232     {
2233       state->rpmheadsize = l + 128;
2234       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2235     }
2236   rpmhead = state->rpmhead;
2237   if (fread(rpmhead->data, l, 1, fp) != 1)
2238     {
2239       fprintf(stderr, "%s: unexpected EOF\n", name);
2240       fclose(fp);
2241       return 0;
2242     }
2243   rpmhead->cnt = sigcnt;
2244   rpmhead->dcnt = sigdsize;
2245   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2246   return rpmhead;
2247 }
2248