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