add utf8 helpers to util.c
[platform/upstream/libsolv.git] / ext / repo_rpmdb.c
1 /*
2  * Copyright (c) 2007-2012, Novell Inc.
3  *
4  * This program is licensed under the BSD license, read LICENSE.BSD
5  * for further information
6  */
7
8 /*
9  * repo_rpmdb
10  *
11  * convert rpm db to repo
12  *
13  */
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <limits.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <assert.h>
24 #include <stdint.h>
25 #include <errno.h>
26
27 #include <rpm/rpmio.h>
28 #include <rpm/rpmpgp.h>
29 #ifndef RPM5
30 #include <rpm/header.h>
31 #endif
32 #include <rpm/rpmdb.h>
33
34 #ifndef DB_CREATE
35 # if defined(SUSE) || defined(HAVE_RPM_DB_H)
36 #  include <rpm/db.h>
37 # else
38 #  include <db.h>
39 # endif
40 #endif
41
42 #include "pool.h"
43 #include "repo.h"
44 #include "hash.h"
45 #include "util.h"
46 #include "queue.h"
47 #include "chksum.h"
48 #include "repo_rpmdb.h"
49 #include "repo_solv.h"
50
51 /* 3: added triggers */
52 /* 4: fixed triggers */
53 #define RPMDB_COOKIE_VERSION 4
54
55 #define TAG_NAME                1000
56 #define TAG_VERSION             1001
57 #define TAG_RELEASE             1002
58 #define TAG_EPOCH               1003
59 #define TAG_SUMMARY             1004
60 #define TAG_DESCRIPTION         1005
61 #define TAG_BUILDTIME           1006
62 #define TAG_BUILDHOST           1007
63 #define TAG_INSTALLTIME         1008
64 #define TAG_SIZE                1009
65 #define TAG_DISTRIBUTION        1010
66 #define TAG_VENDOR              1011
67 #define TAG_LICENSE             1014
68 #define TAG_PACKAGER            1015
69 #define TAG_GROUP               1016
70 #define TAG_URL                 1020
71 #define TAG_ARCH                1022
72 #define TAG_FILESIZES           1028
73 #define TAG_FILEMODES           1030
74 #define TAG_FILEMD5S            1035
75 #define TAG_FILELINKTOS         1036
76 #define TAG_FILEFLAGS           1037
77 #define TAG_SOURCERPM           1044
78 #define TAG_PROVIDENAME         1047
79 #define TAG_REQUIREFLAGS        1048
80 #define TAG_REQUIRENAME         1049
81 #define TAG_REQUIREVERSION      1050
82 #define TAG_NOSOURCE            1051
83 #define TAG_NOPATCH             1052
84 #define TAG_CONFLICTFLAGS       1053
85 #define TAG_CONFLICTNAME        1054
86 #define TAG_CONFLICTVERSION     1055
87 #define TAG_TRIGGERNAME         1066
88 #define TAG_TRIGGERVERSION      1067
89 #define TAG_TRIGGERFLAGS        1068
90 #define TAG_CHANGELOGTIME       1080
91 #define TAG_CHANGELOGNAME       1081
92 #define TAG_CHANGELOGTEXT       1082
93 #define TAG_OBSOLETENAME        1090
94 #define TAG_FILEDEVICES         1095
95 #define TAG_FILEINODES          1096
96 #define TAG_SOURCEPACKAGE       1106
97 #define TAG_PROVIDEFLAGS        1112
98 #define TAG_PROVIDEVERSION      1113
99 #define TAG_OBSOLETEFLAGS       1114
100 #define TAG_OBSOLETEVERSION     1115
101 #define TAG_DIRINDEXES          1116
102 #define TAG_BASENAMES           1117
103 #define TAG_DIRNAMES            1118
104 #define TAG_PAYLOADFORMAT       1124
105 #define TAG_PATCHESNAME         1133
106 #define TAG_FILECOLORS          1140
107 #define TAG_SUGGESTSNAME        1156
108 #define TAG_SUGGESTSVERSION     1157
109 #define TAG_SUGGESTSFLAGS       1158
110 #define TAG_ENHANCESNAME        1159
111 #define TAG_ENHANCESVERSION     1160
112 #define TAG_ENHANCESFLAGS       1161
113
114 /* rpm5 tags */
115 #define TAG_DISTEPOCH           1218
116
117 /* rpm4 tags */
118 #define TAG_LONGFILESIZES       5008
119 #define TAG_LONGSIZE            5009
120
121 /* signature tags */
122 #define TAG_SIGBASE             256
123 #define TAG_SIGMD5              (TAG_SIGBASE + 5)
124 #define TAG_SHA1HEADER          (TAG_SIGBASE + 13)
125
126 #define SIGTAG_SIZE             1000
127 #define SIGTAG_PGP              1002    /* RSA signature */
128 #define SIGTAG_MD5              1004    /* header+payload md5 checksum */
129 #define SIGTAG_GPG              1005    /* DSA signature */
130
131 #define DEP_LESS                (1 << 1)
132 #define DEP_GREATER             (1 << 2)
133 #define DEP_EQUAL               (1 << 3)
134 #define DEP_STRONG              (1 << 27)
135 #define DEP_PRE                 ((1 << 6) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 12))
136
137 #define FILEFLAG_GHOST          (1 <<  6)
138
139
140 #ifdef RPM5
141 # define RPM_INDEX_SIZE 4
142 #else
143 # define RPM_INDEX_SIZE 8
144 #endif
145
146
147 typedef struct rpmhead {
148   int cnt;
149   int dcnt;
150   unsigned char *dp;
151   int forcebinary;              /* sigh, see rh#478907 */
152   unsigned char data[1];
153 } RpmHead;
154
155
156 static inline unsigned char *
157 headfindtag(RpmHead *h, int tag)
158 {
159   unsigned int i;
160   unsigned char *d, taga[4];
161   d = h->dp - 16;
162   taga[0] = tag >> 24;
163   taga[1] = tag >> 16;
164   taga[2] = tag >> 8;
165   taga[3] = tag;
166   for (i = 0; i < h->cnt; i++, d -= 16)
167     if (d[3] == taga[3] && d[2] == taga[2] && d[1] == taga[1] && d[0] == taga[0])
168       return d;
169   return 0;
170 }
171
172 static int
173 headexists(RpmHead *h, int tag)
174 {
175   return headfindtag(h, tag) ? 1 : 0;
176 }
177
178 static unsigned int *
179 headint32array(RpmHead *h, int tag, int *cnt)
180 {
181   unsigned int i, o, *r;
182   unsigned char *d = headfindtag(h, tag);
183
184   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
185     return 0;
186   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
187   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
188   if (o + 4 * i > h->dcnt)
189     return 0;
190   d = h->dp + o;
191   r = solv_calloc(i ? i : 1, sizeof(unsigned int));
192   if (cnt)
193     *cnt = i;
194   for (o = 0; o < i; o++, d += 4)
195     r[o] = d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
196   return r;
197 }
198
199 /* returns the first entry of an integer array */
200 static unsigned int
201 headint32(RpmHead *h, int tag)
202 {
203   unsigned int i, o;
204   unsigned char *d = headfindtag(h, tag);
205
206   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 4)
207     return 0;
208   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
209   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
210   if (i == 0 || o + 4 * i > h->dcnt)
211     return 0;
212   d = h->dp + o;
213   return d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
214 }
215
216 static unsigned long long *
217 headint64array(RpmHead *h, int tag, int *cnt)
218 {
219   unsigned int i, o;
220   unsigned long long *r;
221   unsigned char *d = headfindtag(h, tag);
222
223   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 5)
224     return 0;
225   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
226   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
227   if (o + 8 * i > h->dcnt)
228     return 0;
229   d = h->dp + o;
230   r = solv_calloc(i ? i : 1, sizeof(unsigned long long));
231   if (cnt)
232     *cnt = i;
233   for (o = 0; o < i; o++, d += 8)
234     {
235       unsigned int x = d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
236       r[o] = (unsigned long long)x << 32 | (d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7]);
237     }
238   return r;
239 }
240
241 /* returns the first entry of an 64bit integer array */
242 static unsigned long long
243 headint64(RpmHead *h, int tag)
244 {
245   unsigned int i, o;
246   unsigned char *d = headfindtag(h, tag);
247   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 5)
248     return 0;
249   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
250   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
251   if (i == 0 || o + 8 * i > h->dcnt)
252     return 0;
253   d = h->dp + o;
254   i = d[0] << 24 | d[1] << 16 | d[2] << 8 | d[3];
255   return (unsigned long long)i << 32 | (d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7]);
256 }
257
258 static unsigned int *
259 headint16array(RpmHead *h, int tag, int *cnt)
260 {
261   unsigned int i, o, *r;
262   unsigned char *d = headfindtag(h, tag);
263
264   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 3)
265     return 0;
266   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
267   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
268   if (o + 4 * i > h->dcnt)
269     return 0;
270   d = h->dp + o;
271   r = solv_calloc(i ? i : 1, sizeof(unsigned int));
272   if (cnt)
273     *cnt = i;
274   for (o = 0; o < i; o++, d += 2)
275     r[o] = d[0] << 8 | d[1];
276   return r;
277 }
278
279 static char *
280 headstring(RpmHead *h, int tag)
281 {
282   unsigned int o;
283   unsigned char *d = headfindtag(h, tag);
284   /* 6: STRING, 9: I18NSTRING */
285   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || (d[7] != 6 && d[7] != 9))
286     return 0;
287   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
288   if (o >= h->dcnt)
289     return 0;
290   return (char *)h->dp + o;
291 }
292
293 static char **
294 headstringarray(RpmHead *h, int tag, int *cnt)
295 {
296   unsigned int i, o;
297   unsigned char *d = headfindtag(h, tag);
298   char **r;
299
300   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 8)
301     return 0;
302   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
303   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
304   r = solv_calloc(i ? i : 1, sizeof(char *));
305   if (cnt)
306     *cnt = i;
307   d = h->dp + o;
308   for (o = 0; o < i; o++)
309     {
310       r[o] = (char *)d;
311       if (o + 1 < i)
312         d += strlen((char *)d) + 1;
313       if (d >= h->dp + h->dcnt)
314         {
315           solv_free(r);
316           return 0;
317         }
318     }
319   return r;
320 }
321
322 static unsigned char *
323 headbinary(RpmHead *h, int tag, unsigned int *sizep)
324 {
325   unsigned int i, o;
326   unsigned char *d = headfindtag(h, tag);
327   if (!d || d[4] != 0 || d[5] != 0 || d[6] != 0 || d[7] != 7)
328     return 0;
329   o = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];
330   i = d[12] << 24 | d[13] << 16 | d[14] << 8 | d[15];
331   if (o > h->dcnt || o + i < o || o + i > h->dcnt)
332     return 0;
333   if (sizep)
334     *sizep = i;
335   return h->dp + o;
336 }
337
338 static char *headtoevr(RpmHead *h)
339 {
340   unsigned int epoch;
341   char *version, *v;
342   char *release;
343   char *evr;
344   char *distepoch;
345
346   version  = headstring(h, TAG_VERSION);
347   release  = headstring(h, TAG_RELEASE);
348   epoch = headint32(h, TAG_EPOCH);
349   if (!version || !release)
350     {
351       fprintf(stderr, "headtoevr: bad rpm header\n");
352       return 0;
353     }
354   for (v = version; *v >= '0' && *v <= '9'; v++)
355     ;
356   if (epoch || (v != version && *v == ':'))
357     {
358       char epochbuf[11];        /* 32bit decimal will fit in */
359       sprintf(epochbuf, "%u", epoch);
360       evr = solv_malloc(strlen(epochbuf) + 1 + strlen(version) + 1 + strlen(release) + 1);
361       sprintf(evr, "%s:%s-%s", epochbuf, version, release);
362     }
363   else
364     {
365       evr = solv_malloc(strlen(version) + 1 + strlen(release) + 1);
366       sprintf(evr, "%s-%s", version, release);
367     }
368   distepoch = headstring(h, TAG_DISTEPOCH);
369   if (distepoch && *distepoch)
370     {
371       int l = strlen(evr);
372       evr = solv_realloc(evr, l + strlen(distepoch) + 2);
373       evr[l++] = ':';
374       strcpy(evr + l, distepoch);
375     }
376   return evr;
377 }
378
379
380 static void
381 setutf8string(Repodata *repodata, Id handle, Id tag, const char *str)
382 {
383   if (str[solv_validutf8(str)])
384     {
385       char *ustr = solv_latin1toutf8(str);      /* not utf8, assume latin1 */
386       repodata_set_str(repodata, handle, tag, ustr);
387       solv_free(ustr);
388     }
389   else
390     repodata_set_str(repodata, handle, tag, str);
391 }
392
393
394 #define MAKEDEPS_FILTER_WEAK    (1 << 0)
395 #define MAKEDEPS_FILTER_STRONG  (1 << 1)
396 #define MAKEDEPS_NO_RPMLIB      (1 << 2)
397
398 /*
399  * strong: 0: ignore strongness
400  *         1: filter to strong
401  *         2: filter to weak
402  */
403 static unsigned int
404 makedeps(Pool *pool, Repo *repo, RpmHead *rpmhead, int tagn, int tagv, int tagf, int flags)
405 {
406   char **n, **v;
407   unsigned int *f;
408   int i, cc, nc, vc, fc;
409   int haspre;
410   unsigned int olddeps;
411   Id *ida;
412   int strong;
413
414   strong = flags & (MAKEDEPS_FILTER_STRONG|MAKEDEPS_FILTER_WEAK);
415   n = headstringarray(rpmhead, tagn, &nc);
416   if (!n || !nc)
417     return 0;
418   vc = fc = 0;
419   v = headstringarray(rpmhead, tagv, &vc);
420   f = headint32array(rpmhead, tagf, &fc);
421   if (!v || !f || nc != vc || nc != fc)
422     {
423       char *pkgname = rpm_query(rpmhead, 0);
424       pool_error(pool, 0, "bad dependency entries for %s: %d %d %d", pkgname ? pkgname : "<NULL>", nc, vc, fc);
425       solv_free(pkgname);
426       solv_free(n);
427       solv_free(v);
428       solv_free(f);
429       return 0;
430     }
431
432   cc = nc;
433   haspre = 0;   /* add no prereq marker */
434   if (flags)
435     {
436       /* we do filtering */
437       cc = 0;
438       for (i = 0; i < nc; i++)
439         {
440           if (strong && (f[i] & DEP_STRONG) != (strong == MAKEDEPS_FILTER_WEAK ? 0 : DEP_STRONG))
441             continue;
442           if ((flags & MAKEDEPS_NO_RPMLIB) != 0)
443             if (!strncmp(n[i], "rpmlib(", 7))
444               continue;
445           if ((f[i] & DEP_PRE) != 0)
446             haspre = 1;
447           cc++;
448         }
449     }
450   else if (tagn == TAG_REQUIRENAME)
451     {
452       /* no filtering, just look for the first prereq */
453       for (i = 0; i < nc; i++)
454         if ((f[i] & DEP_PRE) != 0)
455           {
456             haspre = 1;
457             break;
458           }
459     }
460   if (cc == 0)
461     {
462       solv_free(n);
463       solv_free(v);
464       solv_free(f);
465       return 0;
466     }
467   cc += haspre;
468   olddeps = repo_reserve_ids(repo, 0, cc);
469   ida = repo->idarraydata + olddeps;
470   for (i = 0; ; i++)
471     {
472       if (i == nc)
473         {
474           if (haspre != 1)
475             break;
476           haspre = 2;   /* pass two: prereqs */
477           i = 0;
478           *ida++ = SOLVABLE_PREREQMARKER;
479         }
480       if (strong && (f[i] & DEP_STRONG) != (strong == MAKEDEPS_FILTER_WEAK ? 0 : DEP_STRONG))
481         continue;
482       if (haspre == 1 && (f[i] & DEP_PRE) != 0)
483         continue;
484       if (haspre == 2 && (f[i] & DEP_PRE) == 0)
485         continue;
486       if ((flags & MAKEDEPS_NO_RPMLIB) != 0)
487         if (!strncmp(n[i], "rpmlib(", 7))
488           continue;
489       if (f[i] & (DEP_LESS|DEP_GREATER|DEP_EQUAL))
490         {
491           Id name, evr;
492           int flags = 0;
493           if ((f[i] & DEP_LESS) != 0)
494             flags |= 4;
495           if ((f[i] & DEP_EQUAL) != 0)
496             flags |= 2;
497           if ((f[i] & DEP_GREATER) != 0)
498             flags |= 1;
499           name = pool_str2id(pool, n[i], 1);
500           if (v[i][0] == '0' && v[i][1] == ':' && v[i][2])
501             evr = pool_str2id(pool, v[i] + 2, 1);
502           else
503             evr = pool_str2id(pool, v[i], 1);
504           *ida++ = pool_rel2id(pool, name, evr, flags, 1);
505         }
506       else
507         *ida++ = pool_str2id(pool, n[i], 1);
508     }
509   *ida++ = 0;
510   repo->idarraysize += cc + 1;
511   solv_free(n);
512   solv_free(v);
513   solv_free(f);
514   return olddeps;
515 }
516
517
518 static void
519 adddudata(Repodata *data, Id handle, RpmHead *rpmhead, char **dn, unsigned int *di, int fc, int dc)
520 {
521   Id did;
522   int i, fszc;
523   unsigned int *fkb, *fn, *fsz, *fm, *fino;
524   unsigned long long *fsz64;
525   unsigned int inotest[256], inotestok;
526
527   if (!fc)
528     return;
529   if ((fsz64 = headint64array(rpmhead, TAG_LONGFILESIZES, &fszc)) != 0)
530     {
531       /* convert to kbyte */
532       fsz = solv_malloc2(fszc, sizeof(*fsz));
533       for (i = 0; i < fszc; i++)
534         fsz[i] = fsz64[i] ? fsz64[i] / 1024 + 1 : 0;
535       solv_free(fsz64);
536     }
537   else if ((fsz = headint32array(rpmhead, TAG_FILESIZES, &fszc)) != 0)
538     {
539       /* convert to kbyte */
540       for (i = 0; i < fszc; i++)
541         if (fsz[i])
542           fsz[i] = fsz[i] / 1024 + 1;
543     }
544   else
545     return;
546   if (fc != fszc)
547     {
548       solv_free(fsz);
549       return;
550     }
551
552   /* stupid rpm records sizes of directories, so we have to check the mode */
553   fm = headint16array(rpmhead, TAG_FILEMODES, &fszc);
554   if (!fm || fc != fszc)
555     {
556       solv_free(fsz);
557       solv_free(fm);
558       return;
559     }
560   fino = headint32array(rpmhead, TAG_FILEINODES, &fszc);
561   if (!fino || fc != fszc)
562     {
563       solv_free(fsz);
564       solv_free(fm);
565       solv_free(fino);
566       return;
567     }
568
569   /* kill hardlinked entries */
570   inotestok = 0;
571   if (fc < sizeof(inotest))
572     {
573       /* quick test just hashing the inode numbers */
574       memset(inotest, 0, sizeof(inotest));
575       for (i = 0; i < fc; i++)
576         {
577           int off, bit;
578           if (fsz[i] == 0 || !S_ISREG(fm[i]))
579             continue;   /* does not matter */
580           off = (fino[i] >> 5) & (sizeof(inotest)/sizeof(*inotest) - 1);
581           bit = 1 << (fino[i] & 31);
582           if ((inotest[off] & bit) != 0)
583             break;
584           inotest[off] |= bit;
585         }
586       if (i == fc)
587         inotestok = 1;  /* no conflict found */
588     }
589   if (!inotestok)
590     {
591       /* hardlinked files are possible, check ino/dev pairs */
592       unsigned int *fdev = headint32array(rpmhead, TAG_FILEDEVICES, &fszc);
593       unsigned int *fx, j;
594       unsigned int mask, hash, hh;
595       if (!fdev || fc != fszc)
596         {
597           solv_free(fsz);
598           solv_free(fm);
599           solv_free(fdev);
600           solv_free(fino);
601           return;
602         }
603       mask = fc;
604       while ((mask & (mask - 1)) != 0)
605         mask = mask & (mask - 1);
606       mask <<= 2;
607       if (mask > sizeof(inotest)/sizeof(*inotest))
608         fx = solv_calloc(mask, sizeof(unsigned int));
609       else
610         {
611           fx = inotest;
612           memset(fx, 0, mask * sizeof(unsigned int));
613         }
614       mask--;
615       for (i = 0; i < fc; i++)
616         {
617           if (fsz[i] == 0 || !S_ISREG(fm[i]))
618             continue;
619           hash = (fino[i] + fdev[i] * 31) & mask;
620           hh = 7;
621           while ((j = fx[hash]) != 0)
622             {
623               if (fino[j - 1] == fino[i] && fdev[j - 1] == fdev[i])
624                 {
625                   fsz[i] = 0;   /* kill entry */
626                   break;
627                 }
628               hash = (hash + hh++) & mask;
629             }
630           if (!j)
631             fx[hash] = i + 1;
632         }
633       if (fx != inotest)
634         solv_free(fx);
635       solv_free(fdev);
636     }
637   solv_free(fino);
638
639   /* sum up inode count and kbytes for each directory */
640   fn = solv_calloc(dc, sizeof(unsigned int));
641   fkb = solv_calloc(dc, sizeof(unsigned int));
642   for (i = 0; i < fc; i++)
643     {
644       if (di[i] >= dc)
645         continue;
646       fn[di[i]]++;
647       if (fsz[i] == 0 || !S_ISREG(fm[i]))
648         continue;
649       fkb[di[i]] += fsz[i];
650     }
651   solv_free(fsz);
652   solv_free(fm);
653   /* commit */
654   for (i = 0; i < dc; i++)
655     {
656       if (!fn[i])
657         continue;
658       if (!*dn[i])
659         {
660           Solvable *s = data->repo->pool->solvables + handle;
661           if (s->arch == ARCH_SRC || s->arch == ARCH_NOSRC)
662             did = repodata_str2dir(data, "/usr/src", 1);
663           else
664             continue;   /* work around rpm bug */
665         }
666       else
667         did = repodata_str2dir(data, dn[i], 1);
668       repodata_add_dirnumnum(data, handle, SOLVABLE_DISKUSAGE, did, fkb[i], fn[i]);
669     }
670   solv_free(fn);
671   solv_free(fkb);
672 }
673
674 static void
675 addfilelist(Repodata *data, Id handle, RpmHead *rpmhead)
676 {
677   char **bn;
678   char **dn;
679   unsigned int *di;
680   int bnc, dnc, dic;
681   int i;
682   Id lastdid = 0;
683   int lastdii = -1;
684
685   if (!data)
686     return;
687   bn = headstringarray(rpmhead, TAG_BASENAMES, &bnc);
688   if (!bn)
689     return;
690   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dnc);
691   if (!dn)
692     {
693       solv_free(bn);
694       return;
695     }
696   di = headint32array(rpmhead, TAG_DIRINDEXES, &dic);
697   if (!di)
698     {
699       solv_free(bn);
700       solv_free(dn);
701       return;
702     }
703   if (bnc != dic)
704     {
705       pool_error(data->repo->pool, 0, "bad filelist");
706       return;
707     }
708
709   adddudata(data, handle, rpmhead, dn, di, bnc, dnc);
710
711   for (i = 0; i < bnc; i++)
712     {
713       Id did;
714       char *b = bn[i];
715
716       if (di[i] == lastdii)
717         did = lastdid;
718       else
719         {
720           did = repodata_str2dir(data, dn[di[i]], 1);
721           if (!did)
722             did = repodata_str2dir(data, "/", 1);
723           lastdid = did;
724           lastdii = di[i];
725         }
726       if (b && *b == '/')       /* work around rpm bug */
727         b++;
728       repodata_add_dirstr(data, handle, SOLVABLE_FILELIST, did, b);
729     }
730   solv_free(bn);
731   solv_free(dn);
732   solv_free(di);
733 }
734
735 static void
736 addchangelog(Repodata *data, Id handle, RpmHead *rpmhead)
737 {
738   char **cn;
739   char **cx;
740   unsigned int *ct;
741   int i, cnc, cxc, ctc;
742   Queue hq;
743
744   ct = headint32array(rpmhead, TAG_CHANGELOGTIME, &ctc);
745   cx = headstringarray(rpmhead, TAG_CHANGELOGTEXT, &cxc);
746   cn = headstringarray(rpmhead, TAG_CHANGELOGNAME, &cnc);
747   if (!ct || !cx || !cn || !ctc || ctc != cxc || ctc != cnc)
748     {
749       solv_free(ct);
750       solv_free(cx);
751       solv_free(cn);
752       return;
753     }
754   queue_init(&hq);
755   for (i = 0; i < ctc; i++)
756     {
757       Id h = repodata_new_handle(data);
758       if (ct[i])
759         repodata_set_num(data, h, SOLVABLE_CHANGELOG_TIME, ct[i]);
760       if (cn[i])
761         setutf8string(data, h, SOLVABLE_CHANGELOG_AUTHOR, cn[i]);
762       if (cx[i])
763         setutf8string(data, h, SOLVABLE_CHANGELOG_TEXT, cx[i]);
764       queue_push(&hq, h);
765     }
766   for (i = 0; i < hq.count; i++)
767     repodata_add_flexarray(data, handle, SOLVABLE_CHANGELOG, hq.elements[i]);
768   queue_free(&hq);
769   solv_free(ct);
770   solv_free(cx);
771   solv_free(cn);
772 }
773
774
775 static int
776 rpm2solv(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, int flags)
777 {
778   char *name;
779   char *evr;
780   char *sourcerpm;
781
782   name = headstring(rpmhead, TAG_NAME);
783   if (!name)
784     {
785       pool_error(pool, 0, "package has no name");
786       return 0;
787     }
788   if (!strcmp(name, "gpg-pubkey"))
789     return 0;
790   s->name = pool_str2id(pool, name, 1);
791   sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
792   if (sourcerpm || (rpmhead->forcebinary && !headexists(rpmhead, TAG_SOURCEPACKAGE)))
793     s->arch = pool_str2id(pool, headstring(rpmhead, TAG_ARCH), 1);
794   else
795     {
796       if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
797         s->arch = ARCH_NOSRC;
798       else
799         s->arch = ARCH_SRC;
800     }
801   if (!s->arch)
802     s->arch = ARCH_NOARCH;
803   evr = headtoevr(rpmhead);
804   s->evr = pool_str2id(pool, evr, 1);
805   s->vendor = pool_str2id(pool, headstring(rpmhead, TAG_VENDOR), 1);
806
807   s->provides = makedeps(pool, repo, rpmhead, TAG_PROVIDENAME, TAG_PROVIDEVERSION, TAG_PROVIDEFLAGS, 0);
808   if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
809     s->provides = repo_addid_dep(repo, s->provides, pool_rel2id(pool, s->name, s->evr, REL_EQ, 1), 0);
810   s->requires = makedeps(pool, repo, rpmhead, TAG_REQUIRENAME, TAG_REQUIREVERSION, TAG_REQUIREFLAGS, (flags & RPM_ADD_NO_RPMLIBREQS) ? MAKEDEPS_NO_RPMLIB : 0);
811   s->conflicts = makedeps(pool, repo, rpmhead, TAG_CONFLICTNAME, TAG_CONFLICTVERSION, TAG_CONFLICTFLAGS, 0);
812   s->obsoletes = makedeps(pool, repo, rpmhead, TAG_OBSOLETENAME, TAG_OBSOLETEVERSION, TAG_OBSOLETEFLAGS, 0);
813
814   s->recommends = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_STRONG);
815   s->suggests = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_WEAK);
816   s->supplements = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_STRONG);
817   s->enhances  = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_WEAK);
818   s->supplements = repo_fix_supplements(repo, s->provides, s->supplements, 0);
819   s->conflicts = repo_fix_conflicts(repo, s->conflicts);
820
821   if (data)
822     {
823       Id handle;
824       char *str;
825       unsigned int u32;
826       unsigned long long u64;
827
828       handle = s - pool->solvables;
829       str = headstring(rpmhead, TAG_SUMMARY);
830       if (str)
831         setutf8string(data, handle, SOLVABLE_SUMMARY, str);
832       str = headstring(rpmhead, TAG_DESCRIPTION);
833       if (str)
834         {
835           char *aut, *p;
836           for (aut = str; (aut = strchr(aut, '\n')) != 0; aut++)
837             if (!strncmp(aut, "\nAuthors:\n--------\n", 19))
838               break;
839           if (aut)
840             {
841               /* oh my, found SUSE special author section */
842               int l = aut - str;
843               str = solv_strdup(str);
844               aut = str + l;
845               str[l] = 0;
846               while (l > 0 && str[l - 1] == '\n')
847                 str[--l] = 0;
848               if (l)
849                 setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
850               p = aut + 19;
851               aut = str;        /* copy over */
852               while (*p == ' ' || *p == '\n')
853                 p++;
854               while (*p)
855                 {
856                   if (*p == '\n')
857                     {
858                       *aut++ = *p++;
859                       while (*p == ' ')
860                         p++;
861                       continue;
862                     }
863                   *aut++ = *p++;
864                 }
865               while (aut != str && aut[-1] == '\n')
866                 aut--;
867               *aut = 0;
868               if (*str)
869                 setutf8string(data, handle, SOLVABLE_AUTHORS, str);
870               free(str);
871             }
872           else if (*str)
873             setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
874         }
875       str = headstring(rpmhead, TAG_GROUP);
876       if (str)
877         repodata_set_poolstr(data, handle, SOLVABLE_GROUP, str);
878       str = headstring(rpmhead, TAG_LICENSE);
879       if (str)
880         repodata_set_poolstr(data, handle, SOLVABLE_LICENSE, str);
881       str = headstring(rpmhead, TAG_URL);
882       if (str)
883         repodata_set_str(data, handle, SOLVABLE_URL, str);
884       str = headstring(rpmhead, TAG_DISTRIBUTION);
885       if (str)
886         repodata_set_poolstr(data, handle, SOLVABLE_DISTRIBUTION, str);
887       str = headstring(rpmhead, TAG_PACKAGER);
888       if (str)
889         repodata_set_poolstr(data, handle, SOLVABLE_PACKAGER, str);
890       if ((flags & RPM_ADD_WITH_PKGID) != 0)
891         {
892           unsigned char *chksum;
893           unsigned int chksumsize;
894           chksum = headbinary(rpmhead, TAG_SIGMD5, &chksumsize);
895           if (chksum && chksumsize == 16)
896             repodata_set_bin_checksum(data, handle, SOLVABLE_PKGID, REPOKEY_TYPE_MD5, chksum);
897         }
898       if ((flags & RPM_ADD_WITH_HDRID) != 0)
899         {
900           str = headstring(rpmhead, TAG_SHA1HEADER);
901           if (str && strlen(str) == 40)
902             repodata_set_checksum(data, handle, SOLVABLE_HDRID, REPOKEY_TYPE_SHA1, str);
903           else if (str && strlen(str) == 64)
904             repodata_set_checksum(data, handle, SOLVABLE_HDRID, REPOKEY_TYPE_SHA256, str);
905         }
906       u32 = headint32(rpmhead, TAG_BUILDTIME);
907       if (u32)
908         repodata_set_num(data, handle, SOLVABLE_BUILDTIME, u32);
909       u32 = headint32(rpmhead, TAG_INSTALLTIME);
910       if (u32)
911         repodata_set_num(data, handle, SOLVABLE_INSTALLTIME, u32);
912       u64 = headint64(rpmhead, TAG_LONGSIZE);
913       if (u64)
914         repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, u64);
915       else
916         {
917           u32 = headint32(rpmhead, TAG_SIZE);
918           if (u32)
919             repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, u32);
920         }
921       if (sourcerpm)
922         repodata_set_sourcepkg(data, handle, sourcerpm);
923       if ((flags & RPM_ADD_TRIGGERS) != 0)
924         {
925           Id id, lastid;
926           unsigned int ida = makedeps(pool, repo, rpmhead, TAG_TRIGGERNAME, TAG_TRIGGERVERSION, TAG_TRIGGERFLAGS, 0);
927
928           lastid = 0;
929           for (; (id = repo->idarraydata[ida]) != 0; ida++)
930             {
931               /* we currently do not support rel ids in incore data, so
932                * strip off versioning information */
933               while (ISRELDEP(id))
934                 {
935                   Reldep *rd = GETRELDEP(pool, id);
936                   id = rd->name;
937                 }
938               if (id == lastid)
939                 continue;
940               repodata_add_idarray(data, handle, SOLVABLE_TRIGGERS, id);
941               lastid = id;
942             }
943         }
944       if ((flags & RPM_ADD_NO_FILELIST) == 0)
945         addfilelist(data, handle, rpmhead);
946       if ((flags & RPM_ADD_WITH_CHANGELOG) != 0)
947         addchangelog(data, handle, rpmhead);
948     }
949   solv_free(evr);
950   return 1;
951 }
952
953
954 /******************************************************************/
955 /*  Rpm Database stuff
956  */
957
958 struct rpmdbstate {
959   Pool *pool; 
960   char *rootdir;
961
962   RpmHead *rpmhead;     /* header storage space */
963   int rpmheadsize;
964
965   int dbopened;
966   DB_ENV *dbenv;        /* database environment */
967   DB *db;               /* packages database */
968   int byteswapped;      /* endianess of packages database */
969 };
970
971 struct rpmdbentry {
972   Id rpmdbid;
973   Id nameoff;
974 };
975
976 #define ENTRIES_BLOCK 255
977 #define NAMEDATA_BLOCK 1023
978
979
980 static inline Id db2rpmdbid(unsigned char *db, int byteswapped)
981 {
982 #ifdef RPM5
983   return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
984 #else
985 # if defined(WORDS_BIGENDIAN)
986   if (!byteswapped)
987 # else
988   if (byteswapped)
989 # endif
990     return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
991   else
992     return db[3] << 24 | db[2] << 16 | db[1] << 8 | db[0];
993 #endif
994 }
995
996 static inline void rpmdbid2db(unsigned char *db, Id id, int byteswapped)
997 {
998 #ifdef RPM5
999   db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1000 #else
1001 # if defined(WORDS_BIGENDIAN)
1002   if (!byteswapped)
1003 # else
1004   if (byteswapped)
1005 # endif
1006     db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1007   else
1008     db[3] = id >> 24, db[2] = id >> 16, db[1] = id >> 8, db[0] = id;
1009 #endif
1010 }
1011
1012 /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1013 static int
1014 opendbenv(struct rpmdbstate *state, const char *rootdir)
1015 {
1016   char dbpath[PATH_MAX];
1017   DB_ENV *dbenv = 0;
1018   int r;
1019
1020   if (db_env_create(&dbenv, 0))
1021     return pool_error(state->pool, 0, "db_env_create: %s", strerror(errno));
1022 #if defined(FEDORA) && (DB_VERSION_MAJOR >= 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 5))
1023   dbenv->set_thread_count(dbenv, 8);
1024 #endif
1025   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1026   if (access(dbpath, W_OK) == -1)
1027     {
1028       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1029     }
1030   else
1031     {
1032 #ifdef FEDORA
1033       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0644);
1034 #else
1035       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1036 #endif
1037     }
1038   if (r)
1039     {
1040       pool_error(state->pool, 0, "dbenv->open: %s", strerror(errno));
1041       dbenv->close(dbenv, 0);
1042       return 0;
1043     }
1044   state->dbenv = dbenv;
1045   return 1;
1046 }
1047
1048 static int
1049 openpkgdb(struct rpmdbstate *state)
1050 {
1051   if (state->dbopened)
1052     return state->dbopened > 0 ? 1 : 0;
1053   state->dbopened = -1;
1054   if (!state->dbenv && !opendbenv(state, state->rootdir))
1055     return 0;
1056   if (db_create(&state->db, state->dbenv, 0))
1057     {
1058       pool_error(state->pool, 0, "db_create: %s", strerror(errno));
1059       state->db = 0;
1060       state->dbenv->close(state->dbenv, 0);
1061       state->dbenv = 0;
1062       return 0;
1063     }
1064   if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1065     {
1066       pool_error(state->pool, 0, "db->open Packages: %s", strerror(errno));
1067       state->db->close(state->db, 0);
1068       state->db = 0;
1069       state->dbenv->close(state->dbenv, 0);
1070       state->dbenv = 0;
1071       return 0;
1072     }
1073   if (state->db->get_byteswapped(state->db, &state->byteswapped))
1074     {
1075       pool_error(state->pool, 0, "db->get_byteswapped: %s", strerror(errno));
1076       state->db->close(state->db, 0);
1077       state->db = 0;
1078       state->dbenv->close(state->dbenv, 0);
1079       state->dbenv = 0;
1080       return 0;
1081     }
1082   state->dbopened = 1;
1083   return 1;
1084 }
1085
1086 /* get the rpmdbids of all installed packages from the Name index database.
1087  * This is much faster then querying the big Packages database */
1088 static struct rpmdbentry *
1089 getinstalledrpmdbids(struct rpmdbstate *state, const char *index, const char *match, int *nentriesp, char **namedatap)
1090 {
1091   DB_ENV *dbenv = 0;
1092   DB *db = 0;
1093   DBC *dbc = 0;
1094   int byteswapped;
1095   DBT dbkey;
1096   DBT dbdata;
1097   unsigned char *dp;
1098   int dl;
1099   Id nameoff;
1100
1101   char *namedata = 0;
1102   int namedatal = 0;
1103   struct rpmdbentry *entries = 0;
1104   int nentries = 0;
1105
1106   *nentriesp = 0;
1107   if (namedatap)
1108     *namedatap = 0;
1109
1110   if (!state->dbenv && !opendbenv(state, state->rootdir))
1111     return 0;
1112   dbenv = state->dbenv;
1113   if (db_create(&db, dbenv, 0))
1114     {
1115       pool_error(state->pool, 0, "db_create: %s", strerror(errno));
1116       return 0;
1117     }
1118   if (db->open(db, 0, index, 0, DB_UNKNOWN, DB_RDONLY, 0664))
1119     {
1120       pool_error(state->pool, 0, "db->open %s: %s", index, strerror(errno));
1121       db->close(db, 0);
1122       return 0;
1123     }
1124   if (db->get_byteswapped(db, &byteswapped))
1125     {
1126       pool_error(state->pool, 0, "db->get_byteswapped: %s", strerror(errno));
1127       db->close(db, 0);
1128       return 0;
1129     }
1130   if (db->cursor(db, NULL, &dbc, 0))
1131     {
1132       pool_error(state->pool, 0, "db->cursor: %s", strerror(errno));
1133       db->close(db, 0);
1134       return 0;
1135     }
1136   memset(&dbkey, 0, sizeof(dbkey));
1137   memset(&dbdata, 0, sizeof(dbdata));
1138   if (match)
1139     {
1140       dbkey.data = (void *)match;
1141       dbkey.size = strlen(match);
1142     }
1143   while (dbc->c_get(dbc, &dbkey, &dbdata, match ? DB_SET : DB_NEXT) == 0)
1144     {
1145       if (!match && dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1146         continue;
1147       dl = dbdata.size;
1148       dp = dbdata.data;
1149       nameoff = namedatal;
1150       if (namedatap)
1151         {
1152           namedata = solv_extend(namedata, namedatal, dbkey.size + 1, 1, NAMEDATA_BLOCK);
1153           memcpy(namedata + namedatal, dbkey.data, dbkey.size);
1154           namedata[namedatal + dbkey.size] = 0;
1155           namedatal += dbkey.size + 1;
1156         }
1157       while(dl >= RPM_INDEX_SIZE)
1158         {
1159           entries = solv_extend(entries, nentries, 1, sizeof(*entries), ENTRIES_BLOCK);
1160           entries[nentries].rpmdbid = db2rpmdbid(dp, byteswapped);
1161           entries[nentries].nameoff = nameoff;
1162           nentries++;
1163           dp += RPM_INDEX_SIZE;
1164           dl -= RPM_INDEX_SIZE;
1165         }
1166       if (match)
1167         break;
1168     }
1169   dbc->c_close(dbc);
1170   db->close(db, 0);
1171   /* make sure that enteries is != 0 if there was no error */
1172   if (!entries)
1173     entries = solv_extend(entries, 1, 1, sizeof(*entries), ENTRIES_BLOCK);
1174   *nentriesp = nentries;
1175   if (namedatap)
1176     *namedatap = namedata;
1177   return entries;
1178 }
1179
1180 /* retrive header by rpmdbid */
1181 static int
1182 getrpmdbid(struct rpmdbstate *state, Id rpmdbid)
1183 {
1184   unsigned char buf[16];
1185   DBT dbkey;
1186   DBT dbdata;
1187   RpmHead *rpmhead;
1188
1189   if (!rpmdbid)
1190     {
1191       pool_error(state->pool, 0, "illegal rpmdbid");
1192       return -1;
1193     }
1194   if (state->dbopened != 1 && !openpkgdb(state))
1195     return -1;
1196   rpmdbid2db(buf, rpmdbid, state->byteswapped);
1197   memset(&dbkey, 0, sizeof(dbkey));
1198   memset(&dbdata, 0, sizeof(dbdata));
1199   dbkey.data = buf;
1200   dbkey.size = 4;
1201   dbdata.data = 0;
1202   dbdata.size = 0;
1203   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
1204     return 0;
1205   if (dbdata.size < 8)
1206     {
1207       pool_error(state->pool, 0, "corrupt rpm database (size)");
1208       return -1;
1209     }
1210   if (dbdata.size > state->rpmheadsize)
1211     {
1212       state->rpmheadsize = dbdata.size + 128;
1213       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
1214     }
1215   rpmhead = state->rpmhead;
1216   memcpy(buf, dbdata.data, 8);
1217   rpmhead->forcebinary = 1;
1218   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1219   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1220   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1221     {
1222       pool_error(state->pool, 0, "corrupt rpm database (data size)");
1223       return -1;
1224     }
1225   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1226   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1227   return 1;
1228 }
1229
1230 /* retrive header by berkeleydb cursor */
1231 static Id
1232 getrpmcursor(struct rpmdbstate *state, DBC *dbc)
1233 {
1234   unsigned char buf[16];
1235   DBT dbkey;
1236   DBT dbdata;
1237   RpmHead *rpmhead;
1238   Id dbid;
1239
1240   memset(&dbkey, 0, sizeof(dbkey));
1241   memset(&dbdata, 0, sizeof(dbdata));
1242   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1243     {
1244       if (dbkey.size != 4)
1245         return pool_error(state->pool, -1, "corrupt Packages database (key size)");
1246       dbid = db2rpmdbid(dbkey.data, state->byteswapped);
1247       if (dbid == 0)            /* the join key */
1248         continue;
1249       if (dbdata.size < 8)
1250         return pool_error(state->pool, -1, "corrupt rpm database (size %u)\n", dbdata.size);
1251       if (dbdata.size > state->rpmheadsize)
1252         {
1253           state->rpmheadsize = dbdata.size + 128;
1254           state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
1255         }
1256       rpmhead = state->rpmhead;
1257       memcpy(buf, dbdata.data, 8);
1258       rpmhead->forcebinary = 1;
1259       rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1260       rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1261       if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1262         return pool_error(state->pool, -1, "corrupt rpm database (data size)\n");
1263       memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1264       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1265       return dbid;
1266     }
1267   return 0;
1268 }
1269
1270 static void
1271 freestate(struct rpmdbstate *state)
1272 {
1273   /* close down */
1274   if (!state)
1275     return;
1276   if (state->rootdir)
1277     solv_free(state->rootdir);
1278   if (state->db)
1279     state->db->close(state->db, 0);
1280   if (state->dbenv)
1281     state->dbenv->close(state->dbenv, 0);
1282   solv_free(state->rpmhead);
1283 }
1284
1285 void *
1286 rpm_state_create(Pool *pool, const char *rootdir)
1287 {
1288   struct rpmdbstate *state;
1289   state = solv_calloc(1, sizeof(*state));
1290   state->pool = pool;
1291   if (rootdir)
1292     state->rootdir = solv_strdup(rootdir);
1293   return state;
1294 }
1295
1296 void *
1297 rpm_state_free(void *state)
1298 {
1299   freestate(state);
1300   return solv_free(state);
1301 }
1302
1303 static int
1304 count_headers(Pool *pool, const char *rootdir, DB_ENV *dbenv)
1305 {
1306   char dbpath[PATH_MAX];
1307   struct stat statbuf;
1308   DB *db = 0;
1309   DBC *dbc = 0;
1310   int count = 0;
1311   DBT dbkey;
1312   DBT dbdata;
1313
1314   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir ? rootdir : "");
1315   if (stat(dbpath, &statbuf))
1316     return 0;
1317   memset(&dbkey, 0, sizeof(dbkey));
1318   memset(&dbdata, 0, sizeof(dbdata));
1319   if (db_create(&db, dbenv, 0))
1320     {
1321       pool_error(pool, 0, "db_create: %s", strerror(errno));
1322       return 0;
1323     }
1324   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1325     {
1326       pool_error(pool, 0, "db->open Name: %s", strerror(errno));
1327       db->close(db, 0);
1328       return 0;
1329     }
1330   if (db->cursor(db, NULL, &dbc, 0))
1331     {
1332       db->close(db, 0);
1333       pool_error(pool, 0, "db->cursor: %s", strerror(errno));
1334       return 0;
1335     }
1336   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1337     count += dbdata.size / RPM_INDEX_SIZE;
1338   dbc->c_close(dbc);
1339   db->close(db, 0);
1340   return count;
1341 }
1342
1343 /******************************************************************/
1344
1345 static Offset
1346 copydeps(Pool *pool, Repo *repo, Offset fromoff, Repo *fromrepo)
1347 {
1348   int cc;
1349   Id *ida, *from;
1350   Offset ido;
1351
1352   if (!fromoff)
1353     return 0;
1354   from = fromrepo->idarraydata + fromoff;
1355   for (ida = from, cc = 0; *ida; ida++, cc++)
1356     ;
1357   if (cc == 0)
1358     return 0;
1359   ido = repo_reserve_ids(repo, 0, cc);
1360   ida = repo->idarraydata + ido;
1361   memcpy(ida, from, (cc + 1) * sizeof(Id));
1362   repo->idarraysize += cc + 1;
1363   return ido;
1364 }
1365
1366 #define COPYDIR_DIRCACHE_SIZE 512
1367
1368 static Id copydir_complex(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache);
1369
1370 static inline Id
1371 copydir(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache)
1372 {
1373   if (cache && cache[did & 255] == did)
1374     return cache[(did & 255) + 256];
1375   return copydir_complex(pool, data, fromdata, did, cache);
1376 }
1377
1378 static Id
1379 copydir_complex(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache)
1380 {
1381   Id parent = dirpool_parent(&fromdata->dirpool, did);
1382   Id compid = dirpool_compid(&fromdata->dirpool, did);
1383   if (parent)
1384     parent = copydir(pool, data, fromdata, parent, cache);
1385   if (data->localpool || fromdata->localpool)
1386     compid = repodata_translate_id(data, fromdata, compid, 1);
1387   compid = dirpool_add_dir(&data->dirpool, parent, compid, 1);
1388   if (cache)
1389     {
1390       cache[did & 255] = did;
1391       cache[(did & 255) + 256] = compid;
1392     }
1393   return compid;
1394 }
1395
1396 struct solvable_copy_cbdata {
1397   Repodata *data;
1398   Id handle;
1399   Id subhandle;
1400   Id *dircache;
1401 };
1402
1403 static int
1404 solvable_copy_cb(void *vcbdata, Solvable *r, Repodata *fromdata, Repokey *key, KeyValue *kv)
1405 {
1406   struct solvable_copy_cbdata *cbdata = vcbdata;
1407   Id id, keyname;
1408   Repodata *data = cbdata->data;
1409   Id handle = cbdata->handle;
1410   Pool *pool = data->repo->pool;
1411
1412   keyname = key->name;
1413   switch(key->type)
1414     {
1415     case REPOKEY_TYPE_ID:
1416     case REPOKEY_TYPE_CONSTANTID:
1417     case REPOKEY_TYPE_IDARRAY:  /* used for triggers */
1418       id = kv->id;
1419       if (data->localpool || fromdata->localpool)
1420         id = repodata_translate_id(data, fromdata, id, 1);
1421       if (key->type == REPOKEY_TYPE_ID)
1422         repodata_set_id(data, handle, keyname, id);
1423       else if (key->type == REPOKEY_TYPE_CONSTANTID)
1424         repodata_set_constantid(data, handle, keyname, id);
1425       else
1426         repodata_add_idarray(data, handle, keyname, id);
1427       break;
1428     case REPOKEY_TYPE_STR:
1429       repodata_set_str(data, handle, keyname, kv->str);
1430       break;
1431     case REPOKEY_TYPE_VOID:
1432       repodata_set_void(data, handle, keyname);
1433       break;
1434     case REPOKEY_TYPE_NUM:
1435       repodata_set_num(data, handle, keyname, SOLV_KV_NUM64(kv));
1436       break;
1437     case REPOKEY_TYPE_CONSTANT:
1438       repodata_set_constant(data, handle, keyname, kv->num);
1439       break;
1440     case REPOKEY_TYPE_DIRNUMNUMARRAY:
1441       id = kv->id;
1442       id = copydir(pool, data, fromdata, id, cbdata->dircache);
1443       repodata_add_dirnumnum(data, handle, keyname, id, kv->num, kv->num2);
1444       break;
1445     case REPOKEY_TYPE_DIRSTRARRAY:
1446       id = kv->id;
1447       id = copydir(pool, data, fromdata, id, cbdata->dircache);
1448       repodata_add_dirstr(data, handle, keyname, id, kv->str);
1449       break;
1450     case REPOKEY_TYPE_FLEXARRAY:
1451       if (kv->eof == 2)
1452         {
1453           assert(cbdata->subhandle);
1454           cbdata->handle = cbdata->subhandle;
1455           cbdata->subhandle = 0;
1456           break;
1457         }
1458       if (!kv->entry)
1459         {
1460           assert(!cbdata->subhandle);
1461           cbdata->subhandle = cbdata->handle;
1462         }
1463       cbdata->handle = repodata_new_handle(data);
1464       repodata_add_flexarray(data, cbdata->subhandle, keyname, cbdata->handle);
1465       break;
1466     default:
1467       break;
1468     }
1469   return 0;
1470 }
1471
1472 static void
1473 solvable_copy(Solvable *s, Solvable *r, Repodata *data, Id *dircache)
1474 {
1475   int p, i;
1476   Repo *repo = s->repo;
1477   Pool *pool = repo->pool;
1478   Repo *fromrepo = r->repo;
1479   struct solvable_copy_cbdata cbdata;
1480
1481   /* copy solvable data */
1482   s->name = r->name;
1483   s->evr = r->evr;
1484   s->arch = r->arch;
1485   s->vendor = r->vendor;
1486   s->provides = copydeps(pool, repo, r->provides, fromrepo);
1487   s->requires = copydeps(pool, repo, r->requires, fromrepo);
1488   s->conflicts = copydeps(pool, repo, r->conflicts, fromrepo);
1489   s->obsoletes = copydeps(pool, repo, r->obsoletes, fromrepo);
1490   s->recommends = copydeps(pool, repo, r->recommends, fromrepo);
1491   s->suggests = copydeps(pool, repo, r->suggests, fromrepo);
1492   s->supplements = copydeps(pool, repo, r->supplements, fromrepo);
1493   s->enhances  = copydeps(pool, repo, r->enhances, fromrepo);
1494
1495   /* copy all attributes */
1496   if (!data)
1497     return;
1498   cbdata.data = data;
1499   cbdata.handle = s - pool->solvables;
1500   cbdata.subhandle = 0;
1501   cbdata.dircache = dircache;
1502   p = r - fromrepo->pool->solvables;
1503 #if 0
1504   repo_search(fromrepo, p, 0, 0, SEARCH_NO_STORAGE_SOLVABLE | SEARCH_SUB | SEARCH_ARRAYSENTINEL, solvable_copy_cb, &cbdata);
1505 #else
1506   FOR_REPODATAS(fromrepo, i, data)
1507     {
1508       if (p < data->start || p >= data->end)
1509         continue;
1510       repodata_search(data, p, 0, SEARCH_SUB | SEARCH_ARRAYSENTINEL, solvable_copy_cb, &cbdata);
1511     }
1512 #endif
1513 }
1514
1515 /* used to sort entries by package name that got returned in some database order */
1516 static int
1517 rpmids_sort_cmp(const void *va, const void *vb, void *dp)
1518 {
1519   struct rpmdbentry const *a = va, *b = vb;
1520   char *namedata = dp;
1521   int r;
1522   r = strcmp(namedata + a->nameoff, namedata + b->nameoff);
1523   if (r)
1524     return r;
1525   return a->rpmdbid - b->rpmdbid;
1526 }
1527
1528 static int
1529 pkgids_sort_cmp(const void *va, const void *vb, void *dp)
1530 {
1531   Repo *repo = dp;
1532   Pool *pool = repo->pool;
1533   Solvable *a = pool->solvables + *(Id *)va;
1534   Solvable *b = pool->solvables + *(Id *)vb;
1535   Id *rpmdbid;
1536
1537   if (a->name != b->name)
1538     return strcmp(pool_id2str(pool, a->name), pool_id2str(pool, b->name));
1539   rpmdbid = repo->rpmdbid;
1540   return rpmdbid[(a - pool->solvables) - repo->start] - rpmdbid[(b - pool->solvables) - repo->start];
1541 }
1542
1543 static void
1544 swap_solvables(Repo *repo, Repodata *data, Id pa, Id pb)
1545 {
1546   Pool *pool = repo->pool;
1547   Solvable tmp;
1548
1549   tmp = pool->solvables[pa];
1550   pool->solvables[pa] = pool->solvables[pb];
1551   pool->solvables[pb] = tmp;
1552   if (repo->rpmdbid)
1553     {
1554       Id tmpid = repo->rpmdbid[pa - repo->start];
1555       repo->rpmdbid[pa - repo->start] = repo->rpmdbid[pb - repo->start];
1556       repo->rpmdbid[pb - repo->start] = tmpid;
1557     }
1558   /* only works if nothing is already internalized! */
1559   if (data)
1560     repodata_swap_attrs(data, pa, pb);
1561 }
1562
1563 static void
1564 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1565 {
1566   memset(cookie, 0, 32);
1567   cookie[3] = RPMDB_COOKIE_VERSION;
1568   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1569   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1570 }
1571
1572 /*
1573  * read rpm db as repo
1574  *
1575  */
1576
1577 int
1578 repo_add_rpmdb(Repo *repo, Repo *ref, int flags)
1579 {
1580   Pool *pool = repo->pool;
1581   char dbpath[PATH_MAX];
1582   struct stat packagesstat;
1583   unsigned char newcookie[32];
1584   const unsigned char *oldcookie = 0;
1585   Id oldcookietype = 0;
1586   Repodata *data;
1587   int count = 0, done = 0;
1588   const char *rootdir = 0;
1589   struct rpmdbstate state;
1590   int i;
1591   Solvable *s;
1592   unsigned int now;
1593
1594   now = solv_timems(0);
1595   memset(&state, 0, sizeof(state));
1596   state.pool = pool;
1597
1598   data = repo_add_repodata(repo, flags);
1599
1600   if (ref && !(ref->nsolvables && ref->rpmdbid && ref->pool == repo->pool))
1601     {
1602       if ((flags & RPMDB_EMPTY_REFREPO) != 0)
1603         repo_empty(ref, 1);
1604       ref = 0;
1605     }
1606
1607   if (flags & REPO_USE_ROOTDIR)
1608     rootdir = pool_get_rootdir(pool);
1609   if (!opendbenv(&state, rootdir))
1610     return -1;
1611
1612   /* XXX: should get ro lock of Packages database! */
1613   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir ? rootdir : "");
1614   if (stat(dbpath, &packagesstat))
1615     {
1616       pool_error(pool, -1, "%s: %s", dbpath, strerror(errno));
1617       freestate(&state);
1618       return -1;
1619     }
1620   mkrpmdbcookie(&packagesstat, newcookie);
1621   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1622
1623   if (ref)
1624     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1625   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1626     {
1627       int solvstart = 0, solvend = 0;
1628       Id dbid;
1629       DBC *dbc = 0;
1630
1631       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1632         repo_empty(ref, 1);     /* get it out of the way */
1633       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1634         count = count_headers(pool, rootdir, state.dbenv);
1635       if (!openpkgdb(&state))
1636         {
1637           freestate(&state);
1638           return -1;
1639         }
1640       if (state.db->cursor(state.db, NULL, &dbc, 0))
1641         {
1642           freestate(&state);
1643           return pool_error(pool, -1, "db->cursor failed");
1644         }
1645       i = 0;
1646       s = 0;
1647       while ((dbid = getrpmcursor(&state, dbc)) != 0)
1648         {
1649           if (dbid == -1)
1650             {
1651               dbc->c_close(dbc);
1652               freestate(&state);
1653               return -1;
1654             }
1655           if (!s)
1656             {
1657               s = pool_id2solvable(pool, repo_add_solvable(repo));
1658               if (!solvstart)
1659                 solvstart = s - pool->solvables;
1660               solvend = s - pool->solvables + 1;
1661             }
1662           if (!repo->rpmdbid)
1663             repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1664           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1665           if (rpm2solv(pool, repo, data, s, state.rpmhead, flags | RPM_ADD_TRIGGERS))
1666             {
1667               i++;
1668               s = 0;
1669             }
1670           else
1671             {
1672               /* We can reuse this solvable, but make sure it's still
1673                  associated with this repo.  */
1674               memset(s, 0, sizeof(*s));
1675               s->repo = repo;
1676             }
1677           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1678             {
1679               if (done < count)
1680                 done++;
1681               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1682                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1683             }
1684         }
1685       dbc->c_close(dbc);
1686       if (s)
1687         {
1688           /* oops, could not reuse. free it instead */
1689           repo_free_solvable(repo, s - pool->solvables, 1);
1690           solvend--;
1691           s = 0;
1692         }
1693       /* now sort all solvables in the new solvstart..solvend block */
1694       if (solvend - solvstart > 1)
1695         {
1696           Id *pkgids = solv_malloc2(solvend - solvstart, sizeof(Id));
1697           for (i = solvstart; i < solvend; i++)
1698             pkgids[i - solvstart] = i;
1699           solv_sort(pkgids, solvend - solvstart, sizeof(Id), pkgids_sort_cmp, repo);
1700           /* adapt order */
1701           for (i = solvstart; i < solvend; i++)
1702             {
1703               int j = pkgids[i - solvstart];
1704               while (j < i)
1705                 j = pkgids[i - solvstart] = pkgids[j - solvstart];
1706               if (j != i)
1707                 swap_solvables(repo, data, i, j);
1708             }
1709           solv_free(pkgids);
1710         }
1711     }
1712   else
1713     {
1714       Id dircache[COPYDIR_DIRCACHE_SIZE];               /* see copydir */
1715       struct rpmdbentry *entries = 0, *rp;
1716       int nentries = 0;
1717       char *namedata = 0;
1718       unsigned int refmask, h;
1719       Id id, *refhash;
1720       int res;
1721
1722       memset(dircache, 0, sizeof(dircache));
1723
1724       /* get ids of installed rpms */
1725       entries = getinstalledrpmdbids(&state, "Name", 0, &nentries, &namedata);
1726       if (!entries)
1727         {
1728           freestate(&state);
1729           return -1;
1730         }
1731
1732       /* sort by name */
1733       if (nentries > 1)
1734         solv_sort(entries, nentries, sizeof(*entries), rpmids_sort_cmp, namedata);
1735
1736       /* create hash from dbid to ref */
1737       refmask = mkmask(ref->nsolvables);
1738       refhash = solv_calloc(refmask + 1, sizeof(Id));
1739       for (i = 0; i < ref->end - ref->start; i++)
1740         {
1741           if (!ref->rpmdbid[i])
1742             continue;
1743           h = ref->rpmdbid[i] & refmask;
1744           while (refhash[h])
1745             h = (h + 317) & refmask;
1746           refhash[h] = i + 1;   /* make it non-zero */
1747         }
1748
1749       /* count the misses, they will cost us time */
1750       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1751         {
1752           for (i = 0, rp = entries; i < nentries; i++, rp++)
1753             {
1754               if (refhash)
1755                 {
1756                   Id dbid = rp->rpmdbid;
1757                   h = dbid & refmask;
1758                   while ((id = refhash[h]))
1759                     {
1760                       if (ref->rpmdbid[id - 1] == dbid)
1761                         break;
1762                       h = (h + 317) & refmask;
1763                     }
1764                   if (id)
1765                     continue;
1766                 }
1767               count++;
1768             }
1769         }
1770
1771       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1772         s = pool_id2solvable(pool, repo_add_solvable_block_before(repo, nentries, ref));
1773       else
1774         s = pool_id2solvable(pool, repo_add_solvable_block(repo, nentries));
1775       if (!repo->rpmdbid)
1776         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1777
1778       for (i = 0, rp = entries; i < nentries; i++, rp++, s++)
1779         {
1780           Id dbid = rp->rpmdbid;
1781           repo->rpmdbid[(s - pool->solvables) - repo->start] = rp->rpmdbid;
1782           if (refhash)
1783             {
1784               h = dbid & refmask;
1785               while ((id = refhash[h]))
1786                 {
1787                   if (ref->rpmdbid[id - 1] == dbid)
1788                     break;
1789                   h = (h + 317) & refmask;
1790                 }
1791               if (id)
1792                 {
1793                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1794                   if (r->repo == ref)
1795                     {
1796                       solvable_copy(s, r, data, dircache);
1797                       continue;
1798                     }
1799                 }
1800             }
1801           res = getrpmdbid(&state, dbid);
1802           if (res <= 0)
1803             {
1804               if (!res)
1805                 return pool_error(pool, -1, "inconsistent rpm database, key %d not found. run 'rpm --rebuilddb' to fix.", dbid);
1806               freestate(&state);
1807               solv_free(entries);
1808               solv_free(namedata);
1809               solv_free(refhash);
1810               return -1;
1811             }
1812           rpm2solv(pool, repo, data, s, state.rpmhead, flags | RPM_ADD_TRIGGERS);
1813           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1814             {
1815               if (done < count)
1816                 done++;
1817               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1818                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1819             }
1820         }
1821
1822       solv_free(entries);
1823       solv_free(namedata);
1824       solv_free(refhash);
1825       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1826         repo_empty(ref, 1);
1827     }
1828
1829   freestate(&state);
1830   if (!(flags & REPO_NO_INTERNALIZE))
1831     repodata_internalize(data);
1832   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1833     pool_debug(pool, SOLV_ERROR, "%%%% 100\n");
1834   POOL_DEBUG(SOLV_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", solv_timems(now));
1835   POOL_DEBUG(SOLV_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1836   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)));
1837   return 0;
1838 }
1839
1840 int
1841 repo_add_rpmdb_reffp(Repo *repo, FILE *fp, int flags)
1842 {
1843   int res;
1844   Repo *ref = 0;
1845
1846   if (!fp)
1847     return repo_add_rpmdb(repo, 0, flags);
1848   ref = repo_create(repo->pool, "add_rpmdb_reffp");
1849   if (repo_add_solv(ref, fp, 0) != 0)
1850     {
1851       repo_free(ref, 1);
1852       ref = 0;
1853     }
1854   if (ref && ref->start == ref->end)
1855     {
1856       repo_free(ref, 1);
1857       ref = 0;
1858     }
1859   if (ref)
1860     repo_disable_paging(ref);
1861   res = repo_add_rpmdb(repo, ref, flags | RPMDB_EMPTY_REFREPO);
1862   if (ref)
1863     repo_free(ref, 1);
1864   return res;
1865 }
1866
1867 static inline unsigned int
1868 getu32(const unsigned char *dp)
1869 {
1870   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1871 }
1872
1873
1874 Id
1875 repo_add_rpm(Repo *repo, const char *rpm, int flags)
1876 {
1877   unsigned int sigdsize, sigcnt, l;
1878   Pool *pool = repo->pool;
1879   Solvable *s;
1880   RpmHead *rpmhead = 0;
1881   int rpmheadsize = 0;
1882   char *payloadformat;
1883   FILE *fp;
1884   unsigned char lead[4096];
1885   int headerstart, headerend;
1886   struct stat stb;
1887   Repodata *data;
1888   unsigned char pkgid[16];
1889   unsigned char leadsigid[16];
1890   unsigned char hdrid[32];
1891   int pkgidtype, leadsigidtype, hdridtype;
1892   Id chksumtype = 0;
1893   void *chksumh = 0;
1894   void *leadsigchksumh = 0;
1895   int forcebinary = 0;
1896
1897   data = repo_add_repodata(repo, flags);
1898
1899   if ((flags & RPM_ADD_WITH_SHA256SUM) != 0)
1900     chksumtype = REPOKEY_TYPE_SHA256;
1901   else if ((flags & RPM_ADD_WITH_SHA1SUM) != 0)
1902     chksumtype = REPOKEY_TYPE_SHA1;
1903
1904   if ((fp = fopen(flags & REPO_USE_ROOTDIR ? pool_prepend_rootdir_tmp(pool, rpm) : rpm, "r")) == 0)
1905     {
1906       pool_error(pool, -1, "%s: %s", rpm, strerror(errno));
1907       return 0;
1908     }
1909   if (fstat(fileno(fp), &stb))
1910     {
1911       pool_error(pool, -1, "fstat: %s", strerror(errno));
1912       fclose(fp);
1913       return 0;
1914     }
1915   if (chksumtype)
1916     chksumh = solv_chksum_create(chksumtype);
1917   if ((flags & RPM_ADD_WITH_LEADSIGID) != 0)
1918     leadsigchksumh = solv_chksum_create(REPOKEY_TYPE_MD5);
1919   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1920     {
1921       pool_error(pool, -1, "%s: not a rpm", rpm);
1922       fclose(fp);
1923       return 0;
1924     }
1925   forcebinary = lead[6] != 0 || lead[7] != 1;
1926   if (chksumh)
1927     solv_chksum_add(chksumh, lead, 96 + 16);
1928   if (leadsigchksumh)
1929     solv_chksum_add(leadsigchksumh, lead, 96 + 16);
1930   if (lead[78] != 0 || lead[79] != 5)
1931     {
1932       pool_error(pool, -1, "%s: not a rpm v5 header", rpm);
1933       fclose(fp);
1934       return 0;
1935     }
1936   if (getu32(lead + 96) != 0x8eade801)
1937     {
1938       pool_error(pool, -1, "%s: bad signature header", rpm);
1939       fclose(fp);
1940       return 0;
1941     }
1942   sigcnt = getu32(lead + 96 + 8);
1943   sigdsize = getu32(lead + 96 + 12);
1944   if (sigcnt >= 0x100000 || sigdsize >= 0x100000)
1945     {
1946       pool_error(pool, -1, "%s: bad signature header", rpm);
1947       fclose(fp);
1948       return 0;
1949     }
1950   sigdsize += sigcnt * 16;
1951   sigdsize = (sigdsize + 7) & ~7;
1952   headerstart = 96 + 16 + sigdsize;
1953   pkgidtype = leadsigidtype = hdridtype = 0;
1954   if ((flags & (RPM_ADD_WITH_PKGID | RPM_ADD_WITH_HDRID)) != 0)
1955     {
1956       /* extract pkgid or hdrid from the signature header */
1957       if (sigdsize > rpmheadsize)
1958         {
1959           rpmheadsize = sigdsize + 128;
1960           rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1961         }
1962       if (fread(rpmhead->data, sigdsize, 1, fp) != 1)
1963         {
1964           pool_error(pool, -1, "%s: unexpected EOF", rpm);
1965           fclose(fp);
1966           return 0;
1967         }
1968       if (chksumh)
1969         solv_chksum_add(chksumh, rpmhead->data, sigdsize);
1970       if (leadsigchksumh)
1971         solv_chksum_add(leadsigchksumh, rpmhead->data, sigdsize);
1972       rpmhead->forcebinary = 0;
1973       rpmhead->cnt = sigcnt;
1974       rpmhead->dcnt = sigdsize - sigcnt * 16;
1975       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1976       if ((flags & RPM_ADD_WITH_PKGID) != 0)
1977         {
1978           unsigned char *chksum;
1979           unsigned int chksumsize;
1980           chksum = headbinary(rpmhead, SIGTAG_MD5, &chksumsize);
1981           if (chksum && chksumsize == 16)
1982             {
1983               pkgidtype = REPOKEY_TYPE_MD5;
1984               memcpy(pkgid, chksum, 16);
1985             }
1986         }
1987       if ((flags & RPM_ADD_WITH_HDRID) != 0)
1988         {
1989           const char *str = headstring(rpmhead, TAG_SHA1HEADER);
1990           if (str && strlen(str) == 40)
1991             {
1992               if (solv_hex2bin(&str, hdrid, 20) == 20)
1993                 hdridtype = REPOKEY_TYPE_SHA1;
1994             }
1995           else if (str && strlen(str) == 64)
1996             {
1997               if (solv_hex2bin(&str, hdrid, 32) == 32)
1998                 hdridtype = REPOKEY_TYPE_SHA256;
1999             }
2000         }
2001     }
2002   else
2003     {
2004       /* just skip the signature header */
2005       while (sigdsize)
2006         {
2007           l = sigdsize > 4096 ? 4096 : sigdsize;
2008           if (fread(lead, l, 1, fp) != 1)
2009             {
2010               pool_error(pool, -1, "%s: unexpected EOF", rpm);
2011               fclose(fp);
2012               return 0;
2013             }
2014           if (chksumh)
2015             solv_chksum_add(chksumh, lead, l);
2016           if (leadsigchksumh)
2017             solv_chksum_add(leadsigchksumh, lead, l);
2018           sigdsize -= l;
2019         }
2020     }
2021   if (leadsigchksumh)
2022     {
2023       leadsigchksumh = solv_chksum_free(leadsigchksumh, leadsigid);
2024       leadsigidtype = REPOKEY_TYPE_MD5;
2025     }
2026   if (fread(lead, 16, 1, fp) != 1)
2027     {
2028       pool_error(pool, -1, "%s: unexpected EOF", rpm);
2029       fclose(fp);
2030       return 0;
2031     }
2032   if (chksumh)
2033     solv_chksum_add(chksumh, lead, 16);
2034   if (getu32(lead) != 0x8eade801)
2035     {
2036       pool_error(pool, -1, "%s: bad header", rpm);
2037       fclose(fp);
2038       return 0;
2039     }
2040   sigcnt = getu32(lead + 8);
2041   sigdsize = getu32(lead + 12);
2042   if (sigcnt >= 0x100000 || sigdsize >= 0x2000000)
2043     {
2044       pool_error(pool, -1, "%s: bad header", rpm);
2045       fclose(fp);
2046       return 0;
2047     }
2048   l = sigdsize + sigcnt * 16;
2049   headerend = headerstart + 16 + l;
2050   if (l > rpmheadsize)
2051     {
2052       rpmheadsize = l + 128;
2053       rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
2054     }
2055   if (fread(rpmhead->data, l, 1, fp) != 1)
2056     {
2057       pool_error(pool, -1, "%s: unexpected EOF", rpm);
2058       fclose(fp);
2059       return 0;
2060     }
2061   if (chksumh)
2062     solv_chksum_add(chksumh, rpmhead->data, l);
2063   rpmhead->forcebinary = forcebinary;
2064   rpmhead->cnt = sigcnt;
2065   rpmhead->dcnt = sigdsize;
2066   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2067   if (headexists(rpmhead, TAG_PATCHESNAME))
2068     {
2069       /* this is a patch rpm, ignore */
2070       pool_error(pool, -1, "%s: is patch rpm", rpm);
2071       fclose(fp);
2072       solv_chksum_free(chksumh, 0);
2073       solv_free(rpmhead);
2074       return 0;
2075     }
2076   payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
2077   if (payloadformat && !strcmp(payloadformat, "drpm"))
2078     {
2079       /* this is a delta rpm */
2080       pool_error(pool, -1, "%s: is delta rpm", rpm);
2081       fclose(fp);
2082       solv_chksum_free(chksumh, 0);
2083       solv_free(rpmhead);
2084       return 0;
2085     }
2086   if (chksumh)
2087     while ((l = fread(lead, 1, sizeof(lead), fp)) > 0)
2088       solv_chksum_add(chksumh, lead, l);
2089   fclose(fp);
2090   s = pool_id2solvable(pool, repo_add_solvable(repo));
2091   if (!rpm2solv(pool, repo, data, s, rpmhead, flags & ~(RPM_ADD_WITH_HDRID | RPM_ADD_WITH_PKGID)))
2092     {
2093       repo_free_solvable(repo, s - pool->solvables, 1);
2094       solv_chksum_free(chksumh, 0);
2095       solv_free(rpmhead);
2096       return 0;
2097     }
2098   if (!(flags & REPO_NO_LOCATION))
2099     repodata_set_location(data, s - pool->solvables, 0, 0, rpm);
2100   if (S_ISREG(stb.st_mode))
2101     repodata_set_num(data, s - pool->solvables, SOLVABLE_DOWNLOADSIZE, (unsigned long long)stb.st_size);
2102   repodata_set_num(data, s - pool->solvables, SOLVABLE_HEADEREND, headerend);
2103   if (pkgidtype)
2104     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_PKGID, pkgidtype, pkgid);
2105   if (hdridtype)
2106     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_HDRID, hdridtype, hdrid);
2107   if (leadsigidtype)
2108     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_LEADSIGID, leadsigidtype, leadsigid);
2109   if (chksumh)
2110     {
2111       repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_CHECKSUM, chksumtype, solv_chksum_get(chksumh, 0));
2112       chksumh = solv_chksum_free(chksumh, 0);
2113     }
2114   if (rpmhead)
2115     solv_free(rpmhead);
2116   if (!(flags & REPO_NO_INTERNALIZE))
2117     repodata_internalize(data);
2118   return s - pool->solvables;
2119 }
2120
2121 Id
2122 repo_add_rpm_handle(Repo *repo, void *rpmhandle, int flags)
2123 {
2124   Pool *pool = repo->pool;
2125   Repodata *data;
2126   RpmHead *rpmhead = rpmhandle;
2127   Solvable *s;
2128   char *payloadformat;
2129
2130   data = repo_add_repodata(repo, flags);
2131   if (headexists(rpmhead, TAG_PATCHESNAME))
2132     {
2133       pool_error(pool, -1, "is a patch rpm");
2134       return 0;
2135     }
2136   payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
2137   if (payloadformat && !strcmp(payloadformat, "drpm"))
2138     {
2139       /* this is a delta rpm */
2140       pool_error(pool, -1, "is a delta rpm");
2141       return 0;
2142     }
2143   s = pool_id2solvable(pool, repo_add_solvable(repo));
2144   if (!rpm2solv(pool, repo, data, s, rpmhead, flags))
2145     {
2146       repo_free_solvable(repo, s - pool->solvables, 1);
2147       return 0;
2148     }
2149   if (!(flags & REPO_NO_INTERNALIZE))
2150     repodata_internalize(data);
2151   return s - pool->solvables;
2152 }
2153
2154 static inline void
2155 linkhash(const char *lt, char *hash)
2156 {
2157   unsigned int r = 0;
2158   const unsigned char *str = (const unsigned char *)lt;
2159   int l, c;
2160
2161   l = strlen(lt);
2162   while ((c = *str++) != 0)
2163     r += (r << 3) + c;
2164   sprintf(hash, "%08x%08x%08x%08x", r, l, 0, 0);
2165 }
2166
2167 void
2168 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, struct filelistinfo *), void *cbdata)
2169 {
2170   RpmHead *rpmhead = rpmhandle;
2171   char **bn;
2172   char **dn;
2173   char **md = 0;
2174   char **lt = 0;
2175   unsigned int *di, diidx;
2176   unsigned int *co = 0;
2177   unsigned int *ff = 0;
2178   unsigned int lastdir;
2179   int lastdirl;
2180   unsigned int *fm;
2181   int cnt, dcnt, cnt2;
2182   int i, l1, l;
2183   char *space = 0;
2184   int spacen = 0;
2185   char md5[33];
2186   struct filelistinfo info;
2187
2188   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
2189   if (!dn)
2190     return;
2191   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
2192     {
2193       for (i = 0; i < dcnt; i++)
2194         (*cb)(cbdata, dn[i], 0);
2195       solv_free(dn);
2196       return;
2197     }
2198   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
2199   if (!bn)
2200     {
2201       solv_free(dn);
2202       return;
2203     }
2204   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
2205   if (!di || cnt != cnt2)
2206     {
2207       solv_free(di);
2208       solv_free(bn);
2209       solv_free(dn);
2210       return;
2211     }
2212   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
2213   if (!fm || cnt != cnt2)
2214     {
2215       solv_free(fm);
2216       solv_free(di);
2217       solv_free(bn);
2218       solv_free(dn);
2219       return;
2220     }
2221   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
2222     {
2223       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
2224       if (!md || cnt != cnt2)
2225         {
2226           solv_free(md);
2227           solv_free(fm);
2228           solv_free(di);
2229           solv_free(bn);
2230           solv_free(dn);
2231           return;
2232         }
2233     }
2234   if ((flags & RPM_ITERATE_FILELIST_WITHCOL) != 0)
2235     {
2236       co = headint32array(rpmhead, TAG_FILECOLORS, &cnt2);
2237       if (!co || cnt != cnt2)
2238         {
2239           solv_free(co);
2240           solv_free(md);
2241           solv_free(fm);
2242           solv_free(di);
2243           solv_free(bn);
2244           solv_free(dn);
2245           return;
2246         }
2247     }
2248   if ((flags & RPM_ITERATE_FILELIST_NOGHOSTS) != 0)
2249     {
2250       ff = headint32array(rpmhead, TAG_FILEFLAGS, &cnt2);
2251       if (!ff || cnt != cnt2)
2252         {
2253           solv_free(ff);
2254           solv_free(co);
2255           solv_free(md);
2256           solv_free(fm);
2257           solv_free(di);
2258           solv_free(bn);
2259           solv_free(dn);
2260           return;
2261         }
2262     }
2263   lastdir = dcnt;
2264   lastdirl = 0;
2265   memset(&info, 0, sizeof(info));
2266   for (i = 0; i < cnt; i++)
2267     {
2268       if (ff && (ff[i] & FILEFLAG_GHOST) != 0)
2269         continue;
2270       diidx = di[i];
2271       if (diidx >= dcnt)
2272         continue;
2273       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
2274       l = l1 + strlen(bn[i]) + 1;
2275       if (l > spacen)
2276         {
2277           spacen = l + 16;
2278           space = solv_realloc(space, spacen);
2279         }
2280       if (lastdir != diidx)
2281         {
2282           strcpy(space, dn[diidx]);
2283           lastdir = diidx;
2284           lastdirl = l1;
2285         }
2286       strcpy(space + l1, bn[i]);
2287       info.diridx = diidx;
2288       info.dirlen = l1;
2289       if (fm)
2290         info.mode = fm[i];
2291       if (md)
2292         {
2293           info.digest = md[i];
2294           if (fm && S_ISLNK(fm[i]))
2295             {
2296               info.digest = 0;
2297               if (!lt)
2298                 {
2299                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
2300                   if (cnt != cnt2)
2301                     lt = solv_free(lt);
2302                 }
2303               if (lt)
2304                 {
2305                   linkhash(lt[i], md5);
2306                   info.digest = md5;
2307                 }
2308             }
2309           if (!info.digest)
2310             {
2311               sprintf(md5, "%08x%08x%08x%08x", (fm[i] >> 12) & 65535, 0, 0, 0);
2312               info.digest = md5;
2313             }
2314         }
2315       if (co)
2316         info.color = co[i];
2317       (*cb)(cbdata, space, &info);
2318     }
2319   solv_free(space);
2320   solv_free(lt);
2321   solv_free(md);
2322   solv_free(fm);
2323   solv_free(di);
2324   solv_free(bn);
2325   solv_free(dn);
2326   solv_free(co);
2327   solv_free(ff);
2328 }
2329
2330 char *
2331 rpm_query(void *rpmhandle, Id what)
2332 {
2333   const char *name, *arch, *sourcerpm;
2334   char *evr, *r;
2335   int l;
2336
2337   RpmHead *rpmhead = rpmhandle;
2338   r = 0;
2339   switch (what)
2340     {
2341     case 0:
2342       name = headstring(rpmhead, TAG_NAME);
2343       if (!name)
2344         name = "";
2345       sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
2346       if (sourcerpm || (rpmhead->forcebinary && !headexists(rpmhead, TAG_SOURCEPACKAGE)))
2347         arch = headstring(rpmhead, TAG_ARCH);
2348       else
2349         {
2350           if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
2351             arch = "nosrc";
2352           else
2353             arch = "src";
2354         }
2355       if (!arch)
2356         arch = "noarch";
2357       evr = headtoevr(rpmhead);
2358       l = strlen(name) + 1 + strlen(evr ? evr : "") + 1 + strlen(arch) + 1;
2359       r = solv_malloc(l);
2360       sprintf(r, "%s-%s.%s", name, evr ? evr : "", arch);
2361       solv_free(evr);
2362       break;
2363     case SOLVABLE_NAME:
2364       name = headstring(rpmhead, TAG_NAME);
2365       r = solv_strdup(name);
2366       break;
2367     case SOLVABLE_SUMMARY:
2368       name = headstring(rpmhead, TAG_SUMMARY);
2369       r = solv_strdup(name);
2370       break;
2371     case SOLVABLE_DESCRIPTION:
2372       name = headstring(rpmhead, TAG_DESCRIPTION);
2373       r = solv_strdup(name);
2374       break;
2375     case SOLVABLE_EVR:
2376       r = headtoevr(rpmhead);
2377       break;
2378     }
2379   return r;
2380 }
2381
2382 unsigned long long
2383 rpm_query_num(void *rpmhandle, Id what, unsigned long long notfound)
2384 {
2385   RpmHead *rpmhead = rpmhandle;
2386   unsigned int u32;
2387
2388   switch (what)
2389     {
2390     case SOLVABLE_INSTALLTIME:
2391       u32 = headint32(rpmhead, TAG_INSTALLTIME);
2392       return u32 ? u32 : notfound;
2393     }
2394   return notfound;
2395 }
2396
2397 int
2398 rpm_installedrpmdbids(void *rpmstate, const char *index, const char *match, Queue *rpmdbidq)
2399 {
2400   struct rpmdbentry *entries;
2401   int nentries, i;
2402
2403   entries = getinstalledrpmdbids(rpmstate, index ? index : "Name", match, &nentries, 0);
2404   if (rpmdbidq)
2405     {
2406       queue_empty(rpmdbidq);
2407       for (i = 0; i < nentries; i++)
2408         queue_push(rpmdbidq, entries[i].rpmdbid);
2409     }
2410   solv_free(entries);
2411   return nentries;
2412 }
2413
2414 void *
2415 rpm_byrpmdbid(void *rpmstate, Id rpmdbid)
2416 {
2417   struct rpmdbstate *state = rpmstate;
2418   int r;
2419
2420   r = getrpmdbid(state, rpmdbid);
2421   if (!r)
2422     pool_error(state->pool, 0, "header #%d not in database", rpmdbid);
2423   return r <= 0 ? 0 : state->rpmhead;
2424 }
2425
2426 void *
2427 rpm_byfp(void *rpmstate, FILE *fp, const char *name)
2428 {
2429   struct rpmdbstate *state = rpmstate;
2430   /* int headerstart, headerend; */
2431   RpmHead *rpmhead;
2432   unsigned int sigdsize, sigcnt, l;
2433   unsigned char lead[4096];
2434   int forcebinary = 0;
2435
2436   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2437     {
2438       pool_error(state->pool, 0, "%s: not a rpm", name);
2439       return 0;
2440     }
2441   forcebinary = lead[6] != 0 || lead[7] != 1;
2442   if (lead[78] != 0 || lead[79] != 5)
2443     {
2444       pool_error(state->pool, 0, "%s: not a V5 header", name);
2445       return 0;
2446     }
2447   if (getu32(lead + 96) != 0x8eade801)
2448     {
2449       pool_error(state->pool, 0, "%s: bad signature header", name);
2450       return 0;
2451     }
2452   sigcnt = getu32(lead + 96 + 8);
2453   sigdsize = getu32(lead + 96 + 12);
2454   if (sigcnt >= 0x100000 || sigdsize >= 0x100000)
2455     {
2456       pool_error(state->pool, 0, "%s: bad signature header", name);
2457       return 0;
2458     }
2459   sigdsize += sigcnt * 16;
2460   sigdsize = (sigdsize + 7) & ~7;
2461   /* headerstart = 96 + 16 + sigdsize; */
2462   while (sigdsize)
2463     {
2464       l = sigdsize > 4096 ? 4096 : sigdsize;
2465       if (fread(lead, l, 1, fp) != 1)
2466         {
2467           pool_error(state->pool, 0, "%s: unexpected EOF", name);
2468           return 0;
2469         }
2470       sigdsize -= l;
2471     }
2472   if (fread(lead, 16, 1, fp) != 1)
2473     {
2474       pool_error(state->pool, 0, "%s: unexpected EOF", name);
2475       return 0;
2476     }
2477   if (getu32(lead) != 0x8eade801)
2478     {
2479       pool_error(state->pool, 0, "%s: bad header", name);
2480       return 0;
2481     }
2482   sigcnt = getu32(lead + 8);
2483   sigdsize = getu32(lead + 12);
2484   if (sigcnt >= 0x100000 || sigdsize >= 0x2000000)
2485     {
2486       pool_error(state->pool, 0, "%s: bad header", name);
2487       return 0;
2488     }
2489   l = sigdsize + sigcnt * 16;
2490   /* headerend = headerstart + 16 + l; */
2491   if (l > state->rpmheadsize)
2492     {
2493       state->rpmheadsize = l + 128;
2494       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2495     }
2496   rpmhead = state->rpmhead;
2497   if (fread(rpmhead->data, l, 1, fp) != 1)
2498     {
2499       pool_error(state->pool, 0, "%s: unexpected EOF", name);
2500       return 0;
2501     }
2502   rpmhead->forcebinary = forcebinary;
2503   rpmhead->cnt = sigcnt;
2504   rpmhead->dcnt = sigdsize;
2505   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2506   return rpmhead;
2507 }
2508
2509 #ifdef ENABLE_RPMDB_BYRPMHEADER
2510
2511 void *
2512 rpm_byrpmh(void *rpmstate, Header h)
2513 {
2514   struct rpmdbstate *state = rpmstate;
2515   const unsigned char *uh;
2516   unsigned int sigdsize, sigcnt, l;
2517   RpmHead *rpmhead;
2518
2519 #ifndef RPM5
2520   uh = headerUnload(h);
2521 #else
2522   uh = headerUnload(h, NULL);
2523 #endif
2524   if (!uh)
2525     return 0;
2526   sigcnt = getu32(uh);
2527   sigdsize = getu32(uh + 4);
2528   l = sigdsize + sigcnt * 16;
2529   if (l > state->rpmheadsize)
2530     {
2531       state->rpmheadsize = l + 128;
2532       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2533     }
2534   rpmhead = state->rpmhead;
2535   memcpy(rpmhead->data, uh + 8, l - 8);
2536   free((void *)uh);
2537   rpmhead->forcebinary = 0;
2538   rpmhead->cnt = sigcnt;
2539   rpmhead->dcnt = sigdsize;
2540   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2541   return rpmhead;
2542 }
2543
2544 #endif
2545