Oops, rpmfiFInode() gone missing...
[platform/upstream/rpm.git] / lib / rpmfi.c
1 /** \ingroup rpmdep
2  * \file lib/rpmfi.c
3  * Routines to handle file info tag sets.
4  */
5
6 #include "system.h"
7
8 #include <rpm/rpmlog.h>
9 #include <rpm/rpmts.h>
10 #include <rpm/rpmfileutil.h>    /* XXX rpmDoDigest */
11 #include <rpm/rpmstring.h>
12 #include <rpm/rpmmacro.h>       /* XXX rpmCleanPath */
13 #include <rpm/rpmds.h>
14
15 #include "lib/rpmfi_internal.h"
16 #include "lib/rpmte_internal.h" /* relocations */
17 #include "lib/cpio.h"   /* XXX CPIO_FOO */
18 #include "lib/fsm.h"    /* XXX newFSM() */
19
20 #include "debug.h"
21
22 /*
23  * Simple and stupid string "cache."
24  * Store each unique string just once, retrieve by index value. 
25  * For data where number of unique names is typically very low,
26  * the dumb linear lookup appears to be fast enough and hash table seems
27  * like an overkill.
28  */
29 struct strcache_s {
30     char **uniq;
31     scidx_t num;
32 };
33
34 static struct strcache_s _ugcache = { NULL, 0 };
35 static strcache ugcache = &_ugcache;
36 static struct strcache_s _langcache = { NULL, 0 };
37 static strcache langcache = &_langcache;
38
39 static scidx_t strcachePut(strcache cache, const char *str)
40 {
41     int found = 0;
42     scidx_t ret;
43
44     for (scidx_t i = 0; i < cache->num; i++) {
45         if (strcmp(str, cache->uniq[i]) == 0) {
46             ret = i;
47             found = 1;
48             break;
49         }
50     }
51     if (!found) {
52         /* blow up on index wraparound */
53         assert((scidx_t)(cache->num + 1) > cache->num);
54         cache->uniq = xrealloc(cache->uniq, 
55                                 sizeof(cache->uniq) * (cache->num+1));
56         cache->uniq[cache->num] = xstrdup(str);
57         ret = cache->num;
58         cache->num++;
59     }
60     return ret;
61 }
62
63 static const char *strcacheGet(strcache cache, scidx_t idx)
64 {
65     const char *name = NULL;
66     if (idx >= 0 && idx < cache->num && cache->uniq != NULL)
67         name = cache->uniq[idx];
68     return name;
69 }
70     
71 static strcache strcacheNew(void)
72 {
73     strcache cache = xcalloc(1, sizeof(*cache));
74     return cache;
75 }
76
77 static strcache strcacheFree(strcache cache)
78 {
79     if (cache != NULL) {
80         for (scidx_t i = 0; i < cache->num; i++) {
81             free(cache->uniq[i]);
82         }
83         cache->uniq = _free(cache->uniq);
84         free(cache);
85     }
86     return NULL;
87
88
89
90 int _rpmfi_debug = 0;
91
92 rpmfi rpmfiUnlink(rpmfi fi, const char * msg)
93 {
94     if (fi == NULL) return NULL;
95 if (_rpmfi_debug && msg != NULL)
96 fprintf(stderr, "--> fi %p -- %d %s\n", fi, fi->nrefs, msg);
97     fi->nrefs--;
98     return NULL;
99 }
100
101 rpmfi rpmfiLink(rpmfi fi, const char * msg)
102 {
103     if (fi == NULL) return NULL;
104     fi->nrefs++;
105 if (_rpmfi_debug && msg != NULL)
106 fprintf(stderr, "--> fi %p ++ %d %s\n", fi, fi->nrefs, msg);
107     return fi;
108 }
109
110 rpm_count_t rpmfiFC(rpmfi fi)
111 {
112     return (fi != NULL ? fi->fc : 0);
113 }
114
115 rpm_count_t rpmfiDC(rpmfi fi)
116 {
117     return (fi != NULL ? fi->dc : 0);
118 }
119
120 #ifdef  NOTYET
121 int rpmfiDI(rpmfi fi)
122 {
123 }
124 #endif
125
126 int rpmfiFX(rpmfi fi)
127 {
128     return (fi != NULL ? fi->i : -1);
129 }
130
131 int rpmfiSetFX(rpmfi fi, int fx)
132 {
133     int i = -1;
134
135     if (fi != NULL && fx >= 0 && fx < fi->fc) {
136         i = fi->i;
137         fi->i = fx;
138         fi->j = fi->dil[fi->i];
139     }
140     return i;
141 }
142
143 int rpmfiDX(rpmfi fi)
144 {
145     return (fi != NULL ? fi->j : -1);
146 }
147
148 int rpmfiSetDX(rpmfi fi, int dx)
149 {
150     int j = -1;
151
152     if (fi != NULL && dx >= 0 && dx < fi->dc) {
153         j = fi->j;
154         fi->j = dx;
155     }
156     return j;
157 }
158
159 int rpmfiDIIndex(rpmfi fi, int dx)
160 {
161     int j = -1;
162     if (fi != NULL && dx >= 0 && dx < fi->fc) {
163         if (fi->dil != NULL)
164             j = fi->dil[dx];
165     }
166     return j;
167 }
168
169 const char * rpmfiBNIndex(rpmfi fi, int ix)
170 {
171     const char * BN = NULL;
172
173     if (fi != NULL && ix >= 0 && ix < fi->fc) {
174         if (fi->bnl != NULL)
175             BN = fi->bnl[ix];
176     }
177     return BN;
178 }
179
180 const char * rpmfiDNIndex(rpmfi fi, int jx)
181 {
182     const char * DN = NULL;
183
184     if (fi != NULL && jx >= 0 && jx < fi->dc) {
185         if (fi->dnl != NULL)
186             DN = fi->dnl[jx];
187     }
188     return DN;
189 }
190
191 const char * rpmfiFNIndex(rpmfi fi, int ix)
192 {
193     const char * FN = "";
194
195     if (fi != NULL && ix >= 0 && ix < fi->fc) {
196         char * t;
197         if (fi->fn == NULL) {
198             size_t dnlmax = 0, bnlmax = 0, len;
199             for (int i = 0; i < fi->dc; i++) {
200                 if ((len = strlen(fi->dnl[i])) > dnlmax)
201                     dnlmax = len;
202             }
203             for (int i = 0; i < fi->fc; i++) {
204                 if ((len = strlen(fi->bnl[i])) > bnlmax)
205                     bnlmax = len;
206             }
207             fi->fn = xmalloc(dnlmax + bnlmax + 1);
208         }
209         FN = t = fi->fn;
210         *t = '\0';
211         t = stpcpy(t, fi->dnl[fi->dil[ix]]);
212         t = stpcpy(t, fi->bnl[ix]);
213     }
214     return FN;
215 }
216
217 rpmfileAttrs rpmfiFFlagsIndex(rpmfi fi, int ix)
218 {
219     rpmfileAttrs FFlags = 0;
220
221     if (fi != NULL && ix >= 0 && ix < fi->fc) {
222         if (fi->fflags != NULL)
223             FFlags = fi->fflags[ix];
224     }
225     return FFlags;
226 }
227
228 rpmVerifyAttrs rpmfiVFlagsIndex(rpmfi fi, int ix)
229 {
230     rpmVerifyAttrs VFlags = 0;
231
232     if (fi != NULL && ix >= 0 && ix < fi->fc) {
233         if (fi->vflags != NULL)
234             VFlags = fi->vflags[ix];
235     }
236     return VFlags;
237 }
238
239 rpm_mode_t rpmfiFModeIndex(rpmfi fi, int ix)
240 {
241     rpm_mode_t fmode = 0;
242
243     if (fi != NULL && ix >= 0 && ix < fi->fc) {
244         if (fi->fmodes != NULL)
245             fmode = fi->fmodes[ix];
246     }
247     return fmode;
248 }
249
250 rpmfileState rpmfiFStateIndex(rpmfi fi, int ix)
251 {
252     rpmfileState fstate = RPMFILE_STATE_MISSING;
253
254     if (fi != NULL && ix >= 0 && ix < fi->fc) {
255         if (fi->fstates != NULL)
256             fstate = fi->fstates[ix];
257     }
258     return fstate;
259 }
260
261 const unsigned char * rpmfiMD5(rpmfi fi)
262 {
263     const unsigned char *digest;
264     pgpHashAlgo algo = 0;
265
266     digest = rpmfiFDigest(fi, &algo, NULL);
267     return (algo == PGPHASHALGO_MD5) ? digest : NULL;
268 }
269
270 pgpHashAlgo rpmfiDigestAlgo(rpmfi fi)
271 {
272     return fi ? fi->digestalgo : 0;
273 }
274
275 const unsigned char * rpmfiFDigestIndex(rpmfi fi, int ix, pgpHashAlgo *algo, size_t *len)
276 {
277     const unsigned char *digest = NULL;
278
279     if (fi != NULL && ix >= 0 && ix < fi->fc) {
280         size_t diglen = rpmDigestLength(fi->digestalgo);
281         if (fi->digests != NULL)
282             digest = fi->digests + (diglen * ix);
283         if (len) 
284             *len = diglen;
285         if (algo) 
286             *algo = fi->digestalgo;
287     }
288     return digest;
289 }
290
291 char * rpmfiFDigestHex(rpmfi fi, pgpHashAlgo *algo)
292 {
293     size_t diglen = 0;
294     char *fdigest = NULL;
295     const unsigned char *digest = rpmfiFDigest(fi, algo, &diglen);
296     if (digest) {
297         fdigest = pgpHexStr(digest, diglen);
298     }
299     return fdigest;
300 }
301
302 const char * rpmfiFLinkIndex(rpmfi fi, int ix)
303 {
304     const char * flink = NULL;
305
306     if (fi != NULL && ix >= 0 && ix < fi->fc) {
307         if (fi->flinks != NULL)
308             flink = strcacheGet(fi->flinkcache, fi->flinks[ix]);
309     }
310     return flink;
311 }
312
313 rpm_loff_t rpmfiFSizeIndex(rpmfi fi, int ix)
314 {
315     rpm_loff_t fsize = 0;
316
317     if (fi != NULL && ix >= 0 && ix < fi->fc) {
318         if (fi->fsizes != NULL)
319             fsize = fi->fsizes[ix];
320     }
321     return fsize;
322 }
323
324 rpm_rdev_t rpmfiFRdevIndex(rpmfi fi, int ix)
325 {
326     rpm_rdev_t frdev = 0;
327
328     if (fi != NULL && ix >= 0 && ix < fi->fc) {
329         if (fi->frdevs != NULL)
330             frdev = fi->frdevs[ix];
331     }
332     return frdev;
333 }
334
335 rpm_ino_t rpmfiFInodeIndex(rpmfi fi, int ix)
336 {
337     rpm_ino_t finode = 0;
338
339     if (fi != NULL && ix >= 0 && ix < fi->fc) {
340         if (fi->finodes != NULL)
341             finode = fi->finodes[ix];
342     }
343     return finode;
344 }
345
346 rpm_color_t rpmfiColor(rpmfi fi)
347 {
348     rpm_color_t color = 0;
349
350     if (fi != NULL && fi->fcolors != NULL) {
351         for (int i = 0; i < fi->fc; i++)
352             color |= fi->fcolors[i];
353         /* XXX ignore all but lsnibble for now. */
354         color &= 0xf;
355     }
356     return color;
357 }
358
359 rpm_color_t rpmfiFColorIndex(rpmfi fi, int ix)
360 {
361     rpm_color_t fcolor = 0;
362
363     if (fi != NULL && ix >= 0 && ix < fi->fc) {
364         if (fi->fcolors != NULL)
365             /* XXX ignore all but lsnibble for now. */
366             fcolor = (fi->fcolors[ix] & 0x0f);
367     }
368     return fcolor;
369 }
370
371 const char * rpmfiFClassIndex(rpmfi fi, int ix)
372 {
373     const char * fclass = NULL;
374     int cdictx;
375
376     if (fi != NULL && fi->fcdictx != NULL && ix >= 0 && ix < fi->fc) {
377         cdictx = fi->fcdictx[ix];
378         if (fi->cdict != NULL && cdictx >= 0 && cdictx < fi->ncdict)
379             fclass = fi->cdict[cdictx];
380     }
381     return fclass;
382 }
383
384 uint32_t rpmfiFDependsIndex(rpmfi fi, int ix, const uint32_t ** fddictp)
385 {
386     int fddictx = -1;
387     int fddictn = 0;
388     const uint32_t * fddict = NULL;
389
390     if (fi != NULL && ix >= 0 && ix < fi->fc) {
391         if (fi->fddictn != NULL)
392             fddictn = fi->fddictn[ix];
393         if (fddictn > 0 && fi->fddictx != NULL)
394             fddictx = fi->fddictx[ix];
395         if (fi->ddict != NULL && fddictx >= 0 && (fddictx+fddictn) <= fi->nddict)
396             fddict = fi->ddict + fddictx;
397     }
398     if (fddictp)
399         *fddictp = fddict;
400     return fddictn;
401 }
402
403 uint32_t rpmfiFNlinkIndex(rpmfi fi, int ix)
404 {
405     uint32_t nlink = 0;
406
407     if (fi != NULL && ix >= 0 && ix < fi->fc) {
408         /* XXX rpm-2.3.12 has not RPMTAG_FILEINODES */
409         if (fi->finodes && fi->frdevs) {
410             rpm_ino_t finode = fi->finodes[ix];
411             rpm_rdev_t frdev = fi->frdevs[ix];
412             int j;
413
414             for (j = 0; j < fi->fc; j++) {
415                 if (fi->frdevs[j] == frdev && fi->finodes[j] == finode)
416                     nlink++;
417             }
418         }
419     }
420     return nlink;
421 }
422
423 rpm_time_t rpmfiFMtimeIndex(rpmfi fi, int ix)
424 {
425     rpm_time_t fmtime = 0;
426
427     if (fi != NULL && ix >= 0 && ix < fi->fc) {
428         if (fi->fmtimes != NULL)
429             fmtime = fi->fmtimes[ix];
430     }
431     return fmtime;
432 }
433
434 const char * rpmfiFUserIndex(rpmfi fi, int ix)
435 {
436     const char * fuser = NULL;
437
438     if (fi != NULL && ix >= 0 && ix < fi->fc) {
439         if (fi->fuser != NULL)
440             fuser = strcacheGet(ugcache, fi->fuser[ix]);
441     }
442     return fuser;
443 }
444
445 const char * rpmfiFGroupIndex(rpmfi fi, int ix)
446 {
447     const char * fgroup = NULL;
448
449     if (fi != NULL && ix >= 0 && ix < fi->fc) {
450         if (fi->fgroup != NULL)
451             fgroup = strcacheGet(ugcache, fi->fgroup[ix]);
452     }
453     return fgroup;
454 }
455
456 const char * rpmfiFCapsIndex(rpmfi fi, int ix)
457 {
458     const char *fcaps = NULL;
459     if (fi != NULL && ix >= 0 && ix < fi->fc) {
460         fcaps = fi->fcaps ? fi->fcaps[ix] : "";
461     }
462     return fcaps;
463 }
464
465 const char * rpmfiFLangsIndex(rpmfi fi, int ix)
466 {
467     const char *flangs = NULL;
468     if (fi != NULL && fi->flangs != NULL && ix >= 0 && ix < fi->fc) {
469         flangs = strcacheGet(langcache, fi->flangs[ix]);
470     }
471     return flangs;
472 }
473
474 int rpmfiNext(rpmfi fi)
475 {
476     int i = -1;
477
478     if (fi != NULL && ++fi->i >= 0) {
479         if (fi->i < fi->fc) {
480             i = fi->i;
481             if (fi->dil != NULL)
482                 fi->j = fi->dil[fi->i];
483         } else
484             fi->i = -1;
485
486 if (_rpmfi_debug  < 0 && i != -1)
487 fprintf(stderr, "*** fi %p\t%s[%d] %s%s\n", fi, (fi->Type ? fi->Type : "?Type?"), i, (i >= 0 ? fi->dnl[fi->j] : ""), (i >= 0 ? fi->bnl[fi->i] : ""));
488
489     }
490
491     return i;
492 }
493
494 rpmfi rpmfiInit(rpmfi fi, int fx)
495 {
496     if (fi != NULL) {
497         if (fx >= 0 && fx < fi->fc) {
498             fi->i = fx - 1;
499             fi->j = -1;
500         }
501     }
502
503     return fi;
504 }
505
506 int rpmfiNextD(rpmfi fi)
507 {
508     int j = -1;
509
510     if (fi != NULL && ++fi->j >= 0) {
511         if (fi->j < fi->dc)
512             j = fi->j;
513         else
514             fi->j = -1;
515
516 if (_rpmfi_debug  < 0 && j != -1)
517 fprintf(stderr, "*** fi %p\t%s[%d]\n", fi, (fi->Type ? fi->Type : "?Type?"), j);
518
519     }
520
521     return j;
522 }
523
524 rpmfi rpmfiInitD(rpmfi fi, int dx)
525 {
526     if (fi != NULL) {
527         if (dx >= 0 && dx < fi->fc)
528             fi->j = dx - 1;
529         else
530             fi = NULL;
531     }
532
533     return fi;
534 }
535
536 /**
537  * Identify a file type.
538  * @param ft            file type
539  * @return              string to identify a file type
540  */
541 static
542 const char * ftstring (rpmFileTypes ft)
543 {
544     switch (ft) {
545     case XDIR:  return "directory";
546     case CDEV:  return "char dev";
547     case BDEV:  return "block dev";
548     case LINK:  return "link";
549     case SOCK:  return "sock";
550     case PIPE:  return "fifo/pipe";
551     case REG:   return "file";
552     default:    return "unknown file type";
553     }
554 }
555
556 rpmFileTypes rpmfiWhatis(rpm_mode_t mode)
557 {
558     if (S_ISDIR(mode))  return XDIR;
559     if (S_ISCHR(mode))  return CDEV;
560     if (S_ISBLK(mode))  return BDEV;
561     if (S_ISLNK(mode))  return LINK;
562     if (S_ISSOCK(mode)) return SOCK;
563     if (S_ISFIFO(mode)) return PIPE;
564     return REG;
565 }
566
567 int rpmfiCompare(const rpmfi afi, const rpmfi bfi)
568 {
569     rpmFileTypes awhat = rpmfiWhatis(rpmfiFMode(afi));
570     rpmFileTypes bwhat = rpmfiWhatis(rpmfiFMode(bfi));
571
572     if ((rpmfiFFlags(afi) & RPMFILE_GHOST) ||
573         (rpmfiFFlags(bfi) & RPMFILE_GHOST)) return 0;
574
575     if (awhat != bwhat) return 1;
576
577     if (awhat == LINK) {
578         const char * alink = rpmfiFLink(afi);
579         const char * blink = rpmfiFLink(bfi);
580         if (alink == blink) return 0;
581         if (alink == NULL) return 1;
582         if (blink == NULL) return -1;
583         return strcmp(alink, blink);
584     } else if (awhat == REG) {
585         size_t adiglen, bdiglen;
586         pgpHashAlgo aalgo, balgo;
587         const unsigned char * adigest = rpmfiFDigest(afi, &aalgo, &adiglen);
588         const unsigned char * bdigest = rpmfiFDigest(bfi, &balgo, &bdiglen);
589         if (adigest == bdigest) return 0;
590         if (adigest == NULL) return 1;
591         if (bdigest == NULL) return -1;
592         /* can't meaningfully compare different hash types */
593         if (aalgo != balgo || adiglen != bdiglen) return -1;
594         return memcmp(adigest, bdigest, adiglen);
595     }
596
597     return 0;
598 }
599
600 rpmFileAction rpmfiDecideFate(const rpmfi ofi, rpmfi nfi, int skipMissing)
601 {
602     const char * fn = rpmfiFN(nfi);
603     rpmfileAttrs newFlags = rpmfiFFlags(nfi);
604     char buffer[1024];
605     rpmFileTypes dbWhat, newWhat, diskWhat;
606     struct stat sb;
607     int save = (newFlags & RPMFILE_NOREPLACE) ? FA_ALTNAME : FA_SAVE;
608
609     if (lstat(fn, &sb)) {
610         /*
611          * The file doesn't exist on the disk. Create it unless the new
612          * package has marked it as missingok, or allfiles is requested.
613          */
614         if (skipMissing && (newFlags & RPMFILE_MISSINGOK)) {
615             rpmlog(RPMLOG_DEBUG, "%s skipped due to missingok flag\n",
616                         fn);
617             return FA_SKIP;
618         } else {
619             return FA_CREATE;
620         }
621     }
622
623     diskWhat = rpmfiWhatis((rpm_mode_t)sb.st_mode);
624     dbWhat = rpmfiWhatis(rpmfiFMode(ofi));
625     newWhat = rpmfiWhatis(rpmfiFMode(nfi));
626
627     /*
628      * RPM >= 2.3.10 shouldn't create config directories -- we'll ignore
629      * them in older packages as well.
630      */
631     if (newWhat == XDIR)
632         return FA_CREATE;
633
634     if (diskWhat != newWhat && dbWhat != REG && dbWhat != LINK)
635         return save;
636     else if (newWhat != dbWhat && diskWhat != dbWhat)
637         return save;
638     else if (dbWhat != newWhat)
639         return FA_CREATE;
640     else if (dbWhat != LINK && dbWhat != REG)
641         return FA_CREATE;
642
643     /*
644      * This order matters - we'd prefer to CREATE the file if at all
645      * possible in case something else (like the timestamp) has changed.
646      */
647     memset(buffer, 0, sizeof(buffer));
648     if (dbWhat == REG) {
649         pgpHashAlgo oalgo, nalgo;
650         size_t odiglen, ndiglen;
651         const unsigned char * odigest, * ndigest;
652         odigest = rpmfiFDigest(ofi, &oalgo, &odiglen);
653         if (diskWhat == REG) {
654             if (rpmDoDigest(oalgo, fn, 0, 
655                 (unsigned char *)buffer, NULL))
656                 return FA_CREATE;       /* assume file has been removed */
657             if (odigest && !memcmp(odigest, buffer, odiglen))
658                 return FA_CREATE;       /* unmodified config file, replace. */
659         }
660         ndigest = rpmfiFDigest(nfi, &nalgo, &ndiglen);
661         /* XXX can't compare different hash types, what should we do here? */
662         if (oalgo != nalgo || odiglen != ndiglen)
663             return FA_CREATE;
664         if (odigest && ndigest && !memcmp(odigest, ndigest, odiglen))
665             return FA_SKIP;     /* identical file, don't bother. */
666     } else /* dbWhat == LINK */ {
667         const char * oFLink, * nFLink;
668         oFLink = rpmfiFLink(ofi);
669         if (diskWhat == LINK) {
670             if (readlink(fn, buffer, sizeof(buffer) - 1) == -1)
671                 return FA_CREATE;       /* assume file has been removed */
672             if (oFLink && !strcmp(oFLink, buffer))
673                 return FA_CREATE;       /* unmodified config file, replace. */
674         }
675         nFLink = rpmfiFLink(nfi);
676         if (oFLink && nFLink && !strcmp(oFLink, nFLink))
677             return FA_SKIP;     /* identical file, don't bother. */
678     }
679
680     /*
681      * The config file on the disk has been modified, but
682      * the ones in the two packages are different. It would
683      * be nice if RPM was smart enough to at least try and
684      * merge the difference ala CVS, but...
685      */
686     return save;
687 }
688
689 int rpmfiConfigConflict(const rpmfi fi)
690 {
691     const char * fn = rpmfiFN(fi);
692     rpmfileAttrs flags = rpmfiFFlags(fi);
693     char buffer[1024];
694     rpmFileTypes newWhat, diskWhat;
695     struct stat sb;
696
697     if (!(flags & RPMFILE_CONFIG) || lstat(fn, &sb)) {
698         return 0;
699     }
700
701     diskWhat = rpmfiWhatis((rpm_mode_t)sb.st_mode);
702     newWhat = rpmfiWhatis(rpmfiFMode(fi));
703
704     if (newWhat != LINK && newWhat != REG)
705         return 1;
706
707     if (diskWhat != newWhat)
708         return 1;
709     
710     memset(buffer, 0, sizeof(buffer));
711     if (newWhat == REG) {
712         pgpHashAlgo algo;
713         size_t diglen;
714         const unsigned char *ndigest = rpmfiFDigest(fi, &algo, &diglen);
715         if (rpmDoDigest(algo, fn, 0, (unsigned char *)buffer, NULL))
716             return 0;   /* assume file has been removed */
717         if (ndigest && !memcmp(ndigest, buffer, diglen))
718             return 0;   /* unmodified config file */
719     } else /* newWhat == LINK */ {
720         const char * nFLink;
721         if (readlink(fn, buffer, sizeof(buffer) - 1) == -1)
722             return 0;   /* assume file has been removed */
723         nFLink = rpmfiFLink(fi);
724         if (nFLink && !strcmp(nFLink, buffer))
725             return 0;   /* unmodified config file */
726     }
727
728     return 1;
729 }
730
731 static char **duparray(char ** src, int size)
732 {
733     char **dest = xmalloc((size+1) * sizeof(*dest));
734     for (int i = 0; i < size; i++) {
735         dest[i] = xstrdup(src[i]);
736     }
737     free(src);
738     return dest;
739 }
740
741 /**
742  * Relocate files in header.
743  * @todo multilib file dispositions need to be checked.
744  * @param ts            transaction set
745  * @param fi            transaction element file info
746  * @param origH         package header
747  * @return              header with relocated files
748  */
749 static
750 Header relocateFileList(const rpmts ts, rpmfi fi,
751                 Header origH)
752 {
753     rpmte p = rpmtsRelocateElement(ts);
754     static int _printed = 0;
755     int allowBadRelocate = (rpmtsFilterFlags(ts) & RPMPROB_FILTER_FORCERELOCATE);
756     rpmRelocation * relocations = NULL;
757     int numRelocations;
758     char ** baseNames;
759     char ** dirNames;
760     uint32_t * dirIndexes;
761     uint32_t * newDirIndexes;
762     rpm_count_t fileCount, dirCount, numValid = 0;
763     rpm_color_t * fColors = NULL;
764     rpm_color_t * dColors = NULL;
765     rpm_mode_t * fModes = NULL;
766     Header h;
767     int nrelocated = 0;
768     int fileAlloced = 0;
769     char * fn = NULL;
770     int haveRelocatedBase = 0;
771     int reldel = 0;
772     int len;
773     int i, j;
774     struct rpmtd_s validRelocs;
775     struct rpmtd_s bnames, dnames, dindexes, fcolors, fmodes;
776
777     
778     if (headerGet(origH, RPMTAG_PREFIXES, &validRelocs, HEADERGET_MINMEM)) 
779         numValid = rpmtdCount(&validRelocs);
780
781 assert(p != NULL);
782     numRelocations = 0;
783     if (p->relocs)
784         while (p->relocs[numRelocations].newPath ||
785                p->relocs[numRelocations].oldPath)
786             numRelocations++;
787
788     /*
789      * If no relocations are specified (usually the case), then return the
790      * original header. If there are prefixes, however, then INSTPREFIXES
791      * should be added, but, since relocateFileList() can be called more
792      * than once for the same header, don't bother if already present.
793      */
794     if (p->relocs == NULL || numRelocations == 0) {
795         if (numValid) {
796             if (!headerIsEntry(origH, RPMTAG_INSTPREFIXES)) {
797                 rpmtdSetTag(&validRelocs, RPMTAG_INSTPREFIXES);
798                 headerPut(origH, &validRelocs, HEADERPUT_DEFAULT);
799             }
800             rpmtdFreeData(&validRelocs);
801         }
802         /* XXX FIXME multilib file actions need to be checked. */
803         return headerLink(origH);
804     }
805
806     h = headerLink(origH);
807
808     relocations = xmalloc(sizeof(*relocations) * numRelocations);
809
810     /* Build sorted relocation list from raw relocations. */
811     for (i = 0; i < numRelocations; i++) {
812         char * t;
813
814         /*
815          * Default relocations (oldPath == NULL) are handled in the UI,
816          * not rpmlib.
817          */
818         if (p->relocs[i].oldPath == NULL) continue; /* XXX can't happen */
819
820         /* FIXME: Trailing /'s will confuse us greatly. Internal ones will 
821            too, but those are more trouble to fix up. :-( */
822         t = xstrdup(p->relocs[i].oldPath);
823         relocations[i].oldPath = (t[0] == '/' && t[1] == '\0')
824             ? t
825             : stripTrailingChar(t, '/');
826
827         /* An old path w/o a new path is valid, and indicates exclusion */
828         if (p->relocs[i].newPath) {
829             int del;
830             int valid = 0;
831             const char *validprefix;
832
833             t = xstrdup(p->relocs[i].newPath);
834             relocations[i].newPath = (t[0] == '/' && t[1] == '\0')
835                 ? t
836                 : stripTrailingChar(t, '/');
837
838                 /* FIX:  relocations[i].oldPath == NULL */
839             /* Verify that the relocation's old path is in the header. */
840             rpmtdInit(&validRelocs);
841             while ((validprefix = rpmtdNextString(&validRelocs))) {
842                 if (strcmp(validprefix, relocations[i].oldPath) == 0) {
843                     valid = 1;
844                     break;
845                 }
846             }
847
848             if (!valid && !allowBadRelocate) {
849                 rpmps ps = rpmtsProblems(ts);
850                 rpmpsAppend(ps, RPMPROB_BADRELOCATE,
851                         rpmteNEVRA(p), rpmteKey(p),
852                         relocations[i].oldPath, NULL, NULL, 0);
853                 ps = rpmpsFree(ps);
854             }
855             del =
856                 strlen(relocations[i].newPath) - strlen(relocations[i].oldPath);
857
858             if (del > reldel)
859                 reldel = del;
860         } else {
861             relocations[i].newPath = NULL;
862         }
863     }
864
865     /* stupid bubble sort, but it's probably faster here */
866     for (i = 0; i < numRelocations; i++) {
867         int madeSwap;
868         madeSwap = 0;
869         for (j = 1; j < numRelocations; j++) {
870             rpmRelocation tmpReloc;
871             if (relocations[j - 1].oldPath == NULL || /* XXX can't happen */
872                 relocations[j    ].oldPath == NULL || /* XXX can't happen */
873         strcmp(relocations[j - 1].oldPath, relocations[j].oldPath) <= 0)
874                 continue;
875             /* LCL: ??? */
876             tmpReloc = relocations[j - 1];
877             relocations[j - 1] = relocations[j];
878             relocations[j] = tmpReloc;
879             madeSwap = 1;
880         }
881         if (!madeSwap) break;
882     }
883
884     if (!_printed) {
885         _printed = 1;
886         rpmlog(RPMLOG_DEBUG, "========== relocations\n");
887         for (i = 0; i < numRelocations; i++) {
888             if (relocations[i].oldPath == NULL) continue; /* XXX can't happen */
889             if (relocations[i].newPath == NULL)
890                 rpmlog(RPMLOG_DEBUG, "%5d exclude  %s\n",
891                         i, relocations[i].oldPath);
892             else
893                 rpmlog(RPMLOG_DEBUG, "%5d relocate %s -> %s\n",
894                         i, relocations[i].oldPath, relocations[i].newPath);
895         }
896     }
897
898     /* Add relocation values to the header */
899     if (numValid) {
900         const char *validprefix;
901         const char ** actualRelocations;
902         rpm_count_t numActual;
903
904         actualRelocations = xmalloc(numValid * sizeof(*actualRelocations));
905         numActual = 0;
906         rpmtdInit(&validRelocs);
907         while ((validprefix = rpmtdNextString(&validRelocs))) {
908             for (j = 0; j < numRelocations; j++) {
909                 if (relocations[j].oldPath == NULL || /* XXX can't happen */
910                     strcmp(validprefix, relocations[j].oldPath))
911                     continue;
912                 /* On install, a relocate to NULL means skip the path. */
913                 if (relocations[j].newPath) {
914                     actualRelocations[numActual] = relocations[j].newPath;
915                     numActual++;
916                 }
917                 break;
918             }
919             if (j == numRelocations) {
920                 actualRelocations[numActual] = validprefix;
921                 numActual++;
922             }
923         }
924
925         if (numActual) {
926             headerPutStringArray(h, RPMTAG_INSTPREFIXES,
927                                      actualRelocations, numActual);
928         }
929
930         actualRelocations = _free(actualRelocations);
931         rpmtdFreeData(&validRelocs);
932     }
933
934     headerGet(h, RPMTAG_BASENAMES, &bnames, fi->scareFlags);
935     headerGet(h, RPMTAG_DIRINDEXES, &dindexes, fi->scareFlags);
936     headerGet(h, RPMTAG_DIRNAMES, &dnames, fi->scareFlags);
937     headerGet(h, RPMTAG_FILECOLORS, &fcolors, fi->scareFlags);
938     headerGet(h, RPMTAG_FILEMODES, &fmodes, fi->scareFlags);
939     /* TODO XXX ugh.. use rpmtd iterators & friends instead */
940     baseNames = bnames.data;
941     dirIndexes = dindexes.data;
942     fColors = fcolors.data;
943     fModes = fmodes.data;
944     fileCount = rpmtdCount(&bnames);
945     dirCount = rpmtdCount(&dnames);
946     /* XXX TODO: use rpmtdDup() instead */
947     dirNames = dnames.data = duparray(dnames.data, dirCount);
948     dnames.flags |= RPMTD_PTR_ALLOCED;
949
950     dColors = xcalloc(dirCount, sizeof(*dColors));
951
952     newDirIndexes = xmalloc(sizeof(*newDirIndexes) * fileCount);
953     memcpy(newDirIndexes, dirIndexes, sizeof(*newDirIndexes) * fileCount);
954     dirIndexes = newDirIndexes;
955
956     /*
957      * For all relocations, we go through sorted file/relocation lists 
958      * backwards so that /usr/local relocations take precedence over /usr 
959      * ones.
960      */
961
962     /* Relocate individual paths. */
963
964     for (i = fileCount - 1; i >= 0; i--) {
965         rpmFileTypes ft;
966         int fnlen;
967
968         len = reldel +
969                 strlen(dirNames[dirIndexes[i]]) + strlen(baseNames[i]) + 1;
970         if (len >= fileAlloced) {
971             fileAlloced = len * 2;
972             fn = xrealloc(fn, fileAlloced);
973         }
974
975 assert(fn != NULL);             /* XXX can't happen */
976         *fn = '\0';
977         fnlen = stpcpy( stpcpy(fn, dirNames[dirIndexes[i]]), baseNames[i]) - fn;
978
979 if (fColors != NULL) {
980 /* XXX pkgs may not have unique dirNames, so color all dirNames that match. */
981 for (j = 0; j < dirCount; j++) {
982 if (strcmp(dirNames[dirIndexes[i]], dirNames[j])) continue;
983 dColors[j] |= fColors[i];
984 }
985 }
986
987         /*
988          * See if this file path needs relocating.
989          */
990         /*
991          * XXX FIXME: Would a bsearch of the (already sorted) 
992          * relocation list be a good idea?
993          */
994         for (j = numRelocations - 1; j >= 0; j--) {
995             if (relocations[j].oldPath == NULL) /* XXX can't happen */
996                 continue;
997             len = strcmp(relocations[j].oldPath, "/")
998                 ? strlen(relocations[j].oldPath)
999                 : 0;
1000
1001             if (fnlen < len)
1002                 continue;
1003             /*
1004              * Only subdirectories or complete file paths may be relocated. We
1005              * don't check for '\0' as our directory names all end in '/'.
1006              */
1007             if (!(fn[len] == '/' || fnlen == len))
1008                 continue;
1009
1010             if (strncmp(relocations[j].oldPath, fn, len))
1011                 continue;
1012             break;
1013         }
1014         if (j < 0) continue;
1015
1016 /* FIX: fModes may be NULL */
1017         ft = rpmfiWhatis(fModes[i]);
1018
1019         /* On install, a relocate to NULL means skip the path. */
1020         if (relocations[j].newPath == NULL) {
1021             if (ft == XDIR) {
1022                 /* Start with the parent, looking for directory to exclude. */
1023                 for (j = dirIndexes[i]; j < dirCount; j++) {
1024                     len = strlen(dirNames[j]) - 1;
1025                     while (len > 0 && dirNames[j][len-1] == '/') len--;
1026                     if (fnlen != len)
1027                         continue;
1028                     if (strncmp(fn, dirNames[j], fnlen))
1029                         continue;
1030                     break;
1031                 }
1032             }
1033             rpmfsSetAction(rpmteGetFileStates(p), i, FA_SKIPNSTATE);
1034             rpmlog(RPMLOG_DEBUG, "excluding %s %s\n",
1035                    ftstring(ft), fn);
1036             continue;
1037         }
1038
1039         /* Relocation on full paths only, please. */
1040         if (fnlen != len) continue;
1041
1042         rpmlog(RPMLOG_DEBUG, "relocating %s to %s\n",
1043                fn, relocations[j].newPath);
1044         nrelocated++;
1045
1046         strcpy(fn, relocations[j].newPath);
1047         {   char * te = strrchr(fn, '/');
1048             if (te) {
1049                 if (te > fn) te++;      /* root is special */
1050                 fnlen = te - fn;
1051             } else
1052                 te = fn + strlen(fn);
1053             if (strcmp(baseNames[i], te)) { /* basename changed too? */
1054                 if (!haveRelocatedBase) {
1055                     /* XXX TODO: use rpmtdDup() instead */
1056                     bnames.data = baseNames = duparray(baseNames, fileCount);
1057                     bnames.flags |= RPMTD_PTR_ALLOCED;
1058                     haveRelocatedBase = 1;
1059                 }
1060                 free(baseNames[i]);
1061                 baseNames[i] = xstrdup(te);
1062             }
1063             *te = '\0';                 /* terminate new directory name */
1064         }
1065
1066         /* Does this directory already exist in the directory list? */
1067         for (j = 0; j < dirCount; j++) {
1068             if (fnlen != strlen(dirNames[j]))
1069                 continue;
1070             if (strncmp(fn, dirNames[j], fnlen))
1071                 continue;
1072             break;
1073         }
1074         
1075         if (j < dirCount) {
1076             dirIndexes[i] = j;
1077             continue;
1078         }
1079
1080         /* Creating new paths is a pita */
1081         dirNames = dnames.data = xrealloc(dnames.data, 
1082                                sizeof(*dirNames) * (dirCount + 1));
1083
1084         dirNames[dirCount] = xstrdup(fn);
1085         dirIndexes[i] = dirCount;
1086         dirCount++;
1087         dnames.count++;
1088     }
1089
1090     /* Finish off by relocating directories. */
1091     for (i = dirCount - 1; i >= 0; i--) {
1092         for (j = numRelocations - 1; j >= 0; j--) {
1093
1094             if (relocations[j].oldPath == NULL) /* XXX can't happen */
1095                 continue;
1096             len = strcmp(relocations[j].oldPath, "/")
1097                 ? strlen(relocations[j].oldPath)
1098                 : 0;
1099
1100             if (len && strncmp(relocations[j].oldPath, dirNames[i], len))
1101                 continue;
1102
1103             /*
1104              * Only subdirectories or complete file paths may be relocated. We
1105              * don't check for '\0' as our directory names all end in '/'.
1106              */
1107             if (dirNames[i][len] != '/')
1108                 continue;
1109
1110             if (relocations[j].newPath) { /* Relocate the path */
1111                 char *t = NULL;
1112                 rstrscat(&t, relocations[j].newPath, (dirNames[i] + len), NULL);
1113                 /* Unfortunatly rpmCleanPath strips the trailing slash.. */
1114                 (void) rpmCleanPath(t);
1115                 rstrcat(&t, "/");
1116
1117                 rpmlog(RPMLOG_DEBUG,
1118                        "relocating directory %s to %s\n", dirNames[i], t);
1119                 free(dirNames[i]);
1120                 dirNames[i] = t;
1121                 nrelocated++;
1122             }
1123         }
1124     }
1125
1126     /* Save original filenames in header and replace (relocated) filenames. */
1127     if (nrelocated) {
1128         struct rpmtd_s td;
1129
1130         headerGet(h, RPMTAG_BASENAMES, &td, HEADERGET_MINMEM);
1131         rpmtdSetTag(&td, RPMTAG_ORIGBASENAMES);
1132         headerPut(h, &td, HEADERPUT_DEFAULT);
1133         rpmtdFreeData(&td);
1134
1135         headerGet(h, RPMTAG_DIRNAMES, &td, HEADERGET_MINMEM);
1136         rpmtdSetTag(&td, RPMTAG_ORIGDIRNAMES);
1137         headerPut(h, &td, HEADERPUT_DEFAULT);
1138         rpmtdFreeData(&td);
1139
1140         headerGet(h, RPMTAG_DIRINDEXES, &td, HEADERGET_MINMEM);
1141         rpmtdSetTag(&td, RPMTAG_ORIGDIRINDEXES);
1142         headerPut(h, &td, HEADERPUT_DEFAULT);
1143         rpmtdFreeData(&td);
1144
1145         if (rpmtdFromStringArray(&td, RPMTAG_BASENAMES, (const char**) baseNames, fileCount)) {
1146             headerMod(h, &td);
1147         }
1148         free(fi->bnl);
1149         headerGet(h, RPMTAG_BASENAMES, &td, fi->scareFlags);
1150         fi->fc = rpmtdCount(&td);
1151         fi->bnl = td.data;
1152
1153         if (rpmtdFromStringArray(&td, RPMTAG_DIRNAMES, (const char**) dirNames, dirCount)) {
1154             headerMod(h, &td);
1155         }
1156         free(fi->dnl);
1157         headerGet(h, RPMTAG_DIRNAMES, &td, fi->scareFlags);
1158         fi->dc = rpmtdCount(&td);
1159         fi->dnl = td.data;
1160
1161         if (rpmtdFromUint32(&td, RPMTAG_DIRINDEXES, dirIndexes, fileCount)) {
1162             headerMod(h, &td);
1163         }
1164         headerGet(h, RPMTAG_DIRINDEXES, &td, fi->scareFlags);
1165         /* Ugh, nasty games with how dil is alloced depending on scareMem */
1166         if (fi->scareFlags & HEADERGET_ALLOC)
1167             free(fi->dil);
1168         fi->dil = td.data;
1169     }
1170
1171     rpmtdFreeData(&bnames);
1172     rpmtdFreeData(&dnames);
1173     rpmtdFreeData(&dindexes);
1174     rpmtdFreeData(&fcolors);
1175     rpmtdFreeData(&fmodes);
1176     free(fn);
1177     for (i = 0; i < numRelocations; i++) {
1178         free(relocations[i].oldPath);
1179         free(relocations[i].newPath);
1180     }
1181     free(relocations);
1182     free(newDirIndexes);
1183     free(dColors);
1184
1185     return h;
1186 }
1187
1188 rpmfi rpmfiFree(rpmfi fi)
1189 {
1190     if (fi == NULL) return NULL;
1191
1192     if (fi->nrefs > 1)
1193         return rpmfiUnlink(fi, fi->Type);
1194
1195 if (_rpmfi_debug < 0)
1196 fprintf(stderr, "*** fi %p\t%s[%d]\n", fi, fi->Type, fi->fc);
1197
1198     if (fi->fc > 0) {
1199         fi->bnl = _free(fi->bnl);
1200         fi->dnl = _free(fi->dnl);
1201
1202         fi->flinkcache = strcacheFree(fi->flinkcache);
1203         fi->flinks = _free(fi->flinks);
1204         fi->flangs = _free(fi->flangs);
1205         fi->digests = _free(fi->digests);
1206         fi->fcaps = _free(fi->fcaps);
1207
1208         fi->cdict = _free(fi->cdict);
1209
1210         fi->fuser = _free(fi->fuser);
1211         fi->fgroup = _free(fi->fgroup);
1212
1213         fi->fstates = _free(fi->fstates);
1214
1215         if (!(fi->fiflags & RPMFI_KEEPHEADER) && fi->h == NULL) {
1216             fi->fmtimes = _constfree(fi->fmtimes);
1217             fi->fmodes = _free(fi->fmodes);
1218             fi->fflags = _constfree(fi->fflags);
1219             fi->vflags = _constfree(fi->vflags);
1220             fi->fsizes = _constfree(fi->fsizes);
1221             fi->frdevs = _constfree(fi->frdevs);
1222             fi->finodes = _constfree(fi->finodes);
1223             fi->dil = _free(fi->dil);
1224
1225             fi->fcolors = _constfree(fi->fcolors);
1226             fi->fcdictx = _constfree(fi->fcdictx);
1227             fi->ddict = _constfree(fi->ddict);
1228             fi->fddictx = _constfree(fi->fddictx);
1229             fi->fddictn = _constfree(fi->fddictn);
1230
1231         }
1232     }
1233
1234     fi->fsm = freeFSM(fi->fsm);
1235
1236     fi->fn = _free(fi->fn);
1237     fi->apath = _free(fi->apath);
1238
1239     fi->replacedSizes = _free(fi->replacedSizes);
1240
1241     fi->h = headerFree(fi->h);
1242
1243     (void) rpmfiUnlink(fi, fi->Type);
1244     memset(fi, 0, sizeof(*fi));         /* XXX trash and burn */
1245     fi = _free(fi);
1246
1247     return NULL;
1248 }
1249
1250 /* Helper to push header tag data into a string cache */
1251 static scidx_t *cacheTag(strcache cache, Header h, rpmTag tag)
1252 {
1253     scidx_t *idx = NULL;
1254     struct rpmtd_s td;
1255     if (headerGet(h, tag, &td, HEADERGET_MINMEM)) {
1256        idx = xmalloc(sizeof(*idx) * rpmtdCount(&td));
1257        int i = 0;
1258        const char *str;
1259        while ((str = rpmtdNextString(&td))) {
1260            idx[i++] = strcachePut(cache, str);
1261        }
1262        rpmtdFreeData(&td);
1263     }
1264     return idx;
1265 }
1266
1267 #define _hgfi(_h, _tag, _td, _flags, _data) \
1268     if (headerGet((_h), (_tag), (_td), (_flags))) \
1269         _data = (td.data)
1270
1271 rpmfi rpmfiNew(const rpmts ts, Header h, rpmTag tagN, rpmfiFlags flags)
1272 {
1273     rpmte p;
1274     rpmfi fi = NULL;
1275     const char * Type;
1276     rpm_loff_t *asize = NULL;
1277     unsigned char * t;
1278     int isBuild, isSource;
1279     struct rpmtd_s fdigests, digalgo;
1280     struct rpmtd_s td;
1281     headerGetFlags scareFlags = (flags & RPMFI_KEEPHEADER) ? 
1282                                 HEADERGET_MINMEM : HEADERGET_ALLOC;
1283     headerGetFlags defFlags = HEADERGET_ALLOC;
1284
1285     if (tagN == RPMTAG_BASENAMES) {
1286         Type = "Files";
1287     } else {
1288         Type = "?Type?";
1289         goto exit;
1290     }
1291
1292     fi = xcalloc(1, sizeof(*fi));
1293     if (fi == NULL)     /* XXX can't happen */
1294         goto exit;
1295
1296     fi->magic = RPMFIMAGIC;
1297     fi->Type = Type;
1298     fi->i = -1;
1299     fi->tagN = tagN;
1300
1301     fi->fiflags = flags;
1302     fi->scareFlags = scareFlags;
1303
1304     fi->h = (fi->fiflags & RPMFI_KEEPHEADER) ? headerLink(h) : NULL;
1305
1306     if (headerGet(h, RPMTAG_LONGARCHIVESIZE, &td, HEADERGET_EXT)) {
1307         asize = rpmtdGetUint64(&td);
1308     }
1309     /* 0 means unknown */
1310     fi->archiveSize = asize ? *asize : 0;
1311     rpmtdFreeData(&td);
1312     
1313     /* Archive size is not set when this gets called from build */
1314     isBuild = (asize == NULL);
1315     isSource = headerIsSource(h);
1316     if (isBuild) fi->fiflags |= RPMFI_ISBUILD;
1317     if (isSource) fi->fiflags |= RPMFI_ISSOURCE;
1318
1319     _hgfi(h, RPMTAG_BASENAMES, &td, defFlags, fi->bnl);
1320     fi->fc = rpmtdCount(&td);
1321     if (fi->fc == 0) {
1322         goto exit;
1323     }
1324
1325     _hgfi(h, RPMTAG_DIRNAMES, &td, defFlags, fi->dnl);
1326     fi->dc = rpmtdCount(&td);
1327     _hgfi(h, RPMTAG_DIRINDEXES, &td, scareFlags, fi->dil);
1328     if (!(flags & RPMFI_NOFILEMODES))
1329         _hgfi(h, RPMTAG_FILEMODES, &td, scareFlags, fi->fmodes);
1330     if (!(flags & RPMFI_NOFILEFLAGS))
1331         _hgfi(h, RPMTAG_FILEFLAGS, &td, scareFlags, fi->fflags);
1332     if (!(flags & RPMFI_NOFILEVERIFYFLAGS))
1333         _hgfi(h, RPMTAG_FILEVERIFYFLAGS, &td, scareFlags, fi->vflags);
1334     if (!(flags & RPMFI_NOFILESIZES))
1335         _hgfi(h, RPMTAG_FILESIZES, &td, scareFlags, fi->fsizes);
1336
1337     if (!(flags & RPMFI_NOFILECOLORS))
1338         _hgfi(h, RPMTAG_FILECOLORS, &td, scareFlags, fi->fcolors);
1339
1340     if (!(flags & RPMFI_NOFILECLASS)) {
1341         _hgfi(h, RPMTAG_CLASSDICT, &td, scareFlags, fi->cdict);
1342         fi->ncdict = rpmtdCount(&td);
1343         _hgfi(h, RPMTAG_FILECLASS, &td, scareFlags, fi->fcdictx);
1344     }
1345     if (!(flags & RPMFI_NOFILEDEPS)) {
1346         _hgfi(h, RPMTAG_DEPENDSDICT, &td, scareFlags, fi->ddict);
1347         fi->nddict = rpmtdCount(&td);
1348         _hgfi(h, RPMTAG_FILEDEPENDSX, &td, scareFlags, fi->fddictx);
1349         _hgfi(h, RPMTAG_FILEDEPENDSN, &td, scareFlags, fi->fddictn);
1350     }
1351
1352     if (!(flags & RPMFI_NOFILESTATES))
1353         _hgfi(h, RPMTAG_FILESTATES, &td, defFlags, fi->fstates);
1354
1355     if (!(flags & RPMFI_NOFILECAPS))
1356         _hgfi(h, RPMTAG_FILECAPS, &td, defFlags, fi->fcaps);
1357
1358     if (!(flags & RPMFI_NOFILELINKTOS)) {
1359         fi->flinkcache = strcacheNew();
1360         fi->flinks = cacheTag(fi->flinkcache, h, RPMTAG_FILELINKTOS);
1361     }
1362     /* FILELANGS are only interesting when installing */
1363     if ((headerGetInstance(h) == 0) && !(flags & RPMFI_NOFILELANGS))
1364         fi->flangs = cacheTag(langcache, h, RPMTAG_FILELANGS);
1365
1366     /* See if the package has non-md5 file digests */
1367     fi->digestalgo = PGPHASHALGO_MD5;
1368     if (headerGet(h, RPMTAG_FILEDIGESTALGO, &digalgo, HEADERGET_MINMEM)) {
1369         pgpHashAlgo *algo = rpmtdGetUint32(&digalgo);
1370         /* Hmm, what to do with unknown digest algorithms? */
1371         if (algo && rpmDigestLength(*algo) != 0) {
1372             fi->digestalgo = *algo;
1373         }
1374     }
1375
1376     fi->digests = NULL;
1377     /* grab hex digests from header and store in binary format */
1378     if (!(flags & RPMFI_NOFILEDIGESTS) &&
1379         headerGet(h, RPMTAG_FILEDIGESTS, &fdigests, HEADERGET_MINMEM)) {
1380         const char *fdigest;
1381         size_t diglen = rpmDigestLength(fi->digestalgo);
1382         fi->digests = t = xmalloc(rpmtdCount(&fdigests) * diglen);
1383
1384         while ((fdigest = rpmtdNextString(&fdigests))) {
1385             if (!(fdigest && *fdigest != '\0')) {
1386                 memset(t, 0, diglen);
1387                 t += diglen;
1388                 continue;
1389             }
1390             for (int j = 0; j < diglen; j++, t++, fdigest += 2)
1391                 *t = (rnibble(fdigest[0]) << 4) | rnibble(fdigest[1]);
1392         }
1393         rpmtdFreeData(&fdigests);
1394     }
1395
1396     /* XXX TR_REMOVED doesn;t need fmtimes, frdevs, finodes */
1397     if (!(flags & RPMFI_NOFILEMTIMES))
1398         _hgfi(h, RPMTAG_FILEMTIMES, &td, scareFlags, fi->fmtimes);
1399     if (!(flags & RPMFI_NOFILERDEVS))
1400         _hgfi(h, RPMTAG_FILERDEVS, &td, scareFlags, fi->frdevs);
1401     if (!(flags & RPMFI_NOFILEINODES))
1402         _hgfi(h, RPMTAG_FILEINODES, &td, scareFlags, fi->finodes);
1403
1404     if (!(flags & RPMFI_NOFILEUSER)) 
1405         fi->fuser = cacheTag(ugcache, h, RPMTAG_FILEUSERNAME);
1406     if (!(flags & RPMFI_NOFILEGROUP)) 
1407         fi->fgroup = cacheTag(ugcache, h, RPMTAG_FILEGROUPNAME);
1408
1409     if (ts != NULL)
1410     if (fi != NULL)
1411     if ((p = rpmtsRelocateElement(ts)) != NULL && rpmteType(p) == TR_ADDED
1412      && !headerIsSource(h)
1413      && !headerIsEntry(h, RPMTAG_ORIGBASENAMES))
1414     {
1415         Header foo;
1416
1417         /* FIX: fi-digests undefined */
1418         foo = relocateFileList(ts, fi, h);
1419         fi->h = headerFree(fi->h);
1420         fi->h = headerLink(foo);
1421         foo = headerFree(foo);
1422     }
1423
1424     if (!(fi->fiflags & RPMFI_KEEPHEADER)) {
1425         fi->h = headerFree(fi->h);
1426     }
1427
1428     /* lazily alloced from rpmfiFN() */
1429     fi->fn = NULL;
1430
1431 exit:
1432 if (_rpmfi_debug < 0)
1433 fprintf(stderr, "*** fi %p\t%s[%d]\n", fi, Type, (fi ? fi->fc : 0));
1434
1435     /* FIX: rpmfi null annotations */
1436     return rpmfiLink(fi, (fi ? fi->Type : NULL));
1437 }
1438
1439 void rpmfiSetFReplacedSize(rpmfi fi, rpm_loff_t newsize)
1440 {
1441     if (fi != NULL && fi->i >= 0 && fi->i < fi->fc) {
1442         if (fi->replacedSizes == NULL) {
1443             fi->replacedSizes = xcalloc(fi->fc, sizeof(*fi->replacedSizes));
1444         }
1445         /* XXX watch out, replacedSizes is not rpm_loff_t (yet) */
1446         fi->replacedSizes[fi->i] = (rpm_off_t) newsize;
1447     }
1448 }
1449
1450 rpm_loff_t rpmfiFReplacedSize(rpmfi fi)
1451 {
1452     rpm_loff_t rsize = 0;
1453     if (fi != NULL && fi->i >= 0 && fi->i < fi->fc) {
1454         if (fi->replacedSizes) {
1455             rsize = fi->replacedSizes[fi->i];
1456         }
1457     }
1458     return rsize;
1459 }
1460
1461
1462 FSM_t rpmfiFSM(rpmfi fi)
1463 {
1464     if (fi != NULL && fi->fsm == NULL) {
1465         cpioMapFlags mapflags;
1466         /* Figure out mapflags: 
1467          * - path, mode, uid and gid are used by everything
1468          * - all binary packages get SBIT_CHECK set
1469          * - if archive size is not known, we're only building this package,
1470          *   different rules apply 
1471          */
1472         mapflags = CPIO_MAP_PATH | CPIO_MAP_MODE | CPIO_MAP_UID | CPIO_MAP_GID;
1473         if (fi->fiflags & RPMFI_ISBUILD) {
1474             mapflags |= CPIO_MAP_TYPE;
1475             if (fi->fiflags & RPMFI_ISSOURCE) mapflags |= CPIO_FOLLOW_SYMLINKS;
1476         } else {
1477             if (!(fi->fiflags & RPMFI_ISSOURCE)) mapflags |= CPIO_SBIT_CHECK;
1478         }
1479         fi->fsm = newFSM(mapflags);
1480     }
1481     return (fi != NULL) ? fi->fsm : NULL;
1482 }
1483
1484 /* 
1485  * Generate iterator accessors function wrappers, these do nothing but
1486  * call the corresponding rpmfiFooIndex(fi, fi->[ij])
1487  */
1488
1489 #define RPMFI_ITERFUNC(TYPE, NAME, IXV) \
1490     TYPE rpmfi ## NAME(rpmfi fi) { return rpmfi ## NAME ## Index(fi, fi ? fi->IXV : -1); }
1491
1492 RPMFI_ITERFUNC(const char *, BN, i)
1493 RPMFI_ITERFUNC(const char *, DN, j)
1494 RPMFI_ITERFUNC(const char *, FN, i)
1495 RPMFI_ITERFUNC(const char *, FLink, i)
1496 RPMFI_ITERFUNC(const char *, FUser, i)
1497 RPMFI_ITERFUNC(const char *, FGroup, i)
1498 RPMFI_ITERFUNC(const char *, FCaps, i)
1499 RPMFI_ITERFUNC(const char *, FLangs, i)
1500 RPMFI_ITERFUNC(const char *, FClass, i)
1501 RPMFI_ITERFUNC(rpmfileState, FState, i)
1502 RPMFI_ITERFUNC(rpmfileAttrs, FFlags, i)
1503 RPMFI_ITERFUNC(rpmVerifyAttrs, VFlags, i)
1504 RPMFI_ITERFUNC(rpm_mode_t, FMode, i)
1505 RPMFI_ITERFUNC(rpm_rdev_t, FRdev, i)
1506 RPMFI_ITERFUNC(rpm_time_t, FMtime, i)
1507 RPMFI_ITERFUNC(rpm_ino_t, FInode, i)
1508 RPMFI_ITERFUNC(rpm_loff_t, FSize, i)
1509 RPMFI_ITERFUNC(rpm_color_t, FColor, i)
1510 RPMFI_ITERFUNC(uint32_t, FNlink, i)
1511
1512 const unsigned char * rpmfiFDigest(rpmfi fi, pgpHashAlgo *algo, size_t *len)
1513 {
1514     return rpmfiFDigestIndex(fi, fi ? fi->i : -1, algo, len);
1515 }
1516
1517 uint32_t rpmfiFDepends(rpmfi fi, const uint32_t ** fddictp)
1518 {
1519     return rpmfiFDependsIndex(fi,  fi ? fi->i : -1, fddictp);
1520 }