- fix trigger copying, make rpmdbid handling nicer
[platform/upstream/libsolv.git] / ext / 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 #include <stdint.h>
25
26 #include <rpm/rpmio.h>
27 #include <rpm/rpmpgp.h>
28 #ifndef RPM5
29 #include <rpm/header.h>
30 #endif
31 #include <rpm/rpmdb.h>
32
33 #ifndef DB_CREATE
34 # ifdef FEDORA
35 #  include <db.h>
36 # else
37 #  include <rpm/db.h>
38 # endif
39 #endif
40
41 #include "pool.h"
42 #include "repo.h"
43 #include "hash.h"
44 #include "util.h"
45 #include "queue.h"
46 #include "chksum.h"
47 #include "repo_rpmdb.h"
48
49 /* 3: added triggers */
50 /* 4: fixed triggers */
51 #define RPMDB_COOKIE_VERSION 4
52
53 #define TAG_NAME                1000
54 #define TAG_VERSION             1001
55 #define TAG_RELEASE             1002
56 #define TAG_EPOCH               1003
57 #define TAG_SUMMARY             1004
58 #define TAG_DESCRIPTION         1005
59 #define TAG_BUILDTIME           1006
60 #define TAG_BUILDHOST           1007
61 #define TAG_INSTALLTIME         1008
62 #define TAG_SIZE                1009
63 #define TAG_DISTRIBUTION        1010
64 #define TAG_VENDOR              1011
65 #define TAG_LICENSE             1014
66 #define TAG_PACKAGER            1015
67 #define TAG_GROUP               1016
68 #define TAG_URL                 1020
69 #define TAG_ARCH                1022
70 #define TAG_FILESIZES           1028
71 #define TAG_FILEMODES           1030
72 #define TAG_FILEMD5S            1035
73 #define TAG_FILELINKTOS         1036
74 #define TAG_SOURCERPM           1044
75 #define TAG_PROVIDENAME         1047
76 #define TAG_REQUIREFLAGS        1048
77 #define TAG_REQUIRENAME         1049
78 #define TAG_REQUIREVERSION      1050
79 #define TAG_NOSOURCE            1051
80 #define TAG_NOPATCH             1052
81 #define TAG_CONFLICTFLAGS       1053
82 #define TAG_CONFLICTNAME        1054
83 #define TAG_CONFLICTVERSION     1055
84 #define TAG_TRIGGERNAME         1066
85 #define TAG_TRIGGERVERSION      1067
86 #define TAG_TRIGGERFLAGS        1068
87 #define TAG_OBSOLETENAME        1090
88 #define TAG_FILEDEVICES         1095
89 #define TAG_FILEINODES          1096
90 #define TAG_PROVIDEFLAGS        1112
91 #define TAG_PROVIDEVERSION      1113
92 #define TAG_OBSOLETEFLAGS       1114
93 #define TAG_OBSOLETEVERSION     1115
94 #define TAG_DIRINDEXES          1116
95 #define TAG_BASENAMES           1117
96 #define TAG_DIRNAMES            1118
97 #define TAG_PAYLOADFORMAT       1124
98 #define TAG_PATCHESNAME         1133
99 #define TAG_FILECOLORS          1140
100 #define TAG_SUGGESTSNAME        1156
101 #define TAG_SUGGESTSVERSION     1157
102 #define TAG_SUGGESTSFLAGS       1158
103 #define TAG_ENHANCESNAME        1159
104 #define TAG_ENHANCESVERSION     1160
105 #define TAG_ENHANCESFLAGS       1161
106
107 #define SIGTAG_SIZE             1000
108 #define SIGTAG_PGP              1002    /* RSA signature */
109 #define SIGTAG_MD5              1004    /* header+payload md5 checksum */
110 #define SIGTAG_GPG              1005    /* DSA signature */
111
112 #define DEP_LESS                (1 << 1)
113 #define DEP_GREATER             (1 << 2)
114 #define DEP_EQUAL               (1 << 3)
115 #define DEP_STRONG              (1 << 27)
116 #define DEP_PRE                 ((1 << 6) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 12))
117
118
119 #ifdef RPM5
120 # define RPM_INDEX_SIZE 4
121 #else
122 # define RPM_INDEX_SIZE 8
123 #endif
124
125 struct rpmid {
126   unsigned int dbid;
127   char *name;
128 };
129
130 typedef struct rpmhead {
131   int cnt;
132   int dcnt;
133   unsigned char *dp;
134   unsigned char data[1];
135 } RpmHead;
136
137
138 static inline unsigned char *
139 headfindtag(RpmHead *h, int tag)
140 {
141   unsigned int i;
142   unsigned char *d, taga[4];
143   d = h->dp - 16;
144   taga[0] = tag >> 24;
145   taga[1] = tag >> 16;
146   taga[2] = tag >> 8;
147   taga[3] = tag;
148   for (i = 0; i < h->cnt; i++, d -= 16)
149     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
150       return d;
151   return 0;
152 }
153
154 static int
155 headexists(RpmHead *h, int tag)
156 {
157   return headfindtag(h, tag) ? 1 : 0;
158 }
159
160 static unsigned int *
161 headint32array(RpmHead *h, int tag, int *cnt)
162 {
163   unsigned int i, o, *r;
164   unsigned char *d = headfindtag(h, tag);
165
166   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
167     return 0;
168   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
169   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
170   if (o + 4 * i > h->dcnt)
171     return 0;
172   d = h->dp + o;
173   r = sat_calloc(i ? i : 1, sizeof(unsigned int));
174   if (cnt)
175     *cnt = i;
176   for (o = 0; o < i; o++, d += 4)
177     r[o] = d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
178   return r;
179 }
180
181 /* returns the first entry of an integer array */
182 static unsigned int
183 headint32(RpmHead *h, int tag)
184 {
185   unsigned int i, o;
186   unsigned char *d = headfindtag(h, tag);
187
188   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
189     return 0;
190   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
191   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
192   if (i == 0 || o + 4 * i > h->dcnt)
193     return 0;
194   d = h->dp + o;
195   return d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
196 }
197
198 static unsigned int *
199 headint16array(RpmHead *h, int tag, int *cnt)
200 {
201   unsigned int i, o, *r;
202   unsigned char *d = headfindtag(h, tag);
203
204   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 3)
205     return 0;
206   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
207   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
208   if (o + 4 * i > h->dcnt)
209     return 0;
210   d = h->dp + o;
211   r = sat_calloc(i ? i : 1, sizeof(unsigned int));
212   if (cnt)
213     *cnt = i;
214   for (o = 0; o < i; o++, d += 2)
215     r[o] = d[0] << 8 | d[1];
216   return r;
217 }
218
219 static char *
220 headstring(RpmHead *h, int tag)
221 {
222   unsigned int o;
223   unsigned char *d = headfindtag(h, tag);
224   /* 6: STRING, 9: I18NSTRING */
225   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || (d[7] != 6 && d[7] != 9))
226     return 0;
227   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
228   if (o >= h->dcnt)
229     return 0;
230   return (char *)h->dp + o;
231 }
232
233 static char **
234 headstringarray(RpmHead *h, int tag, int *cnt)
235 {
236   unsigned int i, o;
237   unsigned char *d = headfindtag(h, tag);
238   char **r;
239
240   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 8)
241     return 0;
242   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
243   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
244   r = sat_calloc(i ? i : 1, sizeof(char *));
245   if (cnt)
246     *cnt = i;
247   d = h->dp + o;
248   for (o = 0; o < i; o++)
249     {
250       r[o] = (char *)d;
251       if (o + 1 < i)
252         d += strlen((char *)d) + 1;
253       if (d >= h->dp + h->dcnt)
254         {
255           sat_free(r);
256           return 0;
257         }
258     }
259   return r;
260 }
261
262 static unsigned char *
263 headbinary(RpmHead *h, int tag, unsigned int *sizep)
264 {
265   unsigned int i, o;
266   unsigned char *d = headfindtag(h, tag);
267   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 7)
268     return 0;
269   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
270   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
271   if (o > h->dcnt || o + i < o || o + i > h->dcnt)
272     return 0;
273   if (sizep)
274     *sizep = i;
275   return h->dp + o;
276 }
277
278 static char *headtoevr(RpmHead *h)
279 {
280   unsigned int epoch;
281   char *version, *v;
282   char *release;
283   char *evr;
284
285   version  = headstring(h, TAG_VERSION);
286   release  = headstring(h, TAG_RELEASE);
287   epoch = headint32(h, TAG_EPOCH);
288   if (!version || !release)
289     {
290       fprintf(stderr, "headtoevr: bad rpm header\n");
291       exit(1);
292     }
293   for (v = version; *v >= 0 && *v <= '9'; v++)
294     ;
295   if (epoch || (v != version && *v == ':'))
296     {
297       char epochbuf[11];        /* 32bit decimal will fit in */
298       sprintf(epochbuf, "%u", epoch);
299       evr = sat_malloc(strlen(epochbuf) + 1 + strlen(version) + 1 + strlen(release) + 1);
300       sprintf(evr, "%s:%s-%s", epochbuf, version, release);
301     }
302   else
303     {
304       evr = sat_malloc(strlen(version) + 1 + strlen(release) + 1);
305       sprintf(evr, "%s-%s", version, release);
306     }
307   return evr;
308 }
309
310
311 static void
312 setutf8string(Repodata *repodata, Id handle, Id tag, const char *str)
313 {
314   const unsigned char *cp;
315   int state = 0;
316   int c;
317   unsigned char *buf = 0, *bp;
318
319   /* check if it's already utf8, code taken from screen ;-) */
320   cp = (const unsigned char *)str;
321   while ((c = *cp++) != 0)
322     {
323       if (state)
324         {
325           if ((c & 0xc0) != 0x80)
326             break; /* encoding error */
327           c = (c & 0x3f) | (state << 6);
328           if (!(state & 0x40000000))
329             {
330               /* check for overlong sequences */
331               if ((c & 0x820823e0) == 0x80000000)
332                 c = 0xfdffffff;
333               else if ((c & 0x020821f0) == 0x02000000)
334                 c = 0xfff7ffff;
335               else if ((c & 0x000820f8) == 0x00080000)
336                 c = 0xffffd000;
337               else if ((c & 0x0000207c) == 0x00002000)
338                 c = 0xffffff70;
339             }
340         }
341       else
342         {
343           /* new sequence */
344           if (c >= 0xfe)
345             break;
346           else if (c >= 0xfc)
347             c = (c & 0x01) | 0xbffffffc;    /* 5 bytes to follow */
348           else if (c >= 0xf8)
349             c = (c & 0x03) | 0xbfffff00;    /* 4 */
350           else if (c >= 0xf0)
351             c = (c & 0x07) | 0xbfffc000;    /* 3 */
352           else if (c >= 0xe0)
353             c = (c & 0x0f) | 0xbff00000;    /* 2 */
354           else if (c >= 0xc2)
355             c = (c & 0x1f) | 0xfc000000;    /* 1 */
356           else if (c >= 0x80)
357             break;
358         }
359       state = (c & 0x80000000) ? c : 0;
360     }
361   if (c)
362     {
363       /* not utf8, assume latin1 */
364       buf = sat_malloc(2 * strlen(str) + 1);
365       cp = (const unsigned char *)str;
366       str = (char *)buf;
367       bp = buf;
368       while ((c = *cp++) != 0)
369         {
370           if (c >= 0xc0)
371             {
372               *bp++ = 0xc3;
373               c ^= 0x80;
374             }
375           else if (c >= 0x80)
376             *bp++ = 0xc2;
377           *bp++ = c;
378         }
379       *bp++ = 0;
380     }
381   repodata_set_str(repodata, handle, tag, str);
382   if (buf)
383     sat_free(buf);
384 }
385
386
387 #define MAKEDEPS_FILTER_WEAK    (1 << 0)
388 #define MAKEDEPS_FILTER_STRONG  (1 << 1)
389 #define MAKEDEPS_NO_RPMLIB      (1 << 2)
390
391 /*
392  * strong: 0: ignore strongness
393  *         1: filter to strong
394  *         2: filter to weak
395  */
396 static unsigned int
397 makedeps(Pool *pool, Repo *repo, RpmHead *rpmhead, int tagn, int tagv, int tagf, int flags)
398 {
399   char **n, **v;
400   unsigned int *f;
401   int i, cc, nc, vc, fc;
402   int haspre;
403   unsigned int olddeps;
404   Id *ida;
405   int strong;
406
407   strong = flags & (MAKEDEPS_FILTER_STRONG|MAKEDEPS_FILTER_WEAK);
408   n = headstringarray(rpmhead, tagn, &nc);
409   if (!n)
410     return 0;
411   v = headstringarray(rpmhead, tagv, &vc);
412   if (!v)
413     {
414       sat_free(n);
415       return 0;
416     }
417   f = headint32array(rpmhead, tagf, &fc);
418   if (!f)
419     {
420       sat_free(n);
421       free(v);
422       return 0;
423     }
424   if (nc != vc || nc != fc)
425     {
426       fprintf(stderr, "bad dependency entries\n");
427       exit(1);
428     }
429
430   cc = nc;
431   haspre = 0;   /* add no prereq marker */
432   if (flags)
433     {
434       /* we do filtering */
435       cc = 0;
436       for (i = 0; i < nc; i++)
437         {
438           if (strong && (f[i] & DEP_STRONG) != (strong == MAKEDEPS_FILTER_WEAK ? 0 : DEP_STRONG))
439             continue;
440           if ((flags & MAKEDEPS_NO_RPMLIB) != 0)
441             if (!strncmp(n[i], "rpmlib(", 7))
442               continue;
443           if ((f[i] & DEP_PRE) != 0)
444             haspre = 1;
445           cc++;
446         }
447     }
448   else if (tagn == TAG_REQUIRENAME)
449     {
450       /* no filtering, just look for the first prereq */
451       for (i = 0; i < nc; i++)
452         if ((f[i] & DEP_PRE) != 0)
453           {
454             haspre = 1;
455             break;
456           }
457     }
458   if (cc == 0)
459     {
460       sat_free(n);
461       sat_free(v);
462       sat_free(f);
463       return 0;
464     }
465   cc += haspre;
466   olddeps = repo_reserve_ids(repo, 0, cc);
467   ida = repo->idarraydata + olddeps;
468   for (i = 0; ; i++)
469     {
470       if (i == nc)
471         {
472           if (haspre != 1)
473             break;
474           haspre = 2;   /* pass two: prereqs */
475           i = 0;
476           *ida++ = SOLVABLE_PREREQMARKER;
477         }
478       if (strong && (f[i] & DEP_STRONG) != (strong == MAKEDEPS_FILTER_WEAK ? 0 : DEP_STRONG))
479         continue;
480       if (haspre == 1 && (f[i] & DEP_PRE) != 0)
481         continue;
482       if (haspre == 2 && (f[i] & DEP_PRE) == 0)
483         continue;
484       if ((flags & MAKEDEPS_NO_RPMLIB) != 0)
485         if (!strncmp(n[i], "rpmlib(", 7))
486           continue;
487       if (f[i] & (DEP_LESS|DEP_GREATER|DEP_EQUAL))
488         {
489           Id name, evr;
490           int flags = 0;
491           if ((f[i] & DEP_LESS) != 0)
492             flags |= 4;
493           if ((f[i] & DEP_EQUAL) != 0)
494             flags |= 2;
495           if ((f[i] & DEP_GREATER) != 0)
496             flags |= 1;
497           name = str2id(pool, n[i], 1);
498           if (v[i][0] == '0' && v[i][1] == ':' && v[i][2])
499             evr = str2id(pool, v[i] + 2, 1);
500           else
501             evr = str2id(pool, v[i], 1);
502           *ida++ = rel2id(pool, name, evr, flags, 1);
503         }
504       else
505         *ida++ = str2id(pool, n[i], 1);
506     }
507   *ida++ = 0;
508   repo->idarraysize += cc + 1;
509   sat_free(n);
510   sat_free(v);
511   sat_free(f);
512   return olddeps;
513 }
514
515
516 #ifdef USE_FILEFILTER
517
518 #define FILEFILTER_EXACT    0
519 #define FILEFILTER_STARTS   1
520 #define FILEFILTER_CONTAINS 2
521
522 struct filefilter {
523   int dirmatch;
524   char *dir;
525   char *base;
526 };
527
528 static struct filefilter filefilters[] = {
529   { FILEFILTER_CONTAINS, "/bin/", 0},
530   { FILEFILTER_CONTAINS, "/sbin/", 0},
531   { FILEFILTER_CONTAINS, "/lib/", 0},
532   { FILEFILTER_CONTAINS, "/lib64/", 0},
533   { FILEFILTER_CONTAINS, "/etc/", 0},
534   { FILEFILTER_STARTS, "/usr/games/", 0},
535   { FILEFILTER_EXACT, "/usr/share/dict/", "words"},
536   { FILEFILTER_STARTS, "/usr/share/", "magic.mime"},
537   { FILEFILTER_STARTS, "/opt/gnome/games/", 0},
538 };
539
540 #endif
541
542 static void
543 adddudata(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, char **dn, unsigned int *di, int fc, int dc)
544 {
545   Id handle, did;
546   int i, fszc;
547   unsigned int *fkb, *fn, *fsz, *fm, *fino;
548   unsigned int inotest[256], inotestok;
549
550   if (!fc)
551     return;
552   fsz = headint32array(rpmhead, TAG_FILESIZES, &fszc);
553   if (!fsz || fc != fszc)
554     {
555       sat_free(fsz);
556       return;
557     }
558   /* stupid rpm records sizes of directories, so we have to check the mode */
559   fm = headint16array(rpmhead, TAG_FILEMODES, &fszc);
560   if (!fm || fc != fszc)
561     {
562       sat_free(fsz);
563       sat_free(fm);
564       return;
565     }
566   fino = headint32array(rpmhead, TAG_FILEINODES, &fszc);
567   if (!fino || fc != fszc)
568     {
569       sat_free(fsz);
570       sat_free(fm);
571       sat_free(fino);
572       return;
573     }
574   inotestok = 0;
575   if (fc < sizeof(inotest))
576     {
577       memset(inotest, 0, sizeof(inotest));
578       for (i = 0; i < fc; i++)
579         {
580           int off, bit;
581           if (fsz[i] == 0 || !S_ISREG(fm[i]))
582             continue;
583           off = (fino[i] >> 5) & (sizeof(inotest)/sizeof(*inotest) - 1);
584           bit = 1 << (fino[i] & 31);
585           if ((inotest[off] & bit) != 0)
586             break;
587           inotest[off] |= bit;
588         }
589       if (i == fc)
590         inotestok = 1;
591     }
592   if (!inotestok)
593     {
594       unsigned int *fdev = headint32array(rpmhead, TAG_FILEDEVICES, &fszc);
595       unsigned int *fx, j;
596       unsigned int mask, hash, hh;
597       if (!fdev || fc != fszc)
598         {
599           sat_free(fsz);
600           sat_free(fm);
601           sat_free(fdev);
602           sat_free(fino);
603           return;
604         }
605       mask = fc;
606       while ((mask & (mask - 1)) != 0)
607         mask = mask & (mask - 1);
608       mask <<= 2;
609       if (mask > sizeof(inotest)/sizeof(*inotest))
610         fx = sat_calloc(mask, sizeof(unsigned int));
611       else
612         {
613           fx = inotest;
614           memset(fx, 0, mask * sizeof(unsigned int));
615         }
616       mask--;
617       for (i = 0; i < fc; i++)
618         {
619           if (fsz[i] == 0 || !S_ISREG(fm[i]))
620             continue;
621           hash = (fino[i] + fdev[i] * 31) & mask;
622           hh = 7;
623           while ((j = fx[hash]) != 0)
624             {
625               if (fino[j - 1] == fino[i] && fdev[j - 1] == fdev[i])
626                 {
627                   fsz[i] = 0;   /* kill entry */
628                   break;
629                 }
630               hash = (hash + hh++) & mask;
631             }
632           if (!j)
633             fx[hash] = i + 1;
634         }
635       if (fx != inotest)
636         sat_free(fx);
637       sat_free(fdev);
638     }
639   sat_free(fino);
640   fn = sat_calloc(dc, sizeof(unsigned int));
641   fkb = sat_calloc(dc, sizeof(unsigned int));
642   for (i = 0; i < fc; i++)
643     {
644       if (di[i] >= dc)
645         continue;
646       fn[di[i]]++;
647       if (fsz[i] == 0 || !S_ISREG(fm[i]))
648         continue;
649       fkb[di[i]] += fsz[i] / 1024 + 1;
650     }
651   sat_free(fsz);
652   sat_free(fm);
653   /* commit */
654   handle = s - pool->solvables;
655   for (i = 0; i < dc; i++)
656     {
657       if (!fn[i])
658         continue;
659       if (!*dn[i])
660         {
661           if (s->arch == ARCH_SRC || s->arch == ARCH_NOSRC)
662             did = repodata_str2dir(data, "/usr/src", 1);
663           else
664             continue;   /* work around rpm bug */
665         }
666       else
667         did = repodata_str2dir(data, dn[i], 1);
668       repodata_add_dirnumnum(data, handle, SOLVABLE_DISKUSAGE, did, fkb[i], fn[i]);
669     }
670   sat_free(fn);
671   sat_free(fkb);
672 }
673
674 /* assumes last processed array is provides! */
675 static unsigned int
676 addfileprovides(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, unsigned int olddeps)
677 {
678   char **bn;
679   char **dn;
680   unsigned int *di;
681   int bnc, dnc, dic;
682   int i;
683 #ifdef USE_FILEFILTER
684   int j;
685   struct filefilter *ff;
686 #endif
687 #if 0
688   char *fn = 0;
689   int fna = 0;
690 #endif
691
692   if (!data)
693     return olddeps;
694   bn = headstringarray(rpmhead, TAG_BASENAMES, &bnc);
695   if (!bn)
696     return olddeps;
697   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dnc);
698   if (!dn)
699     {
700       sat_free(bn);
701       return olddeps;
702     }
703   di = headint32array(rpmhead, TAG_DIRINDEXES, &dic);
704   if (!di)
705     {
706       sat_free(bn);
707       sat_free(dn);
708       return olddeps;
709     }
710   if (bnc != dic)
711     {
712       fprintf(stderr, "bad filelist\n");
713       exit(1);
714     }
715
716   if (data)
717     adddudata(pool, repo, data, s, rpmhead, dn, di, bnc, dnc);
718
719   for (i = 0; i < bnc; i++)
720     {
721 #ifdef USE_FILEFILTER
722       ff = filefilters;
723       for (j = 0; j < sizeof(filefilters)/sizeof(*filefilters); j++, ff++)
724         {
725           if (ff->dir)
726             {
727               switch (ff->dirmatch)
728                 {
729                 case FILEFILTER_STARTS:
730                   if (strncmp(dn[di[i]], ff->dir, strlen(ff->dir)))
731                     continue;
732                   break;
733                 case FILEFILTER_CONTAINS:
734                   if (!strstr(dn[di[i]], ff->dir))
735                     continue;
736                   break;
737                 case FILEFILTER_EXACT:
738                 default:
739                   if (strcmp(dn[di[i]], ff->dir))
740                     continue;
741                   break;
742                 }
743             }
744           if (ff->base)
745             {
746               if (strcmp(bn[i], ff->base))
747                 continue;
748             }
749           break;
750         }
751       if (j == sizeof(filefilters)/sizeof(*filefilters))
752         continue;
753 #endif
754 #if 0
755       j = strlen(bn[i]) + strlen(dn[di[i]]) + 1;
756       if (j > fna)
757         {
758           fna = j + 256;
759           fn = sat_realloc(fn, fna);
760         }
761       strcpy(fn, dn[di[i]]);
762       strcat(fn, bn[i]);
763       olddeps = repo_addid_dep(repo, olddeps, str2id(pool, fn, 1), SOLVABLE_FILEMARKER);
764 #endif
765       if (data)
766         {
767           Id handle, did;
768           char *b = bn[i];
769
770           handle = s - pool->solvables;
771           did = repodata_str2dir(data, dn[di[i]], 1);
772           if (!did)
773             {
774               did = repodata_str2dir(data, "/", 1);
775               if (b && b[0] == '/')
776                 b++;    /* work around rpm bug */
777             }
778           repodata_add_dirstr(data, handle, SOLVABLE_FILELIST, did, b);
779         }
780     }
781 #if 0
782   if (fn)
783     sat_free(fn);
784 #endif
785   sat_free(bn);
786   sat_free(dn);
787   sat_free(di);
788   return olddeps;
789 }
790
791 static void
792 addsourcerpm(Pool *pool, Repodata *data, Id handle, char *sourcerpm, char *name, char *evr)
793 {
794   const char *p, *sevr, *sarch;
795
796   p = strrchr(sourcerpm, '.');
797   if (!p || strcmp(p, ".rpm") != 0)
798     return;
799   p--;
800   while (p > sourcerpm && *p != '.')
801     p--;
802   if (*p != '.' || p == sourcerpm)
803     return;
804   sarch = p-- + 1;
805   while (p > sourcerpm && *p != '-')
806     p--;
807   if (*p != '-' || p == sourcerpm)
808     return;
809   p--;
810   while (p > sourcerpm && *p != '-')
811     p--;
812   if (*p != '-' || p == sourcerpm)
813     return;
814   sevr = p + 1;
815   if (!strcmp(sarch, "src.rpm"))
816     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, ARCH_SRC);
817   else if (!strcmp(sarch, "nosrc.rpm"))
818     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, ARCH_NOSRC);
819   else
820     repodata_set_constantid(data, handle, SOLVABLE_SOURCEARCH, strn2id(pool, sarch, strlen(sarch) - 4, 1));
821   if (evr && !strncmp(sevr, evr, sarch - sevr - 1) && evr[sarch - sevr - 1] == 0)
822     repodata_set_void(data, handle, SOLVABLE_SOURCEEVR);
823   else
824     repodata_set_id(data, handle, SOLVABLE_SOURCEEVR, strn2id(pool, sevr, sarch - sevr - 1, 1));
825   if (name && !strncmp(sourcerpm, name, sevr - sourcerpm - 1) && name[sevr - sourcerpm - 1] == 0)
826     repodata_set_void(data, handle, SOLVABLE_SOURCENAME);
827   else
828     repodata_set_id(data, handle, SOLVABLE_SOURCENAME, strn2id(pool, sourcerpm, sevr - sourcerpm - 1, 1));
829 }
830
831 static int
832 rpm2solv(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, int flags)
833 {
834   char *name;
835   char *evr;
836   char *sourcerpm;
837
838   name = headstring(rpmhead, TAG_NAME);
839   if (!strcmp(name, "gpg-pubkey"))
840     return 0;
841   s->name = str2id(pool, name, 1);
842   if (!s->name)
843     {
844       fprintf(stderr, "package has no name\n");
845       exit(1);
846     }
847   sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
848   if (sourcerpm)
849     s->arch = str2id(pool, headstring(rpmhead, TAG_ARCH), 1);
850   else
851     {
852       if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
853         s->arch = ARCH_NOSRC;
854       else
855         s->arch = ARCH_SRC;
856     }
857   if (!s->arch)
858     s->arch = ARCH_NOARCH;
859   evr = headtoevr(rpmhead);
860   s->evr = str2id(pool, evr, 1);
861   s->vendor = str2id(pool, headstring(rpmhead, TAG_VENDOR), 1);
862
863   s->provides = makedeps(pool, repo, rpmhead, TAG_PROVIDENAME, TAG_PROVIDEVERSION, TAG_PROVIDEFLAGS, 0);
864   if ((flags & RPM_ADD_NO_FILELIST) == 0)
865     s->provides = addfileprovides(pool, repo, data, s, rpmhead, s->provides);
866   if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
867     s->provides = repo_addid_dep(repo, s->provides, rel2id(pool, s->name, s->evr, REL_EQ, 1), 0);
868   s->requires = makedeps(pool, repo, rpmhead, TAG_REQUIRENAME, TAG_REQUIREVERSION, TAG_REQUIREFLAGS, (flags & RPM_ADD_NO_RPMLIBREQS) ? MAKEDEPS_NO_RPMLIB : 0);
869   s->conflicts = makedeps(pool, repo, rpmhead, TAG_CONFLICTNAME, TAG_CONFLICTVERSION, TAG_CONFLICTFLAGS, 0);
870   s->obsoletes = makedeps(pool, repo, rpmhead, TAG_OBSOLETENAME, TAG_OBSOLETEVERSION, TAG_OBSOLETEFLAGS, 0);
871
872   s->recommends = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_STRONG);
873   s->suggests = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_WEAK);
874   s->supplements = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_STRONG);
875   s->enhances  = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_WEAK);
876   s->supplements = repo_fix_supplements(repo, s->provides, s->supplements, 0);
877   s->conflicts = repo_fix_conflicts(repo, s->conflicts);
878
879   if (data)
880     {
881       Id handle;
882       char *str;
883       unsigned int u32;
884
885       handle = s - pool->solvables;
886       str = headstring(rpmhead, TAG_SUMMARY);
887       if (str)
888         setutf8string(data, handle, SOLVABLE_SUMMARY, str);
889       str = headstring(rpmhead, TAG_DESCRIPTION);
890       if (str)
891         {
892           char *aut, *p;
893           for (aut = str; (aut = strchr(aut, '\n')) != 0; aut++)
894             if (!strncmp(aut, "\nAuthors:\n--------\n", 19))
895               break;
896           if (aut)
897             {
898               /* oh my, found SUSE special author section */
899               int l = aut - str;
900               str = strdup(str);
901               aut = str + l;
902               str[l] = 0;
903               while (l > 0 && str[l - 1] == '\n')
904                 str[--l] = 0;
905               if (l)
906                 setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
907               p = aut + 19;
908               aut = str;        /* copy over */
909               while (*p == ' ' || *p == '\n')
910                 p++;
911               while (*p)
912                 {
913                   if (*p == '\n')
914                     {
915                       *aut++ = *p++;
916                       while (*p == ' ')
917                         p++;
918                       continue;
919                     }
920                   *aut++ = *p++;
921                 }
922               while (aut != str && aut[-1] == '\n')
923                 aut--;
924               *aut = 0;
925               if (*str)
926                 setutf8string(data, handle, SOLVABLE_AUTHORS, str);
927               free(str);
928             }
929           else if (*str)
930             setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
931         }
932       str = headstring(rpmhead, TAG_GROUP);
933       if (str)
934         repodata_set_poolstr(data, handle, SOLVABLE_GROUP, str);
935       str = headstring(rpmhead, TAG_LICENSE);
936       if (str)
937         repodata_set_poolstr(data, handle, SOLVABLE_LICENSE, str);
938       str = headstring(rpmhead, TAG_URL);
939       if (str)
940         repodata_set_str(data, handle, SOLVABLE_URL, str);
941       str = headstring(rpmhead, TAG_DISTRIBUTION);
942       if (str)
943         repodata_set_poolstr(data, handle, SOLVABLE_DISTRIBUTION, str);
944       str = headstring(rpmhead, TAG_PACKAGER);
945       if (str)
946         repodata_set_poolstr(data, handle, SOLVABLE_PACKAGER, str);
947       u32 = headint32(rpmhead, TAG_BUILDTIME);
948       if (u32)
949         repodata_set_num(data, handle, SOLVABLE_BUILDTIME, u32);
950       u32 = headint32(rpmhead, TAG_INSTALLTIME);
951       if (u32)
952         repodata_set_num(data, handle, SOLVABLE_INSTALLTIME, u32);
953       u32 = headint32(rpmhead, TAG_SIZE);
954       if (u32)
955         repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, (u32 + 1023) / 1024);
956       if (sourcerpm)
957         addsourcerpm(pool, data, handle, sourcerpm, name, evr);
958       if ((flags & RPM_ADD_TRIGGERS) != 0)
959         {
960           Id id, lastid;
961           unsigned int ida = makedeps(pool, repo, rpmhead, TAG_TRIGGERNAME, TAG_TRIGGERVERSION, TAG_TRIGGERFLAGS, 0);
962
963           lastid = 0;
964           for (; (id = repo->idarraydata[ida]) != 0; ida++)
965             {
966               /* we currently do not support rel ids in incore data, so
967                * strip off versioning information */
968               while (ISRELDEP(id))
969                 {
970                   Reldep *rd = GETRELDEP(pool, id);
971                   id = rd->name;
972                 }
973               if (id == lastid)
974                 continue;
975               repodata_add_idarray(data, handle, SOLVABLE_TRIGGERS, id);
976               lastid = id;
977             }
978         }
979     }
980   sat_free(evr);
981   return 1;
982 }
983
984 static Id
985 copyreldep(Pool *pool, Pool *frompool, Id id)
986 {
987   Reldep *rd = GETRELDEP(frompool, id);
988   Id name = rd->name, evr = rd->evr;
989   if (ISRELDEP(name))
990     name = copyreldep(pool, frompool, name);
991   else
992     name = str2id(pool, id2str(frompool, name), 1);
993   if (ISRELDEP(evr))
994     evr = copyreldep(pool, frompool, evr);
995   else
996     evr = str2id(pool, id2str(frompool, evr), 1);
997   return rel2id(pool, name, evr, rd->flags, 1);
998 }
999
1000 static Offset
1001 copydeps(Pool *pool, Repo *repo, Offset fromoff, Repo *fromrepo)
1002 {
1003   int cc;
1004   Id id, *ida, *from;
1005   Offset ido;
1006   Pool *frompool = fromrepo->pool;
1007
1008   if (!fromoff)
1009     return 0;
1010   from = fromrepo->idarraydata + fromoff;
1011   for (ida = from, cc = 0; *ida; ida++, cc++)
1012     ;
1013   if (cc == 0)
1014     return 0;
1015   ido = repo_reserve_ids(repo, 0, cc);
1016   ida = repo->idarraydata + ido;
1017   if (frompool && pool != frompool)
1018     {
1019       while (*from)
1020         {
1021           id = *from++;
1022           if (ISRELDEP(id))
1023             id = copyreldep(pool, frompool, id);
1024           else
1025             id = str2id(pool, id2str(frompool, id), 1);
1026           *ida++ = id;
1027         }
1028       *ida = 0;
1029     }
1030   else
1031     memcpy(ida, from, (cc + 1) * sizeof(Id));
1032   repo->idarraysize += cc + 1;
1033   return ido;
1034 }
1035
1036 #define COPYDIR_DIRCACHE_SIZE 512
1037
1038 static Id copydir_complex(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache);
1039
1040 static inline Id
1041 copydir(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache)
1042 {
1043   if (cache && cache[did & 255] == did)
1044     return cache[(did & 255) + 256];
1045   return copydir_complex(pool, data, fromspool, fromdata, did, cache);
1046 }
1047
1048 static Id
1049 copydir_complex(Pool *pool, Repodata *data, Stringpool *fromspool, Repodata *fromdata, Id did, Id *cache)
1050 {
1051   Id parent = dirpool_parent(&fromdata->dirpool, did);
1052   Id compid = dirpool_compid(&fromdata->dirpool, did);
1053   if (parent)
1054     parent = copydir(pool, data, fromspool, fromdata, parent, cache);
1055   if (fromspool != &pool->ss)
1056     compid = str2id(pool, stringpool_id2str(fromspool, compid), 1);
1057   compid = dirpool_add_dir(&data->dirpool, parent, compid, 1);
1058   if (cache)
1059     {
1060       cache[did & 255] = did;
1061       cache[(did & 255) + 256] = compid;
1062     }
1063   return compid;
1064 }
1065
1066 struct solvable_copy_cbdata {
1067   Repodata *data;
1068   Id handle;
1069   Id *dircache;
1070 };
1071
1072 static int
1073 solvable_copy_cb(void *vcbdata, Solvable *r, Repodata *fromdata, Repokey *key, KeyValue *kv)
1074 {
1075   struct solvable_copy_cbdata *cbdata = vcbdata;
1076   Id id, keyname;
1077   Repodata *data = cbdata->data;
1078   Id handle = cbdata->handle;
1079   Pool *pool = data->repo->pool, *frompool = fromdata->repo->pool;
1080   Stringpool *fromspool = fromdata->localpool ? &fromdata->spool : &frompool->ss;
1081
1082   keyname = key->name;
1083   if (keyname >= ID_NUM_INTERNAL)
1084     keyname = str2id(pool, id2str(frompool, keyname), 1);
1085   switch(key->type)
1086     {
1087     case REPOKEY_TYPE_ID:
1088     case REPOKEY_TYPE_CONSTANTID:
1089       id = kv->id;
1090       assert(!data->localpool); /* implement me! */
1091       if (pool != frompool || fromdata->localpool)
1092         {
1093           if (ISRELDEP(id))
1094             id = copyreldep(pool, frompool, id);
1095           else
1096             id = str2id(pool, stringpool_id2str(fromspool, id), 1);
1097         }
1098       if (key->type == REPOKEY_TYPE_ID)
1099         repodata_set_id(data, handle, keyname, id);
1100       else
1101         repodata_set_constantid(data, handle, keyname, id);
1102       break;
1103     case REPOKEY_TYPE_STR:
1104       repodata_set_str(data, handle, keyname, kv->str);
1105       break;
1106     case REPOKEY_TYPE_VOID:
1107       repodata_set_void(data, handle, keyname);
1108       break;
1109     case REPOKEY_TYPE_NUM:
1110       repodata_set_num(data, handle, keyname, kv->num);
1111       break;
1112     case REPOKEY_TYPE_CONSTANT:
1113       repodata_set_constant(data, handle, keyname, kv->num);
1114       break;
1115     case REPOKEY_TYPE_DIRNUMNUMARRAY:
1116       id = kv->id;
1117       assert(!data->localpool); /* implement me! */
1118       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1119       repodata_add_dirnumnum(data, handle, keyname, id, kv->num, kv->num2);
1120       break;
1121     case REPOKEY_TYPE_DIRSTRARRAY:
1122       id = kv->id;
1123       assert(!data->localpool); /* implement me! */
1124       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1125       repodata_add_dirstr(data, handle, keyname, id, kv->str);
1126       break;
1127     case REPOKEY_TYPE_IDARRAY:  /* used for triggers */
1128       id = kv->id;
1129       assert(!data->localpool); /* implement me! */
1130       if (ISRELDEP(id))
1131         break;          /* can't do those at the moment */
1132       if (pool != frompool || fromdata->localpool)
1133         id = str2id(pool, stringpool_id2str(fromspool, id), 1);
1134       repodata_add_idarray(data, handle, keyname, id);
1135       break;
1136     default:
1137       break;
1138     }
1139   return 0;
1140 }
1141
1142 static void
1143 solvable_copy(Solvable *s, Solvable *r, Repodata *data, Id *dircache)
1144 {
1145   Repo *repo = s->repo;
1146   Repo *fromrepo = r->repo;
1147   Pool *pool = repo->pool;
1148   struct solvable_copy_cbdata cbdata;
1149
1150   /* copy solvable data */
1151   if (pool == fromrepo->pool)
1152     {
1153       s->name = r->name;
1154       s->evr = r->evr;
1155       s->arch = r->arch;
1156       s->vendor = r->vendor;
1157     }
1158   else
1159     {
1160       if (r->name)
1161         s->name = str2id(pool, id2str(fromrepo->pool, r->name), 1);
1162       if (r->evr)
1163         s->evr = str2id(pool, id2str(fromrepo->pool, r->evr), 1);
1164       if (r->arch)
1165         s->arch = str2id(pool, id2str(fromrepo->pool, r->arch), 1);
1166       if (r->vendor)
1167         s->vendor = str2id(pool, id2str(fromrepo->pool, r->vendor), 1);
1168     }
1169   s->provides = copydeps(pool, repo, r->provides, fromrepo);
1170   s->requires = copydeps(pool, repo, r->requires, fromrepo);
1171   s->conflicts = copydeps(pool, repo, r->conflicts, fromrepo);
1172   s->obsoletes = copydeps(pool, repo, r->obsoletes, fromrepo);
1173   s->recommends = copydeps(pool, repo, r->recommends, fromrepo);
1174   s->suggests = copydeps(pool, repo, r->suggests, fromrepo);
1175   s->supplements = copydeps(pool, repo, r->supplements, fromrepo);
1176   s->enhances  = copydeps(pool, repo, r->enhances, fromrepo);
1177
1178   /* copy all attributes */
1179   if (!data)
1180     return;
1181   cbdata.data = data;
1182   cbdata.handle = s - pool->solvables;
1183   cbdata.dircache = dircache;
1184   repo_search(fromrepo, (r - fromrepo->pool->solvables), 0, 0, SEARCH_NO_STORAGE_SOLVABLE, solvable_copy_cb, &cbdata);
1185 }
1186
1187 /* used to sort entries returned in some database order */
1188 static int
1189 rpmids_sort_cmp(const void *va, const void *vb, void *dp)
1190 {
1191   struct rpmid const *a = va, *b = vb;
1192   int r;
1193   r = strcmp(a->name, b->name);
1194   if (r)
1195     return r;
1196   return a->dbid - b->dbid;
1197 }
1198
1199 static int
1200 pkgids_sort_cmp(const void *va, const void *vb, void *dp)
1201 {
1202   Repo *repo = dp;
1203   Pool *pool = repo->pool;
1204   Solvable *a = pool->solvables + *(Id *)va;
1205   Solvable *b = pool->solvables + *(Id *)vb;
1206   Id *rpmdbid;
1207
1208   if (a->name != b->name)
1209     return strcmp(id2str(pool, a->name), id2str(pool, b->name));
1210   rpmdbid = repo->rpmdbid;
1211   return rpmdbid[(a - pool->solvables) - repo->start] - rpmdbid[(b - pool->solvables) - repo->start];
1212 }
1213
1214 static void
1215 swap_solvables(Repo *repo, Repodata *data, Id pa, Id pb)
1216 {
1217   Pool *pool = repo->pool;
1218   Solvable tmp;
1219
1220   tmp = pool->solvables[pa];
1221   pool->solvables[pa] = pool->solvables[pb];
1222   pool->solvables[pb] = tmp;
1223   if (repo->rpmdbid)
1224     {
1225       Id tmpid = repo->rpmdbid[pa - repo->start];
1226       repo->rpmdbid[pa - repo->start] = repo->rpmdbid[pb - repo->start];
1227       repo->rpmdbid[pb - repo->start] = tmpid;
1228     }
1229   /* only works if nothing is already internalized! */
1230   if (data && data->attrs)
1231     {
1232       Id *tmpattrs = data->attrs[pa - data->start];
1233       data->attrs[pa - data->start] = data->attrs[pb - data->start];
1234       data->attrs[pb - data->start] = tmpattrs;
1235     }
1236 }
1237
1238
1239 static inline Id db2rpmdbid(unsigned char *db, int byteswapped)
1240 {
1241 #ifdef RPM5
1242   return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
1243 #else
1244 # if defined(WORDS_BIGENDIAN)
1245   if (!byteswapped)
1246 # else
1247   if (byteswapped)
1248 # endif
1249     return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
1250   else
1251     return db[3] << 24 | db[2] << 16 | db[1] << 8 | db[0];
1252 #endif
1253 }
1254
1255 static inline void rpmdbid2db(unsigned char *db, Id id, int byteswapped)
1256 {
1257 #ifdef RPM5
1258   db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1259 #else
1260 # if defined(WORDS_BIGENDIAN)
1261   if (!byteswapped)
1262     db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1263 # else
1264   if (byteswapped)
1265     db[3] = id >> 24, db[2] = id >> 16, db[1] = id >> 8, db[0] = id;
1266 # endif
1267 #endif
1268 }
1269
1270 static void
1271 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1272 {
1273   memset(cookie, 0, 32);
1274   cookie[3] = RPMDB_COOKIE_VERSION;
1275   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1276   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1277 }
1278
1279 /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1280 static DB_ENV *
1281 opendbenv(const char *rootdir)
1282 {
1283   char dbpath[PATH_MAX];
1284   DB_ENV *dbenv = 0;
1285   int r;
1286
1287   if (db_env_create(&dbenv, 0))
1288     {
1289       perror("db_env_create");
1290       return 0;
1291     }
1292 #if defined(FEDORA) && (DB_VERSION_MAJOR >= 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 5))
1293   dbenv->set_thread_count(dbenv, 8);
1294 #endif
1295   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1296   if (access(dbpath, W_OK) == -1)
1297     {
1298       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1299     }
1300   else
1301     {
1302 #ifdef FEDORA
1303       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0644);
1304 #else
1305       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1306 #endif
1307     }
1308   if (r)
1309     {
1310       perror("dbenv open");
1311       dbenv->close(dbenv, 0);
1312       return 0;
1313     }
1314   return dbenv;
1315 }
1316
1317
1318 static int
1319 count_headers(const char *rootdir, DB_ENV *dbenv)
1320 {
1321   char dbpath[PATH_MAX];
1322   struct stat statbuf;
1323   DB *db = 0;
1324   DBC *dbc = 0;
1325   int count = 0;
1326   DBT dbkey;
1327   DBT dbdata;
1328
1329   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir);
1330   if (stat(dbpath, &statbuf))
1331     return 0;
1332   memset(&dbkey, 0, sizeof(dbkey));
1333   memset(&dbdata, 0, sizeof(dbdata));
1334   if (db_create(&db, dbenv, 0))
1335     {
1336       perror("db_create");
1337       exit(1);
1338     }
1339   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1340     {
1341       perror("db->open Name index");
1342       exit(1);
1343     }
1344   if (db->cursor(db, NULL, &dbc, 0))
1345     {
1346       perror("db->cursor");
1347       exit(1);
1348     }
1349   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1350     count += dbdata.size / RPM_INDEX_SIZE;
1351   dbc->c_close(dbc);
1352   db->close(db, 0);
1353   return count;
1354 }
1355
1356 /*
1357  * read rpm db as repo
1358  *
1359  */
1360
1361 void
1362 repo_add_rpmdb(Repo *repo, Repo *ref, const char *rootdir, int flags)
1363 {
1364   Pool *pool = repo->pool;
1365   unsigned char buf[16];
1366   DB *db = 0;
1367   DBC *dbc = 0;
1368   int byteswapped;
1369   unsigned int dbid;
1370   unsigned char *dp, *dbidp;
1371   int dl, nrpmids;
1372   struct rpmid *rpmids, *rp;
1373   int i;
1374   int rpmheadsize;
1375   RpmHead *rpmhead;
1376   Solvable *s;
1377   Id id, *refhash;
1378   unsigned int refmask, h;
1379   char dbpath[PATH_MAX];
1380   DB_ENV *dbenv = 0;
1381   DBT dbkey;
1382   DBT dbdata;
1383   struct stat packagesstat;
1384   unsigned char newcookie[32];
1385   const unsigned char *oldcookie = 0;
1386   Id oldcookietype = 0;
1387   Repodata *data;
1388   int count = 0, done = 0;
1389   unsigned int now;
1390
1391   now = sat_timems(0);
1392   memset(&dbkey, 0, sizeof(dbkey));
1393   memset(&dbdata, 0, sizeof(dbdata));
1394
1395   if (!rootdir)
1396     rootdir = "";
1397
1398   data = repo_add_repodata(repo, flags);
1399
1400   if (ref && !(ref->nsolvables && ref->rpmdbid))
1401     ref = 0;
1402
1403   if (!(dbenv = opendbenv(rootdir)))
1404     exit(1);
1405
1406   /* XXX: should get ro lock of Packages database! */
1407   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir);
1408   if (stat(dbpath, &packagesstat))
1409     {
1410       perror(dbpath);
1411       exit(1);
1412     }
1413   mkrpmdbcookie(&packagesstat, newcookie);
1414   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1415
1416   if (ref)
1417     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1418   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1419     {
1420       Id *pkgids;
1421       int solvstart = 0, solvend = 0;
1422
1423       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1424         count = count_headers(rootdir, dbenv);
1425       if (db_create(&db, dbenv, 0))
1426         {
1427           perror("db_create");
1428           exit(1);
1429         }
1430       if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1431         {
1432           perror("db->open Packages index");
1433           exit(1);
1434         }
1435       if (db->get_byteswapped(db, &byteswapped))
1436         {
1437           perror("db->get_byteswapped");
1438           exit(1);
1439         }
1440       if (db->cursor(db, NULL, &dbc, 0))
1441         {
1442           perror("db->cursor");
1443           exit(1);
1444         }
1445       dbidp = (unsigned char *)&dbid;
1446       rpmheadsize = 0;
1447       rpmhead = 0;
1448       i = 0;
1449       s = 0;
1450       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1451         {
1452           if (!s)
1453             {
1454               s = pool_id2solvable(pool, repo_add_solvable(repo));
1455               if (!solvstart)
1456                 solvstart = s - pool->solvables;
1457               solvend = s - pool->solvables + 1;
1458             }
1459           if (!repo->rpmdbid)
1460             repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1461           if (dbkey.size != 4)
1462             {
1463               fprintf(stderr, "corrupt Packages database (key size)\n");
1464               exit(1);
1465             }
1466           dbid = db2rpmdbid(dbkey.data, byteswapped);
1467           if (dbid == 0)                /* the join key */
1468             continue;
1469           if (dbdata.size < 8)
1470             {
1471               fprintf(stderr, "corrupt rpm database (size %u)\n", dbdata.size);
1472               exit(1);
1473             }
1474           if (dbdata.size > rpmheadsize)
1475             {
1476               rpmheadsize = dbdata.size + 128;
1477               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1478             }
1479           memcpy(buf, dbdata.data, 8);
1480           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1481           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1482           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1483             {
1484               fprintf(stderr, "corrupt rpm database (data size)\n");
1485               exit(1);
1486             }
1487           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1488           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1489           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1490           if (rpm2solv(pool, repo, data, s, rpmhead, flags | RPM_ADD_TRIGGERS))
1491             {
1492               i++;
1493               s = 0;
1494             }
1495           else
1496             {
1497               /* We can reuse this solvable, but make sure it's still
1498                  associated with this repo.  */
1499               memset(s, 0, sizeof(*s));
1500               s->repo = repo;
1501             }
1502           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1503             {
1504               if (done < count)
1505                 done++;
1506               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1507                 pool_debug(pool, SAT_ERROR, "%%%% %d\n", done * 100 / count);
1508             }
1509         }
1510       if (s)
1511         {
1512           /* oops, could not reuse. free it instead */
1513           repo_free_solvable_block(repo, s - pool->solvables, 1, 1);
1514           solvend--;
1515           s = 0;
1516         }
1517       dbc->c_close(dbc);
1518       db->close(db, 0);
1519       db = 0;
1520       /* now sort all solvables in the new solvstart..solvend block */
1521       if (solvend - solvstart > 1)
1522         {
1523           pkgids = sat_malloc2(solvend - solvstart, sizeof(Id));
1524           for (i = solvstart; i < solvend; i++)
1525             pkgids[i - solvstart] = i;
1526           sat_sort(pkgids, solvend - solvstart, sizeof(Id), pkgids_sort_cmp, repo);
1527           /* adapt order */
1528           for (i = solvstart; i < solvend; i++)
1529             {
1530               int j = pkgids[i - solvstart];
1531               while (j < i)
1532                 j = pkgids[i - solvstart] = pkgids[j - solvstart];
1533               if (j != i)
1534                 swap_solvables(repo, data, i, j);
1535             }
1536           sat_free(pkgids);
1537         }
1538     }
1539   else
1540     {
1541       Id dircache[COPYDIR_DIRCACHE_SIZE];               /* see copydir */
1542
1543       memset(dircache, 0, sizeof(dircache));
1544       if (db_create(&db, dbenv, 0))
1545         {
1546           perror("db_create");
1547           exit(1);
1548         }
1549       if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1550         {
1551           perror("db->open Name index");
1552           exit(1);
1553         }
1554       if (db->get_byteswapped(db, &byteswapped))
1555         {
1556           perror("db->get_byteswapped");
1557           exit(1);
1558         }
1559       if (db->cursor(db, NULL, &dbc, 0))
1560         {
1561           perror("db->cursor");
1562           exit(1);
1563         }
1564       dbidp = (unsigned char *)&dbid;
1565       nrpmids = 0;
1566       rpmids = 0;
1567       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1568         {
1569           if (dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1570             continue;
1571           dl = dbdata.size;
1572           dp = dbdata.data;
1573           while(dl >= RPM_INDEX_SIZE)
1574             {
1575               rpmids = sat_extend(rpmids, nrpmids, 1, sizeof(*rpmids), 255);
1576               rpmids[nrpmids].dbid = db2rpmdbid(dp, byteswapped);
1577               rpmids[nrpmids].name = sat_malloc((int)dbkey.size + 1);
1578               memcpy(rpmids[nrpmids].name, dbkey.data, (int)dbkey.size);
1579               rpmids[nrpmids].name[(int)dbkey.size] = 0;
1580               nrpmids++;
1581               dp += RPM_INDEX_SIZE;
1582               dl -= RPM_INDEX_SIZE;
1583             }
1584         }
1585       dbc->c_close(dbc);
1586       db->close(db, 0);
1587       db = 0;
1588
1589       /* sort rpmids */
1590       sat_sort(rpmids, nrpmids, sizeof(*rpmids), rpmids_sort_cmp, 0);
1591
1592       dbidp = (unsigned char *)&dbid;
1593       rpmheadsize = 0;
1594       rpmhead = 0;
1595
1596       /* create hash from dbid to ref */
1597       refmask = mkmask(ref->nsolvables);
1598       refhash = sat_calloc(refmask + 1, sizeof(Id));
1599       for (i = 0; i < ref->end - ref->start; i++)
1600         {
1601           if (!ref->rpmdbid[i])
1602             continue;
1603           h = ref->rpmdbid[i] & refmask;
1604           while (refhash[h])
1605             h = (h + 317) & refmask;
1606           refhash[h] = i + 1;   /* make it non-zero */
1607         }
1608
1609       /* count the misses, they will cost us time */
1610       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1611         {
1612           for (i = 0, rp = rpmids; i < nrpmids; i++, rp++)
1613             {
1614               dbid = rp->dbid;
1615               if (refhash)
1616                 {
1617                   h = dbid & refmask;
1618                   while ((id = refhash[h]))
1619                     {
1620                       if (ref->rpmdbid[id - 1] == dbid)
1621                         break;
1622                       h = (h + 317) & refmask;
1623                     }
1624                   if (id)
1625                     continue;
1626                 }
1627               count++;
1628             }
1629         }
1630
1631       s = pool_id2solvable(pool, repo_add_solvable_block(repo, nrpmids));
1632       if (!repo->rpmdbid)
1633         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1634
1635       for (i = 0, rp = rpmids; i < nrpmids; i++, rp++, s++)
1636         {
1637           dbid = rp->dbid;
1638           repo->rpmdbid[(s - pool->solvables) - repo->start] = rp->dbid;
1639           if (refhash)
1640             {
1641               h = dbid & refmask;
1642               while ((id = refhash[h]))
1643                 {
1644                   if (ref->rpmdbid[id - 1] == dbid)
1645                     break;
1646                   h = (h + 317) & refmask;
1647                 }
1648               if (id)
1649                 {
1650                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1651                   if (r->repo == ref)
1652                     {
1653                       solvable_copy(s, r, data, dircache);
1654                       continue;
1655                     }
1656                 }
1657             }
1658           if (!db)
1659             {
1660               if (db_create(&db, dbenv, 0))
1661                 {
1662                   perror("db_create");
1663                   exit(1);
1664                 }
1665               if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1666                 {
1667                   perror("db->open var/lib/rpm/Packages");
1668                   exit(1);
1669                 }
1670               if (db->get_byteswapped(db, &byteswapped))
1671                 {
1672                   perror("db->get_byteswapped");
1673                   exit(1);
1674                 }
1675             }
1676           rpmdbid2db(buf, rp->dbid, byteswapped);
1677           dbkey.data = buf;
1678           dbkey.size = 4;
1679           dbdata.data = 0;
1680           dbdata.size = 0;
1681           if (db->get(db, NULL, &dbkey, &dbdata, 0))
1682             {
1683               perror("db->get");
1684               fprintf(stderr, "corrupt rpm database, key %d not found\n", dbid);
1685               fprintf(stderr, "please run 'rpm --rebuilddb' to recreate the database index files\n");
1686               exit(1);
1687             }
1688           if (dbdata.size < 8)
1689             {
1690               fprintf(stderr, "corrupt rpm database (size)\n");
1691               exit(1);
1692             }
1693           if (dbdata.size > rpmheadsize)
1694             {
1695               rpmheadsize = dbdata.size + 128;
1696               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1697             }
1698           memcpy(buf, dbdata.data, 8);
1699           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1700           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1701           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1702             {
1703               fprintf(stderr, "corrupt rpm database (data size)\n");
1704               exit(1);
1705             }
1706           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1707           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1708
1709           rpm2solv(pool, repo, data, s, rpmhead, flags | RPM_ADD_TRIGGERS);
1710           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1711             {
1712               if (done < count)
1713                 done++;
1714               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1715                 pool_debug(pool, SAT_ERROR, "%%%% %d\n", done * 100 / count);
1716             }
1717         }
1718
1719       if (refhash)
1720         sat_free(refhash);
1721       if (rpmids)
1722         {
1723           for (i = 0; i < nrpmids; i++)
1724             sat_free(rpmids[i].name);
1725           sat_free(rpmids);
1726         }
1727     }
1728   if (db)
1729     db->close(db, 0);
1730   dbenv->close(dbenv, 0);
1731   if (rpmhead)
1732     sat_free(rpmhead);
1733   if (!(flags & REPO_NO_INTERNALIZE))
1734     repodata_internalize(data);
1735   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1736     pool_debug(pool, SAT_ERROR, "%%%% 100\n");
1737   POOL_DEBUG(SAT_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", sat_timems(now));
1738   POOL_DEBUG(SAT_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1739   POOL_DEBUG(SAT_DEBUG_STATS, "repo memory used: %d K incore, %d K idarray\n", data->incoredatalen/1024, repo->idarraysize / (int)(1024/sizeof(Id)));
1740 }
1741
1742
1743 static inline unsigned int
1744 getu32(const unsigned char *dp)
1745 {
1746   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1747 }
1748
1749
1750 void
1751 repo_add_rpms(Repo *repo, const char **rpms, int nrpms, int flags)
1752 {
1753   int i, sigdsize, sigcnt, l;
1754   Pool *pool = repo->pool;
1755   Solvable *s;
1756   RpmHead *rpmhead = 0;
1757   int rpmheadsize = 0;
1758   char *payloadformat;
1759   FILE *fp;
1760   unsigned char lead[4096];
1761   int headerstart, headerend;
1762   struct stat stb;
1763   Repodata *data;
1764   unsigned char pkgid[16];
1765   int gotpkgid;
1766   Id chksumtype = 0;
1767   void *chksumh = 0;
1768
1769   data = repo_add_repodata(repo, flags);
1770
1771   if ((flags & RPM_ADD_WITH_SHA256SUM) != 0)
1772     chksumtype = REPOKEY_TYPE_SHA256;
1773   else if ((flags & RPM_ADD_WITH_SHA1SUM) != 0)
1774     chksumtype = REPOKEY_TYPE_SHA1;
1775   for (i = 0; i < nrpms; i++)
1776     {
1777       if ((fp = fopen(rpms[i], "r")) == 0)
1778         {
1779           perror(rpms[i]);
1780           continue;
1781         }
1782       if (fstat(fileno(fp), &stb))
1783         {
1784           perror("stat");
1785           continue;
1786         }
1787       if (chksumh)
1788         chksumh = sat_chksum_free(chksumh, 0);
1789       if (chksumtype)
1790         chksumh = sat_chksum_create(chksumtype);
1791       if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1792         {
1793           fprintf(stderr, "%s: not a rpm\n", rpms[i]);
1794           fclose(fp);
1795           continue;
1796         }
1797       if (chksumh)
1798         sat_chksum_add(chksumh, lead, 96 + 16);
1799       if (lead[78] != 0 || lead[79] != 5)
1800         {
1801           fprintf(stderr, "%s: not a V5 header\n", rpms[i]);
1802           fclose(fp);
1803           continue;
1804         }
1805       if (getu32(lead + 96) != 0x8eade801)
1806         {
1807           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1808           fclose(fp);
1809           continue;
1810         }
1811       sigcnt = getu32(lead + 96 + 8);
1812       sigdsize = getu32(lead + 96 + 12);
1813       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1814         {
1815           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1816           fclose(fp);
1817           continue;
1818         }
1819       sigdsize += sigcnt * 16;
1820       sigdsize = (sigdsize + 7) & ~7;
1821       headerstart = 96 + 16 + sigdsize;
1822       gotpkgid = 0;
1823       if ((flags & RPM_ADD_WITH_PKGID) != 0)
1824         {
1825           unsigned char *chksum;
1826           unsigned int chksumsize;
1827           /* extract pkgid from the signature header */
1828           if (sigdsize > rpmheadsize)
1829             {
1830               rpmheadsize = sigdsize + 128;
1831               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1832             }
1833           if (fread(rpmhead->data, sigdsize, 1, fp) != 1)
1834             {
1835               fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1836               fclose(fp);
1837               continue;
1838             }
1839           if (chksumh)
1840             sat_chksum_add(chksumh, rpmhead->data, sigdsize);
1841           rpmhead->cnt = sigcnt;
1842           rpmhead->dcnt = sigdsize - sigcnt * 16;
1843           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1844           chksum = headbinary(rpmhead, SIGTAG_MD5, &chksumsize);
1845           if (chksum && chksumsize == 16)
1846             {
1847               gotpkgid = 1;
1848               memcpy(pkgid, chksum, 16);
1849             }
1850         }
1851       else
1852         {
1853           /* just skip the signature header */
1854           while (sigdsize)
1855             {
1856               l = sigdsize > 4096 ? 4096 : sigdsize;
1857               if (fread(lead, l, 1, fp) != 1)
1858                 {
1859                   fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1860                   fclose(fp);
1861                   continue;
1862                 }
1863               if (chksumh)
1864                 sat_chksum_add(chksumh, lead, l);
1865               sigdsize -= l;
1866             }
1867         }
1868       if (fread(lead, 16, 1, fp) != 1)
1869         {
1870           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1871           fclose(fp);
1872           continue;
1873         }
1874       if (chksumh)
1875         sat_chksum_add(chksumh, lead, 16);
1876       if (getu32(lead) != 0x8eade801)
1877         {
1878           fprintf(stderr, "%s: bad header\n", rpms[i]);
1879           fclose(fp);
1880           continue;
1881         }
1882       sigcnt = getu32(lead + 8);
1883       sigdsize = getu32(lead + 12);
1884       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1885         {
1886           fprintf(stderr, "%s: bad header\n", rpms[i]);
1887           fclose(fp);
1888           continue;
1889         }
1890       l = sigdsize + sigcnt * 16;
1891       headerend = headerstart + 16 + l;
1892       if (l > rpmheadsize)
1893         {
1894           rpmheadsize = l + 128;
1895           rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1896         }
1897       if (fread(rpmhead->data, l, 1, fp) != 1)
1898         {
1899           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1900           fclose(fp);
1901           continue;
1902         }
1903       if (chksumh)
1904         sat_chksum_add(chksumh, rpmhead->data, l);
1905       rpmhead->cnt = sigcnt;
1906       rpmhead->dcnt = sigdsize;
1907       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1908       if (headexists(rpmhead, TAG_PATCHESNAME))
1909         {
1910           /* this is a patch rpm, ignore */
1911           fclose(fp);
1912           continue;
1913         }
1914       payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
1915       if (payloadformat && !strcmp(payloadformat, "drpm"))
1916         {
1917           /* this is a delta rpm */
1918           fclose(fp);
1919           continue;
1920         }
1921       if (chksumh)
1922         while ((l = fread(lead, 1, sizeof(lead), fp)) > 0)
1923           sat_chksum_add(chksumh, lead, l);
1924       fclose(fp);
1925       s = pool_id2solvable(pool, repo_add_solvable(repo));
1926       rpm2solv(pool, repo, data, s, rpmhead, flags);
1927       if (data)
1928         {
1929           Id handle = s - pool->solvables;
1930           repodata_set_location(data, handle, 0, 0, rpms[i]);
1931           if (S_ISREG(stb.st_mode))
1932             repodata_set_num(data, handle, SOLVABLE_DOWNLOADSIZE, (unsigned int)((stb.st_size + 1023) / 1024));
1933           repodata_set_num(data, handle, SOLVABLE_HEADEREND, headerend);
1934           if (gotpkgid)
1935             repodata_set_bin_checksum(data, handle, SOLVABLE_PKGID, REPOKEY_TYPE_MD5, pkgid);
1936           if (chksumh)
1937             repodata_set_bin_checksum(data, handle, SOLVABLE_CHECKSUM, chksumtype, sat_chksum_get(chksumh, 0));
1938         }
1939     }
1940   if (chksumh)
1941     chksumh = sat_chksum_free(chksumh, 0);
1942   if (rpmhead)
1943     sat_free(rpmhead);
1944   if (!(flags & REPO_NO_INTERNALIZE))
1945     repodata_internalize(data);
1946 }
1947
1948 Id
1949 repo_add_rpm(Repo *repo, const char *rpm, int flags)
1950 {
1951   int end = repo->end;
1952   repo_add_rpms(repo, &rpm, 1, flags);
1953   if (end == repo->end)
1954     return 0;
1955   else
1956     return repo->end - 1;
1957 }
1958
1959 static inline void
1960 linkhash(const char *lt, char *hash)
1961 {
1962   unsigned int r = 0;
1963   const unsigned char *str = (const unsigned char *)lt;
1964   int l, c;
1965
1966   l = strlen(lt);
1967   while ((c = *str++) != 0)
1968     r += (r << 3) + c;
1969   sprintf(hash, "%08x", r);
1970   sprintf(hash + 8, "%08x", l);
1971   sprintf(hash + 16, "%08x", 0);
1972   sprintf(hash + 24, "%08x", 0);
1973 }
1974
1975 void
1976 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, int, const char *), void *cbdata)
1977 {
1978   RpmHead *rpmhead = rpmhandle;
1979   char **bn;
1980   char **dn;
1981   char **md = 0;
1982   char **lt = 0;
1983   unsigned int *di, diidx;
1984   unsigned int *co = 0;
1985   unsigned int lastdir;
1986   int lastdirl;
1987   unsigned int *fm;
1988   int cnt, dcnt, cnt2;
1989   int i, l1, l;
1990   char *space = 0;
1991   int spacen = 0;
1992   char md5[33], *md5p = 0;
1993
1994   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
1995   if (!dn)
1996     return;
1997   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
1998     {
1999       for (i = 0; i < dcnt; i++)
2000         (*cb)(cbdata, dn[i], 0, (char *)0);
2001       sat_free(dn);
2002       return;
2003     }
2004   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
2005   if (!bn)
2006     {
2007       sat_free(dn);
2008       return;
2009     }
2010   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
2011   if (!di || cnt != cnt2)
2012     {
2013       sat_free(di);
2014       sat_free(bn);
2015       sat_free(dn);
2016       return;
2017     }
2018   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
2019   if (!fm || cnt != cnt2)
2020     {
2021       sat_free(fm);
2022       sat_free(di);
2023       sat_free(bn);
2024       sat_free(dn);
2025       return;
2026     }
2027   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
2028     {
2029       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
2030       if (!md || cnt != cnt2)
2031         {
2032           sat_free(md);
2033           sat_free(fm);
2034           sat_free(di);
2035           sat_free(bn);
2036           sat_free(dn);
2037           return;
2038         }
2039     }
2040   if ((flags & RPM_ITERATE_FILELIST_WITHCOL) != 0)
2041     {
2042       co = headint32array(rpmhead, TAG_FILECOLORS, &cnt2);
2043       if (!co || cnt != cnt2)
2044         {
2045           sat_free(co);
2046           sat_free(md);
2047           sat_free(fm);
2048           sat_free(di);
2049           sat_free(bn);
2050           sat_free(dn);
2051           return;
2052         }
2053     }
2054   lastdir = dcnt;
2055   lastdirl = 0;
2056   for (i = 0; i < cnt; i++)
2057     {
2058       diidx = di[i];
2059       if (diidx >= dcnt)
2060         continue;
2061       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
2062       if (l1 == 0)
2063         continue;
2064       l = l1 + strlen(bn[i]) + 1;
2065       if (l > spacen)
2066         {
2067           spacen = l + 16;
2068           space = sat_realloc(space, spacen);
2069         }
2070       if (lastdir != diidx)
2071         {
2072           strcpy(space, dn[diidx]);
2073           lastdir = diidx;
2074           lastdirl = l1;
2075         }
2076       strcpy(space + l1, bn[i]);
2077       if (md)
2078         {
2079           md5p = md[i];
2080           if (S_ISLNK(fm[i]))
2081             {
2082               md5p = 0;
2083               if (!lt)
2084                 {
2085                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
2086                   if (cnt != cnt2)
2087                     lt = sat_free(lt);
2088                 }
2089               if (lt)
2090                 {
2091                   linkhash(lt[i], md5);
2092                   md5p = md5;
2093                 }
2094             }
2095           if (!md5p)
2096             {
2097               sprintf(md5, "%08x%08x", (fm[i] >> 12) & 65535, 0);
2098               md5p = md5;
2099             }
2100         }
2101       (*cb)(cbdata, space, co ? (fm[i] | co[i] << 24) : fm[i], md5p);
2102     }
2103   sat_free(space);
2104   sat_free(lt);
2105   sat_free(md);
2106   sat_free(fm);
2107   sat_free(di);
2108   sat_free(bn);
2109   sat_free(dn);
2110   sat_free(co);
2111 }
2112
2113 char *
2114 rpm_query(void *rpmhandle, Id what)
2115 {
2116   const char *name, *arch, *sourcerpm;
2117   char *evr, *r;
2118   int l;
2119
2120   RpmHead *rpmhead = rpmhandle;
2121   r = 0;
2122   switch (what)
2123     {
2124     case 0:
2125       name = headstring(rpmhead, TAG_NAME);
2126       if (!name)
2127         name = "";
2128       sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
2129       if (sourcerpm)
2130         arch = headstring(rpmhead, TAG_ARCH);
2131       else
2132         {
2133           if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
2134             arch = "nosrc";
2135           else
2136             arch = "src";
2137         }
2138       if (!arch)
2139         arch = "noarch";
2140       evr = headtoevr(rpmhead);
2141       l = strlen(name) + 1 + strlen(evr) + 1 + strlen(arch) + 1;
2142       r = sat_malloc(l);
2143       sprintf(r, "%s-%s.%s", name, evr, arch);
2144       free(evr);
2145       break;
2146     case SOLVABLE_NAME:
2147       name = headstring(rpmhead, TAG_NAME);
2148       r = strdup(name);
2149       break;
2150     case SOLVABLE_EVR:
2151       r = headtoevr(rpmhead);
2152       break;
2153     }
2154   return r;
2155 }
2156
2157
2158 struct rpm_by_state {
2159   RpmHead *rpmhead;
2160   int rpmheadsize;
2161
2162   int dbopened;
2163   DB_ENV *dbenv;
2164   DB *db;
2165   int byteswapped;
2166 };
2167
2168 struct rpmdbentry {
2169   Id rpmdbid;
2170   Id nameoff;
2171 };
2172
2173 #define ENTRIES_BLOCK 255
2174 #define NAMEDATA_BLOCK 1023
2175
2176 static struct rpmdbentry *
2177 getinstalledrpmdbids(struct rpm_by_state *state, const char *index, const char *match, int *nentriesp, char **namedatap)
2178 {
2179   DB_ENV *dbenv = 0;
2180   DB *db = 0;
2181   DBC *dbc = 0;
2182   int byteswapped;
2183   DBT dbkey;
2184   DBT dbdata;
2185   unsigned char *dp;
2186   int dl;
2187
2188   char *namedata = 0;
2189   int namedatal = 0;
2190   struct rpmdbentry *entries = 0;
2191   int nentries = 0;
2192
2193   *nentriesp = 0;
2194   *namedatap = 0;
2195
2196   dbenv = state->dbenv;
2197   if (db_create(&db, dbenv, 0))
2198     {
2199       perror("db_create");
2200       return 0;
2201     }
2202   if (db->open(db, 0, index, 0, DB_UNKNOWN, DB_RDONLY, 0664))
2203     {
2204       perror("db->open index");
2205       db->close(db, 0);
2206       return 0;
2207     }
2208   if (db->get_byteswapped(db, &byteswapped))
2209     {
2210       perror("db->get_byteswapped");
2211       db->close(db, 0);
2212       return 0;
2213     }
2214   if (db->cursor(db, NULL, &dbc, 0))
2215     {
2216       perror("db->cursor");
2217       db->close(db, 0);
2218       return 0;
2219     }
2220   memset(&dbkey, 0, sizeof(dbkey));
2221   memset(&dbdata, 0, sizeof(dbdata));
2222   if (match)
2223     {
2224       dbkey.data = (void *)match;
2225       dbkey.size = strlen(match);
2226     }
2227   while (dbc->c_get(dbc, &dbkey, &dbdata, match ? DB_SET : DB_NEXT) == 0)
2228     {
2229       if (!match && dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
2230         continue;
2231       dl = dbdata.size;
2232       dp = dbdata.data;
2233       while(dl >= RPM_INDEX_SIZE)
2234         {
2235           entries = sat_extend(entries, nentries, 1, sizeof(*entries), ENTRIES_BLOCK);
2236           entries[nentries].rpmdbid = db2rpmdbid(dp, byteswapped);
2237           entries[nentries].nameoff = namedatal;
2238           nentries++;
2239           namedata = sat_extend(namedata, namedatal, dbkey.size + 1, 1, NAMEDATA_BLOCK);
2240           memcpy(namedata + namedatal, dbkey.data, dbkey.size);
2241           namedata[namedatal + dbkey.size] = 0;
2242           namedatal += dbkey.size + 1;
2243           dp += RPM_INDEX_SIZE;
2244           dl -= RPM_INDEX_SIZE;
2245         }
2246       if (match)
2247         break;
2248     }
2249   dbc->c_close(dbc);
2250   db->close(db, 0);
2251   *nentriesp = nentries;
2252   *namedatap = namedata;
2253   return entries;
2254 }
2255
2256 static void
2257 freestate(struct rpm_by_state *state)
2258 {
2259   /* close down */
2260   if (!state)
2261     return;
2262   if (state->db)
2263     state->db->close(state->db, 0);
2264   if (state->dbenv)
2265     state->dbenv->close(state->dbenv, 0);
2266   sat_free(state->rpmhead);
2267 }
2268
2269 int
2270 rpm_installedrpmdbids(const char *rootdir, const char *index, const char *match, Queue *rpmdbidq)
2271 {
2272   struct rpm_by_state state;
2273   struct rpmdbentry *entries;
2274   int nentries, i;
2275   char *namedata;
2276
2277   if (!index)
2278     index = "Name";
2279   if (rpmdbidq)
2280     queue_empty(rpmdbidq);
2281   memset(&state, 0, sizeof(state));
2282   if (!(state.dbenv = opendbenv(rootdir)))
2283     return 0;
2284   entries = getinstalledrpmdbids(&state, index, match, &nentries, &namedata);
2285   if (rpmdbidq)
2286     for (i = 0; i < nentries; i++)
2287       queue_push(rpmdbidq, entries[i].rpmdbid);
2288   sat_free(entries);
2289   sat_free(namedata);
2290   freestate(&state);
2291   return nentries;
2292 }
2293
2294 void *
2295 rpm_byrpmdbid(Id rpmdbid, const char *rootdir, void **statep)
2296 {
2297   struct rpm_by_state *state = *statep;
2298   unsigned char buf[16];
2299   DBT dbkey;
2300   DBT dbdata;
2301   RpmHead *rpmhead;
2302
2303   if (!rpmdbid)
2304     {
2305       /* close down */
2306       freestate(state);
2307       sat_free(state);
2308       *statep = (void *)0;
2309       return 0;
2310     }
2311
2312   if (!state)
2313     {
2314       state = sat_calloc(1, sizeof(*state));
2315       *statep = state;
2316     }
2317   if (!state->dbopened)
2318     {
2319       state->dbopened = 1;
2320       if (!state->dbenv && !(state->dbenv = opendbenv(rootdir)))
2321         return 0;
2322       if (db_create(&state->db, state->dbenv, 0))
2323         {
2324           perror("db_create");
2325           state->db = 0;
2326           state->dbenv->close(state->dbenv, 0);
2327           state->dbenv = 0;
2328           return 0;
2329         }
2330       if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
2331         {
2332           perror("db->open var/lib/rpm/Packages");
2333           state->db->close(state->db, 0);
2334           state->db = 0;
2335           state->dbenv->close(state->dbenv, 0);
2336           state->dbenv = 0;
2337           return 0;
2338         }
2339       if (state->db->get_byteswapped(state->db, &state->byteswapped))
2340         {
2341           perror("db->get_byteswapped");
2342           state->db->close(state->db, 0);
2343           state->db = 0;
2344           state->dbenv->close(state->dbenv, 0);
2345           state->dbenv = 0;
2346           return 0;
2347         }
2348     }
2349   rpmdbid2db(buf, rpmdbid, state->byteswapped);
2350   memset(&dbkey, 0, sizeof(dbkey));
2351   memset(&dbdata, 0, sizeof(dbdata));
2352   dbkey.data = buf;
2353   dbkey.size = 4;
2354   dbdata.data = 0;
2355   dbdata.size = 0;
2356   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
2357     {
2358       perror("db->get");
2359       return 0;
2360     }
2361   if (dbdata.size < 8)
2362     {
2363       fprintf(stderr, "corrupt rpm database (size)\n");
2364       return 0;
2365     }
2366   if (dbdata.size > state->rpmheadsize)
2367     {
2368       state->rpmheadsize = dbdata.size + 128;
2369       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
2370     }
2371   rpmhead = state->rpmhead;
2372   memcpy(buf, dbdata.data, 8);
2373   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
2374   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
2375   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
2376     {
2377       fprintf(stderr, "corrupt rpm database (data size)\n");
2378       return 0;
2379     }
2380   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
2381   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2382   return rpmhead;
2383 }
2384
2385 void *
2386 rpm_byfp(FILE *fp, const char *name, void **statep)
2387 {
2388   struct rpm_by_state *state = *statep;
2389   int headerstart, headerend;
2390   RpmHead *rpmhead;
2391   int sigdsize, sigcnt, l;
2392   unsigned char lead[4096];
2393
2394   if (!fp)
2395     return rpm_byrpmdbid(0, 0, statep);
2396   if (!state)
2397     {
2398       state = sat_calloc(1, sizeof(*state));
2399       *statep = state;
2400     }
2401   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2402     {
2403       fprintf(stderr, "%s: not a rpm\n", name);
2404       return 0;
2405     }
2406   if (lead[78] != 0 || lead[79] != 5)
2407     {
2408       fprintf(stderr, "%s: not a V5 header\n", name);
2409       return 0;
2410     }
2411   if (getu32(lead + 96) != 0x8eade801)
2412     {
2413       fprintf(stderr, "%s: bad signature header\n", name);
2414       return 0;
2415     }
2416   sigcnt = getu32(lead + 96 + 8);
2417   sigdsize = getu32(lead + 96 + 12);
2418   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2419     {
2420       fprintf(stderr, "%s: bad signature header\n", name);
2421       return 0;
2422     }
2423   sigdsize += sigcnt * 16;
2424   sigdsize = (sigdsize + 7) & ~7;
2425   headerstart = 96 + 16 + sigdsize;
2426   while (sigdsize)
2427     {
2428       l = sigdsize > 4096 ? 4096 : sigdsize;
2429       if (fread(lead, l, 1, fp) != 1)
2430         {
2431           fprintf(stderr, "%s: unexpected EOF\n", name);
2432           return 0;
2433         }
2434       sigdsize -= l;
2435     }
2436   if (fread(lead, 16, 1, fp) != 1)
2437     {
2438       fprintf(stderr, "%s: unexpected EOF\n", name);
2439       return 0;
2440     }
2441   if (getu32(lead) != 0x8eade801)
2442     {
2443       fprintf(stderr, "%s: bad header\n", name);
2444       fclose(fp);
2445       return 0;
2446     }
2447   sigcnt = getu32(lead + 8);
2448   sigdsize = getu32(lead + 12);
2449   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2450     {
2451       fprintf(stderr, "%s: bad header\n", name);
2452       fclose(fp);
2453       return 0;
2454     }
2455   l = sigdsize + sigcnt * 16;
2456   headerend = headerstart + 16 + l;
2457   if (l > state->rpmheadsize)
2458     {
2459       state->rpmheadsize = l + 128;
2460       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2461     }
2462   rpmhead = state->rpmhead;
2463   if (fread(rpmhead->data, l, 1, fp) != 1)
2464     {
2465       fprintf(stderr, "%s: unexpected EOF\n", name);
2466       fclose(fp);
2467       return 0;
2468     }
2469   rpmhead->cnt = sigcnt;
2470   rpmhead->dcnt = sigdsize;
2471   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2472   return rpmhead;
2473 }
2474
2475 void *
2476 rpm_byrpmh(Header h, void **statep)
2477 {
2478   struct rpm_by_state *state = *statep;
2479   const unsigned char *uh;
2480   int sigdsize, sigcnt, l;
2481   RpmHead *rpmhead;
2482
2483 #ifndef RPM5
2484   uh = headerUnload(h);
2485 #else
2486   uh = headerUnload(h, NULL);
2487 #endif
2488   if (!uh)
2489     return 0;
2490   sigcnt = getu32(uh);
2491   sigdsize = getu32(uh + 4);
2492   l = sigdsize + sigcnt * 16;
2493   if (!state)
2494     {
2495       state = sat_calloc(1, sizeof(*state));
2496       *statep = state;
2497     }
2498   if (l > state->rpmheadsize)
2499     {
2500       state->rpmheadsize = l + 128;
2501       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2502     }
2503   rpmhead = state->rpmhead;
2504   memcpy(rpmhead->data, uh + 8, l - 8);
2505   free((void *)uh);
2506   rpmhead->cnt = sigcnt;
2507   rpmhead->dcnt = sigdsize;
2508   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2509   return rpmhead;
2510 }
2511
2512
2513 static char *
2514 r64dec1(char *p, unsigned int *vp, int *eofp)
2515 {
2516   int i, x;
2517   unsigned int v = 0;
2518
2519   for (i = 0; i < 4; )
2520     {
2521       x = *p++;
2522       if (!x)
2523         return 0;
2524       if (x >= 'A' && x <= 'Z')
2525         x -= 'A';
2526       else if (x >= 'a' && x <= 'z')
2527         x -= 'a' - 26;
2528       else if (x >= '0' && x <= '9')
2529         x -= '0' - 52;
2530       else if (x == '+')
2531         x = 62;
2532       else if (x == '/')
2533         x = 63;
2534       else if (x == '=')
2535         {
2536           x = 0;
2537           if (i == 0)
2538             {
2539               *eofp = 3;
2540               *vp = 0;
2541               return p - 1;
2542             }
2543           *eofp += 1;
2544         }
2545       else
2546         continue;
2547       v = v << 6 | x;
2548       i++;
2549     }
2550   *vp = v;
2551   return p;
2552 }
2553
2554 static unsigned int
2555 crc24(unsigned char *p, int len)
2556 {
2557   unsigned int crc = 0xb704ceL;
2558   int i;
2559
2560   while (len--)
2561     {
2562       crc ^= (*p++) << 16;
2563       for (i = 0; i < 8; i++)
2564         if ((crc <<= 1) & 0x1000000)
2565           crc ^= 0x1864cfbL;
2566     }
2567   return crc & 0xffffffL;
2568 }
2569
2570 static unsigned char *
2571 unarmor(char *pubkey, int *pktlp)
2572 {
2573   char *p;
2574   int l, eof;
2575   unsigned char *buf, *bp;
2576   unsigned int v;
2577
2578   *pktlp = 0;
2579   while (strncmp(pubkey, "-----BEGIN PGP PUBLIC KEY BLOCK-----", 36) != 0)
2580     {
2581       pubkey = strchr(pubkey, '\n');
2582       if (!pubkey)
2583         return 0;
2584       pubkey++;
2585     }
2586   pubkey = strchr(pubkey, '\n');
2587   if (!pubkey++)
2588     return 0;
2589   /* skip header lines */
2590   for (;;)
2591     {
2592       while (*pubkey == ' ' || *pubkey == '\t')
2593         pubkey++;
2594       if (*pubkey == '\n')
2595         break;
2596       pubkey = strchr(pubkey, '\n');
2597       if (!pubkey++)
2598         return 0;
2599     }
2600   pubkey++;
2601   p = strchr(pubkey, '=');
2602   if (!p)
2603     return 0;
2604   l = p - pubkey;
2605   bp = buf = sat_malloc(l * 3 / 4 + 4);
2606   eof = 0;
2607   while (!eof)
2608     {
2609       pubkey = r64dec1(pubkey, &v, &eof);
2610       if (!pubkey)
2611         {
2612           sat_free(buf);
2613           return 0;
2614         }
2615       *bp++ = v >> 16;
2616       *bp++ = v >> 8;
2617       *bp++ = v;
2618     }
2619   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2620     pubkey++;
2621   bp -= eof;
2622   if (*pubkey != '=' || (pubkey = r64dec1(pubkey + 1, &v, &eof)) == 0)
2623     {
2624       sat_free(buf);
2625       return 0;
2626     }
2627   if (v != crc24(buf, bp - buf))
2628     {
2629       sat_free(buf);
2630       return 0;
2631     }
2632   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2633     pubkey++;
2634   if (strncmp(pubkey, "-----END PGP PUBLIC KEY BLOCK-----", 34) != 0)
2635     {
2636       sat_free(buf);
2637       return 0;
2638     }
2639   *pktlp = bp - buf;
2640   return buf;
2641 }
2642
2643 static void
2644 parsekeydata(Solvable *s, Repodata *data, unsigned char *p, int pl)
2645 {
2646   int x, tag, l;
2647   unsigned char keyid[8];
2648   unsigned int kcr = 0, maxex = 0;
2649   unsigned char *pubkey = 0;
2650   int pubkeyl = 0;
2651   unsigned char *userid = 0;
2652   int useridl = 0;
2653
2654   for (; pl; p += l, pl -= l)
2655     {
2656       x = *p++;
2657       pl--;
2658       if (!(x & 128) || pl <= 0)
2659         return;
2660       if ((x & 64) == 0)
2661         {
2662           /* old format */
2663           tag = (x & 0x3c) >> 2;
2664           x &= 3;
2665           if (x == 3)
2666             return;
2667           l = 1 << x;
2668           if (pl < l)
2669             return;
2670           x = 0;
2671           while (l--)
2672             {
2673               x = x << 8 | *p++;
2674               pl--;
2675             }
2676           l = x;
2677         }
2678       else
2679         {
2680           tag = (x & 0x3f);
2681           x = *p++;
2682           pl--;
2683           if (x < 192)
2684             l = x;
2685           else if (x >= 192 && x < 224)
2686             {
2687               if (pl <= 0)
2688                 return;
2689               l = ((x - 192) << 8) + *p++ + 192;
2690               pl--;
2691             }
2692           else if (x == 255)
2693             {
2694               if (pl <= 4)
2695                 return;
2696               l = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
2697               p += 4;
2698               pl -= 4;
2699             }
2700           else
2701             return;
2702         }
2703       if (pl < l)
2704         return;
2705       if (tag == 6)
2706         {
2707           pubkey = sat_realloc(pubkey, l);
2708           if (l)
2709             memcpy(pubkey, p, l);
2710           pubkeyl = l;
2711           kcr = 0;
2712           if (p[0] == 3)
2713             {
2714               unsigned int ex;
2715               void *h;
2716               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2717               ex = 0;
2718               if (p[5] || p[6])
2719                 {
2720                   ex = kcr + 24*3600 * (p[5] << 8 | p[6]);
2721                   if (ex > maxex)
2722                     maxex = ex;
2723                 }
2724               memset(keyid, 0, 8);
2725               if (p[7] == 1)    /* RSA */
2726                 {
2727                   int i, ql;
2728                   unsigned char fp[16];
2729                   char fpx[32 + 1];
2730                   unsigned char *q;
2731
2732                   ql = ((p[8] << 8 | p[9]) + 7) / 8;
2733                   memcpy(keyid, p + 10 + ql - 8, 8);
2734                   h = sat_chksum_create(REPOKEY_TYPE_MD5);
2735                   sat_chksum_add(h, p + 10, ql);
2736                   q = p + 10 + ql;
2737                   ql = ((q[0] << 8 | q[1]) + 7) / 8;
2738                   sat_chksum_add(h, q + 2, ql);
2739                   sat_chksum_free(h, fp);
2740                   for (i = 0; i < 16; i++)
2741                     sprintf(fpx + i * 2, "%02x", fp[i]);
2742                   setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2743                 }
2744             }
2745           else if (p[0] == 4)
2746             {
2747               int i;
2748               void *h;
2749               unsigned char hdr[3];
2750               unsigned char fp[20];
2751               char fpx[40 + 1];
2752
2753               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2754               hdr[0] = 0x99;
2755               hdr[1] = l >> 8;
2756               hdr[2] = l;
2757               h = sat_chksum_create(REPOKEY_TYPE_SHA1);
2758               sat_chksum_add(h, hdr, 3);
2759               sat_chksum_add(h, p, l);
2760               sat_chksum_free(h, fp);
2761               for (i = 0; i < 20; i++)
2762                 sprintf(fpx + i * 2, "%02x", fp[i]);
2763               setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2764               memcpy(keyid, fp + 12, 8);
2765             }
2766         }
2767       if (tag == 2)
2768         {
2769           if (p[0] == 3 && p[1] == 5)
2770             {
2771 #if 0
2772               Id htype = 0;
2773 #endif
2774               // printf("V3 signature packet\n");
2775               if (l < 17)
2776                 continue;
2777               if (p[2] != 0x10 && p[2] != 0x11 && p[2] != 0x12 && p[2] != 0x13 && p[2] != 0x1f)
2778                 continue;
2779               if (!memcmp(keyid, p + 6, 8))
2780                 {
2781                   // printf("SELF SIG\n");
2782                 }
2783               else
2784                 {
2785                   // printf("OTHER SIG\n");
2786                 }
2787 #if 0
2788               if (p[16] == 1)
2789                 htype = REPOKEY_TYPE_MD5;
2790               else if (p[16] == 2)
2791                 htype = REPOKEY_TYPE_SHA1;
2792               else if (p[16] == 8)
2793                 htype = REPOKEY_TYPE_SHA256;
2794               if (htype)
2795                 {
2796                   void *h = sat_chksum_create(htype);
2797                   unsigned char b[3], *cs;
2798
2799                   b[0] = 0x99;
2800                   b[1] = pubkeyl >> 8;
2801                   b[2] = pubkeyl;
2802                   sat_chksum_add(h, b, 3);
2803                   sat_chksum_add(h, pubkey, pubkeyl);
2804                   if (p[2] >= 0x10 && p[2] <= 0x13)
2805                     sat_chksum_add(h, userid, useridl);
2806                   sat_chksum_add(h, p + 2, 5);
2807                   cs = sat_chksum_get(h, 0);
2808                   sat_chksum_free(h, 0);
2809                 }
2810 #endif
2811             }
2812           if (p[0] == 4)
2813             {
2814               int j, ql, haveissuer;
2815               unsigned char *q;
2816               unsigned int ex = 0, scr = 0;
2817               unsigned char issuer[8];
2818
2819               // printf("V4 signature packet\n");
2820               if (l < 6)
2821                 continue;
2822               if (p[1] != 0x10 && p[1] != 0x11 && p[1] != 0x12 && p[1] != 0x13 && p[1] != 0x1f)
2823                 continue;
2824               haveissuer = 0;
2825               ex = 0;
2826               q = p + 4;
2827               for (j = 0; q && j < 2; j++)
2828                 {
2829                   if (q + 2 > p + l)
2830                     {
2831                       q = 0;
2832                       break;
2833                     }
2834                   ql = q[0] << 8 | q[1];
2835                   q += 2;
2836                   if (q + ql > p + l)
2837                     {
2838                       q = 0;
2839                       break;
2840                     }
2841                   while (ql)
2842                     {
2843                       int sl;
2844                       x = *q++;
2845                       ql--;
2846                       if (x < 192)
2847                         sl = x;
2848                       else if (x == 255)
2849                         {
2850                           if (ql < 4)
2851                             {
2852                               q = 0;
2853                               break;
2854                             }
2855                           sl = q[0] << 24 | q[1] << 16 | q[2] << 8 | q[3];
2856                           q += 4;
2857                           ql -= 4;
2858                         }
2859                       else
2860                         {
2861                           if (ql < 1)
2862                             {
2863                               q = 0;
2864                               break;
2865                             }
2866                           sl = ((x - 192) << 8) + *q++ + 192;
2867                           ql--;
2868                         }
2869                       if (ql < sl)
2870                         {
2871                           q = 0;
2872                           break;
2873                         }
2874                       x = q[0] & 127;
2875                       // printf("%d SIGSUB %d %d\n", j, x, sl);
2876                       if (x == 16 && sl == 9 && !haveissuer)
2877                         {
2878                           memcpy(issuer, q + 1, 8);
2879                           haveissuer = 1;
2880                         }
2881                       if (x == 2 && j == 0)
2882                         scr = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2883                       if (x == 9 && j == 0)
2884                         ex = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2885                       q += sl;
2886                       ql -= sl;
2887                     }
2888                 }
2889               if (ex)
2890                 ex += kcr;
2891               if (haveissuer)
2892                 {
2893 #if 0
2894                   Id htype = 0;
2895                   if (p[3] == 1)
2896                     htype = REPOKEY_TYPE_MD5;
2897                   else if (p[3] == 2)
2898                     htype = REPOKEY_TYPE_SHA1;
2899                   else if (p[3] == 8)
2900                     htype = REPOKEY_TYPE_SHA256;
2901                   if (htype && pubkeyl)
2902                     {
2903                       void *h = sat_chksum_create(htype);
2904                       unsigned char b[6], *cs;
2905                       unsigned int hl;
2906
2907                       b[0] = 0x99;
2908                       b[1] = pubkeyl >> 8;
2909                       b[2] = pubkeyl;
2910                       sat_chksum_add(h, b, 3);
2911                       sat_chksum_add(h, pubkey, pubkeyl);
2912                       if (p[1] >= 0x10 && p[1] <= 0x13)
2913                         {
2914                           b[0] = 0xb4;
2915                           b[1] = useridl >> 24;
2916                           b[2] = useridl >> 16;
2917                           b[3] = useridl >> 8;
2918                           b[4] = useridl;
2919                           sat_chksum_add(h, b, 5);
2920                           sat_chksum_add(h, userid, useridl);
2921                         }
2922                       hl = 6 + (p[4] << 8 | p[5]);
2923                       sat_chksum_add(h, p, hl);
2924                       b[0] = 4;
2925                       b[1] = 0xff;
2926                       b[2] = hl >> 24;
2927                       b[3] = hl >> 16;
2928                       b[4] = hl >> 8;
2929                       b[5] = hl;
2930                       sat_chksum_add(h, b, 6);
2931                       cs = sat_chksum_get(h, 0);
2932                       sat_chksum_free(h, 0);
2933                     }
2934 #endif
2935                   if (!memcmp(keyid, issuer, 8))
2936                     {
2937                       // printf("SELF SIG cr %d ex %d\n", cr, ex);
2938                       if (ex > maxex)
2939                         maxex = ex;
2940                     }
2941                   else
2942                     {
2943                       // printf("OTHER SIG cr %d ex %d\n", cr, ex);
2944                     }
2945                 }
2946             }
2947         }
2948       if (tag == 13)
2949         {
2950           userid = sat_realloc(userid, l);
2951           if (l)
2952             memcpy(userid, p, l);
2953           useridl = l;
2954         }
2955     }
2956   if (maxex)
2957     repodata_set_num(data, s - s->repo->pool->solvables, PUBKEY_EXPIRES, maxex);
2958   sat_free(pubkey);
2959   sat_free(userid);
2960 }
2961
2962 /* this is private to rpm, but rpm lacks an interface to retrieve
2963  * the values. Sigh. */
2964 struct pgpDigParams_s {
2965     const char * userid;
2966     const unsigned char * hash;
2967     const char * params[4];
2968     unsigned char tag;
2969     unsigned char version;               /*!< version number. */
2970     unsigned char time[4];               /*!< time that the key was created. */
2971     unsigned char pubkey_algo;           /*!< public key algorithm. */
2972     unsigned char hash_algo;
2973     unsigned char sigtype;
2974     unsigned char hashlen;
2975     unsigned char signhash16[2];
2976     unsigned char signid[8];
2977     unsigned char saved;
2978 };
2979
2980 struct pgpDig_s {
2981     struct pgpDigParams_s signature;
2982     struct pgpDigParams_s pubkey;
2983 };
2984
2985 static int
2986 pubkey2solvable(Solvable *s, Repodata *data, char *pubkey)
2987 {
2988   Pool *pool = s->repo->pool;
2989   unsigned char *pkts;
2990   unsigned int btime;
2991   int pktsl, i;
2992   pgpDig dig = 0;
2993   char keyid[16 + 1];
2994   char evrbuf[8 + 1 + 8 + 1];
2995
2996   pkts = unarmor(pubkey, &pktsl);
2997   if (!pkts)
2998     return 0;
2999   setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_DESCRIPTION, pubkey);
3000   parsekeydata(s, data, pkts, pktsl);
3001   /* only rpm knows how to do the release calculation, we don't dare
3002    * to recreate all the bugs */
3003 #ifndef RPM5
3004   dig = pgpNewDig();
3005 #else
3006   dig = pgpDigNew(RPMVSF_DEFAULT, 0);
3007 #endif
3008   (void) pgpPrtPkts(pkts, pktsl, dig, 0);
3009   btime = dig->pubkey.time[0] << 24 | dig->pubkey.time[1] << 16 | dig->pubkey.time[2] << 8 | dig->pubkey.signid[3];
3010   sprintf(evrbuf, "%02x%02x%02x%02x-%02x%02x%02x%02x", dig->pubkey.signid[4], dig->pubkey.signid[5], dig->pubkey.signid[6], dig->pubkey.signid[7], dig->pubkey.time[0], dig->pubkey.time[1], dig->pubkey.time[2], dig->pubkey.time[3]);
3011   repodata_set_num(data, s - s->repo->pool->solvables, SOLVABLE_BUILDTIME, btime);
3012
3013   s->name = str2id(pool, "gpg-pubkey", 1);
3014   s->evr = str2id(pool, evrbuf, 1);
3015   s->arch = 1;
3016   for (i = 0; i < 8; i++)
3017     sprintf(keyid + 2 * i, "%02x", dig->pubkey.signid[i]);
3018   repodata_set_str(data, s - s->repo->pool->solvables, PUBKEY_KEYID, keyid);
3019   if (dig->pubkey.userid)
3020     setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_SUMMARY, dig->pubkey.userid);
3021   (void)pgpFreeDig(dig);
3022   sat_free((void *)pkts);
3023   return 1;
3024 }
3025
3026 void
3027 repo_add_rpmdb_pubkeys(Repo *repo, const char *rootdir, int flags)
3028 {
3029   Pool *pool = repo->pool;
3030   struct rpm_by_state state;
3031   struct rpmdbentry *entries;
3032   int nentries, i;
3033   char *namedata, *str;
3034   unsigned int u32;
3035   Repodata *data;
3036   Solvable *s;
3037
3038   data = repo_add_repodata(repo, flags);
3039
3040   memset(&state, 0, sizeof(state));
3041   if (!(state.dbenv = opendbenv(rootdir)))
3042     return;
3043   entries = getinstalledrpmdbids(&state, "Name", "gpg-pubkey", &nentries, &namedata);
3044   for (i = 0 ; i < nentries; i++)
3045     {
3046       void *statep = &state;
3047       RpmHead *rpmhead = rpm_byrpmdbid(entries[i].rpmdbid, rootdir, &statep);
3048       if (!rpmhead)
3049         continue;
3050       str = headstring(rpmhead, TAG_DESCRIPTION);
3051       if (!str)
3052         continue;
3053       s = pool_id2solvable(pool, repo_add_solvable(repo));
3054       pubkey2solvable(s, data, str);
3055       u32 = headint32(rpmhead, TAG_INSTALLTIME);
3056       if (u32)
3057         repodata_set_num(data, s - pool->solvables, SOLVABLE_INSTALLTIME, u32);
3058       if (!repo->rpmdbid)
3059         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
3060       repo->rpmdbid[s - pool->solvables - repo->start] = entries[i].rpmdbid;
3061     }
3062   sat_free(entries);
3063   sat_free(namedata);
3064   freestate(&state);
3065   if (!(flags & REPO_NO_INTERNALIZE))
3066     repodata_internalize(data);
3067 }
3068
3069 void
3070 repo_add_pubkeys(Repo *repo, const char **keys, int nkeys, int flags)
3071 {
3072   Pool *pool = repo->pool;
3073   Repodata *data;
3074   Solvable *s;
3075   char *buf;
3076   int i, bufl, l, ll;
3077   FILE *fp;
3078
3079   data = repo_add_repodata(repo, flags);
3080   buf = 0;
3081   bufl = 0;
3082   for (i = 0; i < nkeys; i++)
3083     {
3084       if ((fp = fopen(keys[i], "r")) == 0)
3085         {
3086           perror(keys[i]);
3087           continue;
3088         }
3089       for (l = 0; ;)
3090         {
3091           if (bufl - l < 4096)
3092             {
3093               bufl += 4096;
3094               buf = sat_realloc(buf, bufl);
3095             }
3096           ll = fread(buf, 1, bufl - l, fp);
3097           if (ll <= 0)
3098             break;
3099           l += ll;
3100         }
3101       buf[l] = 0;
3102       fclose(fp);
3103       s = pool_id2solvable(pool, repo_add_solvable(repo));
3104       pubkey2solvable(s, data, buf);
3105     }
3106   sat_free(buf);
3107   if (!(flags & REPO_NO_INTERNALIZE))
3108     repodata_internalize(data);
3109 }