refactor a bit, no functional changes
[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 static void 
775 set_description_author(Repodata *data, Id handle, char *str)
776 {
777   char *aut, *p;
778   for (aut = str; (aut = strchr(aut, '\n')) != 0; aut++)
779     if (!strncmp(aut, "\nAuthors:\n--------\n", 19))
780       break;
781   if (aut)
782     {
783       /* oh my, found SUSE special author section */
784       int l = aut - str;
785       str = solv_strdup(str);
786       aut = str + l;
787       str[l] = 0;
788       while (l > 0 && str[l - 1] == '\n')
789         str[--l] = 0;
790       if (l)
791         setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
792       p = aut + 19;
793       aut = str;        /* copy over */
794       while (*p == ' ' || *p == '\n')
795         p++;
796       while (*p)
797         {
798           if (*p == '\n')
799             {
800               *aut++ = *p++;
801               while (*p == ' ')
802                 p++;
803               continue;
804             }
805           *aut++ = *p++;
806         }
807       while (aut != str && aut[-1] == '\n')
808         aut--;
809       *aut = 0;
810       if (*str)
811         setutf8string(data, handle, SOLVABLE_AUTHORS, str);
812       free(str);
813     }
814   else if (*str)
815     setutf8string(data, handle, SOLVABLE_DESCRIPTION, str);
816 }
817
818 static int
819 rpm2solv(Pool *pool, Repo *repo, Repodata *data, Solvable *s, RpmHead *rpmhead, int flags)
820 {
821   char *name;
822   char *evr;
823   char *sourcerpm;
824
825   name = headstring(rpmhead, TAG_NAME);
826   if (!name)
827     {
828       pool_error(pool, 0, "package has no name");
829       return 0;
830     }
831   if (!strcmp(name, "gpg-pubkey"))
832     return 0;
833   s->name = pool_str2id(pool, name, 1);
834   sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
835   if (sourcerpm || (rpmhead->forcebinary && !headexists(rpmhead, TAG_SOURCEPACKAGE)))
836     s->arch = pool_str2id(pool, headstring(rpmhead, TAG_ARCH), 1);
837   else
838     {
839       if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
840         s->arch = ARCH_NOSRC;
841       else
842         s->arch = ARCH_SRC;
843     }
844   if (!s->arch)
845     s->arch = ARCH_NOARCH;
846   evr = headtoevr(rpmhead);
847   s->evr = pool_str2id(pool, evr, 1);
848   s->vendor = pool_str2id(pool, headstring(rpmhead, TAG_VENDOR), 1);
849
850   s->provides = makedeps(pool, repo, rpmhead, TAG_PROVIDENAME, TAG_PROVIDEVERSION, TAG_PROVIDEFLAGS, 0);
851   if (s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
852     s->provides = repo_addid_dep(repo, s->provides, pool_rel2id(pool, s->name, s->evr, REL_EQ, 1), 0);
853   s->requires = makedeps(pool, repo, rpmhead, TAG_REQUIRENAME, TAG_REQUIREVERSION, TAG_REQUIREFLAGS, (flags & RPM_ADD_NO_RPMLIBREQS) ? MAKEDEPS_NO_RPMLIB : 0);
854   s->conflicts = makedeps(pool, repo, rpmhead, TAG_CONFLICTNAME, TAG_CONFLICTVERSION, TAG_CONFLICTFLAGS, 0);
855   s->obsoletes = makedeps(pool, repo, rpmhead, TAG_OBSOLETENAME, TAG_OBSOLETEVERSION, TAG_OBSOLETEFLAGS, 0);
856
857   s->recommends = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_STRONG);
858   s->suggests = makedeps(pool, repo, rpmhead, TAG_SUGGESTSNAME, TAG_SUGGESTSVERSION, TAG_SUGGESTSFLAGS, MAKEDEPS_FILTER_WEAK);
859   s->supplements = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_STRONG);
860   s->enhances  = makedeps(pool, repo, rpmhead, TAG_ENHANCESNAME, TAG_ENHANCESVERSION, TAG_ENHANCESFLAGS, MAKEDEPS_FILTER_WEAK);
861   s->supplements = repo_fix_supplements(repo, s->provides, s->supplements, 0);
862   s->conflicts = repo_fix_conflicts(repo, s->conflicts);
863
864   if (data)
865     {
866       Id handle;
867       char *str;
868       unsigned int u32;
869       unsigned long long u64;
870
871       handle = s - pool->solvables;
872       str = headstring(rpmhead, TAG_SUMMARY);
873       if (str)
874         setutf8string(data, handle, SOLVABLE_SUMMARY, str);
875       str = headstring(rpmhead, TAG_DESCRIPTION);
876       if (str)
877         set_description_author(data, handle, str);
878       str = headstring(rpmhead, TAG_GROUP);
879       if (str)
880         repodata_set_poolstr(data, handle, SOLVABLE_GROUP, str);
881       str = headstring(rpmhead, TAG_LICENSE);
882       if (str)
883         repodata_set_poolstr(data, handle, SOLVABLE_LICENSE, str);
884       str = headstring(rpmhead, TAG_URL);
885       if (str)
886         repodata_set_str(data, handle, SOLVABLE_URL, str);
887       str = headstring(rpmhead, TAG_DISTRIBUTION);
888       if (str)
889         repodata_set_poolstr(data, handle, SOLVABLE_DISTRIBUTION, str);
890       str = headstring(rpmhead, TAG_PACKAGER);
891       if (str)
892         repodata_set_poolstr(data, handle, SOLVABLE_PACKAGER, str);
893       if ((flags & RPM_ADD_WITH_PKGID) != 0)
894         {
895           unsigned char *chksum;
896           unsigned int chksumsize;
897           chksum = headbinary(rpmhead, TAG_SIGMD5, &chksumsize);
898           if (chksum && chksumsize == 16)
899             repodata_set_bin_checksum(data, handle, SOLVABLE_PKGID, REPOKEY_TYPE_MD5, chksum);
900         }
901       if ((flags & RPM_ADD_WITH_HDRID) != 0)
902         {
903           str = headstring(rpmhead, TAG_SHA1HEADER);
904           if (str && strlen(str) == 40)
905             repodata_set_checksum(data, handle, SOLVABLE_HDRID, REPOKEY_TYPE_SHA1, str);
906           else if (str && strlen(str) == 64)
907             repodata_set_checksum(data, handle, SOLVABLE_HDRID, REPOKEY_TYPE_SHA256, str);
908         }
909       u32 = headint32(rpmhead, TAG_BUILDTIME);
910       if (u32)
911         repodata_set_num(data, handle, SOLVABLE_BUILDTIME, u32);
912       u32 = headint32(rpmhead, TAG_INSTALLTIME);
913       if (u32)
914         repodata_set_num(data, handle, SOLVABLE_INSTALLTIME, u32);
915       u64 = headint64(rpmhead, TAG_LONGSIZE);
916       if (u64)
917         repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, u64);
918       else
919         {
920           u32 = headint32(rpmhead, TAG_SIZE);
921           if (u32)
922             repodata_set_num(data, handle, SOLVABLE_INSTALLSIZE, u32);
923         }
924       if (sourcerpm)
925         repodata_set_sourcepkg(data, handle, sourcerpm);
926       if ((flags & RPM_ADD_TRIGGERS) != 0)
927         {
928           Id id, lastid;
929           unsigned int ida = makedeps(pool, repo, rpmhead, TAG_TRIGGERNAME, TAG_TRIGGERVERSION, TAG_TRIGGERFLAGS, 0);
930
931           lastid = 0;
932           for (; (id = repo->idarraydata[ida]) != 0; ida++)
933             {
934               /* we currently do not support rel ids in incore data, so
935                * strip off versioning information */
936               while (ISRELDEP(id))
937                 {
938                   Reldep *rd = GETRELDEP(pool, id);
939                   id = rd->name;
940                 }
941               if (id == lastid)
942                 continue;
943               repodata_add_idarray(data, handle, SOLVABLE_TRIGGERS, id);
944               lastid = id;
945             }
946         }
947       if ((flags & RPM_ADD_NO_FILELIST) == 0)
948         addfilelist(data, handle, rpmhead);
949       if ((flags & RPM_ADD_WITH_CHANGELOG) != 0)
950         addchangelog(data, handle, rpmhead);
951     }
952   solv_free(evr);
953   return 1;
954 }
955
956
957 /******************************************************************/
958 /*  Rpm Database stuff
959  */
960
961 struct rpmdbstate {
962   Pool *pool; 
963   char *rootdir;
964
965   RpmHead *rpmhead;     /* header storage space */
966   int rpmheadsize;
967
968   int dbopened;
969   DB_ENV *dbenv;        /* database environment */
970   DB *db;               /* packages database */
971   int byteswapped;      /* endianess of packages database */
972 };
973
974 struct rpmdbentry {
975   Id rpmdbid;
976   Id nameoff;
977 };
978
979 #define ENTRIES_BLOCK 255
980 #define NAMEDATA_BLOCK 1023
981
982
983 static inline Id db2rpmdbid(unsigned char *db, int byteswapped)
984 {
985 #ifdef RPM5
986   return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
987 #else
988 # if defined(WORDS_BIGENDIAN)
989   if (!byteswapped)
990 # else
991   if (byteswapped)
992 # endif
993     return db[0] << 24 | db[1] << 16 | db[2] << 8 | db[3];
994   else
995     return db[3] << 24 | db[2] << 16 | db[1] << 8 | db[0];
996 #endif
997 }
998
999 static inline void rpmdbid2db(unsigned char *db, Id id, int byteswapped)
1000 {
1001 #ifdef RPM5
1002   db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1003 #else
1004 # if defined(WORDS_BIGENDIAN)
1005   if (!byteswapped)
1006 # else
1007   if (byteswapped)
1008 # endif
1009     db[0] = id >> 24, db[1] = id >> 16, db[2] = id >> 8, db[3] = id;
1010   else
1011     db[3] = id >> 24, db[2] = id >> 16, db[1] = id >> 8, db[0] = id;
1012 #endif
1013 }
1014
1015 /* should look in /usr/lib/rpm/macros instead, but we want speed... */
1016 static int
1017 opendbenv(struct rpmdbstate *state, const char *rootdir)
1018 {
1019   char dbpath[PATH_MAX];
1020   DB_ENV *dbenv = 0;
1021   int r;
1022
1023   if (db_env_create(&dbenv, 0))
1024     return pool_error(state->pool, 0, "db_env_create: %s", strerror(errno));
1025 #if defined(FEDORA) && (DB_VERSION_MAJOR >= 5 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 5))
1026   dbenv->set_thread_count(dbenv, 8);
1027 #endif
1028   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm", rootdir ? rootdir : "");
1029   if (access(dbpath, W_OK) == -1)
1030     {
1031       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1032     }
1033   else
1034     {
1035 #ifdef FEDORA
1036       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL, 0644);
1037 #else
1038       r = dbenv->open(dbenv, dbpath, DB_CREATE|DB_PRIVATE|DB_INIT_MPOOL, 0);
1039 #endif
1040     }
1041   if (r)
1042     {
1043       pool_error(state->pool, 0, "dbenv->open: %s", strerror(errno));
1044       dbenv->close(dbenv, 0);
1045       return 0;
1046     }
1047   state->dbenv = dbenv;
1048   return 1;
1049 }
1050
1051 static int
1052 openpkgdb(struct rpmdbstate *state)
1053 {
1054   if (state->dbopened)
1055     return state->dbopened > 0 ? 1 : 0;
1056   state->dbopened = -1;
1057   if (!state->dbenv && !opendbenv(state, state->rootdir))
1058     return 0;
1059   if (db_create(&state->db, state->dbenv, 0))
1060     {
1061       pool_error(state->pool, 0, "db_create: %s", strerror(errno));
1062       state->db = 0;
1063       state->dbenv->close(state->dbenv, 0);
1064       state->dbenv = 0;
1065       return 0;
1066     }
1067   if (state->db->open(state->db, 0, "Packages", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1068     {
1069       pool_error(state->pool, 0, "db->open Packages: %s", strerror(errno));
1070       state->db->close(state->db, 0);
1071       state->db = 0;
1072       state->dbenv->close(state->dbenv, 0);
1073       state->dbenv = 0;
1074       return 0;
1075     }
1076   if (state->db->get_byteswapped(state->db, &state->byteswapped))
1077     {
1078       pool_error(state->pool, 0, "db->get_byteswapped: %s", strerror(errno));
1079       state->db->close(state->db, 0);
1080       state->db = 0;
1081       state->dbenv->close(state->dbenv, 0);
1082       state->dbenv = 0;
1083       return 0;
1084     }
1085   state->dbopened = 1;
1086   return 1;
1087 }
1088
1089 /* get the rpmdbids of all installed packages from the Name index database.
1090  * This is much faster then querying the big Packages database */
1091 static struct rpmdbentry *
1092 getinstalledrpmdbids(struct rpmdbstate *state, const char *index, const char *match, int *nentriesp, char **namedatap)
1093 {
1094   DB_ENV *dbenv = 0;
1095   DB *db = 0;
1096   DBC *dbc = 0;
1097   int byteswapped;
1098   DBT dbkey;
1099   DBT dbdata;
1100   unsigned char *dp;
1101   int dl;
1102   Id nameoff;
1103
1104   char *namedata = 0;
1105   int namedatal = 0;
1106   struct rpmdbentry *entries = 0;
1107   int nentries = 0;
1108
1109   *nentriesp = 0;
1110   if (namedatap)
1111     *namedatap = 0;
1112
1113   if (!state->dbenv && !opendbenv(state, state->rootdir))
1114     return 0;
1115   dbenv = state->dbenv;
1116   if (db_create(&db, dbenv, 0))
1117     {
1118       pool_error(state->pool, 0, "db_create: %s", strerror(errno));
1119       return 0;
1120     }
1121   if (db->open(db, 0, index, 0, DB_UNKNOWN, DB_RDONLY, 0664))
1122     {
1123       pool_error(state->pool, 0, "db->open %s: %s", index, strerror(errno));
1124       db->close(db, 0);
1125       return 0;
1126     }
1127   if (db->get_byteswapped(db, &byteswapped))
1128     {
1129       pool_error(state->pool, 0, "db->get_byteswapped: %s", strerror(errno));
1130       db->close(db, 0);
1131       return 0;
1132     }
1133   if (db->cursor(db, NULL, &dbc, 0))
1134     {
1135       pool_error(state->pool, 0, "db->cursor: %s", strerror(errno));
1136       db->close(db, 0);
1137       return 0;
1138     }
1139   memset(&dbkey, 0, sizeof(dbkey));
1140   memset(&dbdata, 0, sizeof(dbdata));
1141   if (match)
1142     {
1143       dbkey.data = (void *)match;
1144       dbkey.size = strlen(match);
1145     }
1146   while (dbc->c_get(dbc, &dbkey, &dbdata, match ? DB_SET : DB_NEXT) == 0)
1147     {
1148       if (!match && dbkey.size == 10 && !memcmp(dbkey.data, "gpg-pubkey", 10))
1149         continue;
1150       dl = dbdata.size;
1151       dp = dbdata.data;
1152       nameoff = namedatal;
1153       if (namedatap)
1154         {
1155           namedata = solv_extend(namedata, namedatal, dbkey.size + 1, 1, NAMEDATA_BLOCK);
1156           memcpy(namedata + namedatal, dbkey.data, dbkey.size);
1157           namedata[namedatal + dbkey.size] = 0;
1158           namedatal += dbkey.size + 1;
1159         }
1160       while(dl >= RPM_INDEX_SIZE)
1161         {
1162           entries = solv_extend(entries, nentries, 1, sizeof(*entries), ENTRIES_BLOCK);
1163           entries[nentries].rpmdbid = db2rpmdbid(dp, byteswapped);
1164           entries[nentries].nameoff = nameoff;
1165           nentries++;
1166           dp += RPM_INDEX_SIZE;
1167           dl -= RPM_INDEX_SIZE;
1168         }
1169       if (match)
1170         break;
1171     }
1172   dbc->c_close(dbc);
1173   db->close(db, 0);
1174   /* make sure that enteries is != 0 if there was no error */
1175   if (!entries)
1176     entries = solv_extend(entries, 1, 1, sizeof(*entries), ENTRIES_BLOCK);
1177   *nentriesp = nentries;
1178   if (namedatap)
1179     *namedatap = namedata;
1180   return entries;
1181 }
1182
1183 /* retrive header by rpmdbid */
1184 static int
1185 getrpmdbid(struct rpmdbstate *state, Id rpmdbid)
1186 {
1187   unsigned char buf[16];
1188   DBT dbkey;
1189   DBT dbdata;
1190   RpmHead *rpmhead;
1191
1192   if (!rpmdbid)
1193     {
1194       pool_error(state->pool, 0, "illegal rpmdbid");
1195       return -1;
1196     }
1197   if (state->dbopened != 1 && !openpkgdb(state))
1198     return -1;
1199   rpmdbid2db(buf, rpmdbid, state->byteswapped);
1200   memset(&dbkey, 0, sizeof(dbkey));
1201   memset(&dbdata, 0, sizeof(dbdata));
1202   dbkey.data = buf;
1203   dbkey.size = 4;
1204   dbdata.data = 0;
1205   dbdata.size = 0;
1206   if (state->db->get(state->db, NULL, &dbkey, &dbdata, 0))
1207     return 0;
1208   if (dbdata.size < 8)
1209     {
1210       pool_error(state->pool, 0, "corrupt rpm database (size)");
1211       return -1;
1212     }
1213   if (dbdata.size > state->rpmheadsize)
1214     {
1215       state->rpmheadsize = dbdata.size + 128;
1216       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*rpmhead) + state->rpmheadsize);
1217     }
1218   rpmhead = state->rpmhead;
1219   memcpy(buf, dbdata.data, 8);
1220   rpmhead->forcebinary = 1;
1221   rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1222   rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1223   if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1224     {
1225       pool_error(state->pool, 0, "corrupt rpm database (data size)");
1226       return -1;
1227     }
1228   memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1229   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1230   return 1;
1231 }
1232
1233 /* retrive header by berkeleydb cursor */
1234 static Id
1235 getrpmcursor(struct rpmdbstate *state, DBC *dbc)
1236 {
1237   unsigned char buf[16];
1238   DBT dbkey;
1239   DBT dbdata;
1240   RpmHead *rpmhead;
1241   Id dbid;
1242
1243   memset(&dbkey, 0, sizeof(dbkey));
1244   memset(&dbdata, 0, sizeof(dbdata));
1245   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1246     {
1247       if (dbkey.size != 4)
1248         return pool_error(state->pool, -1, "corrupt Packages database (key size)");
1249       dbid = db2rpmdbid(dbkey.data, state->byteswapped);
1250       if (dbid == 0)            /* the join key */
1251         continue;
1252       if (dbdata.size < 8)
1253         return pool_error(state->pool, -1, "corrupt rpm database (size %u)\n", dbdata.size);
1254       if (dbdata.size > state->rpmheadsize)
1255         {
1256           state->rpmheadsize = dbdata.size + 128;
1257           state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
1258         }
1259       rpmhead = state->rpmhead;
1260       memcpy(buf, dbdata.data, 8);
1261       rpmhead->forcebinary = 1;
1262       rpmhead->cnt = buf[0] << 24  | buf[1] << 16  | buf[2] << 8 | buf[3];
1263       rpmhead->dcnt = buf[4] << 24  | buf[5] << 16  | buf[6] << 8 | buf[7];
1264       if (8 + rpmhead->cnt * 16 + rpmhead->dcnt > dbdata.size)
1265         return pool_error(state->pool, -1, "corrupt rpm database (data size)\n");
1266       memcpy(rpmhead->data, (unsigned char *)dbdata.data + 8, rpmhead->cnt * 16 + rpmhead->dcnt);
1267       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1268       return dbid;
1269     }
1270   return 0;
1271 }
1272
1273 static void
1274 freestate(struct rpmdbstate *state)
1275 {
1276   /* close down */
1277   if (!state)
1278     return;
1279   if (state->rootdir)
1280     solv_free(state->rootdir);
1281   if (state->db)
1282     state->db->close(state->db, 0);
1283   if (state->dbenv)
1284     state->dbenv->close(state->dbenv, 0);
1285   solv_free(state->rpmhead);
1286 }
1287
1288 void *
1289 rpm_state_create(Pool *pool, const char *rootdir)
1290 {
1291   struct rpmdbstate *state;
1292   state = solv_calloc(1, sizeof(*state));
1293   state->pool = pool;
1294   if (rootdir)
1295     state->rootdir = solv_strdup(rootdir);
1296   return state;
1297 }
1298
1299 void *
1300 rpm_state_free(void *state)
1301 {
1302   freestate(state);
1303   return solv_free(state);
1304 }
1305
1306 static int
1307 count_headers(Pool *pool, const char *rootdir, DB_ENV *dbenv)
1308 {
1309   char dbpath[PATH_MAX];
1310   struct stat statbuf;
1311   DB *db = 0;
1312   DBC *dbc = 0;
1313   int count = 0;
1314   DBT dbkey;
1315   DBT dbdata;
1316
1317   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Name", rootdir ? rootdir : "");
1318   if (stat(dbpath, &statbuf))
1319     return 0;
1320   memset(&dbkey, 0, sizeof(dbkey));
1321   memset(&dbdata, 0, sizeof(dbdata));
1322   if (db_create(&db, dbenv, 0))
1323     {
1324       pool_error(pool, 0, "db_create: %s", strerror(errno));
1325       return 0;
1326     }
1327   if (db->open(db, 0, "Name", 0, DB_UNKNOWN, DB_RDONLY, 0664))
1328     {
1329       pool_error(pool, 0, "db->open Name: %s", strerror(errno));
1330       db->close(db, 0);
1331       return 0;
1332     }
1333   if (db->cursor(db, NULL, &dbc, 0))
1334     {
1335       db->close(db, 0);
1336       pool_error(pool, 0, "db->cursor: %s", strerror(errno));
1337       return 0;
1338     }
1339   while (dbc->c_get(dbc, &dbkey, &dbdata, DB_NEXT) == 0)
1340     count += dbdata.size / RPM_INDEX_SIZE;
1341   dbc->c_close(dbc);
1342   db->close(db, 0);
1343   return count;
1344 }
1345
1346 /******************************************************************/
1347
1348 static Offset
1349 copydeps(Pool *pool, Repo *repo, Offset fromoff, Repo *fromrepo)
1350 {
1351   int cc;
1352   Id *ida, *from;
1353   Offset ido;
1354
1355   if (!fromoff)
1356     return 0;
1357   from = fromrepo->idarraydata + fromoff;
1358   for (ida = from, cc = 0; *ida; ida++, cc++)
1359     ;
1360   if (cc == 0)
1361     return 0;
1362   ido = repo_reserve_ids(repo, 0, cc);
1363   ida = repo->idarraydata + ido;
1364   memcpy(ida, from, (cc + 1) * sizeof(Id));
1365   repo->idarraysize += cc + 1;
1366   return ido;
1367 }
1368
1369 #define COPYDIR_DIRCACHE_SIZE 512
1370
1371 static Id copydir_complex(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache);
1372
1373 static inline Id
1374 copydir(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache)
1375 {
1376   if (cache && cache[did & 255] == did)
1377     return cache[(did & 255) + 256];
1378   return copydir_complex(pool, data, fromdata, did, cache);
1379 }
1380
1381 static Id
1382 copydir_complex(Pool *pool, Repodata *data, Repodata *fromdata, Id did, Id *cache)
1383 {
1384   Id parent = dirpool_parent(&fromdata->dirpool, did);
1385   Id compid = dirpool_compid(&fromdata->dirpool, did);
1386   if (parent)
1387     parent = copydir(pool, data, fromdata, parent, cache);
1388   if (data->localpool || fromdata->localpool)
1389     compid = repodata_translate_id(data, fromdata, compid, 1);
1390   compid = dirpool_add_dir(&data->dirpool, parent, compid, 1);
1391   if (cache)
1392     {
1393       cache[did & 255] = did;
1394       cache[(did & 255) + 256] = compid;
1395     }
1396   return compid;
1397 }
1398
1399 struct solvable_copy_cbdata {
1400   Repodata *data;
1401   Id handle;
1402   Id subhandle;
1403   Id *dircache;
1404 };
1405
1406 static int
1407 solvable_copy_cb(void *vcbdata, Solvable *r, Repodata *fromdata, Repokey *key, KeyValue *kv)
1408 {
1409   struct solvable_copy_cbdata *cbdata = vcbdata;
1410   Id id, keyname;
1411   Repodata *data = cbdata->data;
1412   Id handle = cbdata->handle;
1413   Pool *pool = data->repo->pool;
1414
1415   keyname = key->name;
1416   switch(key->type)
1417     {
1418     case REPOKEY_TYPE_ID:
1419     case REPOKEY_TYPE_CONSTANTID:
1420     case REPOKEY_TYPE_IDARRAY:  /* used for triggers */
1421       id = kv->id;
1422       if (data->localpool || fromdata->localpool)
1423         id = repodata_translate_id(data, fromdata, id, 1);
1424       if (key->type == REPOKEY_TYPE_ID)
1425         repodata_set_id(data, handle, keyname, id);
1426       else if (key->type == REPOKEY_TYPE_CONSTANTID)
1427         repodata_set_constantid(data, handle, keyname, id);
1428       else
1429         repodata_add_idarray(data, handle, keyname, id);
1430       break;
1431     case REPOKEY_TYPE_STR:
1432       repodata_set_str(data, handle, keyname, kv->str);
1433       break;
1434     case REPOKEY_TYPE_VOID:
1435       repodata_set_void(data, handle, keyname);
1436       break;
1437     case REPOKEY_TYPE_NUM:
1438       repodata_set_num(data, handle, keyname, SOLV_KV_NUM64(kv));
1439       break;
1440     case REPOKEY_TYPE_CONSTANT:
1441       repodata_set_constant(data, handle, keyname, kv->num);
1442       break;
1443     case REPOKEY_TYPE_DIRNUMNUMARRAY:
1444       id = kv->id;
1445       id = copydir(pool, data, fromdata, id, cbdata->dircache);
1446       repodata_add_dirnumnum(data, handle, keyname, id, kv->num, kv->num2);
1447       break;
1448     case REPOKEY_TYPE_DIRSTRARRAY:
1449       id = kv->id;
1450       id = copydir(pool, data, fromdata, id, cbdata->dircache);
1451       repodata_add_dirstr(data, handle, keyname, id, kv->str);
1452       break;
1453     case REPOKEY_TYPE_FLEXARRAY:
1454       if (kv->eof == 2)
1455         {
1456           assert(cbdata->subhandle);
1457           cbdata->handle = cbdata->subhandle;
1458           cbdata->subhandle = 0;
1459           break;
1460         }
1461       if (!kv->entry)
1462         {
1463           assert(!cbdata->subhandle);
1464           cbdata->subhandle = cbdata->handle;
1465         }
1466       cbdata->handle = repodata_new_handle(data);
1467       repodata_add_flexarray(data, cbdata->subhandle, keyname, cbdata->handle);
1468       break;
1469     default:
1470       break;
1471     }
1472   return 0;
1473 }
1474
1475 static void
1476 solvable_copy(Solvable *s, Solvable *r, Repodata *data, Id *dircache)
1477 {
1478   int p, i;
1479   Repo *repo = s->repo;
1480   Pool *pool = repo->pool;
1481   Repo *fromrepo = r->repo;
1482   struct solvable_copy_cbdata cbdata;
1483
1484   /* copy solvable data */
1485   s->name = r->name;
1486   s->evr = r->evr;
1487   s->arch = r->arch;
1488   s->vendor = r->vendor;
1489   s->provides = copydeps(pool, repo, r->provides, fromrepo);
1490   s->requires = copydeps(pool, repo, r->requires, fromrepo);
1491   s->conflicts = copydeps(pool, repo, r->conflicts, fromrepo);
1492   s->obsoletes = copydeps(pool, repo, r->obsoletes, fromrepo);
1493   s->recommends = copydeps(pool, repo, r->recommends, fromrepo);
1494   s->suggests = copydeps(pool, repo, r->suggests, fromrepo);
1495   s->supplements = copydeps(pool, repo, r->supplements, fromrepo);
1496   s->enhances  = copydeps(pool, repo, r->enhances, fromrepo);
1497
1498   /* copy all attributes */
1499   if (!data)
1500     return;
1501   cbdata.data = data;
1502   cbdata.handle = s - pool->solvables;
1503   cbdata.subhandle = 0;
1504   cbdata.dircache = dircache;
1505   p = r - fromrepo->pool->solvables;
1506 #if 0
1507   repo_search(fromrepo, p, 0, 0, SEARCH_NO_STORAGE_SOLVABLE | SEARCH_SUB | SEARCH_ARRAYSENTINEL, solvable_copy_cb, &cbdata);
1508 #else
1509   FOR_REPODATAS(fromrepo, i, data)
1510     {
1511       if (p < data->start || p >= data->end)
1512         continue;
1513       repodata_search(data, p, 0, SEARCH_SUB | SEARCH_ARRAYSENTINEL, solvable_copy_cb, &cbdata);
1514     }
1515 #endif
1516 }
1517
1518 /* used to sort entries by package name that got returned in some database order */
1519 static int
1520 rpmids_sort_cmp(const void *va, const void *vb, void *dp)
1521 {
1522   struct rpmdbentry const *a = va, *b = vb;
1523   char *namedata = dp;
1524   int r;
1525   r = strcmp(namedata + a->nameoff, namedata + b->nameoff);
1526   if (r)
1527     return r;
1528   return a->rpmdbid - b->rpmdbid;
1529 }
1530
1531 static int
1532 pkgids_sort_cmp(const void *va, const void *vb, void *dp)
1533 {
1534   Repo *repo = dp;
1535   Pool *pool = repo->pool;
1536   Solvable *a = pool->solvables + *(Id *)va;
1537   Solvable *b = pool->solvables + *(Id *)vb;
1538   Id *rpmdbid;
1539
1540   if (a->name != b->name)
1541     return strcmp(pool_id2str(pool, a->name), pool_id2str(pool, b->name));
1542   rpmdbid = repo->rpmdbid;
1543   return rpmdbid[(a - pool->solvables) - repo->start] - rpmdbid[(b - pool->solvables) - repo->start];
1544 }
1545
1546 static void
1547 swap_solvables(Repo *repo, Repodata *data, Id pa, Id pb)
1548 {
1549   Pool *pool = repo->pool;
1550   Solvable tmp;
1551
1552   tmp = pool->solvables[pa];
1553   pool->solvables[pa] = pool->solvables[pb];
1554   pool->solvables[pb] = tmp;
1555   if (repo->rpmdbid)
1556     {
1557       Id tmpid = repo->rpmdbid[pa - repo->start];
1558       repo->rpmdbid[pa - repo->start] = repo->rpmdbid[pb - repo->start];
1559       repo->rpmdbid[pb - repo->start] = tmpid;
1560     }
1561   /* only works if nothing is already internalized! */
1562   if (data)
1563     repodata_swap_attrs(data, pa, pb);
1564 }
1565
1566 static void
1567 mkrpmdbcookie(struct stat *st, unsigned char *cookie)
1568 {
1569   memset(cookie, 0, 32);
1570   cookie[3] = RPMDB_COOKIE_VERSION;
1571   memcpy(cookie + 16, &st->st_ino, sizeof(st->st_ino));
1572   memcpy(cookie + 24, &st->st_dev, sizeof(st->st_dev));
1573 }
1574
1575 /*
1576  * read rpm db as repo
1577  *
1578  */
1579
1580 int
1581 repo_add_rpmdb(Repo *repo, Repo *ref, int flags)
1582 {
1583   Pool *pool = repo->pool;
1584   char dbpath[PATH_MAX];
1585   struct stat packagesstat;
1586   unsigned char newcookie[32];
1587   const unsigned char *oldcookie = 0;
1588   Id oldcookietype = 0;
1589   Repodata *data;
1590   int count = 0, done = 0;
1591   const char *rootdir = 0;
1592   struct rpmdbstate state;
1593   int i;
1594   Solvable *s;
1595   unsigned int now;
1596
1597   now = solv_timems(0);
1598   memset(&state, 0, sizeof(state));
1599   state.pool = pool;
1600
1601   data = repo_add_repodata(repo, flags);
1602
1603   if (ref && !(ref->nsolvables && ref->rpmdbid && ref->pool == repo->pool))
1604     {
1605       if ((flags & RPMDB_EMPTY_REFREPO) != 0)
1606         repo_empty(ref, 1);
1607       ref = 0;
1608     }
1609
1610   if (flags & REPO_USE_ROOTDIR)
1611     rootdir = pool_get_rootdir(pool);
1612   if (!opendbenv(&state, rootdir))
1613     return -1;
1614
1615   /* XXX: should get ro lock of Packages database! */
1616   snprintf(dbpath, PATH_MAX, "%s/var/lib/rpm/Packages", rootdir ? rootdir : "");
1617   if (stat(dbpath, &packagesstat))
1618     {
1619       pool_error(pool, -1, "%s: %s", dbpath, strerror(errno));
1620       freestate(&state);
1621       return -1;
1622     }
1623   mkrpmdbcookie(&packagesstat, newcookie);
1624   repodata_set_bin_checksum(data, SOLVID_META, REPOSITORY_RPMDBCOOKIE, REPOKEY_TYPE_SHA256, newcookie);
1625
1626   if (ref)
1627     oldcookie = repo_lookup_bin_checksum(ref, SOLVID_META, REPOSITORY_RPMDBCOOKIE, &oldcookietype);
1628   if (!ref || !oldcookie || oldcookietype != REPOKEY_TYPE_SHA256 || memcmp(oldcookie, newcookie, 32) != 0)
1629     {
1630       int solvstart = 0, solvend = 0;
1631       Id dbid;
1632       DBC *dbc = 0;
1633
1634       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1635         repo_empty(ref, 1);     /* get it out of the way */
1636       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1637         count = count_headers(pool, rootdir, state.dbenv);
1638       if (!openpkgdb(&state))
1639         {
1640           freestate(&state);
1641           return -1;
1642         }
1643       if (state.db->cursor(state.db, NULL, &dbc, 0))
1644         {
1645           freestate(&state);
1646           return pool_error(pool, -1, "db->cursor failed");
1647         }
1648       i = 0;
1649       s = 0;
1650       while ((dbid = getrpmcursor(&state, dbc)) != 0)
1651         {
1652           if (dbid == -1)
1653             {
1654               dbc->c_close(dbc);
1655               freestate(&state);
1656               return -1;
1657             }
1658           if (!s)
1659             {
1660               s = pool_id2solvable(pool, repo_add_solvable(repo));
1661               if (!solvstart)
1662                 solvstart = s - pool->solvables;
1663               solvend = s - pool->solvables + 1;
1664             }
1665           if (!repo->rpmdbid)
1666             repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1667           repo->rpmdbid[(s - pool->solvables) - repo->start] = dbid;
1668           if (rpm2solv(pool, repo, data, s, state.rpmhead, flags | RPM_ADD_TRIGGERS))
1669             {
1670               i++;
1671               s = 0;
1672             }
1673           else
1674             {
1675               /* We can reuse this solvable, but make sure it's still
1676                  associated with this repo.  */
1677               memset(s, 0, sizeof(*s));
1678               s->repo = repo;
1679             }
1680           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1681             {
1682               if (done < count)
1683                 done++;
1684               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1685                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1686             }
1687         }
1688       dbc->c_close(dbc);
1689       if (s)
1690         {
1691           /* oops, could not reuse. free it instead */
1692           repo_free_solvable(repo, s - pool->solvables, 1);
1693           solvend--;
1694           s = 0;
1695         }
1696       /* now sort all solvables in the new solvstart..solvend block */
1697       if (solvend - solvstart > 1)
1698         {
1699           Id *pkgids = solv_malloc2(solvend - solvstart, sizeof(Id));
1700           for (i = solvstart; i < solvend; i++)
1701             pkgids[i - solvstart] = i;
1702           solv_sort(pkgids, solvend - solvstart, sizeof(Id), pkgids_sort_cmp, repo);
1703           /* adapt order */
1704           for (i = solvstart; i < solvend; i++)
1705             {
1706               int j = pkgids[i - solvstart];
1707               while (j < i)
1708                 j = pkgids[i - solvstart] = pkgids[j - solvstart];
1709               if (j != i)
1710                 swap_solvables(repo, data, i, j);
1711             }
1712           solv_free(pkgids);
1713         }
1714     }
1715   else
1716     {
1717       Id dircache[COPYDIR_DIRCACHE_SIZE];               /* see copydir */
1718       struct rpmdbentry *entries = 0, *rp;
1719       int nentries = 0;
1720       char *namedata = 0;
1721       unsigned int refmask, h;
1722       Id id, *refhash;
1723       int res;
1724
1725       memset(dircache, 0, sizeof(dircache));
1726
1727       /* get ids of installed rpms */
1728       entries = getinstalledrpmdbids(&state, "Name", 0, &nentries, &namedata);
1729       if (!entries)
1730         {
1731           freestate(&state);
1732           return -1;
1733         }
1734
1735       /* sort by name */
1736       if (nentries > 1)
1737         solv_sort(entries, nentries, sizeof(*entries), rpmids_sort_cmp, namedata);
1738
1739       /* create hash from dbid to ref */
1740       refmask = mkmask(ref->nsolvables);
1741       refhash = solv_calloc(refmask + 1, sizeof(Id));
1742       for (i = 0; i < ref->end - ref->start; i++)
1743         {
1744           if (!ref->rpmdbid[i])
1745             continue;
1746           h = ref->rpmdbid[i] & refmask;
1747           while (refhash[h])
1748             h = (h + 317) & refmask;
1749           refhash[h] = i + 1;   /* make it non-zero */
1750         }
1751
1752       /* count the misses, they will cost us time */
1753       if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1754         {
1755           for (i = 0, rp = entries; i < nentries; i++, rp++)
1756             {
1757               if (refhash)
1758                 {
1759                   Id dbid = rp->rpmdbid;
1760                   h = dbid & refmask;
1761                   while ((id = refhash[h]))
1762                     {
1763                       if (ref->rpmdbid[id - 1] == dbid)
1764                         break;
1765                       h = (h + 317) & refmask;
1766                     }
1767                   if (id)
1768                     continue;
1769                 }
1770               count++;
1771             }
1772         }
1773
1774       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1775         s = pool_id2solvable(pool, repo_add_solvable_block_before(repo, nentries, ref));
1776       else
1777         s = pool_id2solvable(pool, repo_add_solvable_block(repo, nentries));
1778       if (!repo->rpmdbid)
1779         repo->rpmdbid = repo_sidedata_create(repo, sizeof(Id));
1780
1781       for (i = 0, rp = entries; i < nentries; i++, rp++, s++)
1782         {
1783           Id dbid = rp->rpmdbid;
1784           repo->rpmdbid[(s - pool->solvables) - repo->start] = rp->rpmdbid;
1785           if (refhash)
1786             {
1787               h = dbid & refmask;
1788               while ((id = refhash[h]))
1789                 {
1790                   if (ref->rpmdbid[id - 1] == dbid)
1791                     break;
1792                   h = (h + 317) & refmask;
1793                 }
1794               if (id)
1795                 {
1796                   Solvable *r = ref->pool->solvables + ref->start + (id - 1);
1797                   if (r->repo == ref)
1798                     {
1799                       solvable_copy(s, r, data, dircache);
1800                       continue;
1801                     }
1802                 }
1803             }
1804           res = getrpmdbid(&state, dbid);
1805           if (res <= 0)
1806             {
1807               if (!res)
1808                 return pool_error(pool, -1, "inconsistent rpm database, key %d not found. run 'rpm --rebuilddb' to fix.", dbid);
1809               freestate(&state);
1810               solv_free(entries);
1811               solv_free(namedata);
1812               solv_free(refhash);
1813               return -1;
1814             }
1815           rpm2solv(pool, repo, data, s, state.rpmhead, flags | RPM_ADD_TRIGGERS);
1816           if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1817             {
1818               if (done < count)
1819                 done++;
1820               if (done < count && (done - 1) * 100 / count != done * 100 / count)
1821                 pool_debug(pool, SOLV_ERROR, "%%%% %d\n", done * 100 / count);
1822             }
1823         }
1824
1825       solv_free(entries);
1826       solv_free(namedata);
1827       solv_free(refhash);
1828       if (ref && (flags & RPMDB_EMPTY_REFREPO) != 0)
1829         repo_empty(ref, 1);
1830     }
1831
1832   freestate(&state);
1833   if (!(flags & REPO_NO_INTERNALIZE))
1834     repodata_internalize(data);
1835   if ((flags & RPMDB_REPORT_PROGRESS) != 0)
1836     pool_debug(pool, SOLV_ERROR, "%%%% 100\n");
1837   POOL_DEBUG(SOLV_DEBUG_STATS, "repo_add_rpmdb took %d ms\n", solv_timems(now));
1838   POOL_DEBUG(SOLV_DEBUG_STATS, "repo size: %d solvables\n", repo->nsolvables);
1839   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)));
1840   return 0;
1841 }
1842
1843 int
1844 repo_add_rpmdb_reffp(Repo *repo, FILE *fp, int flags)
1845 {
1846   int res;
1847   Repo *ref = 0;
1848
1849   if (!fp)
1850     return repo_add_rpmdb(repo, 0, flags);
1851   ref = repo_create(repo->pool, "add_rpmdb_reffp");
1852   if (repo_add_solv(ref, fp, 0) != 0)
1853     {
1854       repo_free(ref, 1);
1855       ref = 0;
1856     }
1857   if (ref && ref->start == ref->end)
1858     {
1859       repo_free(ref, 1);
1860       ref = 0;
1861     }
1862   if (ref)
1863     repo_disable_paging(ref);
1864   res = repo_add_rpmdb(repo, ref, flags | RPMDB_EMPTY_REFREPO);
1865   if (ref)
1866     repo_free(ref, 1);
1867   return res;
1868 }
1869
1870 static inline unsigned int
1871 getu32(const unsigned char *dp)
1872 {
1873   return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3];
1874 }
1875
1876
1877 Id
1878 repo_add_rpm(Repo *repo, const char *rpm, int flags)
1879 {
1880   unsigned int sigdsize, sigcnt, l;
1881   Pool *pool = repo->pool;
1882   Solvable *s;
1883   RpmHead *rpmhead = 0;
1884   int rpmheadsize = 0;
1885   char *payloadformat;
1886   FILE *fp;
1887   unsigned char lead[4096];
1888   int headerstart, headerend;
1889   struct stat stb;
1890   Repodata *data;
1891   unsigned char pkgid[16];
1892   unsigned char leadsigid[16];
1893   unsigned char hdrid[32];
1894   int pkgidtype, leadsigidtype, hdridtype;
1895   Id chksumtype = 0;
1896   void *chksumh = 0;
1897   void *leadsigchksumh = 0;
1898   int forcebinary = 0;
1899
1900   data = repo_add_repodata(repo, flags);
1901
1902   if ((flags & RPM_ADD_WITH_SHA256SUM) != 0)
1903     chksumtype = REPOKEY_TYPE_SHA256;
1904   else if ((flags & RPM_ADD_WITH_SHA1SUM) != 0)
1905     chksumtype = REPOKEY_TYPE_SHA1;
1906
1907   if ((fp = fopen(flags & REPO_USE_ROOTDIR ? pool_prepend_rootdir_tmp(pool, rpm) : rpm, "r")) == 0)
1908     {
1909       pool_error(pool, -1, "%s: %s", rpm, strerror(errno));
1910       return 0;
1911     }
1912   if (fstat(fileno(fp), &stb))
1913     {
1914       pool_error(pool, -1, "fstat: %s", strerror(errno));
1915       fclose(fp);
1916       return 0;
1917     }
1918   if (chksumtype)
1919     chksumh = solv_chksum_create(chksumtype);
1920   if ((flags & RPM_ADD_WITH_LEADSIGID) != 0)
1921     leadsigchksumh = solv_chksum_create(REPOKEY_TYPE_MD5);
1922   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
1923     {
1924       pool_error(pool, -1, "%s: not a rpm", rpm);
1925       fclose(fp);
1926       return 0;
1927     }
1928   forcebinary = lead[6] != 0 || lead[7] != 1;
1929   if (chksumh)
1930     solv_chksum_add(chksumh, lead, 96 + 16);
1931   if (leadsigchksumh)
1932     solv_chksum_add(leadsigchksumh, lead, 96 + 16);
1933   if (lead[78] != 0 || lead[79] != 5)
1934     {
1935       pool_error(pool, -1, "%s: not a rpm v5 header", rpm);
1936       fclose(fp);
1937       return 0;
1938     }
1939   if (getu32(lead + 96) != 0x8eade801)
1940     {
1941       pool_error(pool, -1, "%s: bad signature header", rpm);
1942       fclose(fp);
1943       return 0;
1944     }
1945   sigcnt = getu32(lead + 96 + 8);
1946   sigdsize = getu32(lead + 96 + 12);
1947   if (sigcnt >= 0x100000 || sigdsize >= 0x100000)
1948     {
1949       pool_error(pool, -1, "%s: bad signature header", rpm);
1950       fclose(fp);
1951       return 0;
1952     }
1953   sigdsize += sigcnt * 16;
1954   sigdsize = (sigdsize + 7) & ~7;
1955   headerstart = 96 + 16 + sigdsize;
1956   pkgidtype = leadsigidtype = hdridtype = 0;
1957   if ((flags & (RPM_ADD_WITH_PKGID | RPM_ADD_WITH_HDRID)) != 0)
1958     {
1959       /* extract pkgid or hdrid from the signature header */
1960       if (sigdsize > rpmheadsize)
1961         {
1962           rpmheadsize = sigdsize + 128;
1963           rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
1964         }
1965       if (fread(rpmhead->data, sigdsize, 1, fp) != 1)
1966         {
1967           pool_error(pool, -1, "%s: unexpected EOF", rpm);
1968           fclose(fp);
1969           return 0;
1970         }
1971       if (chksumh)
1972         solv_chksum_add(chksumh, rpmhead->data, sigdsize);
1973       if (leadsigchksumh)
1974         solv_chksum_add(leadsigchksumh, rpmhead->data, sigdsize);
1975       rpmhead->forcebinary = 0;
1976       rpmhead->cnt = sigcnt;
1977       rpmhead->dcnt = sigdsize - sigcnt * 16;
1978       rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
1979       if ((flags & RPM_ADD_WITH_PKGID) != 0)
1980         {
1981           unsigned char *chksum;
1982           unsigned int chksumsize;
1983           chksum = headbinary(rpmhead, SIGTAG_MD5, &chksumsize);
1984           if (chksum && chksumsize == 16)
1985             {
1986               pkgidtype = REPOKEY_TYPE_MD5;
1987               memcpy(pkgid, chksum, 16);
1988             }
1989         }
1990       if ((flags & RPM_ADD_WITH_HDRID) != 0)
1991         {
1992           const char *str = headstring(rpmhead, TAG_SHA1HEADER);
1993           if (str && strlen(str) == 40)
1994             {
1995               if (solv_hex2bin(&str, hdrid, 20) == 20)
1996                 hdridtype = REPOKEY_TYPE_SHA1;
1997             }
1998           else if (str && strlen(str) == 64)
1999             {
2000               if (solv_hex2bin(&str, hdrid, 32) == 32)
2001                 hdridtype = REPOKEY_TYPE_SHA256;
2002             }
2003         }
2004     }
2005   else
2006     {
2007       /* just skip the signature header */
2008       while (sigdsize)
2009         {
2010           l = sigdsize > 4096 ? 4096 : sigdsize;
2011           if (fread(lead, l, 1, fp) != 1)
2012             {
2013               pool_error(pool, -1, "%s: unexpected EOF", rpm);
2014               fclose(fp);
2015               return 0;
2016             }
2017           if (chksumh)
2018             solv_chksum_add(chksumh, lead, l);
2019           if (leadsigchksumh)
2020             solv_chksum_add(leadsigchksumh, lead, l);
2021           sigdsize -= l;
2022         }
2023     }
2024   if (leadsigchksumh)
2025     {
2026       leadsigchksumh = solv_chksum_free(leadsigchksumh, leadsigid);
2027       leadsigidtype = REPOKEY_TYPE_MD5;
2028     }
2029   if (fread(lead, 16, 1, fp) != 1)
2030     {
2031       pool_error(pool, -1, "%s: unexpected EOF", rpm);
2032       fclose(fp);
2033       return 0;
2034     }
2035   if (chksumh)
2036     solv_chksum_add(chksumh, lead, 16);
2037   if (getu32(lead) != 0x8eade801)
2038     {
2039       pool_error(pool, -1, "%s: bad header", rpm);
2040       fclose(fp);
2041       return 0;
2042     }
2043   sigcnt = getu32(lead + 8);
2044   sigdsize = getu32(lead + 12);
2045   if (sigcnt >= 0x100000 || sigdsize >= 0x2000000)
2046     {
2047       pool_error(pool, -1, "%s: bad header", rpm);
2048       fclose(fp);
2049       return 0;
2050     }
2051   l = sigdsize + sigcnt * 16;
2052   headerend = headerstart + 16 + l;
2053   if (l > rpmheadsize)
2054     {
2055       rpmheadsize = l + 128;
2056       rpmhead = solv_realloc(rpmhead, sizeof(*rpmhead) + rpmheadsize);
2057     }
2058   if (fread(rpmhead->data, l, 1, fp) != 1)
2059     {
2060       pool_error(pool, -1, "%s: unexpected EOF", rpm);
2061       fclose(fp);
2062       return 0;
2063     }
2064   if (chksumh)
2065     solv_chksum_add(chksumh, rpmhead->data, l);
2066   rpmhead->forcebinary = forcebinary;
2067   rpmhead->cnt = sigcnt;
2068   rpmhead->dcnt = sigdsize;
2069   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2070   if (headexists(rpmhead, TAG_PATCHESNAME))
2071     {
2072       /* this is a patch rpm, ignore */
2073       pool_error(pool, -1, "%s: is patch rpm", rpm);
2074       fclose(fp);
2075       solv_chksum_free(chksumh, 0);
2076       solv_free(rpmhead);
2077       return 0;
2078     }
2079   payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
2080   if (payloadformat && !strcmp(payloadformat, "drpm"))
2081     {
2082       /* this is a delta rpm */
2083       pool_error(pool, -1, "%s: is delta rpm", rpm);
2084       fclose(fp);
2085       solv_chksum_free(chksumh, 0);
2086       solv_free(rpmhead);
2087       return 0;
2088     }
2089   if (chksumh)
2090     while ((l = fread(lead, 1, sizeof(lead), fp)) > 0)
2091       solv_chksum_add(chksumh, lead, l);
2092   fclose(fp);
2093   s = pool_id2solvable(pool, repo_add_solvable(repo));
2094   if (!rpm2solv(pool, repo, data, s, rpmhead, flags & ~(RPM_ADD_WITH_HDRID | RPM_ADD_WITH_PKGID)))
2095     {
2096       repo_free_solvable(repo, s - pool->solvables, 1);
2097       solv_chksum_free(chksumh, 0);
2098       solv_free(rpmhead);
2099       return 0;
2100     }
2101   if (!(flags & REPO_NO_LOCATION))
2102     repodata_set_location(data, s - pool->solvables, 0, 0, rpm);
2103   if (S_ISREG(stb.st_mode))
2104     repodata_set_num(data, s - pool->solvables, SOLVABLE_DOWNLOADSIZE, (unsigned long long)stb.st_size);
2105   repodata_set_num(data, s - pool->solvables, SOLVABLE_HEADEREND, headerend);
2106   if (pkgidtype)
2107     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_PKGID, pkgidtype, pkgid);
2108   if (hdridtype)
2109     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_HDRID, hdridtype, hdrid);
2110   if (leadsigidtype)
2111     repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_LEADSIGID, leadsigidtype, leadsigid);
2112   if (chksumh)
2113     {
2114       repodata_set_bin_checksum(data, s - pool->solvables, SOLVABLE_CHECKSUM, chksumtype, solv_chksum_get(chksumh, 0));
2115       chksumh = solv_chksum_free(chksumh, 0);
2116     }
2117   if (rpmhead)
2118     solv_free(rpmhead);
2119   if (!(flags & REPO_NO_INTERNALIZE))
2120     repodata_internalize(data);
2121   return s - pool->solvables;
2122 }
2123
2124 Id
2125 repo_add_rpm_handle(Repo *repo, void *rpmhandle, int flags)
2126 {
2127   Pool *pool = repo->pool;
2128   Repodata *data;
2129   RpmHead *rpmhead = rpmhandle;
2130   Solvable *s;
2131   char *payloadformat;
2132
2133   data = repo_add_repodata(repo, flags);
2134   if (headexists(rpmhead, TAG_PATCHESNAME))
2135     {
2136       pool_error(pool, -1, "is a patch rpm");
2137       return 0;
2138     }
2139   payloadformat = headstring(rpmhead, TAG_PAYLOADFORMAT);
2140   if (payloadformat && !strcmp(payloadformat, "drpm"))
2141     {
2142       /* this is a delta rpm */
2143       pool_error(pool, -1, "is a delta rpm");
2144       return 0;
2145     }
2146   s = pool_id2solvable(pool, repo_add_solvable(repo));
2147   if (!rpm2solv(pool, repo, data, s, rpmhead, flags))
2148     {
2149       repo_free_solvable(repo, s - pool->solvables, 1);
2150       return 0;
2151     }
2152   if (!(flags & REPO_NO_INTERNALIZE))
2153     repodata_internalize(data);
2154   return s - pool->solvables;
2155 }
2156
2157 static inline void
2158 linkhash(const char *lt, char *hash)
2159 {
2160   unsigned int r = 0;
2161   const unsigned char *str = (const unsigned char *)lt;
2162   int l, c;
2163
2164   l = strlen(lt);
2165   while ((c = *str++) != 0)
2166     r += (r << 3) + c;
2167   sprintf(hash, "%08x%08x%08x%08x", r, l, 0, 0);
2168 }
2169
2170 void
2171 rpm_iterate_filelist(void *rpmhandle, int flags, void (*cb)(void *, const char *, struct filelistinfo *), void *cbdata)
2172 {
2173   RpmHead *rpmhead = rpmhandle;
2174   char **bn;
2175   char **dn;
2176   char **md = 0;
2177   char **lt = 0;
2178   unsigned int *di, diidx;
2179   unsigned int *co = 0;
2180   unsigned int *ff = 0;
2181   unsigned int lastdir;
2182   int lastdirl;
2183   unsigned int *fm;
2184   int cnt, dcnt, cnt2;
2185   int i, l1, l;
2186   char *space = 0;
2187   int spacen = 0;
2188   char md5[33];
2189   struct filelistinfo info;
2190
2191   dn = headstringarray(rpmhead, TAG_DIRNAMES, &dcnt);
2192   if (!dn)
2193     return;
2194   if ((flags & RPM_ITERATE_FILELIST_ONLYDIRS) != 0)
2195     {
2196       for (i = 0; i < dcnt; i++)
2197         (*cb)(cbdata, dn[i], 0);
2198       solv_free(dn);
2199       return;
2200     }
2201   bn = headstringarray(rpmhead, TAG_BASENAMES, &cnt);
2202   if (!bn)
2203     {
2204       solv_free(dn);
2205       return;
2206     }
2207   di = headint32array(rpmhead, TAG_DIRINDEXES, &cnt2);
2208   if (!di || cnt != cnt2)
2209     {
2210       solv_free(di);
2211       solv_free(bn);
2212       solv_free(dn);
2213       return;
2214     }
2215   fm = headint16array(rpmhead, TAG_FILEMODES, &cnt2);
2216   if (!fm || cnt != cnt2)
2217     {
2218       solv_free(fm);
2219       solv_free(di);
2220       solv_free(bn);
2221       solv_free(dn);
2222       return;
2223     }
2224   if ((flags & RPM_ITERATE_FILELIST_WITHMD5) != 0)
2225     {
2226       md = headstringarray(rpmhead, TAG_FILEMD5S, &cnt2);
2227       if (!md || cnt != cnt2)
2228         {
2229           solv_free(md);
2230           solv_free(fm);
2231           solv_free(di);
2232           solv_free(bn);
2233           solv_free(dn);
2234           return;
2235         }
2236     }
2237   if ((flags & RPM_ITERATE_FILELIST_WITHCOL) != 0)
2238     {
2239       co = headint32array(rpmhead, TAG_FILECOLORS, &cnt2);
2240       if (!co || cnt != cnt2)
2241         {
2242           solv_free(co);
2243           solv_free(md);
2244           solv_free(fm);
2245           solv_free(di);
2246           solv_free(bn);
2247           solv_free(dn);
2248           return;
2249         }
2250     }
2251   if ((flags & RPM_ITERATE_FILELIST_NOGHOSTS) != 0)
2252     {
2253       ff = headint32array(rpmhead, TAG_FILEFLAGS, &cnt2);
2254       if (!ff || cnt != cnt2)
2255         {
2256           solv_free(ff);
2257           solv_free(co);
2258           solv_free(md);
2259           solv_free(fm);
2260           solv_free(di);
2261           solv_free(bn);
2262           solv_free(dn);
2263           return;
2264         }
2265     }
2266   lastdir = dcnt;
2267   lastdirl = 0;
2268   memset(&info, 0, sizeof(info));
2269   for (i = 0; i < cnt; i++)
2270     {
2271       if (ff && (ff[i] & FILEFLAG_GHOST) != 0)
2272         continue;
2273       diidx = di[i];
2274       if (diidx >= dcnt)
2275         continue;
2276       l1 = lastdir == diidx ? lastdirl : strlen(dn[diidx]);
2277       l = l1 + strlen(bn[i]) + 1;
2278       if (l > spacen)
2279         {
2280           spacen = l + 16;
2281           space = solv_realloc(space, spacen);
2282         }
2283       if (lastdir != diidx)
2284         {
2285           strcpy(space, dn[diidx]);
2286           lastdir = diidx;
2287           lastdirl = l1;
2288         }
2289       strcpy(space + l1, bn[i]);
2290       info.diridx = diidx;
2291       info.dirlen = l1;
2292       if (fm)
2293         info.mode = fm[i];
2294       if (md)
2295         {
2296           info.digest = md[i];
2297           if (fm && S_ISLNK(fm[i]))
2298             {
2299               info.digest = 0;
2300               if (!lt)
2301                 {
2302                   lt = headstringarray(rpmhead, TAG_FILELINKTOS, &cnt2);
2303                   if (cnt != cnt2)
2304                     lt = solv_free(lt);
2305                 }
2306               if (lt)
2307                 {
2308                   linkhash(lt[i], md5);
2309                   info.digest = md5;
2310                 }
2311             }
2312           if (!info.digest)
2313             {
2314               sprintf(md5, "%08x%08x%08x%08x", (fm[i] >> 12) & 65535, 0, 0, 0);
2315               info.digest = md5;
2316             }
2317         }
2318       if (co)
2319         info.color = co[i];
2320       (*cb)(cbdata, space, &info);
2321     }
2322   solv_free(space);
2323   solv_free(lt);
2324   solv_free(md);
2325   solv_free(fm);
2326   solv_free(di);
2327   solv_free(bn);
2328   solv_free(dn);
2329   solv_free(co);
2330   solv_free(ff);
2331 }
2332
2333 char *
2334 rpm_query(void *rpmhandle, Id what)
2335 {
2336   const char *name, *arch, *sourcerpm;
2337   char *evr, *r;
2338   int l;
2339
2340   RpmHead *rpmhead = rpmhandle;
2341   r = 0;
2342   switch (what)
2343     {
2344     case 0:
2345       name = headstring(rpmhead, TAG_NAME);
2346       if (!name)
2347         name = "";
2348       sourcerpm = headstring(rpmhead, TAG_SOURCERPM);
2349       if (sourcerpm || (rpmhead->forcebinary && !headexists(rpmhead, TAG_SOURCEPACKAGE)))
2350         arch = headstring(rpmhead, TAG_ARCH);
2351       else
2352         {
2353           if (headexists(rpmhead, TAG_NOSOURCE) || headexists(rpmhead, TAG_NOPATCH))
2354             arch = "nosrc";
2355           else
2356             arch = "src";
2357         }
2358       if (!arch)
2359         arch = "noarch";
2360       evr = headtoevr(rpmhead);
2361       l = strlen(name) + 1 + strlen(evr ? evr : "") + 1 + strlen(arch) + 1;
2362       r = solv_malloc(l);
2363       sprintf(r, "%s-%s.%s", name, evr ? evr : "", arch);
2364       solv_free(evr);
2365       break;
2366     case SOLVABLE_NAME:
2367       name = headstring(rpmhead, TAG_NAME);
2368       r = solv_strdup(name);
2369       break;
2370     case SOLVABLE_SUMMARY:
2371       name = headstring(rpmhead, TAG_SUMMARY);
2372       r = solv_strdup(name);
2373       break;
2374     case SOLVABLE_DESCRIPTION:
2375       name = headstring(rpmhead, TAG_DESCRIPTION);
2376       r = solv_strdup(name);
2377       break;
2378     case SOLVABLE_EVR:
2379       r = headtoevr(rpmhead);
2380       break;
2381     }
2382   return r;
2383 }
2384
2385 unsigned long long
2386 rpm_query_num(void *rpmhandle, Id what, unsigned long long notfound)
2387 {
2388   RpmHead *rpmhead = rpmhandle;
2389   unsigned int u32;
2390
2391   switch (what)
2392     {
2393     case SOLVABLE_INSTALLTIME:
2394       u32 = headint32(rpmhead, TAG_INSTALLTIME);
2395       return u32 ? u32 : notfound;
2396     }
2397   return notfound;
2398 }
2399
2400 int
2401 rpm_installedrpmdbids(void *rpmstate, const char *index, const char *match, Queue *rpmdbidq)
2402 {
2403   struct rpmdbentry *entries;
2404   int nentries, i;
2405
2406   entries = getinstalledrpmdbids(rpmstate, index ? index : "Name", match, &nentries, 0);
2407   if (rpmdbidq)
2408     {
2409       queue_empty(rpmdbidq);
2410       for (i = 0; i < nentries; i++)
2411         queue_push(rpmdbidq, entries[i].rpmdbid);
2412     }
2413   solv_free(entries);
2414   return nentries;
2415 }
2416
2417 void *
2418 rpm_byrpmdbid(void *rpmstate, Id rpmdbid)
2419 {
2420   struct rpmdbstate *state = rpmstate;
2421   int r;
2422
2423   r = getrpmdbid(state, rpmdbid);
2424   if (!r)
2425     pool_error(state->pool, 0, "header #%d not in database", rpmdbid);
2426   return r <= 0 ? 0 : state->rpmhead;
2427 }
2428
2429 void *
2430 rpm_byfp(void *rpmstate, FILE *fp, const char *name)
2431 {
2432   struct rpmdbstate *state = rpmstate;
2433   /* int headerstart, headerend; */
2434   RpmHead *rpmhead;
2435   unsigned int sigdsize, sigcnt, l;
2436   unsigned char lead[4096];
2437   int forcebinary = 0;
2438
2439   if (fread(lead, 96 + 16, 1, fp) != 1 || getu32(lead) != 0xedabeedb)
2440     {
2441       pool_error(state->pool, 0, "%s: not a rpm", name);
2442       return 0;
2443     }
2444   forcebinary = lead[6] != 0 || lead[7] != 1;
2445   if (lead[78] != 0 || lead[79] != 5)
2446     {
2447       pool_error(state->pool, 0, "%s: not a V5 header", name);
2448       return 0;
2449     }
2450   if (getu32(lead + 96) != 0x8eade801)
2451     {
2452       pool_error(state->pool, 0, "%s: bad signature header", name);
2453       return 0;
2454     }
2455   sigcnt = getu32(lead + 96 + 8);
2456   sigdsize = getu32(lead + 96 + 12);
2457   if (sigcnt >= 0x100000 || sigdsize >= 0x100000)
2458     {
2459       pool_error(state->pool, 0, "%s: bad signature header", name);
2460       return 0;
2461     }
2462   sigdsize += sigcnt * 16;
2463   sigdsize = (sigdsize + 7) & ~7;
2464   /* headerstart = 96 + 16 + sigdsize; */
2465   while (sigdsize)
2466     {
2467       l = sigdsize > 4096 ? 4096 : sigdsize;
2468       if (fread(lead, l, 1, fp) != 1)
2469         {
2470           pool_error(state->pool, 0, "%s: unexpected EOF", name);
2471           return 0;
2472         }
2473       sigdsize -= l;
2474     }
2475   if (fread(lead, 16, 1, fp) != 1)
2476     {
2477       pool_error(state->pool, 0, "%s: unexpected EOF", name);
2478       return 0;
2479     }
2480   if (getu32(lead) != 0x8eade801)
2481     {
2482       pool_error(state->pool, 0, "%s: bad header", name);
2483       return 0;
2484     }
2485   sigcnt = getu32(lead + 8);
2486   sigdsize = getu32(lead + 12);
2487   if (sigcnt >= 0x100000 || sigdsize >= 0x2000000)
2488     {
2489       pool_error(state->pool, 0, "%s: bad header", name);
2490       return 0;
2491     }
2492   l = sigdsize + sigcnt * 16;
2493   /* headerend = headerstart + 16 + l; */
2494   if (l > state->rpmheadsize)
2495     {
2496       state->rpmheadsize = l + 128;
2497       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2498     }
2499   rpmhead = state->rpmhead;
2500   if (fread(rpmhead->data, l, 1, fp) != 1)
2501     {
2502       pool_error(state->pool, 0, "%s: unexpected EOF", name);
2503       return 0;
2504     }
2505   rpmhead->forcebinary = forcebinary;
2506   rpmhead->cnt = sigcnt;
2507   rpmhead->dcnt = sigdsize;
2508   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2509   return rpmhead;
2510 }
2511
2512 #ifdef ENABLE_RPMDB_BYRPMHEADER
2513
2514 void *
2515 rpm_byrpmh(void *rpmstate, Header h)
2516 {
2517   struct rpmdbstate *state = rpmstate;
2518   const unsigned char *uh;
2519   unsigned int sigdsize, sigcnt, l;
2520   RpmHead *rpmhead;
2521
2522 #ifndef RPM5
2523   uh = headerUnload(h);
2524 #else
2525   uh = headerUnload(h, NULL);
2526 #endif
2527   if (!uh)
2528     return 0;
2529   sigcnt = getu32(uh);
2530   sigdsize = getu32(uh + 4);
2531   l = sigdsize + sigcnt * 16;
2532   if (l > state->rpmheadsize)
2533     {
2534       state->rpmheadsize = l + 128;
2535       state->rpmhead = solv_realloc(state->rpmhead, sizeof(*state->rpmhead) + state->rpmheadsize);
2536     }
2537   rpmhead = state->rpmhead;
2538   memcpy(rpmhead->data, uh + 8, l - 8);
2539   free((void *)uh);
2540   rpmhead->forcebinary = 0;
2541   rpmhead->cnt = sigcnt;
2542   rpmhead->dcnt = sigdsize;
2543   rpmhead->dp = rpmhead->data + rpmhead->cnt * 16;
2544   return rpmhead;
2545 }
2546
2547 #endif
2548