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