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