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