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