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