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