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