- make peace with gcc46
[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 # else
1263   if (byteswapped)
1264 # endif
1265     db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1266   else
1267     db[3] = id >> 24, db[2] = id >> 16, db[1] = id >> 8, db[0] = id;
1268 #endif
1269 }
1270
1271 static void
1272 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1273 {
1274   memset(cookie, 0, 32);
1275   cookie[3] = RPMDB_COOKIE_VERSION;
1276   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1277   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1278 }
1279
1280 /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1281 static DB_ENV *
1282 opendbenv(const char *rootdir)
1283 {
1284   char dbpath[PATH_MAX];
1285   DB_ENV *dbenv = 0;
1286   int r;
1287
1288   if (db_env_create(&dbenv, 0))
1289     {
1290       perror("db_env_create");
1291       return 0;
1292     }
1293 #if defined(FEDORA) && (DB_VERSION_MAJOR >= 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 5))
1294   dbenv->set_thread_count(dbenv, 8);
1295 #endif
1296   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1297   if (access(dbpath, W_OK) == -1)
1298     {
1299       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1300     }
1301   else
1302     {
1303 #ifdef FEDORA
1304       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0644);
1305 #else
1306       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1307 #endif
1308     }
1309   if (r)
1310     {
1311       perror("dbenv open");
1312       dbenv->close(dbenv, 0);
1313       return 0;
1314     }
1315   return dbenv;
1316 }
1317
1318
1319 static int
1320 count_headers(const char *rootdir, DB_ENV *dbenv)
1321 {
1322   char dbpath[PATH_MAX];
1323   struct stat statbuf;
1324   DB *db = 0;
1325   DBC *dbc = 0;
1326   int count = 0;
1327   DBT dbkey;
1328   DBT dbdata;
1329
1330   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir);
1331   if (stat(dbpath, &statbuf))
1332     return 0;
1333   memset(&dbkey, 0, sizeof(dbkey));
1334   memset(&dbdata, 0, sizeof(dbdata));
1335   if (db_create(&db, dbenv, 0))
1336     {
1337       perror("db_create");
1338       exit(1);
1339     }
1340   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1341     {
1342       perror("db->open Name index");
1343       exit(1);
1344     }
1345   if (db->cursor(db, NULL, &dbc, 0))
1346     {
1347       perror("db->cursor");
1348       exit(1);
1349     }
1350   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1351     count += dbdata.size / RPM_INDEX_SIZE;
1352   dbc->c_close(dbc);
1353   db->close(db, 0);
1354   return count;
1355 }
1356
1357 /*
1358  * read rpm db as repo
1359  *
1360  */
1361
1362 void
1363 repo_add_rpmdb(Repo *repo, Repo *ref, const char *rootdir, int flags)
1364 {
1365   Pool *pool = repo->pool;
1366   unsigned char buf[16];
1367   DB *db = 0;
1368   DBC *dbc = 0;
1369   int byteswapped;
1370   unsigned int dbid;
1371   unsigned char *dp;
1372   int dl, nrpmids;
1373   struct rpmid *rpmids, *rp;
1374   int i;
1375   int rpmheadsize;
1376   RpmHead *rpmhead;
1377   Solvable *s;
1378   Id id, *refhash;
1379   unsigned int refmask, h;
1380   char dbpath[PATH_MAX];
1381   DB_ENV *dbenv = 0;
1382   DBT dbkey;
1383   DBT dbdata;
1384   struct stat packagesstat;
1385   unsigned char newcookie[32];
1386   const unsigned char *oldcookie = 0;
1387   Id oldcookietype = 0;
1388   Repodata *data;
1389   int count = 0, done = 0;
1390   unsigned int now;
1391
1392   now = sat_timems(0);
1393   memset(&dbkey, 0, sizeof(dbkey));
1394   memset(&dbdata, 0, sizeof(dbdata));
1395
1396   if (!rootdir)
1397     rootdir = "";
1398
1399   data = repo_add_repodata(repo, flags);
1400
1401   if (ref && !(ref->nsolvables && ref->rpmdbid))
1402     ref = 0;
1403
1404   if (!(dbenv = opendbenv(rootdir)))
1405     exit(1);
1406
1407   /* XXX: should get ro lock of Packages database! */
1408   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir);
1409   if (stat(dbpath, &packagesstat))
1410     {
1411       perror(dbpath);
1412       exit(1);
1413     }
1414   mkrpmdbcookie(&packagesstat, newcookie);
1415   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1416
1417   if (ref)
1418     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1419   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1420     {
1421       Id *pkgids;
1422       int solvstart = 0, solvend = 0;
1423
1424       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1425         count = count_headers(rootdir, dbenv);
1426       if (db_create(&db, dbenv, 0))
1427         {
1428           perror("db_create");
1429           exit(1);
1430         }
1431       if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1432         {
1433           perror("db->open Packages index");
1434           exit(1);
1435         }
1436       if (db->get_byteswapped(db, &byteswapped))
1437         {
1438           perror("db->get_byteswapped");
1439           exit(1);
1440         }
1441       if (db->cursor(db, NULL, &dbc, 0))
1442         {
1443           perror("db->cursor");
1444           exit(1);
1445         }
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       nrpmids = 0;
1565       rpmids = 0;
1566       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1567         {
1568           if (dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1569             continue;
1570           dl = dbdata.size;
1571           dp = dbdata.data;
1572           while(dl >= RPM_INDEX_SIZE)
1573             {
1574               rpmids = sat_extend(rpmids, nrpmids, 1, sizeof(*rpmids), 255);
1575               rpmids[nrpmids].dbid = db2rpmdbid(dp, byteswapped);
1576               rpmids[nrpmids].name = sat_malloc((int)dbkey.size + 1);
1577               memcpy(rpmids[nrpmids].name, dbkey.data, (int)dbkey.size);
1578               rpmids[nrpmids].name[(int)dbkey.size] = 0;
1579               nrpmids++;
1580               dp += RPM_INDEX_SIZE;
1581               dl -= RPM_INDEX_SIZE;
1582             }
1583         }
1584       dbc->c_close(dbc);
1585       db->close(db, 0);
1586       db = 0;
1587
1588       /* sort rpmids */
1589       sat_sort(rpmids, nrpmids, sizeof(*rpmids), rpmids_sort_cmp, 0);
1590
1591       rpmheadsize = 0;
1592       rpmhead = 0;
1593
1594       /* create hash from dbid to ref */
1595       refmask = mkmask(ref->nsolvables);
1596       refhash = sat_calloc(refmask + 1, sizeof(Id));
1597       for (i = 0; i < ref->end - ref->start; i++)
1598         {
1599           if (!ref->rpmdbid[i])
1600             continue;
1601           h = ref->rpmdbid[i] & refmask;
1602           while (refhash[h])
1603             h = (h + 317) & refmask;
1604           refhash[h] = i + 1;   /* make it non-zero */
1605         }
1606
1607       /* count the misses, they will cost us time */
1608       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1609         {
1610           for (i = 0, rp = rpmids; i < nrpmids; i++, rp++)
1611             {
1612               dbid = rp->dbid;
1613               if (refhash)
1614                 {
1615                   h = dbid & refmask;
1616                   while ((id = refhash[h]))
1617                     {
1618                       if (ref->rpmdbid[id - 1] == dbid)
1619                         break;
1620                       h = (h + 317) & refmask;
1621                     }
1622                   if (id)
1623                     continue;
1624                 }
1625               count++;
1626             }
1627         }
1628
1629       s = pool_id2solvable(pool, repo_add_solvable_block(repo, nrpmids));
1630       if (!repo->rpmdbid)
1631         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1632
1633       for (i = 0, rp = rpmids; i < nrpmids; i++, rp++, s++)
1634         {
1635           dbid = rp->dbid;
1636           repo->rpmdbid[(s - pool->solvables) - repo->start] = rp->dbid;
1637           if (refhash)
1638             {
1639               h = dbid & refmask;
1640               while ((id = refhash[h]))
1641                 {
1642                   if (ref->rpmdbid[id - 1] == dbid)
1643                     break;
1644                   h = (h + 317) & refmask;
1645                 }
1646               if (id)
1647                 {
1648                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1649                   if (r->repo == ref)
1650                     {
1651                       solvable_copy(s, r, data, dircache);
1652                       continue;
1653                     }
1654                 }
1655             }
1656           if (!db)
1657             {
1658               if (db_create(&db, dbenv, 0))
1659                 {
1660                   perror("db_create");
1661                   exit(1);
1662                 }
1663               if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1664                 {
1665                   perror("db->open var/lib/rpm/Packages");
1666                   exit(1);
1667                 }
1668               if (db->get_byteswapped(db, &byteswapped))
1669                 {
1670                   perror("db->get_byteswapped");
1671                   exit(1);
1672                 }
1673             }
1674           rpmdbid2db(buf, rp->dbid, byteswapped);
1675           dbkey.data = buf;
1676           dbkey.size = 4;
1677           dbdata.data = 0;
1678           dbdata.size = 0;
1679           if (db->get(db, NULL, &dbkey, &dbdata, 0))
1680             {
1681               perror("db->get");
1682               fprintf(stderr, "corrupt rpm database, key %d not found\n", dbid);
1683               fprintf(stderr, "please run 'rpm --rebuilddb' to recreate the database index files\n");
1684               exit(1);
1685             }
1686           if (dbdata.size < 8)
1687             {
1688               fprintf(stderr, "corrupt rpm database (size)\n");
1689               exit(1);
1690             }
1691           if (dbdata.size > rpmheadsize)
1692             {
1693               rpmheadsize = dbdata.size + 128;
1694               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1695             }
1696           memcpy(buf, dbdata.data, 8);
1697           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1698           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1699           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1700             {
1701               fprintf(stderr, "corrupt rpm database (data size)\n");
1702               exit(1);
1703             }
1704           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1705           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1706
1707           rpm2solv(pool, repo, data, s, rpmhead, flags | RPM_ADD_TRIGGERS);
1708           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1709             {
1710               if (done < count)
1711                 done++;
1712               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1713                 pool_debug(pool, SAT_ERROR, "%%%% %d\n", done * 100 / count);
1714             }
1715         }
1716
1717       if (refhash)
1718         sat_free(refhash);
1719       if (rpmids)
1720         {
1721           for (i = 0; i < nrpmids; i++)
1722             sat_free(rpmids[i].name);
1723           sat_free(rpmids);
1724         }
1725     }
1726   if (db)
1727     db->close(db, 0);
1728   dbenv->close(dbenv, 0);
1729   if (rpmhead)
1730     sat_free(rpmhead);
1731   if (!(flags & REPO_NO_INTERNALIZE))
1732     repodata_internalize(data);
1733   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1734     pool_debug(pool, SAT_ERROR, "%%%% 100\n");
1735   POOL_DEBUG(SAT_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", sat_timems(now));
1736   POOL_DEBUG(SAT_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1737   POOL_DEBUG(SAT_DEBUG_STATS, "repo memory used: %d K incore, %d K idarray\n", data->incoredatalen/1024, repo->idarraysize / (int)(1024/sizeof(Id)));
1738 }
1739
1740
1741 static inline unsigned int
1742 getu32(const unsigned char *dp)
1743 {
1744   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1745 }
1746
1747
1748 void
1749 repo_add_rpms(Repo *repo, const char **rpms, int nrpms, int flags)
1750 {
1751   int i, sigdsize, sigcnt, l;
1752   Pool *pool = repo->pool;
1753   Solvable *s;
1754   RpmHead *rpmhead = 0;
1755   int rpmheadsize = 0;
1756   char *payloadformat;
1757   FILE *fp;
1758   unsigned char lead[4096];
1759   int headerstart, headerend;
1760   struct stat stb;
1761   Repodata *data;
1762   unsigned char pkgid[16];
1763   int gotpkgid;
1764   Id chksumtype = 0;
1765   void *chksumh = 0;
1766
1767   data = repo_add_repodata(repo, flags);
1768
1769   if ((flags & RPM_ADD_WITH_SHA256SUM) != 0)
1770     chksumtype = REPOKEY_TYPE_SHA256;
1771   else if ((flags & RPM_ADD_WITH_SHA1SUM) != 0)
1772     chksumtype = REPOKEY_TYPE_SHA1;
1773   for (i = 0; i < nrpms; i++)
1774     {
1775       if ((fp = fopen(rpms[i], "r")) == 0)
1776         {
1777           perror(rpms[i]);
1778           continue;
1779         }
1780       if (fstat(fileno(fp), &stb))
1781         {
1782           perror("stat");
1783           continue;
1784         }
1785       if (chksumh)
1786         chksumh = sat_chksum_free(chksumh, 0);
1787       if (chksumtype)
1788         chksumh = sat_chksum_create(chksumtype);
1789       if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1790         {
1791           fprintf(stderr, "%s: not a rpm\n", rpms[i]);
1792           fclose(fp);
1793           continue;
1794         }
1795       if (chksumh)
1796         sat_chksum_add(chksumh, lead, 96 + 16);
1797       if (lead[78] != 0 || lead[79] != 5)
1798         {
1799           fprintf(stderr, "%s: not a V5 header\n", rpms[i]);
1800           fclose(fp);
1801           continue;
1802         }
1803       if (getu32(lead + 96) != 0x8eade801)
1804         {
1805           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1806           fclose(fp);
1807           continue;
1808         }
1809       sigcnt = getu32(lead + 96 + 8);
1810       sigdsize = getu32(lead + 96 + 12);
1811       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1812         {
1813           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1814           fclose(fp);
1815           continue;
1816         }
1817       sigdsize += sigcnt * 16;
1818       sigdsize = (sigdsize + 7) & ~7;
1819       headerstart = 96 + 16 + sigdsize;
1820       gotpkgid = 0;
1821       if ((flags & RPM_ADD_WITH_PKGID) != 0)
1822         {
1823           unsigned char *chksum;
1824           unsigned int chksumsize;
1825           /* extract pkgid from the signature header */
1826           if (sigdsize > rpmheadsize)
1827             {
1828               rpmheadsize = sigdsize + 128;
1829               rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1830             }
1831           if (fread(rpmhead->data, sigdsize, 1, fp) != 1)
1832             {
1833               fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1834               fclose(fp);
1835               continue;
1836             }
1837           if (chksumh)
1838             sat_chksum_add(chksumh, rpmhead->data, sigdsize);
1839           rpmhead->cnt = sigcnt;
1840           rpmhead->dcnt = sigdsize - sigcnt * 16;
1841           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1842           chksum = headbinary(rpmhead, SIGTAG_MD5, &chksumsize);
1843           if (chksum && chksumsize == 16)
1844             {
1845               gotpkgid = 1;
1846               memcpy(pkgid, chksum, 16);
1847             }
1848         }
1849       else
1850         {
1851           /* just skip the signature header */
1852           while (sigdsize)
1853             {
1854               l = sigdsize > 4096 ? 4096 : sigdsize;
1855               if (fread(lead, l, 1, fp) != 1)
1856                 {
1857                   fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1858                   fclose(fp);
1859                   continue;
1860                 }
1861               if (chksumh)
1862                 sat_chksum_add(chksumh, lead, l);
1863               sigdsize -= l;
1864             }
1865         }
1866       if (fread(lead, 16, 1, fp) != 1)
1867         {
1868           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1869           fclose(fp);
1870           continue;
1871         }
1872       if (chksumh)
1873         sat_chksum_add(chksumh, lead, 16);
1874       if (getu32(lead) != 0x8eade801)
1875         {
1876           fprintf(stderr, "%s: bad header\n", rpms[i]);
1877           fclose(fp);
1878           continue;
1879         }
1880       sigcnt = getu32(lead + 8);
1881       sigdsize = getu32(lead + 12);
1882       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1883         {
1884           fprintf(stderr, "%s: bad header\n", rpms[i]);
1885           fclose(fp);
1886           continue;
1887         }
1888       l = sigdsize + sigcnt * 16;
1889       headerend = headerstart + 16 + l;
1890       if (l > rpmheadsize)
1891         {
1892           rpmheadsize = l + 128;
1893           rpmhead = sat_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1894         }
1895       if (fread(rpmhead->data, l, 1, fp) != 1)
1896         {
1897           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1898           fclose(fp);
1899           continue;
1900         }
1901       if (chksumh)
1902         sat_chksum_add(chksumh, rpmhead->data, l);
1903       rpmhead->cnt = sigcnt;
1904       rpmhead->dcnt = sigdsize;
1905       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1906       if (headexists(rpmhead, TAG_PATCHESNAME))
1907         {
1908           /* this is a patch rpm, ignore */
1909           fclose(fp);
1910           continue;
1911         }
1912       payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
1913       if (payloadformat && !strcmp(payloadformat, "drpm"))
1914         {
1915           /* this is a delta rpm */
1916           fclose(fp);
1917           continue;
1918         }
1919       if (chksumh)
1920         while ((l = fread(lead, 1, sizeof(lead), fp)) > 0)
1921           sat_chksum_add(chksumh, lead, l);
1922       fclose(fp);
1923       s = pool_id2solvable(pool, repo_add_solvable(repo));
1924       rpm2solv(pool, repo, data, s, rpmhead, flags);
1925       if (data)
1926         {
1927           Id handle = s - pool->solvables;
1928           repodata_set_location(data, handle, 0, 0, rpms[i]);
1929           if (S_ISREG(stb.st_mode))
1930             repodata_set_num(data, handle, SOLVABLE_DOWNLOADSIZE, (unsigned int)((stb.st_size + 1023) / 1024));
1931           repodata_set_num(data, handle, SOLVABLE_HEADEREND, headerend);
1932           if (gotpkgid)
1933             repodata_set_bin_checksum(data, handle, SOLVABLE_PKGID, REPOKEY_TYPE_MD5, pkgid);
1934           if (chksumh)
1935             repodata_set_bin_checksum(data, handle, SOLVABLE_CHECKSUM, chksumtype, sat_chksum_get(chksumh, 0));
1936         }
1937     }
1938   if (chksumh)
1939     chksumh = sat_chksum_free(chksumh, 0);
1940   if (rpmhead)
1941     sat_free(rpmhead);
1942   if (!(flags & REPO_NO_INTERNALIZE))
1943     repodata_internalize(data);
1944 }
1945
1946 Id
1947 repo_add_rpm(Repo *repo, const char *rpm, int flags)
1948 {
1949   int end = repo->end;
1950   repo_add_rpms(repo, &rpm, 1, flags);
1951   if (end == repo->end)
1952     return 0;
1953   else
1954     return repo->end - 1;
1955 }
1956
1957 static inline void
1958 linkhash(const char *lt, char *hash)
1959 {
1960   unsigned int r = 0;
1961   const unsigned char *str = (const unsigned char *)lt;
1962   int l, c;
1963
1964   l = strlen(lt);
1965   while ((c = *str++) != 0)
1966     r += (r << 3) + c;
1967   sprintf(hash, "%08x", r);
1968   sprintf(hash + 8, "%08x", l);
1969   sprintf(hash + 16, "%08x", 0);
1970   sprintf(hash + 24, "%08x", 0);
1971 }
1972
1973 void
1974 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, int, const char *), void *cbdata)
1975 {
1976   RpmHead *rpmhead = rpmhandle;
1977   char **bn;
1978   char **dn;
1979   char **md = 0;
1980   char **lt = 0;
1981   unsigned int *di, diidx;
1982   unsigned int *co = 0;
1983   unsigned int lastdir;
1984   int lastdirl;
1985   unsigned int *fm;
1986   int cnt, dcnt, cnt2;
1987   int i, l1, l;
1988   char *space = 0;
1989   int spacen = 0;
1990   char md5[33], *md5p = 0;
1991
1992   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
1993   if (!dn)
1994     return;
1995   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
1996     {
1997       for (i = 0; i < dcnt; i++)
1998         (*cb)(cbdata, dn[i], 0, (char *)0);
1999       sat_free(dn);
2000       return;
2001     }
2002   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
2003   if (!bn)
2004     {
2005       sat_free(dn);
2006       return;
2007     }
2008   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
2009   if (!di || cnt != cnt2)
2010     {
2011       sat_free(di);
2012       sat_free(bn);
2013       sat_free(dn);
2014       return;
2015     }
2016   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
2017   if (!fm || cnt != cnt2)
2018     {
2019       sat_free(fm);
2020       sat_free(di);
2021       sat_free(bn);
2022       sat_free(dn);
2023       return;
2024     }
2025   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
2026     {
2027       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
2028       if (!md || cnt != cnt2)
2029         {
2030           sat_free(md);
2031           sat_free(fm);
2032           sat_free(di);
2033           sat_free(bn);
2034           sat_free(dn);
2035           return;
2036         }
2037     }
2038   if ((flags & RPM_ITERATE_FILELIST_WITHCOL) != 0)
2039     {
2040       co = headint32array(rpmhead, TAG_FILECOLORS, &cnt2);
2041       if (!co || cnt != cnt2)
2042         {
2043           sat_free(co);
2044           sat_free(md);
2045           sat_free(fm);
2046           sat_free(di);
2047           sat_free(bn);
2048           sat_free(dn);
2049           return;
2050         }
2051     }
2052   lastdir = dcnt;
2053   lastdirl = 0;
2054   for (i = 0; i < cnt; i++)
2055     {
2056       diidx = di[i];
2057       if (diidx >= dcnt)
2058         continue;
2059       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
2060       if (l1 == 0)
2061         continue;
2062       l = l1 + strlen(bn[i]) + 1;
2063       if (l > spacen)
2064         {
2065           spacen = l + 16;
2066           space = sat_realloc(space, spacen);
2067         }
2068       if (lastdir != diidx)
2069         {
2070           strcpy(space, dn[diidx]);
2071           lastdir = diidx;
2072           lastdirl = l1;
2073         }
2074       strcpy(space + l1, bn[i]);
2075       if (md)
2076         {
2077           md5p = md[i];
2078           if (S_ISLNK(fm[i]))
2079             {
2080               md5p = 0;
2081               if (!lt)
2082                 {
2083                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
2084                   if (cnt != cnt2)
2085                     lt = sat_free(lt);
2086                 }
2087               if (lt)
2088                 {
2089                   linkhash(lt[i], md5);
2090                   md5p = md5;
2091                 }
2092             }
2093           if (!md5p)
2094             {
2095               sprintf(md5, "%08x%08x", (fm[i] >> 12) & 65535, 0);
2096               md5p = md5;
2097             }
2098         }
2099       (*cb)(cbdata, space, co ? (fm[i] | co[i] << 24) : fm[i], md5p);
2100     }
2101   sat_free(space);
2102   sat_free(lt);
2103   sat_free(md);
2104   sat_free(fm);
2105   sat_free(di);
2106   sat_free(bn);
2107   sat_free(dn);
2108   sat_free(co);
2109 }
2110
2111 char *
2112 rpm_query(void *rpmhandle, Id what)
2113 {
2114   const char *name, *arch, *sourcerpm;
2115   char *evr, *r;
2116   int l;
2117
2118   RpmHead *rpmhead = rpmhandle;
2119   r = 0;
2120   switch (what)
2121     {
2122     case 0:
2123       name = headstring(rpmhead, TAG_NAME);
2124       if (!name)
2125         name = "";
2126       sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
2127       if (sourcerpm)
2128         arch = headstring(rpmhead, TAG_ARCH);
2129       else
2130         {
2131           if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
2132             arch = "nosrc";
2133           else
2134             arch = "src";
2135         }
2136       if (!arch)
2137         arch = "noarch";
2138       evr = headtoevr(rpmhead);
2139       l = strlen(name) + 1 + strlen(evr) + 1 + strlen(arch) + 1;
2140       r = sat_malloc(l);
2141       sprintf(r, "%s-%s.%s", name, evr, arch);
2142       free(evr);
2143       break;
2144     case SOLVABLE_NAME:
2145       name = headstring(rpmhead, TAG_NAME);
2146       r = strdup(name);
2147       break;
2148     case SOLVABLE_EVR:
2149       r = headtoevr(rpmhead);
2150       break;
2151     }
2152   return r;
2153 }
2154
2155
2156 struct rpm_by_state {
2157   RpmHead *rpmhead;
2158   int rpmheadsize;
2159
2160   int dbopened;
2161   DB_ENV *dbenv;
2162   DB *db;
2163   int byteswapped;
2164 };
2165
2166 struct rpmdbentry {
2167   Id rpmdbid;
2168   Id nameoff;
2169 };
2170
2171 #define ENTRIES_BLOCK 255
2172 #define NAMEDATA_BLOCK 1023
2173
2174 static struct rpmdbentry *
2175 getinstalledrpmdbids(struct rpm_by_state *state, const char *index, const char *match, int *nentriesp, char **namedatap)
2176 {
2177   DB_ENV *dbenv = 0;
2178   DB *db = 0;
2179   DBC *dbc = 0;
2180   int byteswapped;
2181   DBT dbkey;
2182   DBT dbdata;
2183   unsigned char *dp;
2184   int dl;
2185
2186   char *namedata = 0;
2187   int namedatal = 0;
2188   struct rpmdbentry *entries = 0;
2189   int nentries = 0;
2190
2191   *nentriesp = 0;
2192   *namedatap = 0;
2193
2194   dbenv = state->dbenv;
2195   if (db_create(&db, dbenv, 0))
2196     {
2197       perror("db_create");
2198       return 0;
2199     }
2200   if (db->open(db, 0, index, 0, DB_UNKNOWN, DB_RDONLY, 0664))
2201     {
2202       perror("db->open index");
2203       db->close(db, 0);
2204       return 0;
2205     }
2206   if (db->get_byteswapped(db, &byteswapped))
2207     {
2208       perror("db->get_byteswapped");
2209       db->close(db, 0);
2210       return 0;
2211     }
2212   if (db->cursor(db, NULL, &dbc, 0))
2213     {
2214       perror("db->cursor");
2215       db->close(db, 0);
2216       return 0;
2217     }
2218   memset(&dbkey, 0, sizeof(dbkey));
2219   memset(&dbdata, 0, sizeof(dbdata));
2220   if (match)
2221     {
2222       dbkey.data = (void *)match;
2223       dbkey.size = strlen(match);
2224     }
2225   while (dbc->c_get(dbc, &dbkey, &dbdata, match ? DB_SET : DB_NEXT) == 0)
2226     {
2227       if (!match && dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
2228         continue;
2229       dl = dbdata.size;
2230       dp = dbdata.data;
2231       while(dl >= RPM_INDEX_SIZE)
2232         {
2233           entries = sat_extend(entries, nentries, 1, sizeof(*entries), ENTRIES_BLOCK);
2234           entries[nentries].rpmdbid = db2rpmdbid(dp, byteswapped);
2235           entries[nentries].nameoff = namedatal;
2236           nentries++;
2237           namedata = sat_extend(namedata, namedatal, dbkey.size + 1, 1, NAMEDATA_BLOCK);
2238           memcpy(namedata + namedatal, dbkey.data, dbkey.size);
2239           namedata[namedatal + dbkey.size] = 0;
2240           namedatal += dbkey.size + 1;
2241           dp += RPM_INDEX_SIZE;
2242           dl -= RPM_INDEX_SIZE;
2243         }
2244       if (match)
2245         break;
2246     }
2247   dbc->c_close(dbc);
2248   db->close(db, 0);
2249   *nentriesp = nentries;
2250   *namedatap = namedata;
2251   return entries;
2252 }
2253
2254 static void
2255 freestate(struct rpm_by_state *state)
2256 {
2257   /* close down */
2258   if (!state)
2259     return;
2260   if (state->db)
2261     state->db->close(state->db, 0);
2262   if (state->dbenv)
2263     state->dbenv->close(state->dbenv, 0);
2264   sat_free(state->rpmhead);
2265 }
2266
2267 int
2268 rpm_installedrpmdbids(const char *rootdir, const char *index, const char *match, Queue *rpmdbidq)
2269 {
2270   struct rpm_by_state state;
2271   struct rpmdbentry *entries;
2272   int nentries, i;
2273   char *namedata;
2274
2275   if (!index)
2276     index = "Name";
2277   if (rpmdbidq)
2278     queue_empty(rpmdbidq);
2279   memset(&state, 0, sizeof(state));
2280   if (!(state.dbenv = opendbenv(rootdir)))
2281     return 0;
2282   entries = getinstalledrpmdbids(&state, index, match, &nentries, &namedata);
2283   if (rpmdbidq)
2284     for (i = 0; i < nentries; i++)
2285       queue_push(rpmdbidq, entries[i].rpmdbid);
2286   sat_free(entries);
2287   sat_free(namedata);
2288   freestate(&state);
2289   return nentries;
2290 }
2291
2292 void *
2293 rpm_byrpmdbid(Id rpmdbid, const char *rootdir, void **statep)
2294 {
2295   struct rpm_by_state *state = *statep;
2296   unsigned char buf[16];
2297   DBT dbkey;
2298   DBT dbdata;
2299   RpmHead *rpmhead;
2300
2301   if (!rpmdbid)
2302     {
2303       /* close down */
2304       freestate(state);
2305       sat_free(state);
2306       *statep = (void *)0;
2307       return 0;
2308     }
2309
2310   if (!state)
2311     {
2312       state = sat_calloc(1, sizeof(*state));
2313       *statep = state;
2314     }
2315   if (!state->dbopened)
2316     {
2317       state->dbopened = 1;
2318       if (!state->dbenv && !(state->dbenv = opendbenv(rootdir)))
2319         return 0;
2320       if (db_create(&state->db, state->dbenv, 0))
2321         {
2322           perror("db_create");
2323           state->db = 0;
2324           state->dbenv->close(state->dbenv, 0);
2325           state->dbenv = 0;
2326           return 0;
2327         }
2328       if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
2329         {
2330           perror("db->open var/lib/rpm/Packages");
2331           state->db->close(state->db, 0);
2332           state->db = 0;
2333           state->dbenv->close(state->dbenv, 0);
2334           state->dbenv = 0;
2335           return 0;
2336         }
2337       if (state->db->get_byteswapped(state->db, &state->byteswapped))
2338         {
2339           perror("db->get_byteswapped");
2340           state->db->close(state->db, 0);
2341           state->db = 0;
2342           state->dbenv->close(state->dbenv, 0);
2343           state->dbenv = 0;
2344           return 0;
2345         }
2346     }
2347   rpmdbid2db(buf, rpmdbid, state->byteswapped);
2348   memset(&dbkey, 0, sizeof(dbkey));
2349   memset(&dbdata, 0, sizeof(dbdata));
2350   dbkey.data = buf;
2351   dbkey.size = 4;
2352   dbdata.data = 0;
2353   dbdata.size = 0;
2354   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
2355     {
2356       perror("db->get");
2357       return 0;
2358     }
2359   if (dbdata.size < 8)
2360     {
2361       fprintf(stderr, "corrupt rpm database (size)\n");
2362       return 0;
2363     }
2364   if (dbdata.size > state->rpmheadsize)
2365     {
2366       state->rpmheadsize = dbdata.size + 128;
2367       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
2368     }
2369   rpmhead = state->rpmhead;
2370   memcpy(buf, dbdata.data, 8);
2371   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
2372   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
2373   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
2374     {
2375       fprintf(stderr, "corrupt rpm database (data size)\n");
2376       return 0;
2377     }
2378   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
2379   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2380   return rpmhead;
2381 }
2382
2383 void *
2384 rpm_byfp(FILE *fp, const char *name, void **statep)
2385 {
2386   struct rpm_by_state *state = *statep;
2387   /* int headerstart, headerend; */
2388   RpmHead *rpmhead;
2389   int sigdsize, sigcnt, l;
2390   unsigned char lead[4096];
2391
2392   if (!fp)
2393     return rpm_byrpmdbid(0, 0, statep);
2394   if (!state)
2395     {
2396       state = sat_calloc(1, sizeof(*state));
2397       *statep = state;
2398     }
2399   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2400     {
2401       fprintf(stderr, "%s: not a rpm\n", name);
2402       return 0;
2403     }
2404   if (lead[78] != 0 || lead[79] != 5)
2405     {
2406       fprintf(stderr, "%s: not a V5 header\n", name);
2407       return 0;
2408     }
2409   if (getu32(lead + 96) != 0x8eade801)
2410     {
2411       fprintf(stderr, "%s: bad signature header\n", name);
2412       return 0;
2413     }
2414   sigcnt = getu32(lead + 96 + 8);
2415   sigdsize = getu32(lead + 96 + 12);
2416   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2417     {
2418       fprintf(stderr, "%s: bad signature header\n", name);
2419       return 0;
2420     }
2421   sigdsize += sigcnt * 16;
2422   sigdsize = (sigdsize + 7) & ~7;
2423   /* headerstart = 96 + 16 + sigdsize; */
2424   while (sigdsize)
2425     {
2426       l = sigdsize > 4096 ? 4096 : sigdsize;
2427       if (fread(lead, l, 1, fp) != 1)
2428         {
2429           fprintf(stderr, "%s: unexpected EOF\n", name);
2430           return 0;
2431         }
2432       sigdsize -= l;
2433     }
2434   if (fread(lead, 16, 1, fp) != 1)
2435     {
2436       fprintf(stderr, "%s: unexpected EOF\n", name);
2437       return 0;
2438     }
2439   if (getu32(lead) != 0x8eade801)
2440     {
2441       fprintf(stderr, "%s: bad header\n", name);
2442       fclose(fp);
2443       return 0;
2444     }
2445   sigcnt = getu32(lead + 8);
2446   sigdsize = getu32(lead + 12);
2447   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2448     {
2449       fprintf(stderr, "%s: bad header\n", name);
2450       fclose(fp);
2451       return 0;
2452     }
2453   l = sigdsize + sigcnt * 16;
2454   /* headerend = headerstart + 16 + l; */
2455   if (l > state->rpmheadsize)
2456     {
2457       state->rpmheadsize = l + 128;
2458       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2459     }
2460   rpmhead = state->rpmhead;
2461   if (fread(rpmhead->data, l, 1, fp) != 1)
2462     {
2463       fprintf(stderr, "%s: unexpected EOF\n", name);
2464       fclose(fp);
2465       return 0;
2466     }
2467   rpmhead->cnt = sigcnt;
2468   rpmhead->dcnt = sigdsize;
2469   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2470   return rpmhead;
2471 }
2472
2473 void *
2474 rpm_byrpmh(Header h, void **statep)
2475 {
2476   struct rpm_by_state *state = *statep;
2477   const unsigned char *uh;
2478   int sigdsize, sigcnt, l;
2479   RpmHead *rpmhead;
2480
2481 #ifndef RPM5
2482   uh = headerUnload(h);
2483 #else
2484   uh = headerUnload(h, NULL);
2485 #endif
2486   if (!uh)
2487     return 0;
2488   sigcnt = getu32(uh);
2489   sigdsize = getu32(uh + 4);
2490   l = sigdsize + sigcnt * 16;
2491   if (!state)
2492     {
2493       state = sat_calloc(1, sizeof(*state));
2494       *statep = state;
2495     }
2496   if (l > state->rpmheadsize)
2497     {
2498       state->rpmheadsize = l + 128;
2499       state->rpmhead = sat_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2500     }
2501   rpmhead = state->rpmhead;
2502   memcpy(rpmhead->data, uh + 8, l - 8);
2503   free((void *)uh);
2504   rpmhead->cnt = sigcnt;
2505   rpmhead->dcnt = sigdsize;
2506   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2507   return rpmhead;
2508 }
2509
2510
2511 static char *
2512 r64dec1(char *p, unsigned int *vp, int *eofp)
2513 {
2514   int i, x;
2515   unsigned int v = 0;
2516
2517   for (i = 0; i < 4; )
2518     {
2519       x = *p++;
2520       if (!x)
2521         return 0;
2522       if (x >= 'A' && x <= 'Z')
2523         x -= 'A';
2524       else if (x >= 'a' && x <= 'z')
2525         x -= 'a' - 26;
2526       else if (x >= '0' && x <= '9')
2527         x -= '0' - 52;
2528       else if (x == '+')
2529         x = 62;
2530       else if (x == '/')
2531         x = 63;
2532       else if (x == '=')
2533         {
2534           x = 0;
2535           if (i == 0)
2536             {
2537               *eofp = 3;
2538               *vp = 0;
2539               return p - 1;
2540             }
2541           *eofp += 1;
2542         }
2543       else
2544         continue;
2545       v = v << 6 | x;
2546       i++;
2547     }
2548   *vp = v;
2549   return p;
2550 }
2551
2552 static unsigned int
2553 crc24(unsigned char *p, int len)
2554 {
2555   unsigned int crc = 0xb704ceL;
2556   int i;
2557
2558   while (len--)
2559     {
2560       crc ^= (*p++) << 16;
2561       for (i = 0; i < 8; i++)
2562         if ((crc <<= 1) & 0x1000000)
2563           crc ^= 0x1864cfbL;
2564     }
2565   return crc & 0xffffffL;
2566 }
2567
2568 static unsigned char *
2569 unarmor(char *pubkey, int *pktlp)
2570 {
2571   char *p;
2572   int l, eof;
2573   unsigned char *buf, *bp;
2574   unsigned int v;
2575
2576   *pktlp = 0;
2577   while (strncmp(pubkey, "-----BEGIN PGP PUBLIC KEY BLOCK-----", 36) != 0)
2578     {
2579       pubkey = strchr(pubkey, '\n');
2580       if (!pubkey)
2581         return 0;
2582       pubkey++;
2583     }
2584   pubkey = strchr(pubkey, '\n');
2585   if (!pubkey++)
2586     return 0;
2587   /* skip header lines */
2588   for (;;)
2589     {
2590       while (*pubkey == ' ' || *pubkey == '\t')
2591         pubkey++;
2592       if (*pubkey == '\n')
2593         break;
2594       pubkey = strchr(pubkey, '\n');
2595       if (!pubkey++)
2596         return 0;
2597     }
2598   pubkey++;
2599   p = strchr(pubkey, '=');
2600   if (!p)
2601     return 0;
2602   l = p - pubkey;
2603   bp = buf = sat_malloc(l * 3 / 4 + 4);
2604   eof = 0;
2605   while (!eof)
2606     {
2607       pubkey = r64dec1(pubkey, &v, &eof);
2608       if (!pubkey)
2609         {
2610           sat_free(buf);
2611           return 0;
2612         }
2613       *bp++ = v >> 16;
2614       *bp++ = v >> 8;
2615       *bp++ = v;
2616     }
2617   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2618     pubkey++;
2619   bp -= eof;
2620   if (*pubkey != '=' || (pubkey = r64dec1(pubkey + 1, &v, &eof)) == 0)
2621     {
2622       sat_free(buf);
2623       return 0;
2624     }
2625   if (v != crc24(buf, bp - buf))
2626     {
2627       sat_free(buf);
2628       return 0;
2629     }
2630   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2631     pubkey++;
2632   if (strncmp(pubkey, "-----END PGP PUBLIC KEY BLOCK-----", 34) != 0)
2633     {
2634       sat_free(buf);
2635       return 0;
2636     }
2637   *pktlp = bp - buf;
2638   return buf;
2639 }
2640
2641 static void
2642 parsekeydata(Solvable *s, Repodata *data, unsigned char *p, int pl)
2643 {
2644   int x, tag, l;
2645   unsigned char keyid[8];
2646   unsigned int kcr = 0, maxex = 0;
2647   unsigned char *pubkey = 0;
2648   unsigned char *userid = 0;
2649 #if 0
2650   int pubkeyl = 0;
2651   int useridl = 0;
2652 #endif
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 #if 0
2711           pubkeyl = l;
2712 #endif
2713           kcr = 0;
2714           if (p[0] == 3)
2715             {
2716               unsigned int ex;
2717               void *h;
2718               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2719               ex = 0;
2720               if (p[5] || p[6])
2721                 {
2722                   ex = kcr + 24*3600 * (p[5] << 8 | p[6]);
2723                   if (ex > maxex)
2724                     maxex = ex;
2725                 }
2726               memset(keyid, 0, 8);
2727               if (p[7] == 1)    /* RSA */
2728                 {
2729                   int i, ql;
2730                   unsigned char fp[16];
2731                   char fpx[32 + 1];
2732                   unsigned char *q;
2733
2734                   ql = ((p[8] << 8 | p[9]) + 7) / 8;
2735                   memcpy(keyid, p + 10 + ql - 8, 8);
2736                   h = sat_chksum_create(REPOKEY_TYPE_MD5);
2737                   sat_chksum_add(h, p + 10, ql);
2738                   q = p + 10 + ql;
2739                   ql = ((q[0] << 8 | q[1]) + 7) / 8;
2740                   sat_chksum_add(h, q + 2, ql);
2741                   sat_chksum_free(h, fp);
2742                   for (i = 0; i < 16; i++)
2743                     sprintf(fpx + i * 2, "%02x", fp[i]);
2744                   setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2745                 }
2746             }
2747           else if (p[0] == 4)
2748             {
2749               int i;
2750               void *h;
2751               unsigned char hdr[3];
2752               unsigned char fp[20];
2753               char fpx[40 + 1];
2754
2755               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2756               hdr[0] = 0x99;
2757               hdr[1] = l >> 8;
2758               hdr[2] = l;
2759               h = sat_chksum_create(REPOKEY_TYPE_SHA1);
2760               sat_chksum_add(h, hdr, 3);
2761               sat_chksum_add(h, p, l);
2762               sat_chksum_free(h, fp);
2763               for (i = 0; i < 20; i++)
2764                 sprintf(fpx + i * 2, "%02x", fp[i]);
2765               setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2766               memcpy(keyid, fp + 12, 8);
2767             }
2768         }
2769       if (tag == 2)
2770         {
2771           if (p[0] == 3 && p[1] == 5)
2772             {
2773 #if 0
2774               Id htype = 0;
2775 #endif
2776               // printf("V3 signature packet\n");
2777               if (l < 17)
2778                 continue;
2779               if (p[2] != 0x10 && p[2] != 0x11 && p[2] != 0x12 && p[2] != 0x13 && p[2] != 0x1f)
2780                 continue;
2781               if (!memcmp(keyid, p + 6, 8))
2782                 {
2783                   // printf("SELF SIG\n");
2784                 }
2785               else
2786                 {
2787                   // printf("OTHER SIG\n");
2788                 }
2789 #if 0
2790               if (p[16] == 1)
2791                 htype = REPOKEY_TYPE_MD5;
2792               else if (p[16] == 2)
2793                 htype = REPOKEY_TYPE_SHA1;
2794               else if (p[16] == 8)
2795                 htype = REPOKEY_TYPE_SHA256;
2796               if (htype)
2797                 {
2798                   void *h = sat_chksum_create(htype);
2799                   unsigned char b[3], *cs;
2800
2801                   b[0] = 0x99;
2802                   b[1] = pubkeyl >> 8;
2803                   b[2] = pubkeyl;
2804                   sat_chksum_add(h, b, 3);
2805                   sat_chksum_add(h, pubkey, pubkeyl);
2806                   if (p[2] >= 0x10 && p[2] <= 0x13)
2807                     sat_chksum_add(h, userid, useridl);
2808                   sat_chksum_add(h, p + 2, 5);
2809                   cs = sat_chksum_get(h, 0);
2810                   sat_chksum_free(h, 0);
2811                 }
2812 #endif
2813             }
2814           if (p[0] == 4)
2815             {
2816               int j, ql, haveissuer;
2817               unsigned char *q;
2818               unsigned int ex = 0;
2819 #if 0
2820               unsigned int scr = 0;
2821 #endif
2822               unsigned char issuer[8];
2823
2824               // printf("V4 signature packet\n");
2825               if (l < 6)
2826                 continue;
2827               if (p[1] != 0x10 && p[1] != 0x11 && p[1] != 0x12 && p[1] != 0x13 && p[1] != 0x1f)
2828                 continue;
2829               haveissuer = 0;
2830               ex = 0;
2831               q = p + 4;
2832               for (j = 0; q && j < 2; j++)
2833                 {
2834                   if (q + 2 > p + l)
2835                     {
2836                       q = 0;
2837                       break;
2838                     }
2839                   ql = q[0] << 8 | q[1];
2840                   q += 2;
2841                   if (q + ql > p + l)
2842                     {
2843                       q = 0;
2844                       break;
2845                     }
2846                   while (ql)
2847                     {
2848                       int sl;
2849                       x = *q++;
2850                       ql--;
2851                       if (x < 192)
2852                         sl = x;
2853                       else if (x == 255)
2854                         {
2855                           if (ql < 4)
2856                             {
2857                               q = 0;
2858                               break;
2859                             }
2860                           sl = q[0] << 24 | q[1] << 16 | q[2] << 8 | q[3];
2861                           q += 4;
2862                           ql -= 4;
2863                         }
2864                       else
2865                         {
2866                           if (ql < 1)
2867                             {
2868                               q = 0;
2869                               break;
2870                             }
2871                           sl = ((x - 192) << 8) + *q++ + 192;
2872                           ql--;
2873                         }
2874                       if (ql < sl)
2875                         {
2876                           q = 0;
2877                           break;
2878                         }
2879                       x = q[0] & 127;
2880                       // printf("%d SIGSUB %d %d\n", j, x, sl);
2881                       if (x == 16 && sl == 9 && !haveissuer)
2882                         {
2883                           memcpy(issuer, q + 1, 8);
2884                           haveissuer = 1;
2885                         }
2886 #if 0
2887                       if (x == 2 && j == 0)
2888                         scr = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2889 #endif
2890                       if (x == 9 && j == 0)
2891                         ex = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2892                       q += sl;
2893                       ql -= sl;
2894                     }
2895                 }
2896               if (ex)
2897                 ex += kcr;
2898               if (haveissuer)
2899                 {
2900 #if 0
2901                   Id htype = 0;
2902                   if (p[3] == 1)
2903                     htype = REPOKEY_TYPE_MD5;
2904                   else if (p[3] == 2)
2905                     htype = REPOKEY_TYPE_SHA1;
2906                   else if (p[3] == 8)
2907                     htype = REPOKEY_TYPE_SHA256;
2908                   if (htype && pubkeyl)
2909                     {
2910                       void *h = sat_chksum_create(htype);
2911                       unsigned char b[6], *cs;
2912                       unsigned int hl;
2913
2914                       b[0] = 0x99;
2915                       b[1] = pubkeyl >> 8;
2916                       b[2] = pubkeyl;
2917                       sat_chksum_add(h, b, 3);
2918                       sat_chksum_add(h, pubkey, pubkeyl);
2919                       if (p[1] >= 0x10 && p[1] <= 0x13)
2920                         {
2921                           b[0] = 0xb4;
2922                           b[1] = useridl >> 24;
2923                           b[2] = useridl >> 16;
2924                           b[3] = useridl >> 8;
2925                           b[4] = useridl;
2926                           sat_chksum_add(h, b, 5);
2927                           sat_chksum_add(h, userid, useridl);
2928                         }
2929                       hl = 6 + (p[4] << 8 | p[5]);
2930                       sat_chksum_add(h, p, hl);
2931                       b[0] = 4;
2932                       b[1] = 0xff;
2933                       b[2] = hl >> 24;
2934                       b[3] = hl >> 16;
2935                       b[4] = hl >> 8;
2936                       b[5] = hl;
2937                       sat_chksum_add(h, b, 6);
2938                       cs = sat_chksum_get(h, 0);
2939                       sat_chksum_free(h, 0);
2940                     }
2941 #endif
2942                   if (!memcmp(keyid, issuer, 8))
2943                     {
2944                       // printf("SELF SIG cr %d ex %d\n", cr, ex);
2945                       if (ex > maxex)
2946                         maxex = ex;
2947                     }
2948                   else
2949                     {
2950                       // printf("OTHER SIG cr %d ex %d\n", cr, ex);
2951                     }
2952                 }
2953             }
2954         }
2955       if (tag == 13)
2956         {
2957           userid = sat_realloc(userid, l);
2958           if (l)
2959             memcpy(userid, p, l);
2960 #if 0
2961           useridl = l;
2962 #endif
2963         }
2964     }
2965   if (maxex)
2966     repodata_set_num(data, s - s->repo->pool->solvables, PUBKEY_EXPIRES, maxex);
2967   sat_free(pubkey);
2968   sat_free(userid);
2969 }
2970
2971 /* this is private to rpm, but rpm lacks an interface to retrieve
2972  * the values. Sigh. */
2973 struct pgpDigParams_s {
2974     const char * userid;
2975     const unsigned char * hash;
2976     const char * params[4];
2977     unsigned char tag;
2978     unsigned char version;               /*!< version number. */
2979     unsigned char time[4];               /*!< time that the key was created. */
2980     unsigned char pubkey_algo;           /*!< public key algorithm. */
2981     unsigned char hash_algo;
2982     unsigned char sigtype;
2983     unsigned char hashlen;
2984     unsigned char signhash16[2];
2985     unsigned char signid[8];
2986     unsigned char saved;
2987 };
2988
2989 struct pgpDig_s {
2990     struct pgpDigParams_s signature;
2991     struct pgpDigParams_s pubkey;
2992 };
2993
2994 static int
2995 pubkey2solvable(Solvable *s, Repodata *data, char *pubkey)
2996 {
2997   Pool *pool = s->repo->pool;
2998   unsigned char *pkts;
2999   unsigned int btime;
3000   int pktsl, i;
3001   pgpDig dig = 0;
3002   char keyid[16 + 1];
3003   char evrbuf[8 + 1 + 8 + 1];
3004
3005   pkts = unarmor(pubkey, &pktsl);
3006   if (!pkts)
3007     return 0;
3008   setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_DESCRIPTION, pubkey);
3009   parsekeydata(s, data, pkts, pktsl);
3010   /* only rpm knows how to do the release calculation, we don't dare
3011    * to recreate all the bugs */
3012 #ifndef RPM5
3013   dig = pgpNewDig();
3014 #else
3015   dig = pgpDigNew(RPMVSF_DEFAULT, 0);
3016 #endif
3017   (void) pgpPrtPkts(pkts, pktsl, dig, 0);
3018   btime = dig->pubkey.time[0] << 24 | dig->pubkey.time[1] << 16 | dig->pubkey.time[2] << 8 | dig->pubkey.signid[3];
3019   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]);
3020   repodata_set_num(data, s - s->repo->pool->solvables, SOLVABLE_BUILDTIME, btime);
3021
3022   s->name = str2id(pool, "gpg-pubkey", 1);
3023   s->evr = str2id(pool, evrbuf, 1);
3024   s->arch = 1;
3025   for (i = 0; i < 8; i++)
3026     sprintf(keyid + 2 * i, "%02x", dig->pubkey.signid[i]);
3027   repodata_set_str(data, s - s->repo->pool->solvables, PUBKEY_KEYID, keyid);
3028   if (dig->pubkey.userid)
3029     setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_SUMMARY, dig->pubkey.userid);
3030   (void)pgpFreeDig(dig);
3031   sat_free((void *)pkts);
3032   return 1;
3033 }
3034
3035 void
3036 repo_add_rpmdb_pubkeys(Repo *repo, const char *rootdir, int flags)
3037 {
3038   Pool *pool = repo->pool;
3039   struct rpm_by_state state;
3040   struct rpmdbentry *entries;
3041   int nentries, i;
3042   char *namedata, *str;
3043   unsigned int u32;
3044   Repodata *data;
3045   Solvable *s;
3046
3047   data = repo_add_repodata(repo, flags);
3048
3049   memset(&state, 0, sizeof(state));
3050   if (!(state.dbenv = opendbenv(rootdir)))
3051     return;
3052   entries = getinstalledrpmdbids(&state, "Name", "gpg-pubkey", &nentries, &namedata);
3053   for (i = 0 ; i < nentries; i++)
3054     {
3055       void *statep = &state;
3056       RpmHead *rpmhead = rpm_byrpmdbid(entries[i].rpmdbid, rootdir, &statep);
3057       if (!rpmhead)
3058         continue;
3059       str = headstring(rpmhead, TAG_DESCRIPTION);
3060       if (!str)
3061         continue;
3062       s = pool_id2solvable(pool, repo_add_solvable(repo));
3063       pubkey2solvable(s, data, str);
3064       u32 = headint32(rpmhead, TAG_INSTALLTIME);
3065       if (u32)
3066         repodata_set_num(data, s - pool->solvables, SOLVABLE_INSTALLTIME, u32);
3067       if (!repo->rpmdbid)
3068         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
3069       repo->rpmdbid[s - pool->solvables - repo->start] = entries[i].rpmdbid;
3070     }
3071   sat_free(entries);
3072   sat_free(namedata);
3073   freestate(&state);
3074   if (!(flags & REPO_NO_INTERNALIZE))
3075     repodata_internalize(data);
3076 }
3077
3078 void
3079 repo_add_pubkeys(Repo *repo, const char **keys, int nkeys, int flags)
3080 {
3081   Pool *pool = repo->pool;
3082   Repodata *data;
3083   Solvable *s;
3084   char *buf;
3085   int i, bufl, l, ll;
3086   FILE *fp;
3087
3088   data = repo_add_repodata(repo, flags);
3089   buf = 0;
3090   bufl = 0;
3091   for (i = 0; i < nkeys; i++)
3092     {
3093       if ((fp = fopen(keys[i], "r")) == 0)
3094         {
3095           perror(keys[i]);
3096           continue;
3097         }
3098       for (l = 0; ;)
3099         {
3100           if (bufl - l < 4096)
3101             {
3102               bufl += 4096;
3103               buf = sat_realloc(buf, bufl);
3104             }
3105           ll = fread(buf, 1, bufl - l, fp);
3106           if (ll <= 0)
3107             break;
3108           l += ll;
3109         }
3110       buf[l] = 0;
3111       fclose(fp);
3112       s = pool_id2solvable(pool, repo_add_solvable(repo));
3113       pubkey2solvable(s, data, buf);
3114     }
3115   sat_free(buf);
3116   if (!(flags & REPO_NO_INTERNALIZE))
3117     repodata_internalize(data);
3118 }