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