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