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