- more cleanup and return type fixes
[platform/upstream/libsolv.git] / ext / repo_rpmdb.c
1 /*
2  * Copyright (c) 2007-2012, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /*
9  * repo_rpmdb
10  *
11  * convert rpm db to repo
12  *
13  */
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <limits.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <assert.h>
24 #include <stdint.h>
25
26 #include <rpm/rpmio.h>
27 #include <rpm/rpmpgp.h>
28 #ifndef RPM5
29 #include <rpm/header.h>
30 #endif
31 #include <rpm/rpmdb.h>
32
33 #ifndef DB_CREATE
34 # ifdef FEDORA
35 #  include <db.h>
36 # else
37 #  include <rpm/db.h>
38 # endif
39 #endif
40
41 #include "pool.h"
42 #include "repo.h"
43 #include "hash.h"
44 #include "util.h"
45 #include "queue.h"
46 #include "chksum.h"
47 #include "repo_rpmdb.h"
48
49 /* 3: added triggers */
50 /* 4: fixed triggers */
51 #define RPMDB_COOKIE_VERSION 4
52
53 #define TAG_NAME                1000
54 #define TAG_VERSION             1001
55 #define TAG_RELEASE             1002
56 #define TAG_EPOCH               1003
57 #define TAG_SUMMARY             1004
58 #define TAG_DESCRIPTION         1005
59 #define TAG_BUILDTIME           1006
60 #define TAG_BUILDHOST           1007
61 #define TAG_INSTALLTIME         1008
62 #define TAG_SIZE                1009
63 #define TAG_DISTRIBUTION        1010
64 #define TAG_VENDOR              1011
65 #define TAG_LICENSE             1014
66 #define TAG_PACKAGER            1015
67 #define TAG_GROUP               1016
68 #define TAG_URL                 1020
69 #define TAG_ARCH                1022
70 #define TAG_FILESIZES           1028
71 #define TAG_FILEMODES           1030
72 #define TAG_FILEMD5S            1035
73 #define TAG_FILELINKTOS         1036
74 #define TAG_FILEFLAGS           1037
75 #define TAG_SOURCERPM           1044
76 #define TAG_PROVIDENAME         1047
77 #define TAG_REQUIREFLAGS        1048
78 #define TAG_REQUIRENAME         1049
79 #define TAG_REQUIREVERSION      1050
80 #define TAG_NOSOURCE            1051
81 #define TAG_NOPATCH             1052
82 #define TAG_CONFLICTFLAGS       1053
83 #define TAG_CONFLICTNAME        1054
84 #define TAG_CONFLICTVERSION     1055
85 #define TAG_TRIGGERNAME         1066
86 #define TAG_TRIGGERVERSION      1067
87 #define TAG_TRIGGERFLAGS        1068
88 #define TAG_OBSOLETENAME        1090
89 #define TAG_FILEDEVICES         1095
90 #define TAG_FILEINODES          1096
91 #define TAG_PROVIDEFLAGS        1112
92 #define TAG_PROVIDEVERSION      1113
93 #define TAG_OBSOLETEFLAGS       1114
94 #define TAG_OBSOLETEVERSION     1115
95 #define TAG_DIRINDEXES          1116
96 #define TAG_BASENAMES           1117
97 #define TAG_DIRNAMES            1118
98 #define TAG_PAYLOADFORMAT       1124
99 #define TAG_PATCHESNAME         1133
100 #define TAG_FILECOLORS          1140
101 #define TAG_SUGGESTSNAME        1156
102 #define TAG_SUGGESTSVERSION     1157
103 #define TAG_SUGGESTSFLAGS       1158
104 #define TAG_ENHANCESNAME        1159
105 #define TAG_ENHANCESVERSION     1160
106 #define TAG_ENHANCESFLAGS       1161
107
108 #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 = solv_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 && pool != frompool)
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     case REPOKEY_TYPE_IDARRAY:  /* used for triggers */
1093       id = kv->id;
1094       assert(!data->localpool); /* implement me! */
1095       if (pool != frompool || fromdata->localpool)
1096         {
1097           if (ISRELDEP(id))
1098             id = copyreldep(pool, frompool, id);
1099           else
1100             id = pool_str2id(pool, stringpool_id2str(fromspool, id), 1);
1101         }
1102       if (key->type == REPOKEY_TYPE_ID)
1103         repodata_set_id(data, handle, keyname, id);
1104       else if (key->type == REPOKEY_TYPE_CONSTANTID)
1105         repodata_set_constantid(data, handle, keyname, id);
1106       else
1107         repodata_add_idarray(data, handle, keyname, id);
1108       break;
1109     case REPOKEY_TYPE_STR:
1110       repodata_set_str(data, handle, keyname, kv->str);
1111       break;
1112     case REPOKEY_TYPE_VOID:
1113       repodata_set_void(data, handle, keyname);
1114       break;
1115     case REPOKEY_TYPE_NUM:
1116       repodata_set_num(data, handle, keyname, kv->num);
1117       break;
1118     case REPOKEY_TYPE_CONSTANT:
1119       repodata_set_constant(data, handle, keyname, kv->num);
1120       break;
1121     case REPOKEY_TYPE_DIRNUMNUMARRAY:
1122       id = kv->id;
1123       assert(!data->localpool); /* implement me! */
1124       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1125       repodata_add_dirnumnum(data, handle, keyname, id, kv->num, kv->num2);
1126       break;
1127     case REPOKEY_TYPE_DIRSTRARRAY:
1128       id = kv->id;
1129       assert(!data->localpool); /* implement me! */
1130       id = copydir(pool, data, fromspool, fromdata, id, cbdata->dircache);
1131       repodata_add_dirstr(data, handle, keyname, id, kv->str);
1132       break;
1133     default:
1134       break;
1135     }
1136   return 0;
1137 }
1138
1139 static void
1140 solvable_copy(Solvable *s, Solvable *r, Repodata *data, Id *dircache)
1141 {
1142   Repo *repo = s->repo;
1143   Repo *fromrepo = r->repo;
1144   Pool *pool = repo->pool;
1145   struct solvable_copy_cbdata cbdata;
1146
1147   /* copy solvable data */
1148   if (pool == fromrepo->pool)
1149     {
1150       s->name = r->name;
1151       s->evr = r->evr;
1152       s->arch = r->arch;
1153       s->vendor = r->vendor;
1154     }
1155   else
1156     {
1157       if (r->name)
1158         s->name = pool_str2id(pool, pool_id2str(fromrepo->pool, r->name), 1);
1159       if (r->evr)
1160         s->evr = pool_str2id(pool, pool_id2str(fromrepo->pool, r->evr), 1);
1161       if (r->arch)
1162         s->arch = pool_str2id(pool, pool_id2str(fromrepo->pool, r->arch), 1);
1163       if (r->vendor)
1164         s->vendor = pool_str2id(pool, pool_id2str(fromrepo->pool, r->vendor), 1);
1165     }
1166   s->provides = copydeps(pool, repo, r->provides, fromrepo);
1167   s->requires = copydeps(pool, repo, r->requires, fromrepo);
1168   s->conflicts = copydeps(pool, repo, r->conflicts, fromrepo);
1169   s->obsoletes = copydeps(pool, repo, r->obsoletes, fromrepo);
1170   s->recommends = copydeps(pool, repo, r->recommends, fromrepo);
1171   s->suggests = copydeps(pool, repo, r->suggests, fromrepo);
1172   s->supplements = copydeps(pool, repo, r->supplements, fromrepo);
1173   s->enhances  = copydeps(pool, repo, r->enhances, fromrepo);
1174
1175   /* copy all attributes */
1176   if (!data)
1177     return;
1178   cbdata.data = data;
1179   cbdata.handle = s - pool->solvables;
1180   cbdata.dircache = dircache;
1181   repo_search(fromrepo, (r - fromrepo->pool->solvables), 0, 0, SEARCH_NO_STORAGE_SOLVABLE, solvable_copy_cb, &cbdata);
1182 }
1183
1184 /* used to sort entries returned in some database order */
1185 static int
1186 rpmids_sort_cmp(const void *va, const void *vb, void *dp)
1187 {
1188   struct rpmid const *a = va, *b = vb;
1189   int r;
1190   r = strcmp(a->name, b->name);
1191   if (r)
1192     return r;
1193   return a->dbid - b->dbid;
1194 }
1195
1196 static int
1197 pkgids_sort_cmp(const void *va, const void *vb, void *dp)
1198 {
1199   Repo *repo = dp;
1200   Pool *pool = repo->pool;
1201   Solvable *a = pool->solvables + *(Id *)va;
1202   Solvable *b = pool->solvables + *(Id *)vb;
1203   Id *rpmdbid;
1204
1205   if (a->name != b->name)
1206     return strcmp(pool_id2str(pool, a->name), pool_id2str(pool, b->name));
1207   rpmdbid = repo->rpmdbid;
1208   return rpmdbid[(a - pool->solvables) - repo->start] - rpmdbid[(b - pool->solvables) - repo->start];
1209 }
1210
1211 static void
1212 swap_solvables(Repo *repo, Repodata *data, Id pa, Id pb)
1213 {
1214   Pool *pool = repo->pool;
1215   Solvable tmp;
1216
1217   tmp = pool->solvables[pa];
1218   pool->solvables[pa] = pool->solvables[pb];
1219   pool->solvables[pb] = tmp;
1220   if (repo->rpmdbid)
1221     {
1222       Id tmpid = repo->rpmdbid[pa - repo->start];
1223       repo->rpmdbid[pa - repo->start] = repo->rpmdbid[pb - repo->start];
1224       repo->rpmdbid[pb - repo->start] = tmpid;
1225     }
1226   /* only works if nothing is already internalized! */
1227   if (data)
1228     repodata_swap_attrs(data, pa, pb);
1229 }
1230
1231
1232 static inline Id db2rpmdbid(unsigned char *db, int byteswapped)
1233 {
1234 #ifdef RPM5
1235   return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
1236 #else
1237 # if defined(WORDS_BIGENDIAN)
1238   if (!byteswapped)
1239 # else
1240   if (byteswapped)
1241 # endif
1242     return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
1243   else
1244     return db[3] << 24 | db[2] << 16 | db[1] << 8 | db[0];
1245 #endif
1246 }
1247
1248 static inline void rpmdbid2db(unsigned char *db, Id id, int byteswapped)
1249 {
1250 #ifdef RPM5
1251   db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1252 #else
1253 # if defined(WORDS_BIGENDIAN)
1254   if (!byteswapped)
1255 # else
1256   if (byteswapped)
1257 # endif
1258     db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1259   else
1260     db[3] = id >> 24, db[2] = id >> 16, db[1] = id >> 8, db[0] = id;
1261 #endif
1262 }
1263
1264 static void
1265 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1266 {
1267   memset(cookie, 0, 32);
1268   cookie[3] = RPMDB_COOKIE_VERSION;
1269   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1270   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1271 }
1272
1273 /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1274 static DB_ENV *
1275 opendbenv(const char *rootdir)
1276 {
1277   char dbpath[PATH_MAX];
1278   DB_ENV *dbenv = 0;
1279   int r;
1280
1281   if (db_env_create(&dbenv, 0))
1282     {
1283       perror("db_env_create");
1284       return 0;
1285     }
1286 #if defined(FEDORA) && (DB_VERSION_MAJOR >= 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 5))
1287   dbenv->set_thread_count(dbenv, 8);
1288 #endif
1289   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1290   if (access(dbpath, W_OK) == -1)
1291     {
1292       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1293     }
1294   else
1295     {
1296 #ifdef FEDORA
1297       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0644);
1298 #else
1299       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1300 #endif
1301     }
1302   if (r)
1303     {
1304       perror("dbenv open");
1305       dbenv->close(dbenv, 0);
1306       return 0;
1307     }
1308   return dbenv;
1309 }
1310
1311
1312 static int
1313 count_headers(const char *rootdir, DB_ENV *dbenv)
1314 {
1315   char dbpath[PATH_MAX];
1316   struct stat statbuf;
1317   DB *db = 0;
1318   DBC *dbc = 0;
1319   int count = 0;
1320   DBT dbkey;
1321   DBT dbdata;
1322
1323   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir);
1324   if (stat(dbpath, &statbuf))
1325     return 0;
1326   memset(&dbkey, 0, sizeof(dbkey));
1327   memset(&dbdata, 0, sizeof(dbdata));
1328   if (db_create(&db, dbenv, 0))
1329     {
1330       perror("db_create");
1331       exit(1);
1332     }
1333   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1334     {
1335       perror("db->open Name index");
1336       exit(1);
1337     }
1338   if (db->cursor(db, NULL, &dbc, 0))
1339     {
1340       perror("db->cursor");
1341       exit(1);
1342     }
1343   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1344     count += dbdata.size / RPM_INDEX_SIZE;
1345   dbc->c_close(dbc);
1346   db->close(db, 0);
1347   return count;
1348 }
1349
1350 /*
1351  * read rpm db as repo
1352  *
1353  */
1354
1355 int
1356 repo_add_rpmdb(Repo *repo, Repo *ref, const char *rootdir, int flags)
1357 {
1358   Pool *pool = repo->pool;
1359   unsigned char buf[16];
1360   DB *db = 0;
1361   DBC *dbc = 0;
1362   int byteswapped;
1363   unsigned int dbid;
1364   unsigned char *dp;
1365   int dl, nrpmids;
1366   struct rpmid *rpmids, *rp;
1367   int i;
1368   int rpmheadsize;
1369   RpmHead *rpmhead;
1370   Solvable *s;
1371   Id id, *refhash;
1372   unsigned int refmask, h;
1373   char dbpath[PATH_MAX];
1374   DB_ENV *dbenv = 0;
1375   DBT dbkey;
1376   DBT dbdata;
1377   struct stat packagesstat;
1378   unsigned char newcookie[32];
1379   const unsigned char *oldcookie = 0;
1380   Id oldcookietype = 0;
1381   Repodata *data;
1382   int count = 0, done = 0;
1383   unsigned int now;
1384
1385   now = solv_timems(0);
1386   memset(&dbkey, 0, sizeof(dbkey));
1387   memset(&dbdata, 0, sizeof(dbdata));
1388
1389   if (!rootdir)
1390     rootdir = "";
1391
1392   data = repo_add_repodata(repo, flags);
1393
1394   if (ref && !(ref->nsolvables && ref->rpmdbid))
1395     ref = 0;
1396
1397   if (!(dbenv = opendbenv(rootdir)))
1398     exit(1);
1399
1400   /* XXX: should get ro lock of Packages database! */
1401   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir);
1402   if (stat(dbpath, &packagesstat))
1403     {
1404       perror(dbpath);
1405       exit(1);
1406     }
1407   mkrpmdbcookie(&packagesstat, newcookie);
1408   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1409
1410   if (ref)
1411     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1412   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1413     {
1414       Id *pkgids;
1415       int solvstart = 0, solvend = 0;
1416
1417       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1418         count = count_headers(rootdir, dbenv);
1419       if (db_create(&db, dbenv, 0))
1420         {
1421           perror("db_create");
1422           exit(1);
1423         }
1424       if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1425         {
1426           perror("db->open Packages index");
1427           exit(1);
1428         }
1429       if (db->get_byteswapped(db, &byteswapped))
1430         {
1431           perror("db->get_byteswapped");
1432           exit(1);
1433         }
1434       if (db->cursor(db, NULL, &dbc, 0))
1435         {
1436           perror("db->cursor");
1437           exit(1);
1438         }
1439       rpmheadsize = 0;
1440       rpmhead = 0;
1441       i = 0;
1442       s = 0;
1443       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1444         {
1445           if (!s)
1446             {
1447               s = pool_id2solvable(pool, repo_add_solvable(repo));
1448               if (!solvstart)
1449                 solvstart = s - pool->solvables;
1450               solvend = s - pool->solvables + 1;
1451             }
1452           if (!repo->rpmdbid)
1453             repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1454           if (dbkey.size != 4)
1455             {
1456               fprintf(stderr, "corrupt Packages database (key size)\n");
1457               exit(1);
1458             }
1459           dbid = db2rpmdbid(dbkey.data, byteswapped);
1460           if (dbid == 0)                /* the join key */
1461             continue;
1462           if (dbdata.size < 8)
1463             {
1464               fprintf(stderr, "corrupt rpm database (size %u)\n", dbdata.size);
1465               exit(1);
1466             }
1467           if (dbdata.size > rpmheadsize)
1468             {
1469               rpmheadsize = dbdata.size + 128;
1470               rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1471             }
1472           memcpy(buf, dbdata.data, 8);
1473           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1474           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1475           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1476             {
1477               fprintf(stderr, "corrupt rpm database (data size)\n");
1478               exit(1);
1479             }
1480           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1481           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1482           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1483           if (rpm2solv(pool, repo, data, s, rpmhead, flags | RPM_ADD_TRIGGERS))
1484             {
1485               i++;
1486               s = 0;
1487             }
1488           else
1489             {
1490               /* We can reuse this solvable, but make sure it's still
1491                  associated with this repo.  */
1492               memset(s, 0, sizeof(*s));
1493               s->repo = repo;
1494             }
1495           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1496             {
1497               if (done < count)
1498                 done++;
1499               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1500                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1501             }
1502         }
1503       if (s)
1504         {
1505           /* oops, could not reuse. free it instead */
1506           repo_free_solvable_block(repo, s - pool->solvables, 1, 1);
1507           solvend--;
1508           s = 0;
1509         }
1510       dbc->c_close(dbc);
1511       db->close(db, 0);
1512       db = 0;
1513       /* now sort all solvables in the new solvstart..solvend block */
1514       if (solvend - solvstart > 1)
1515         {
1516           pkgids = solv_malloc2(solvend - solvstart, sizeof(Id));
1517           for (i = solvstart; i < solvend; i++)
1518             pkgids[i - solvstart] = i;
1519           solv_sort(pkgids, solvend - solvstart, sizeof(Id), pkgids_sort_cmp, repo);
1520           /* adapt order */
1521           for (i = solvstart; i < solvend; i++)
1522             {
1523               int j = pkgids[i - solvstart];
1524               while (j < i)
1525                 j = pkgids[i - solvstart] = pkgids[j - solvstart];
1526               if (j != i)
1527                 swap_solvables(repo, data, i, j);
1528             }
1529           solv_free(pkgids);
1530         }
1531     }
1532   else
1533     {
1534       Id dircache[COPYDIR_DIRCACHE_SIZE];               /* see copydir */
1535
1536       memset(dircache, 0, sizeof(dircache));
1537       if (db_create(&db, dbenv, 0))
1538         {
1539           perror("db_create");
1540           exit(1);
1541         }
1542       if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1543         {
1544           perror("db->open Name index");
1545           exit(1);
1546         }
1547       if (db->get_byteswapped(db, &byteswapped))
1548         {
1549           perror("db->get_byteswapped");
1550           exit(1);
1551         }
1552       if (db->cursor(db, NULL, &dbc, 0))
1553         {
1554           perror("db->cursor");
1555           exit(1);
1556         }
1557       nrpmids = 0;
1558       rpmids = 0;
1559       while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1560         {
1561           if (dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1562             continue;
1563           dl = dbdata.size;
1564           dp = dbdata.data;
1565           while(dl >= RPM_INDEX_SIZE)
1566             {
1567               rpmids = solv_extend(rpmids, nrpmids, 1, sizeof(*rpmids), 255);
1568               rpmids[nrpmids].dbid = db2rpmdbid(dp, byteswapped);
1569               rpmids[nrpmids].name = solv_malloc((int)dbkey.size + 1);
1570               memcpy(rpmids[nrpmids].name, dbkey.data, (int)dbkey.size);
1571               rpmids[nrpmids].name[(int)dbkey.size] = 0;
1572               nrpmids++;
1573               dp += RPM_INDEX_SIZE;
1574               dl -= RPM_INDEX_SIZE;
1575             }
1576         }
1577       dbc->c_close(dbc);
1578       db->close(db, 0);
1579       db = 0;
1580
1581       /* sort rpmids */
1582       solv_sort(rpmids, nrpmids, sizeof(*rpmids), rpmids_sort_cmp, 0);
1583
1584       rpmheadsize = 0;
1585       rpmhead = 0;
1586
1587       /* create hash from dbid to ref */
1588       refmask = mkmask(ref->nsolvables);
1589       refhash = solv_calloc(refmask + 1, sizeof(Id));
1590       for (i = 0; i < ref->end - ref->start; i++)
1591         {
1592           if (!ref->rpmdbid[i])
1593             continue;
1594           h = ref->rpmdbid[i] & refmask;
1595           while (refhash[h])
1596             h = (h + 317) & refmask;
1597           refhash[h] = i + 1;   /* make it non-zero */
1598         }
1599
1600       /* count the misses, they will cost us time */
1601       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1602         {
1603           for (i = 0, rp = rpmids; i < nrpmids; i++, rp++)
1604             {
1605               dbid = rp->dbid;
1606               if (refhash)
1607                 {
1608                   h = dbid & refmask;
1609                   while ((id = refhash[h]))
1610                     {
1611                       if (ref->rpmdbid[id - 1] == dbid)
1612                         break;
1613                       h = (h + 317) & refmask;
1614                     }
1615                   if (id)
1616                     continue;
1617                 }
1618               count++;
1619             }
1620         }
1621
1622       s = pool_id2solvable(pool, repo_add_solvable_block(repo, nrpmids));
1623       if (!repo->rpmdbid)
1624         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1625
1626       for (i = 0, rp = rpmids; i < nrpmids; i++, rp++, s++)
1627         {
1628           dbid = rp->dbid;
1629           repo->rpmdbid[(s - pool->solvables) - repo->start] = rp->dbid;
1630           if (refhash)
1631             {
1632               h = dbid & refmask;
1633               while ((id = refhash[h]))
1634                 {
1635                   if (ref->rpmdbid[id - 1] == dbid)
1636                     break;
1637                   h = (h + 317) & refmask;
1638                 }
1639               if (id)
1640                 {
1641                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1642                   if (r->repo == ref)
1643                     {
1644                       solvable_copy(s, r, data, dircache);
1645                       continue;
1646                     }
1647                 }
1648             }
1649           if (!db)
1650             {
1651               if (db_create(&db, dbenv, 0))
1652                 {
1653                   perror("db_create");
1654                   exit(1);
1655                 }
1656               if (db->open(db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1657                 {
1658                   perror("db->open var/lib/rpm/Packages");
1659                   exit(1);
1660                 }
1661               if (db->get_byteswapped(db, &byteswapped))
1662                 {
1663                   perror("db->get_byteswapped");
1664                   exit(1);
1665                 }
1666             }
1667           rpmdbid2db(buf, rp->dbid, byteswapped);
1668           dbkey.data = buf;
1669           dbkey.size = 4;
1670           dbdata.data = 0;
1671           dbdata.size = 0;
1672           if (db->get(db, NULL, &dbkey, &dbdata, 0))
1673             {
1674               perror("db->get");
1675               fprintf(stderr, "corrupt rpm database, key %d not found\n", dbid);
1676               fprintf(stderr, "please run 'rpm --rebuilddb' to recreate the database index files\n");
1677               exit(1);
1678             }
1679           if (dbdata.size < 8)
1680             {
1681               fprintf(stderr, "corrupt rpm database (size)\n");
1682               exit(1);
1683             }
1684           if (dbdata.size > rpmheadsize)
1685             {
1686               rpmheadsize = dbdata.size + 128;
1687               rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1688             }
1689           memcpy(buf, dbdata.data, 8);
1690           rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1691           rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1692           if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1693             {
1694               fprintf(stderr, "corrupt rpm database (data size)\n");
1695               exit(1);
1696             }
1697           memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1698           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1699
1700           rpm2solv(pool, repo, data, s, rpmhead, flags | RPM_ADD_TRIGGERS);
1701           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1702             {
1703               if (done < count)
1704                 done++;
1705               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1706                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1707             }
1708         }
1709
1710       if (refhash)
1711         solv_free(refhash);
1712       if (rpmids)
1713         {
1714           for (i = 0; i < nrpmids; i++)
1715             solv_free(rpmids[i].name);
1716           solv_free(rpmids);
1717         }
1718     }
1719   if (db)
1720     db->close(db, 0);
1721   dbenv->close(dbenv, 0);
1722   if (rpmhead)
1723     solv_free(rpmhead);
1724   if (!(flags & REPO_NO_INTERNALIZE))
1725     repodata_internalize(data);
1726   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1727     pool_debug(pool, SOLV_ERROR, "%%%% 100\n");
1728   POOL_DEBUG(SOLV_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", solv_timems(now));
1729   POOL_DEBUG(SOLV_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1730   POOL_DEBUG(SOLV_DEBUG_STATS, "repo memory used: %d K incore, %d K idarray\n", repodata_memused(data)/1024, repo->idarraysize / (int)(1024/sizeof(Id)));
1731   return 0;
1732 }
1733
1734
1735 static inline unsigned int
1736 getu32(const unsigned char *dp)
1737 {
1738   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1739 }
1740
1741
1742 int
1743 repo_add_rpms(Repo *repo, const char **rpms, int nrpms, int flags)
1744 {
1745   int i, sigdsize, sigcnt, l;
1746   Pool *pool = repo->pool;
1747   Solvable *s;
1748   RpmHead *rpmhead = 0;
1749   int rpmheadsize = 0;
1750   char *payloadformat;
1751   FILE *fp;
1752   unsigned char lead[4096];
1753   int headerstart, headerend;
1754   struct stat stb;
1755   Repodata *data;
1756   unsigned char pkgid[16];
1757   int gotpkgid;
1758   Id chksumtype = 0;
1759   void *chksumh = 0;
1760
1761   data = repo_add_repodata(repo, flags);
1762
1763   if ((flags & RPM_ADD_WITH_SHA256SUM) != 0)
1764     chksumtype = REPOKEY_TYPE_SHA256;
1765   else if ((flags & RPM_ADD_WITH_SHA1SUM) != 0)
1766     chksumtype = REPOKEY_TYPE_SHA1;
1767   for (i = 0; i < nrpms; i++)
1768     {
1769       if ((fp = fopen(rpms[i], "r")) == 0)
1770         {
1771           perror(rpms[i]);
1772           continue;
1773         }
1774       if (fstat(fileno(fp), &stb))
1775         {
1776           perror("stat");
1777           continue;
1778         }
1779       if (chksumh)
1780         chksumh = solv_chksum_free(chksumh, 0);
1781       if (chksumtype)
1782         chksumh = solv_chksum_create(chksumtype);
1783       if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1784         {
1785           fprintf(stderr, "%s: not a rpm\n", rpms[i]);
1786           fclose(fp);
1787           continue;
1788         }
1789       if (chksumh)
1790         solv_chksum_add(chksumh, lead, 96 + 16);
1791       if (lead[78] != 0 || lead[79] != 5)
1792         {
1793           fprintf(stderr, "%s: not a V5 header\n", rpms[i]);
1794           fclose(fp);
1795           continue;
1796         }
1797       if (getu32(lead + 96) != 0x8eade801)
1798         {
1799           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1800           fclose(fp);
1801           continue;
1802         }
1803       sigcnt = getu32(lead + 96 + 8);
1804       sigdsize = getu32(lead + 96 + 12);
1805       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1806         {
1807           fprintf(stderr, "%s: bad signature header\n", rpms[i]);
1808           fclose(fp);
1809           continue;
1810         }
1811       sigdsize += sigcnt * 16;
1812       sigdsize = (sigdsize + 7) & ~7;
1813       headerstart = 96 + 16 + sigdsize;
1814       gotpkgid = 0;
1815       if ((flags & RPM_ADD_WITH_PKGID) != 0)
1816         {
1817           unsigned char *chksum;
1818           unsigned int chksumsize;
1819           /* extract pkgid from the signature header */
1820           if (sigdsize > rpmheadsize)
1821             {
1822               rpmheadsize = sigdsize + 128;
1823               rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1824             }
1825           if (fread(rpmhead->data, sigdsize, 1, fp) != 1)
1826             {
1827               fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1828               fclose(fp);
1829               continue;
1830             }
1831           if (chksumh)
1832             solv_chksum_add(chksumh, rpmhead->data, sigdsize);
1833           rpmhead->cnt = sigcnt;
1834           rpmhead->dcnt = sigdsize - sigcnt * 16;
1835           rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1836           chksum = headbinary(rpmhead, SIGTAG_MD5, &chksumsize);
1837           if (chksum && chksumsize == 16)
1838             {
1839               gotpkgid = 1;
1840               memcpy(pkgid, chksum, 16);
1841             }
1842         }
1843       else
1844         {
1845           /* just skip the signature header */
1846           while (sigdsize)
1847             {
1848               l = sigdsize > 4096 ? 4096 : sigdsize;
1849               if (fread(lead, l, 1, fp) != 1)
1850                 {
1851                   fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1852                   fclose(fp);
1853                   continue;
1854                 }
1855               if (chksumh)
1856                 solv_chksum_add(chksumh, lead, l);
1857               sigdsize -= l;
1858             }
1859         }
1860       if (fread(lead, 16, 1, fp) != 1)
1861         {
1862           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1863           fclose(fp);
1864           continue;
1865         }
1866       if (chksumh)
1867         solv_chksum_add(chksumh, lead, 16);
1868       if (getu32(lead) != 0x8eade801)
1869         {
1870           fprintf(stderr, "%s: bad header\n", rpms[i]);
1871           fclose(fp);
1872           continue;
1873         }
1874       sigcnt = getu32(lead + 8);
1875       sigdsize = getu32(lead + 12);
1876       if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
1877         {
1878           fprintf(stderr, "%s: bad header\n", rpms[i]);
1879           fclose(fp);
1880           continue;
1881         }
1882       l = sigdsize + sigcnt * 16;
1883       headerend = headerstart + 16 + l;
1884       if (l > rpmheadsize)
1885         {
1886           rpmheadsize = l + 128;
1887           rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1888         }
1889       if (fread(rpmhead->data, l, 1, fp) != 1)
1890         {
1891           fprintf(stderr, "%s: unexpected EOF\n", rpms[i]);
1892           fclose(fp);
1893           continue;
1894         }
1895       if (chksumh)
1896         solv_chksum_add(chksumh, rpmhead->data, l);
1897       rpmhead->cnt = sigcnt;
1898       rpmhead->dcnt = sigdsize;
1899       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1900       if (headexists(rpmhead, TAG_PATCHESNAME))
1901         {
1902           /* this is a patch rpm, ignore */
1903           fclose(fp);
1904           continue;
1905         }
1906       payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
1907       if (payloadformat && !strcmp(payloadformat, "drpm"))
1908         {
1909           /* this is a delta rpm */
1910           fclose(fp);
1911           continue;
1912         }
1913       if (chksumh)
1914         while ((l = fread(lead, 1, sizeof(lead), fp)) > 0)
1915           solv_chksum_add(chksumh, lead, l);
1916       fclose(fp);
1917       s = pool_id2solvable(pool, repo_add_solvable(repo));
1918       rpm2solv(pool, repo, data, s, rpmhead, flags);
1919       if (data)
1920         {
1921           Id handle = s - pool->solvables;
1922           repodata_set_location(data, handle, 0, 0, rpms[i]);
1923           if (S_ISREG(stb.st_mode))
1924             repodata_set_num(data, handle, SOLVABLE_DOWNLOADSIZE, (unsigned int)((stb.st_size + 1023) / 1024));
1925           repodata_set_num(data, handle, SOLVABLE_HEADEREND, headerend);
1926           if (gotpkgid)
1927             repodata_set_bin_checksum(data, handle, SOLVABLE_PKGID, REPOKEY_TYPE_MD5, pkgid);
1928           if (chksumh)
1929             repodata_set_bin_checksum(data, handle, SOLVABLE_CHECKSUM, chksumtype, solv_chksum_get(chksumh, 0));
1930         }
1931     }
1932   if (chksumh)
1933     chksumh = solv_chksum_free(chksumh, 0);
1934   if (rpmhead)
1935     solv_free(rpmhead);
1936   if (!(flags & REPO_NO_INTERNALIZE))
1937     repodata_internalize(data);
1938   return 0;
1939 }
1940
1941 Id
1942 repo_add_rpm(Repo *repo, const char *rpm, int flags)
1943 {
1944   int end = repo->end;
1945   repo_add_rpms(repo, &rpm, 1, flags);
1946   if (end == repo->end)
1947     return 0;
1948   else
1949     return repo->end - 1;
1950 }
1951
1952 static inline void
1953 linkhash(const char *lt, char *hash)
1954 {
1955   unsigned int r = 0;
1956   const unsigned char *str = (const unsigned char *)lt;
1957   int l, c;
1958
1959   l = strlen(lt);
1960   while ((c = *str++) != 0)
1961     r += (r << 3) + c;
1962   sprintf(hash, "%08x", r);
1963   sprintf(hash + 8, "%08x", l);
1964   sprintf(hash + 16, "%08x", 0);
1965   sprintf(hash + 24, "%08x", 0);
1966 }
1967
1968 void
1969 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, int, const char *), void *cbdata)
1970 {
1971   RpmHead *rpmhead = rpmhandle;
1972   char **bn;
1973   char **dn;
1974   char **md = 0;
1975   char **lt = 0;
1976   unsigned int *di, diidx;
1977   unsigned int *co = 0;
1978   unsigned int *ff = 0;
1979   unsigned int lastdir;
1980   int lastdirl;
1981   unsigned int *fm;
1982   int cnt, dcnt, cnt2;
1983   int i, l1, l;
1984   char *space = 0;
1985   int spacen = 0;
1986   char md5[33], *md5p = 0;
1987
1988   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
1989   if (!dn)
1990     return;
1991   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
1992     {
1993       for (i = 0; i < dcnt; i++)
1994         (*cb)(cbdata, dn[i], 0, (char *)0);
1995       solv_free(dn);
1996       return;
1997     }
1998   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
1999   if (!bn)
2000     {
2001       solv_free(dn);
2002       return;
2003     }
2004   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
2005   if (!di || cnt != cnt2)
2006     {
2007       solv_free(di);
2008       solv_free(bn);
2009       solv_free(dn);
2010       return;
2011     }
2012   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
2013   if (!fm || cnt != cnt2)
2014     {
2015       solv_free(fm);
2016       solv_free(di);
2017       solv_free(bn);
2018       solv_free(dn);
2019       return;
2020     }
2021   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
2022     {
2023       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
2024       if (!md || cnt != cnt2)
2025         {
2026           solv_free(md);
2027           solv_free(fm);
2028           solv_free(di);
2029           solv_free(bn);
2030           solv_free(dn);
2031           return;
2032         }
2033     }
2034   if ((flags & RPM_ITERATE_FILELIST_WITHCOL) != 0)
2035     {
2036       co = headint32array(rpmhead, TAG_FILECOLORS, &cnt2);
2037       if (!co || cnt != cnt2)
2038         {
2039           solv_free(co);
2040           solv_free(md);
2041           solv_free(fm);
2042           solv_free(di);
2043           solv_free(bn);
2044           solv_free(dn);
2045           return;
2046         }
2047     }
2048   if ((flags & RPM_ITERATE_FILELIST_NOGHOSTS) != 0)
2049     {
2050       ff = headint32array(rpmhead, TAG_FILEFLAGS, &cnt2);
2051       if (!ff || cnt != cnt2)
2052         {
2053           solv_free(ff);
2054           solv_free(co);
2055           solv_free(md);
2056           solv_free(fm);
2057           solv_free(di);
2058           solv_free(bn);
2059           solv_free(dn);
2060           return;
2061         }
2062     }
2063   lastdir = dcnt;
2064   lastdirl = 0;
2065   for (i = 0; i < cnt; i++)
2066     {
2067       if (ff && (ff[i] & FILEFLAG_GHOST) != 0)
2068         continue;
2069       diidx = di[i];
2070       if (diidx >= dcnt)
2071         continue;
2072       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
2073       if (l1 == 0)
2074         continue;
2075       l = l1 + strlen(bn[i]) + 1;
2076       if (l > spacen)
2077         {
2078           spacen = l + 16;
2079           space = solv_realloc(space, spacen);
2080         }
2081       if (lastdir != diidx)
2082         {
2083           strcpy(space, dn[diidx]);
2084           lastdir = diidx;
2085           lastdirl = l1;
2086         }
2087       strcpy(space + l1, bn[i]);
2088       if (md)
2089         {
2090           md5p = md[i];
2091           if (S_ISLNK(fm[i]))
2092             {
2093               md5p = 0;
2094               if (!lt)
2095                 {
2096                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
2097                   if (cnt != cnt2)
2098                     lt = solv_free(lt);
2099                 }
2100               if (lt)
2101                 {
2102                   linkhash(lt[i], md5);
2103                   md5p = md5;
2104                 }
2105             }
2106           if (!md5p)
2107             {
2108               sprintf(md5, "%08x%08x%08x%08x", (fm[i] >> 12) & 65535, 0, 0, 0);
2109               md5p = md5;
2110             }
2111         }
2112       (*cb)(cbdata, space, co ? (fm[i] | co[i] << 24) : fm[i], md5p);
2113     }
2114   solv_free(space);
2115   solv_free(lt);
2116   solv_free(md);
2117   solv_free(fm);
2118   solv_free(di);
2119   solv_free(bn);
2120   solv_free(dn);
2121   solv_free(co);
2122   solv_free(ff);
2123 }
2124
2125 char *
2126 rpm_query(void *rpmhandle, Id what)
2127 {
2128   const char *name, *arch, *sourcerpm;
2129   char *evr, *r;
2130   int l;
2131
2132   RpmHead *rpmhead = rpmhandle;
2133   r = 0;
2134   switch (what)
2135     {
2136     case 0:
2137       name = headstring(rpmhead, TAG_NAME);
2138       if (!name)
2139         name = "";
2140       sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
2141       if (sourcerpm)
2142         arch = headstring(rpmhead, TAG_ARCH);
2143       else
2144         {
2145           if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
2146             arch = "nosrc";
2147           else
2148             arch = "src";
2149         }
2150       if (!arch)
2151         arch = "noarch";
2152       evr = headtoevr(rpmhead);
2153       l = strlen(name) + 1 + strlen(evr) + 1 + strlen(arch) + 1;
2154       r = solv_malloc(l);
2155       sprintf(r, "%s-%s.%s", name, evr, arch);
2156       free(evr);
2157       break;
2158     case SOLVABLE_NAME:
2159       name = headstring(rpmhead, TAG_NAME);
2160       r = solv_strdup(name);
2161       break;
2162     case SOLVABLE_EVR:
2163       r = headtoevr(rpmhead);
2164       break;
2165     }
2166   return r;
2167 }
2168
2169
2170 struct rpm_by_state {
2171   RpmHead *rpmhead;
2172   int rpmheadsize;
2173
2174   int dbopened;
2175   DB_ENV *dbenv;
2176   DB *db;
2177   int byteswapped;
2178 };
2179
2180 struct rpmdbentry {
2181   Id rpmdbid;
2182   Id nameoff;
2183 };
2184
2185 #define ENTRIES_BLOCK 255
2186 #define NAMEDATA_BLOCK 1023
2187
2188 static struct rpmdbentry *
2189 getinstalledrpmdbids(struct rpm_by_state *state, const char *index, const char *match, int *nentriesp, char **namedatap)
2190 {
2191   DB_ENV *dbenv = 0;
2192   DB *db = 0;
2193   DBC *dbc = 0;
2194   int byteswapped;
2195   DBT dbkey;
2196   DBT dbdata;
2197   unsigned char *dp;
2198   int dl;
2199
2200   char *namedata = 0;
2201   int namedatal = 0;
2202   struct rpmdbentry *entries = 0;
2203   int nentries = 0;
2204
2205   *nentriesp = 0;
2206   *namedatap = 0;
2207
2208   dbenv = state->dbenv;
2209   if (db_create(&db, dbenv, 0))
2210     {
2211       perror("db_create");
2212       return 0;
2213     }
2214   if (db->open(db, 0, index, 0, DB_UNKNOWN, DB_RDONLY, 0664))
2215     {
2216       perror("db->open index");
2217       db->close(db, 0);
2218       return 0;
2219     }
2220   if (db->get_byteswapped(db, &byteswapped))
2221     {
2222       perror("db->get_byteswapped");
2223       db->close(db, 0);
2224       return 0;
2225     }
2226   if (db->cursor(db, NULL, &dbc, 0))
2227     {
2228       perror("db->cursor");
2229       db->close(db, 0);
2230       return 0;
2231     }
2232   memset(&dbkey, 0, sizeof(dbkey));
2233   memset(&dbdata, 0, sizeof(dbdata));
2234   if (match)
2235     {
2236       dbkey.data = (void *)match;
2237       dbkey.size = strlen(match);
2238     }
2239   while (dbc->c_get(dbc, &dbkey, &dbdata, match ? DB_SET : DB_NEXT) == 0)
2240     {
2241       if (!match && dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
2242         continue;
2243       dl = dbdata.size;
2244       dp = dbdata.data;
2245       while(dl >= RPM_INDEX_SIZE)
2246         {
2247           entries = solv_extend(entries, nentries, 1, sizeof(*entries), ENTRIES_BLOCK);
2248           entries[nentries].rpmdbid = db2rpmdbid(dp, byteswapped);
2249           entries[nentries].nameoff = namedatal;
2250           nentries++;
2251           namedata = solv_extend(namedata, namedatal, dbkey.size + 1, 1, NAMEDATA_BLOCK);
2252           memcpy(namedata + namedatal, dbkey.data, dbkey.size);
2253           namedata[namedatal + dbkey.size] = 0;
2254           namedatal += dbkey.size + 1;
2255           dp += RPM_INDEX_SIZE;
2256           dl -= RPM_INDEX_SIZE;
2257         }
2258       if (match)
2259         break;
2260     }
2261   dbc->c_close(dbc);
2262   db->close(db, 0);
2263   *nentriesp = nentries;
2264   *namedatap = namedata;
2265   return entries;
2266 }
2267
2268 static void
2269 freestate(struct rpm_by_state *state)
2270 {
2271   /* close down */
2272   if (!state)
2273     return;
2274   if (state->db)
2275     state->db->close(state->db, 0);
2276   if (state->dbenv)
2277     state->dbenv->close(state->dbenv, 0);
2278   solv_free(state->rpmhead);
2279 }
2280
2281 int
2282 rpm_installedrpmdbids(const char *rootdir, const char *index, const char *match, Queue *rpmdbidq)
2283 {
2284   struct rpm_by_state state;
2285   struct rpmdbentry *entries;
2286   int nentries, i;
2287   char *namedata;
2288
2289   if (!index)
2290     index = "Name";
2291   if (rpmdbidq)
2292     queue_empty(rpmdbidq);
2293   memset(&state, 0, sizeof(state));
2294   if (!(state.dbenv = opendbenv(rootdir)))
2295     return 0;
2296   entries = getinstalledrpmdbids(&state, index, match, &nentries, &namedata);
2297   if (rpmdbidq)
2298     for (i = 0; i < nentries; i++)
2299       queue_push(rpmdbidq, entries[i].rpmdbid);
2300   solv_free(entries);
2301   solv_free(namedata);
2302   freestate(&state);
2303   return nentries;
2304 }
2305
2306 void *
2307 rpm_byrpmdbid(Id rpmdbid, const char *rootdir, void **statep)
2308 {
2309   struct rpm_by_state *state = *statep;
2310   unsigned char buf[16];
2311   DBT dbkey;
2312   DBT dbdata;
2313   RpmHead *rpmhead;
2314
2315   if (!rpmdbid)
2316     {
2317       /* close down */
2318       freestate(state);
2319       solv_free(state);
2320       *statep = (void *)0;
2321       return 0;
2322     }
2323
2324   if (!state)
2325     {
2326       state = solv_calloc(1, sizeof(*state));
2327       *statep = state;
2328     }
2329   if (!state->dbopened)
2330     {
2331       state->dbopened = 1;
2332       if (!state->dbenv && !(state->dbenv = opendbenv(rootdir)))
2333         return 0;
2334       if (db_create(&state->db, state->dbenv, 0))
2335         {
2336           perror("db_create");
2337           state->db = 0;
2338           state->dbenv->close(state->dbenv, 0);
2339           state->dbenv = 0;
2340           return 0;
2341         }
2342       if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
2343         {
2344           perror("db->open var/lib/rpm/Packages");
2345           state->db->close(state->db, 0);
2346           state->db = 0;
2347           state->dbenv->close(state->dbenv, 0);
2348           state->dbenv = 0;
2349           return 0;
2350         }
2351       if (state->db->get_byteswapped(state->db, &state->byteswapped))
2352         {
2353           perror("db->get_byteswapped");
2354           state->db->close(state->db, 0);
2355           state->db = 0;
2356           state->dbenv->close(state->dbenv, 0);
2357           state->dbenv = 0;
2358           return 0;
2359         }
2360     }
2361   rpmdbid2db(buf, rpmdbid, state->byteswapped);
2362   memset(&dbkey, 0, sizeof(dbkey));
2363   memset(&dbdata, 0, sizeof(dbdata));
2364   dbkey.data = buf;
2365   dbkey.size = 4;
2366   dbdata.data = 0;
2367   dbdata.size = 0;
2368   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
2369     {
2370       perror("db->get");
2371       return 0;
2372     }
2373   if (dbdata.size < 8)
2374     {
2375       fprintf(stderr, "corrupt rpm database (size)\n");
2376       return 0;
2377     }
2378   if (dbdata.size > state->rpmheadsize)
2379     {
2380       state->rpmheadsize = dbdata.size + 128;
2381       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
2382     }
2383   rpmhead = state->rpmhead;
2384   memcpy(buf, dbdata.data, 8);
2385   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
2386   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
2387   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
2388     {
2389       fprintf(stderr, "corrupt rpm database (data size)\n");
2390       return 0;
2391     }
2392   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
2393   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2394   return rpmhead;
2395 }
2396
2397 void *
2398 rpm_byfp(FILE *fp, const char *name, void **statep)
2399 {
2400   struct rpm_by_state *state = *statep;
2401   /* int headerstart, headerend; */
2402   RpmHead *rpmhead;
2403   int sigdsize, sigcnt, l;
2404   unsigned char lead[4096];
2405
2406   if (!fp)
2407     return rpm_byrpmdbid(0, 0, statep);
2408   if (!state)
2409     {
2410       state = solv_calloc(1, sizeof(*state));
2411       *statep = state;
2412     }
2413   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2414     {
2415       fprintf(stderr, "%s: not a rpm\n", name);
2416       return 0;
2417     }
2418   if (lead[78] != 0 || lead[79] != 5)
2419     {
2420       fprintf(stderr, "%s: not a V5 header\n", name);
2421       return 0;
2422     }
2423   if (getu32(lead + 96) != 0x8eade801)
2424     {
2425       fprintf(stderr, "%s: bad signature header\n", name);
2426       return 0;
2427     }
2428   sigcnt = getu32(lead + 96 + 8);
2429   sigdsize = getu32(lead + 96 + 12);
2430   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2431     {
2432       fprintf(stderr, "%s: bad signature header\n", name);
2433       return 0;
2434     }
2435   sigdsize += sigcnt * 16;
2436   sigdsize = (sigdsize + 7) & ~7;
2437   /* headerstart = 96 + 16 + sigdsize; */
2438   while (sigdsize)
2439     {
2440       l = sigdsize > 4096 ? 4096 : sigdsize;
2441       if (fread(lead, l, 1, fp) != 1)
2442         {
2443           fprintf(stderr, "%s: unexpected EOF\n", name);
2444           return 0;
2445         }
2446       sigdsize -= l;
2447     }
2448   if (fread(lead, 16, 1, fp) != 1)
2449     {
2450       fprintf(stderr, "%s: unexpected EOF\n", name);
2451       return 0;
2452     }
2453   if (getu32(lead) != 0x8eade801)
2454     {
2455       fprintf(stderr, "%s: bad header\n", name);
2456       fclose(fp);
2457       return 0;
2458     }
2459   sigcnt = getu32(lead + 8);
2460   sigdsize = getu32(lead + 12);
2461   if (sigcnt >= 0x4000000 || sigdsize >= 0x40000000)
2462     {
2463       fprintf(stderr, "%s: bad header\n", name);
2464       fclose(fp);
2465       return 0;
2466     }
2467   l = sigdsize + sigcnt * 16;
2468   /* headerend = headerstart + 16 + l; */
2469   if (l > state->rpmheadsize)
2470     {
2471       state->rpmheadsize = l + 128;
2472       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2473     }
2474   rpmhead = state->rpmhead;
2475   if (fread(rpmhead->data, l, 1, fp) != 1)
2476     {
2477       fprintf(stderr, "%s: unexpected EOF\n", name);
2478       fclose(fp);
2479       return 0;
2480     }
2481   rpmhead->cnt = sigcnt;
2482   rpmhead->dcnt = sigdsize;
2483   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2484   return rpmhead;
2485 }
2486
2487 void *
2488 rpm_byrpmh(Header h, void **statep)
2489 {
2490   struct rpm_by_state *state = *statep;
2491   const unsigned char *uh;
2492   int sigdsize, sigcnt, l;
2493   RpmHead *rpmhead;
2494
2495 #ifndef RPM5
2496   uh = headerUnload(h);
2497 #else
2498   uh = headerUnload(h, NULL);
2499 #endif
2500   if (!uh)
2501     return 0;
2502   sigcnt = getu32(uh);
2503   sigdsize = getu32(uh + 4);
2504   l = sigdsize + sigcnt * 16;
2505   if (!state)
2506     {
2507       state = solv_calloc(1, sizeof(*state));
2508       *statep = state;
2509     }
2510   if (l > state->rpmheadsize)
2511     {
2512       state->rpmheadsize = l + 128;
2513       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2514     }
2515   rpmhead = state->rpmhead;
2516   memcpy(rpmhead->data, uh + 8, l - 8);
2517   free((void *)uh);
2518   rpmhead->cnt = sigcnt;
2519   rpmhead->dcnt = sigdsize;
2520   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2521   return rpmhead;
2522 }
2523
2524
2525 #ifdef ENABLE_RPMDB_PUBKEY
2526
2527 static char *
2528 r64dec1(char *p, unsigned int *vp, int *eofp)
2529 {
2530   int i, x;
2531   unsigned int v = 0;
2532
2533   for (i = 0; i < 4; )
2534     {
2535       x = *p++;
2536       if (!x)
2537         return 0;
2538       if (x >= 'A' && x <= 'Z')
2539         x -= 'A';
2540       else if (x >= 'a' && x <= 'z')
2541         x -= 'a' - 26;
2542       else if (x >= '0' && x <= '9')
2543         x -= '0' - 52;
2544       else if (x == '+')
2545         x = 62;
2546       else if (x == '/')
2547         x = 63;
2548       else if (x == '=')
2549         {
2550           x = 0;
2551           if (i == 0)
2552             {
2553               *eofp = 3;
2554               *vp = 0;
2555               return p - 1;
2556             }
2557           *eofp += 1;
2558         }
2559       else
2560         continue;
2561       v = v << 6 | x;
2562       i++;
2563     }
2564   *vp = v;
2565   return p;
2566 }
2567
2568 static unsigned int
2569 crc24(unsigned char *p, int len)
2570 {
2571   unsigned int crc = 0xb704ceL;
2572   int i;
2573
2574   while (len--)
2575     {
2576       crc ^= (*p++) << 16;
2577       for (i = 0; i < 8; i++)
2578         if ((crc <<= 1) & 0x1000000)
2579           crc ^= 0x1864cfbL;
2580     }
2581   return crc & 0xffffffL;
2582 }
2583
2584 static unsigned char *
2585 unarmor(char *pubkey, int *pktlp)
2586 {
2587   char *p;
2588   int l, eof;
2589   unsigned char *buf, *bp;
2590   unsigned int v;
2591
2592   *pktlp = 0;
2593   while (strncmp(pubkey, "-----BEGIN PGP PUBLIC KEY BLOCK-----", 36) != 0)
2594     {
2595       pubkey = strchr(pubkey, '\n');
2596       if (!pubkey)
2597         return 0;
2598       pubkey++;
2599     }
2600   pubkey = strchr(pubkey, '\n');
2601   if (!pubkey++)
2602     return 0;
2603   /* skip header lines */
2604   for (;;)
2605     {
2606       while (*pubkey == ' ' || *pubkey == '\t')
2607         pubkey++;
2608       if (*pubkey == '\n')
2609         break;
2610       pubkey = strchr(pubkey, '\n');
2611       if (!pubkey++)
2612         return 0;
2613     }
2614   pubkey++;
2615   p = strchr(pubkey, '=');
2616   if (!p)
2617     return 0;
2618   l = p - pubkey;
2619   bp = buf = solv_malloc(l * 3 / 4 + 4);
2620   eof = 0;
2621   while (!eof)
2622     {
2623       pubkey = r64dec1(pubkey, &v, &eof);
2624       if (!pubkey)
2625         {
2626           solv_free(buf);
2627           return 0;
2628         }
2629       *bp++ = v >> 16;
2630       *bp++ = v >> 8;
2631       *bp++ = v;
2632     }
2633   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2634     pubkey++;
2635   bp -= eof;
2636   if (*pubkey != '=' || (pubkey = r64dec1(pubkey + 1, &v, &eof)) == 0)
2637     {
2638       solv_free(buf);
2639       return 0;
2640     }
2641   if (v != crc24(buf, bp - buf))
2642     {
2643       solv_free(buf);
2644       return 0;
2645     }
2646   while (*pubkey == ' ' || *pubkey == '\t' || *pubkey == '\n' || *pubkey == '\r')
2647     pubkey++;
2648   if (strncmp(pubkey, "-----END PGP PUBLIC KEY BLOCK-----", 34) != 0)
2649     {
2650       solv_free(buf);
2651       return 0;
2652     }
2653   *pktlp = bp - buf;
2654   return buf;
2655 }
2656
2657 static void
2658 parsekeydata(Solvable *s, Repodata *data, unsigned char *p, int pl)
2659 {
2660   int x, tag, l;
2661   unsigned char keyid[8];
2662   unsigned int kcr = 0, maxex = 0;
2663   unsigned char *pubkey = 0;
2664   unsigned char *userid = 0;
2665 #if 0
2666   int pubkeyl = 0;
2667   int useridl = 0;
2668 #endif
2669
2670   for (; pl; p += l, pl -= l)
2671     {
2672       x = *p++;
2673       pl--;
2674       if (!(x & 128) || pl <= 0)
2675         return;
2676       if ((x & 64) == 0)
2677         {
2678           /* old format */
2679           tag = (x & 0x3c) >> 2;
2680           x &= 3;
2681           if (x == 3)
2682             return;
2683           l = 1 << x;
2684           if (pl < l)
2685             return;
2686           x = 0;
2687           while (l--)
2688             {
2689               x = x << 8 | *p++;
2690               pl--;
2691             }
2692           l = x;
2693         }
2694       else
2695         {
2696           tag = (x & 0x3f);
2697           x = *p++;
2698           pl--;
2699           if (x < 192)
2700             l = x;
2701           else if (x >= 192 && x < 224)
2702             {
2703               if (pl <= 0)
2704                 return;
2705               l = ((x - 192) << 8) + *p++ + 192;
2706               pl--;
2707             }
2708           else if (x == 255)
2709             {
2710               if (pl <= 4)
2711                 return;
2712               l = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
2713               p += 4;
2714               pl -= 4;
2715             }
2716           else
2717             return;
2718         }
2719       if (pl < l)
2720         return;
2721       if (tag == 6)
2722         {
2723           pubkey = solv_realloc(pubkey, l);
2724           if (l)
2725             memcpy(pubkey, p, l);
2726 #if 0
2727           pubkeyl = l;
2728 #endif
2729           kcr = 0;
2730           if (p[0] == 3)
2731             {
2732               unsigned int ex;
2733               void *h;
2734               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2735               ex = 0;
2736               if (p[5] || p[6])
2737                 {
2738                   ex = kcr + 24*3600 * (p[5] << 8 | p[6]);
2739                   if (ex > maxex)
2740                     maxex = ex;
2741                 }
2742               memset(keyid, 0, 8);
2743               if (p[7] == 1)    /* RSA */
2744                 {
2745                   int i, ql;
2746                   unsigned char fp[16];
2747                   char fpx[32 + 1];
2748                   unsigned char *q;
2749
2750                   ql = ((p[8] << 8 | p[9]) + 7) / 8;
2751                   memcpy(keyid, p + 10 + ql - 8, 8);
2752                   h = solv_chksum_create(REPOKEY_TYPE_MD5);
2753                   solv_chksum_add(h, p + 10, ql);
2754                   q = p + 10 + ql;
2755                   ql = ((q[0] << 8 | q[1]) + 7) / 8;
2756                   solv_chksum_add(h, q + 2, ql);
2757                   solv_chksum_free(h, fp);
2758                   for (i = 0; i < 16; i++)
2759                     sprintf(fpx + i * 2, "%02x", fp[i]);
2760                   setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2761                 }
2762             }
2763           else if (p[0] == 4)
2764             {
2765               int i;
2766               void *h;
2767               unsigned char hdr[3];
2768               unsigned char fp[20];
2769               char fpx[40 + 1];
2770
2771               kcr = p[1] << 24 | p[2] << 16 | p[3] << 8 | p[4];
2772               hdr[0] = 0x99;
2773               hdr[1] = l >> 8;
2774               hdr[2] = l;
2775               h = solv_chksum_create(REPOKEY_TYPE_SHA1);
2776               solv_chksum_add(h, hdr, 3);
2777               solv_chksum_add(h, p, l);
2778               solv_chksum_free(h, fp);
2779               for (i = 0; i < 20; i++)
2780                 sprintf(fpx + i * 2, "%02x", fp[i]);
2781               setutf8string(data, s - s->repo->pool->solvables, PUBKEY_FINGERPRINT, fpx);
2782               memcpy(keyid, fp + 12, 8);
2783             }
2784         }
2785       if (tag == 2)
2786         {
2787           if (p[0] == 3 && p[1] == 5)
2788             {
2789 #if 0
2790               Id htype = 0;
2791 #endif
2792               /* printf("V3 signature packet\n"); */
2793               if (l < 17)
2794                 continue;
2795               if (p[2] != 0x10 && p[2] != 0x11 && p[2] != 0x12 && p[2] != 0x13 && p[2] != 0x1f)
2796                 continue;
2797               if (!memcmp(keyid, p + 6, 8))
2798                 {
2799                   /* printf("SELF SIG\n"); */
2800                 }
2801               else
2802                 {
2803                   /* printf("OTHER SIG\n"); */
2804                 }
2805 #if 0
2806               if (p[16] == 1)
2807                 htype = REPOKEY_TYPE_MD5;
2808               else if (p[16] == 2)
2809                 htype = REPOKEY_TYPE_SHA1;
2810               else if (p[16] == 8)
2811                 htype = REPOKEY_TYPE_SHA256;
2812               if (htype)
2813                 {
2814                   void *h = solv_chksum_create(htype);
2815                   unsigned char b[3], *cs;
2816
2817                   b[0] = 0x99;
2818                   b[1] = pubkeyl >> 8;
2819                   b[2] = pubkeyl;
2820                   solv_chksum_add(h, b, 3);
2821                   solv_chksum_add(h, pubkey, pubkeyl);
2822                   if (p[2] >= 0x10 && p[2] <= 0x13)
2823                     solv_chksum_add(h, userid, useridl);
2824                   solv_chksum_add(h, p + 2, 5);
2825                   cs = solv_chksum_get(h, 0);
2826                   solv_chksum_free(h, 0);
2827                 }
2828 #endif
2829             }
2830           if (p[0] == 4)
2831             {
2832               int j, ql, haveissuer;
2833               unsigned char *q;
2834               unsigned int ex = 0;
2835 #if 0
2836               unsigned int scr = 0;
2837 #endif
2838               unsigned char issuer[8];
2839
2840               /* printf("V4 signature packet\n"); */
2841               if (l < 6)
2842                 continue;
2843               if (p[1] != 0x10 && p[1] != 0x11 && p[1] != 0x12 && p[1] != 0x13 && p[1] != 0x1f)
2844                 continue;
2845               haveissuer = 0;
2846               ex = 0;
2847               q = p + 4;
2848               for (j = 0; q && j < 2; j++)
2849                 {
2850                   if (q + 2 > p + l)
2851                     {
2852                       q = 0;
2853                       break;
2854                     }
2855                   ql = q[0] << 8 | q[1];
2856                   q += 2;
2857                   if (q + ql > p + l)
2858                     {
2859                       q = 0;
2860                       break;
2861                     }
2862                   while (ql)
2863                     {
2864                       int sl;
2865                       x = *q++;
2866                       ql--;
2867                       if (x < 192)
2868                         sl = x;
2869                       else if (x == 255)
2870                         {
2871                           if (ql < 4)
2872                             {
2873                               q = 0;
2874                               break;
2875                             }
2876                           sl = q[0] << 24 | q[1] << 16 | q[2] << 8 | q[3];
2877                           q += 4;
2878                           ql -= 4;
2879                         }
2880                       else
2881                         {
2882                           if (ql < 1)
2883                             {
2884                               q = 0;
2885                               break;
2886                             }
2887                           sl = ((x - 192) << 8) + *q++ + 192;
2888                           ql--;
2889                         }
2890                       if (ql < sl)
2891                         {
2892                           q = 0;
2893                           break;
2894                         }
2895                       x = q[0] & 127;
2896                       /* printf("%d SIGSUB %d %d\n", j, x, sl); */
2897                       if (x == 16 && sl == 9 && !haveissuer)
2898                         {
2899                           memcpy(issuer, q + 1, 8);
2900                           haveissuer = 1;
2901                         }
2902 #if 0
2903                       if (x == 2 && j == 0)
2904                         scr = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2905 #endif
2906                       if (x == 9 && j == 0)
2907                         ex = q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4];
2908                       q += sl;
2909                       ql -= sl;
2910                     }
2911                 }
2912               if (ex)
2913                 ex += kcr;
2914               if (haveissuer)
2915                 {
2916 #if 0
2917                   Id htype = 0;
2918                   if (p[3] == 1)
2919                     htype = REPOKEY_TYPE_MD5;
2920                   else if (p[3] == 2)
2921                     htype = REPOKEY_TYPE_SHA1;
2922                   else if (p[3] == 8)
2923                     htype = REPOKEY_TYPE_SHA256;
2924                   if (htype && pubkeyl)
2925                     {
2926                       void *h = solv_chksum_create(htype);
2927                       unsigned char b[6], *cs;
2928                       unsigned int hl;
2929
2930                       b[0] = 0x99;
2931                       b[1] = pubkeyl >> 8;
2932                       b[2] = pubkeyl;
2933                       solv_chksum_add(h, b, 3);
2934                       solv_chksum_add(h, pubkey, pubkeyl);
2935                       if (p[1] >= 0x10 && p[1] <= 0x13)
2936                         {
2937                           b[0] = 0xb4;
2938                           b[1] = useridl >> 24;
2939                           b[2] = useridl >> 16;
2940                           b[3] = useridl >> 8;
2941                           b[4] = useridl;
2942                           solv_chksum_add(h, b, 5);
2943                           solv_chksum_add(h, userid, useridl);
2944                         }
2945                       hl = 6 + (p[4] << 8 | p[5]);
2946                       solv_chksum_add(h, p, hl);
2947                       b[0] = 4;
2948                       b[1] = 0xff;
2949                       b[2] = hl >> 24;
2950                       b[3] = hl >> 16;
2951                       b[4] = hl >> 8;
2952                       b[5] = hl;
2953                       solv_chksum_add(h, b, 6);
2954                       cs = solv_chksum_get(h, 0);
2955                       solv_chksum_free(h, 0);
2956                     }
2957 #endif
2958                   if (!memcmp(keyid, issuer, 8))
2959                     {
2960                       /* printf("SELF SIG cr %d ex %d\n", cr, ex); */
2961                       if (ex > maxex)
2962                         maxex = ex;
2963                     }
2964                   else
2965                     {
2966                       /* printf("OTHER SIG cr %d ex %d\n", cr, ex); */
2967                     }
2968                 }
2969             }
2970         }
2971       if (tag == 13)
2972         {
2973           userid = solv_realloc(userid, l);
2974           if (l)
2975             memcpy(userid, p, l);
2976 #if 0
2977           useridl = l;
2978 #endif
2979         }
2980     }
2981   if (maxex)
2982     repodata_set_num(data, s - s->repo->pool->solvables, PUBKEY_EXPIRES, maxex);
2983   solv_free(pubkey);
2984   solv_free(userid);
2985 }
2986
2987 /* this is private to rpm, but rpm lacks an interface to retrieve
2988  * the values. Sigh. */
2989 struct pgpDigParams_s {
2990     const char * userid;
2991     const unsigned char * hash;
2992     const char * params[4];
2993     unsigned char tag;
2994     unsigned char version;               /*!< version number. */
2995     unsigned char time[4];               /*!< time that the key was created. */
2996     unsigned char pubkey_algo;           /*!< public key algorithm. */
2997     unsigned char hash_algo;
2998     unsigned char sigtype;
2999     unsigned char hashlen;
3000     unsigned char signhash16[2];
3001     unsigned char signid[8];
3002     unsigned char saved;
3003 };
3004
3005 struct pgpDig_s {
3006     struct pgpDigParams_s signature;
3007     struct pgpDigParams_s pubkey;
3008 };
3009
3010 static int
3011 pubkey2solvable(Solvable *s, Repodata *data, char *pubkey)
3012 {
3013   Pool *pool = s->repo->pool;
3014   unsigned char *pkts;
3015   unsigned int btime;
3016   int pktsl, i;
3017   pgpDig dig = 0;
3018   char keyid[16 + 1];
3019   char evrbuf[8 + 1 + 8 + 1];
3020
3021   pkts = unarmor(pubkey, &pktsl);
3022   if (!pkts)
3023     return 0;
3024   setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_DESCRIPTION, pubkey);
3025   parsekeydata(s, data, pkts, pktsl);
3026   /* only rpm knows how to do the release calculation, we don't dare
3027    * to recreate all the bugs */
3028 #ifndef RPM5
3029   dig = pgpNewDig();
3030 #else
3031   dig = pgpDigNew(RPMVSF_DEFAULT, 0);
3032 #endif
3033   (void) pgpPrtPkts(pkts, pktsl, dig, 0);
3034   btime = dig->pubkey.time[0] << 24 | dig->pubkey.time[1] << 16 | dig->pubkey.time[2] << 8 | dig->pubkey.signid[3];
3035   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]);
3036   repodata_set_num(data, s - s->repo->pool->solvables, SOLVABLE_BUILDTIME, btime);
3037
3038   s->name = pool_str2id(pool, "gpg-pubkey", 1);
3039   s->evr = pool_str2id(pool, evrbuf, 1);
3040   s->arch = 1;
3041   for (i = 0; i < 8; i++)
3042     sprintf(keyid + 2 * i, "%02x", dig->pubkey.signid[i]);
3043   repodata_set_str(data, s - s->repo->pool->solvables, PUBKEY_KEYID, keyid);
3044   if (dig->pubkey.userid)
3045     setutf8string(data, s - s->repo->pool->solvables, SOLVABLE_SUMMARY, dig->pubkey.userid);
3046 #ifndef RPM5
3047   (void)pgpFreeDig(dig);
3048 #else
3049   (void)pgpDigFree(dig);
3050 #endif
3051   solv_free((void *)pkts);
3052   return 1;
3053 }
3054
3055 int
3056 repo_add_rpmdb_pubkeys(Repo *repo, const char *rootdir, int flags)
3057 {
3058   Pool *pool = repo->pool;
3059   struct rpm_by_state state;
3060   struct rpmdbentry *entries;
3061   int nentries, i;
3062   char *namedata, *str;
3063   unsigned int u32;
3064   Repodata *data;
3065   Solvable *s;
3066
3067   data = repo_add_repodata(repo, flags);
3068
3069   memset(&state, 0, sizeof(state));
3070   if (!(state.dbenv = opendbenv(rootdir)))
3071     return 0;
3072   entries = getinstalledrpmdbids(&state, "Name", "gpg-pubkey", &nentries, &namedata);
3073   for (i = 0 ; i < nentries; i++)
3074     {
3075       void *statep = &state;
3076       RpmHead *rpmhead = rpm_byrpmdbid(entries[i].rpmdbid, rootdir, &statep);
3077       if (!rpmhead)
3078         continue;
3079       str = headstring(rpmhead, TAG_DESCRIPTION);
3080       if (!str)
3081         continue;
3082       s = pool_id2solvable(pool, repo_add_solvable(repo));
3083       pubkey2solvable(s, data, str);
3084       u32 = headint32(rpmhead, TAG_INSTALLTIME);
3085       if (u32)
3086         repodata_set_num(data, s - pool->solvables, SOLVABLE_INSTALLTIME, u32);
3087       if (!repo->rpmdbid)
3088         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
3089       repo->rpmdbid[s - pool->solvables - repo->start] = entries[i].rpmdbid;
3090     }
3091   solv_free(entries);
3092   solv_free(namedata);
3093   freestate(&state);
3094   if (!(flags & REPO_NO_INTERNALIZE))
3095     repodata_internalize(data);
3096   return 0;
3097 }
3098
3099 int
3100 repo_add_pubkeys(Repo *repo, const char **keys, int nkeys, int flags)
3101 {
3102   Pool *pool = repo->pool;
3103   Repodata *data;
3104   Solvable *s;
3105   char *buf;
3106   int i, bufl, l, ll;
3107   FILE *fp;
3108
3109   data = repo_add_repodata(repo, flags);
3110   buf = 0;
3111   bufl = 0;
3112   for (i = 0; i < nkeys; i++)
3113     {
3114       if ((fp = fopen(keys[i], "r")) == 0)
3115         {
3116           perror(keys[i]);
3117           continue;
3118         }
3119       for (l = 0; ;)
3120         {
3121           if (bufl - l < 4096)
3122             {
3123               bufl += 4096;
3124               buf = solv_realloc(buf, bufl);
3125             }
3126           ll = fread(buf, 1, bufl - l, fp);
3127           if (ll <= 0)
3128             break;
3129           l += ll;
3130         }
3131       buf[l] = 0;
3132       fclose(fp);
3133       s = pool_id2solvable(pool, repo_add_solvable(repo));
3134       pubkey2solvable(s, data, buf);
3135     }
3136   solv_free(buf);
3137   if (!(flags & REPO_NO_INTERNALIZE))
3138     repodata_internalize(data);
3139   return 0;
3140 }
3141
3142 #endif /* ENABLE_RPMDB_PUBKEY */