Turn rpmtd freeData into flag bitfield, allowing more precise control
[platform/upstream/rpm.git] / lib / header.c
1 /** \ingroup header
2  * \file lib/header.c
3  */
4
5 /* RPM - Copyright (C) 1995-2002 Red Hat Software */
6
7 /* Data written to file descriptors is in network byte order.    */
8 /* Data read from file descriptors is expected to be in          */
9 /* network byte order and is converted on the fly to host order. */
10
11 #include "system.h"
12
13 #include <rpm/rpmtag.h>
14 #include <rpm/rpmstring.h>
15 #include "lib/header_internal.h"
16
17 #include "debug.h"
18
19 int _hdr_debug = 0;
20
21 /** \ingroup header
22  */
23 static unsigned char const header_magic[8] = {
24         0x8e, 0xad, 0xe8, 0x01, 0x00, 0x00, 0x00, 0x00
25 };
26
27 /** \ingroup header
28  * Alignment needed for header data types.
29  */
30 static const int typeAlign[16] =  {
31     1,  /*!< RPM_NULL_TYPE */
32     1,  /*!< RPM_CHAR_TYPE */
33     1,  /*!< RPM_INT8_TYPE */
34     2,  /*!< RPM_INT16_TYPE */
35     4,  /*!< RPM_INT32_TYPE */
36     8,  /*!< RPM_INT64_TYPE */
37     1,  /*!< RPM_STRING_TYPE */
38     1,  /*!< RPM_BIN_TYPE */
39     1,  /*!< RPM_STRING_ARRAY_TYPE */
40     1,  /*!< RPM_I18NSTRING_TYPE */
41     0,
42     0,
43     0,
44     0,
45     0,
46     0
47 };
48
49 /** \ingroup header
50  * Size of header data types.
51  */
52 static const int typeSizes[16] =  { 
53     0,  /*!< RPM_NULL_TYPE */
54     1,  /*!< RPM_CHAR_TYPE */
55     1,  /*!< RPM_INT8_TYPE */
56     2,  /*!< RPM_INT16_TYPE */
57     4,  /*!< RPM_INT32_TYPE */
58     -1, /*!< RPM_INT64_TYPE */
59     -1, /*!< RPM_STRING_TYPE */
60     1,  /*!< RPM_BIN_TYPE */
61     -1, /*!< RPM_STRING_ARRAY_TYPE */
62     -1, /*!< RPM_I18NSTRING_TYPE */
63     0,
64     0,
65     0,
66     0,
67     0,
68     0
69 };
70
71 /* dumb macro to avoid 50 copies of this code while converting... */
72 #define TDWRAP() \
73     if (type) \
74         *type = td.type; \
75     if (p) \
76         *p = td.data; \
77     else \
78         rpmtdFreeData(&td); \
79     if (c) \
80         *c = td.count
81
82 /** \ingroup header
83  * Maximum no. of bytes permitted in a header.
84  */
85 static const size_t headerMaxbytes = (32*1024*1024);
86
87 /** \ingroup header
88  * HEADER_EXT_TAG format function prototype.
89  * This is allowed to fail, which indicates the tag doesn't exist.
90  *
91  * @param h             header
92  * @retval td           tag data container
93  * @return              0 on success
94  */
95 typedef int (*headerTagTagFunction) (Header h, rpmtd td);
96
97 extern void *rpmHeaderTagFunc(rpmTag tag);
98
99 Header headerLink(Header h)
100 {
101     if (h == NULL) return NULL;
102
103     h->nrefs++;
104 if (_hdr_debug)
105 fprintf(stderr, "--> h  %p ++ %d at %s:%u\n", h, h->nrefs, __FILE__, __LINE__);
106
107     return h;
108 }
109
110 Header headerUnlink(Header h)
111 {
112     if (h == NULL) return NULL;
113 if (_hdr_debug)
114 fprintf(stderr, "--> h  %p -- %d at %s:%u\n", h, h->nrefs, __FILE__, __LINE__);
115     h->nrefs--;
116     return NULL;
117 }
118
119 Header headerFree(Header h)
120 {
121     (void) headerUnlink(h);
122
123     if (h == NULL || h->nrefs > 0)
124         return NULL;    /* XXX return previous header? */
125
126     if (h->index) {
127         indexEntry entry = h->index;
128         int i;
129         for (i = 0; i < h->indexUsed; i++, entry++) {
130             if ((h->flags & HEADERFLAG_ALLOCATED) && ENTRY_IS_REGION(entry)) {
131                 if (entry->length > 0) {
132                     int32_t * ei = entry->data;
133                     if ((ei - 2) == h->blob) h->blob = _free(h->blob);
134                     entry->data = NULL;
135                 }
136             } else if (!ENTRY_IN_REGION(entry)) {
137                 entry->data = _free(entry->data);
138             }
139             entry->data = NULL;
140         }
141         h->index = _free(h->index);
142     }
143
144     h = _free(h);
145     return h;
146 }
147
148 Header headerNew(void)
149 {
150     Header h = xcalloc(1, sizeof(*h));
151
152     h->blob = NULL;
153     h->indexAlloced = INDEX_MALLOC_SIZE;
154     h->indexUsed = 0;
155     h->flags |= HEADERFLAG_SORTED;
156
157     h->index = (h->indexAlloced
158         ? xcalloc(h->indexAlloced, sizeof(*h->index))
159         : NULL);
160
161     h->nrefs = 0;
162     return headerLink(h);
163 }
164
165 int headerVerifyInfo(int il, int dl, const void * pev, void * iv, int negate)
166 {
167     entryInfo pe = (entryInfo) pev;
168     entryInfo info = iv;
169     int i;
170
171     for (i = 0; i < il; i++) {
172         info->tag = ntohl(pe[i].tag);
173         info->type = ntohl(pe[i].type);
174         info->offset = ntohl(pe[i].offset);
175         if (negate)
176             info->offset = -info->offset;
177         info->count = ntohl(pe[i].count);
178
179         if (hdrchkType(info->type))
180             return i;
181         if (hdrchkAlign(info->type, info->offset))
182             return i;
183         if (!negate && hdrchkRange(dl, info->offset))
184             return i;
185         if (hdrchkData(info->count))
186             return i;
187
188     }
189     return -1;
190 }
191
192 /**
193  */
194 static int indexCmp(const void * avp, const void * bvp)
195 {
196     indexEntry ap = (indexEntry) avp, bp = (indexEntry) bvp;
197     return (ap->info.tag - bp->info.tag);
198 }
199
200 void headerSort(Header h)
201 {
202     if (!(h->flags & HEADERFLAG_SORTED)) {
203         qsort(h->index, h->indexUsed, sizeof(*h->index), indexCmp);
204         h->flags |= HEADERFLAG_SORTED;
205     }
206 }
207
208 /**
209  */
210 static int offsetCmp(const void * avp, const void * bvp) 
211 {
212     indexEntry ap = (indexEntry) avp, bp = (indexEntry) bvp;
213     int rc = (ap->info.offset - bp->info.offset);
214
215     if (rc == 0) {
216         /* Within a region, entries sort by address. Added drips sort by tag. */
217         if (ap->info.offset < 0)
218             rc = (((char *)ap->data) - ((char *)bp->data));
219         else
220             rc = (ap->info.tag - bp->info.tag);
221     }
222     return rc;
223 }
224
225 /** \ingroup header
226  * Restore tags in header to original ordering.
227  * @param h             header
228  */
229 void headerUnsort(Header h)
230 {
231     qsort(h->index, h->indexUsed, sizeof(*h->index), offsetCmp);
232 }
233
234 unsigned headerSizeof(Header h, enum hMagic magicp)
235 {
236     indexEntry entry;
237     unsigned int size = 0;
238     unsigned int pad = 0;
239     int i;
240
241     if (h == NULL)
242         return size;
243
244     headerSort(h);
245
246     switch (magicp) {
247     case HEADER_MAGIC_YES:
248         size += sizeof(header_magic);
249         break;
250     case HEADER_MAGIC_NO:
251         break;
252     }
253
254     size += 2 * sizeof(int32_t);        /* count of index entries */
255
256     for (i = 0, entry = h->index; i < h->indexUsed; i++, entry++) {
257         unsigned diff;
258         rpmTagType type;
259
260         /* Regions go in as is ... */
261         if (ENTRY_IS_REGION(entry)) {
262             size += entry->length;
263             /* XXX Legacy regions do not include the region tag and data. */
264             if (i == 0 && (h->flags & HEADERFLAG_LEGACY))
265                 size += sizeof(struct entryInfo_s) + entry->info.count;
266             continue;
267         }
268
269         /* ... and region elements are skipped. */
270         if (entry->info.offset < 0)
271             continue;
272
273         /* Alignment */
274         type = entry->info.type;
275         if (typeSizes[type] > 1) {
276             diff = typeSizes[type] - (size % typeSizes[type]);
277             if (diff != typeSizes[type]) {
278                 size += diff;
279                 pad += diff;
280             }
281         }
282
283         size += sizeof(struct entryInfo_s) + entry->length;
284     }
285
286     return size;
287 }
288
289 /**
290  * Return length of entry data.
291  * @param type          entry data type
292  * @param p             entry data
293  * @param count         entry item count
294  * @param onDisk        data is concatenated strings (with NUL's))?
295  * @param pend          pointer to end of data (or NULL)
296  * @return              no. bytes in data, -1 on failure
297  */
298 static int dataLength(rpmTagType type, rpm_constdata_t p, rpm_count_t count,
299                          int onDisk, rpm_constdata_t pend)
300 {
301     const unsigned char * s = p;
302     const unsigned char * se = pend;
303     int length = 0;
304
305     switch (type) {
306     case RPM_STRING_TYPE:
307         if (count != 1)
308             return -1;
309         while (*s++) {
310             if (se && s > se)
311                 return -1;
312             length++;
313         }
314         length++;       /* count nul terminator too. */
315         break;
316
317     case RPM_STRING_ARRAY_TYPE:
318     case RPM_I18NSTRING_TYPE:
319         /* These are like RPM_STRING_TYPE, except they're *always* an array */
320         /* Compute sum of length of all strings, including nul terminators */
321
322         if (onDisk) {
323             while (count--) {
324                 length++;       /* count nul terminator too */
325                while (*s++) {
326                     if (se && s > se)
327                         return -1;
328                     length++;
329                 }
330             }
331         } else {
332             const char ** av = (const char **)p;
333             while (count--) {
334                 /* add one for null termination */
335                 length += strlen(*av++) + 1;
336             }
337         }
338         break;
339
340     default:
341         if (typeSizes[type] == -1)
342             return -1;
343         length = typeSizes[(type & 0xf)] * count;
344         if (length < 0 || (se && (s + length) > se))
345             return -1;
346         break;
347     }
348
349     return length;
350 }
351
352 /** \ingroup header
353  * Swap int32_t and int16_t arrays within header region.
354  *
355  * This code is way more twisty than I would like.
356  *
357  * A bug with RPM_I18NSTRING_TYPE in rpm-2.5.x (fixed in August 1998)
358  * causes the offset and length of elements in a header region to disagree
359  * regarding the total length of the region data.
360  *
361  * The "fix" is to compute the size using both offset and length and
362  * return the larger of the two numbers as the size of the region.
363  * Kinda like computing left and right Riemann sums of the data elements
364  * to determine the size of a data structure, go figger :-).
365  *
366  * There's one other twist if a header region tag is in the set to be swabbed,
367  * as the data for a header region is located after all other tag data.
368  *
369  * @param entry         header entry
370  * @param il            no. of entries
371  * @param dl            start no. bytes of data
372  * @param pe            header physical entry pointer (swapped)
373  * @param dataStart     header data start
374  * @param dataEnd       header data end
375  * @param regionid      region offset
376  * @return              no. bytes of data in region, -1 on error
377  */
378 static int regionSwab(indexEntry entry, int il, int dl,
379                 entryInfo pe,
380                 unsigned char * dataStart,
381                 const unsigned char * dataEnd,
382                 int regionid)
383 {
384     unsigned char * tprev = NULL;
385     unsigned char * t = NULL;
386     int tdel = 0;
387     int tl = dl;
388     struct indexEntry_s ieprev;
389
390     memset(&ieprev, 0, sizeof(ieprev));
391     for (; il > 0; il--, pe++) {
392         struct indexEntry_s ie;
393         rpmTagType type;
394
395         ie.info.tag = ntohl(pe->tag);
396         ie.info.type = ntohl(pe->type);
397         ie.info.count = ntohl(pe->count);
398         ie.info.offset = ntohl(pe->offset);
399
400         if (hdrchkType(ie.info.type))
401             return -1;
402         if (hdrchkData(ie.info.count))
403             return -1;
404         if (hdrchkData(ie.info.offset))
405             return -1;
406         if (hdrchkAlign(ie.info.type, ie.info.offset))
407             return -1;
408
409         ie.data = t = dataStart + ie.info.offset;
410         if (dataEnd && t >= dataEnd)
411             return -1;
412
413         ie.length = dataLength(ie.info.type, ie.data, ie.info.count, 1, dataEnd);
414         if (ie.length < 0 || hdrchkData(ie.length))
415             return -1;
416
417         ie.rdlen = 0;
418
419         if (entry) {
420             ie.info.offset = regionid;
421             *entry = ie;        /* structure assignment */
422             entry++;
423         }
424
425         /* Alignment */
426         type = ie.info.type;
427         if (typeSizes[type] > 1) {
428             unsigned diff;
429             diff = typeSizes[type] - (dl % typeSizes[type]);
430             if (diff != typeSizes[type]) {
431                 dl += diff;
432                 if (ieprev.info.type == RPM_I18NSTRING_TYPE)
433                     ieprev.length += diff;
434             }
435         }
436         tdel = (tprev ? (t - tprev) : 0);
437         if (ieprev.info.type == RPM_I18NSTRING_TYPE)
438             tdel = ieprev.length;
439
440         if (ie.info.tag >= HEADER_I18NTABLE) {
441             tprev = t;
442         } else {
443             tprev = dataStart;
444             /* XXX HEADER_IMAGE tags don't include region sub-tag. */
445             if (ie.info.tag == HEADER_IMAGE)
446                 tprev -= REGION_TAG_COUNT;
447         }
448
449         /* Perform endian conversions */
450         switch (ntohl(pe->type)) {
451         case RPM_INT32_TYPE:
452         {   int32_t * it = (int32_t *)t;
453             for (; ie.info.count > 0; ie.info.count--, it += 1) {
454                 if (dataEnd && ((unsigned char *)it) >= dataEnd)
455                     return -1;
456                 *it = htonl(*it);
457             }
458             t = (unsigned char *) it;
459         }   break;
460         case RPM_INT16_TYPE:
461         {   int16_t * it = (int16_t *) t;
462             for (; ie.info.count > 0; ie.info.count--, it += 1) {
463                 if (dataEnd && ((unsigned char *)it) >= dataEnd)
464                     return -1;
465                 *it = htons(*it);
466             }
467             t = (unsigned char *) it;
468         }   break;
469         default:
470             t += ie.length;
471             break;
472         }
473
474         dl += ie.length;
475         tl += tdel;
476         ieprev = ie;    /* structure assignment */
477
478     }
479     tdel = (tprev ? (t - tprev) : 0);
480     tl += tdel;
481
482     /* XXX
483      * There are two hacks here:
484      *  1) tl is 16b (i.e. REGION_TAG_COUNT) short while doing headerReload().
485      *  2) the 8/98 rpm bug with inserting i18n tags needs to use tl, not dl.
486      */
487     if (tl+REGION_TAG_COUNT == dl)
488         tl += REGION_TAG_COUNT;
489
490     return dl;
491 }
492
493 /** \ingroup header
494  * doHeaderUnload.
495  * @param h             header
496  * @retval *lengthPtr   no. bytes in unloaded header blob
497  * @return              unloaded header blob (NULL on error)
498  */
499 static void * doHeaderUnload(Header h,
500                 size_t * lengthPtr)
501 {
502     int32_t * ei = NULL;
503     entryInfo pe;
504     char * dataStart;
505     char * te;
506     unsigned pad;
507     unsigned len;
508     int32_t il = 0;
509     int32_t dl = 0;
510     indexEntry entry; 
511     rpmTagType type;
512     int i;
513     int drlen, ndribbles;
514     int driplen, ndrips;
515     int legacy = 0;
516
517     /* Sort entries by (offset,tag). */
518     headerUnsort(h);
519
520     /* Compute (il,dl) for all tags, including those deleted in region. */
521     pad = 0;
522     drlen = ndribbles = driplen = ndrips = 0;
523     for (i = 0, entry = h->index; i < h->indexUsed; i++, entry++) {
524         if (ENTRY_IS_REGION(entry)) {
525             int32_t rdl = -entry->info.offset;  /* negative offset */
526             int32_t ril = rdl/sizeof(*pe);
527             int rid = entry->info.offset;
528
529             il += ril;
530             dl += entry->rdlen + entry->info.count;
531             /* XXX Legacy regions do not include the region tag and data. */
532             if (i == 0 && (h->flags & HEADERFLAG_LEGACY))
533                 il += 1;
534
535             /* Skip rest of entries in region, but account for dribbles. */
536             for (; i < h->indexUsed && entry->info.offset <= rid+1; i++, entry++) {
537                 if (entry->info.offset <= rid)
538                     continue;
539
540                 /* Alignment */
541                 type = entry->info.type;
542                 if (typeSizes[type] > 1) {
543                     unsigned diff;
544                     diff = typeSizes[type] - (dl % typeSizes[type]);
545                     if (diff != typeSizes[type]) {
546                         drlen += diff;
547                         pad += diff;
548                         dl += diff;
549                     }
550                 }
551
552                 ndribbles++;
553                 il++;
554                 drlen += entry->length;
555                 dl += entry->length;
556             }
557             i--;
558             entry--;
559             continue;
560         }
561
562         /* Ignore deleted drips. */
563         if (entry->data == NULL || entry->length <= 0)
564             continue;
565
566         /* Alignment */
567         type = entry->info.type;
568         if (typeSizes[type] > 1) {
569             unsigned diff;
570             diff = typeSizes[type] - (dl % typeSizes[type]);
571             if (diff != typeSizes[type]) {
572                 driplen += diff;
573                 pad += diff;
574                 dl += diff;
575             } else
576                 diff = 0;
577         }
578
579         ndrips++;
580         il++;
581         driplen += entry->length;
582         dl += entry->length;
583     }
584
585     /* Sanity checks on header intro. */
586     if (hdrchkTags(il) || hdrchkData(dl))
587         goto errxit;
588
589     len = sizeof(il) + sizeof(dl) + (il * sizeof(*pe)) + dl;
590
591     ei = xmalloc(len);
592     ei[0] = htonl(il);
593     ei[1] = htonl(dl);
594
595     pe = (entryInfo) &ei[2];
596     dataStart = te = (char *) (pe + il);
597
598     pad = 0;
599     for (i = 0, entry = h->index; i < h->indexUsed; i++, entry++) {
600         const char * src;
601         unsigned char *t;
602         int count;
603         int rdlen;
604
605         if (entry->data == NULL || entry->length <= 0)
606             continue;
607
608         t = (unsigned char*)te;
609         pe->tag = htonl(entry->info.tag);
610         pe->type = htonl(entry->info.type);
611         pe->count = htonl(entry->info.count);
612
613         if (ENTRY_IS_REGION(entry)) {
614             int32_t rdl = -entry->info.offset;  /* negative offset */
615             int32_t ril = rdl/sizeof(*pe) + ndribbles;
616             int rid = entry->info.offset;
617
618             src = (char *)entry->data;
619             rdlen = entry->rdlen;
620
621             /* XXX Legacy regions do not include the region tag and data. */
622             if (i == 0 && (h->flags & HEADERFLAG_LEGACY)) {
623                 int32_t stei[4];
624
625                 legacy = 1;
626                 memcpy(pe+1, src, rdl);
627                 memcpy(te, src + rdl, rdlen);
628                 te += rdlen;
629
630                 pe->offset = htonl(te - dataStart);
631                 stei[0] = pe->tag;
632                 stei[1] = pe->type;
633                 stei[2] = htonl(-rdl-entry->info.count);
634                 stei[3] = pe->count;
635                 memcpy(te, stei, entry->info.count);
636                 te += entry->info.count;
637                 ril++;
638                 rdlen += entry->info.count;
639
640                 count = regionSwab(NULL, ril, 0, pe, t, NULL, 0);
641                 if (count != rdlen)
642                     goto errxit;
643
644             } else {
645
646                 memcpy(pe+1, src + sizeof(*pe), ((ril-1) * sizeof(*pe)));
647                 memcpy(te, src + (ril * sizeof(*pe)), rdlen+entry->info.count+drlen);
648                 te += rdlen;
649                 {  
650                     entryInfo se = (entryInfo)src;
651                     int off = ntohl(se->offset);
652                     pe->offset = (off) ? htonl(te - dataStart) : htonl(off);
653                 }
654                 te += entry->info.count + drlen;
655
656                 count = regionSwab(NULL, ril, 0, pe, t, NULL, 0);
657                 if (count != (rdlen + entry->info.count + drlen))
658                     goto errxit;
659             }
660
661             /* Skip rest of entries in region. */
662             while (i < h->indexUsed && entry->info.offset <= rid+1) {
663                 i++;
664                 entry++;
665             }
666             i--;
667             entry--;
668             pe += ril;
669             continue;
670         }
671
672         /* Ignore deleted drips. */
673         if (entry->data == NULL || entry->length <= 0)
674             continue;
675
676         /* Alignment */
677         type = entry->info.type;
678         if (typeSizes[type] > 1) {
679             unsigned diff;
680             diff = typeSizes[type] - ((te - dataStart) % typeSizes[type]);
681             if (diff != typeSizes[type]) {
682                 memset(te, 0, diff);
683                 te += diff;
684                 pad += diff;
685             }
686         }
687
688         pe->offset = htonl(te - dataStart);
689
690         /* copy data w/ endian conversions */
691         switch (entry->info.type) {
692         case RPM_INT32_TYPE:
693             count = entry->info.count;
694             src = entry->data;
695             while (count--) {
696                 *((int32_t *)te) = htonl(*((int32_t *)src));
697                 te += sizeof(int32_t);
698                 src += sizeof(int32_t);
699             }
700             break;
701
702         case RPM_INT16_TYPE:
703             count = entry->info.count;
704             src = entry->data;
705             while (count--) {
706                 *((int16_t *)te) = htons(*((int16_t *)src));
707                 te += sizeof(int16_t);
708                 src += sizeof(int16_t);
709             }
710             break;
711
712         default:
713             memcpy(te, entry->data, entry->length);
714             te += entry->length;
715             break;
716         }
717         pe++;
718     }
719    
720     /* Insure that there are no memcpy underruns/overruns. */
721     if (((char *)pe) != dataStart)
722         goto errxit;
723     if ((((char *)ei)+len) != te)
724         goto errxit;
725
726     if (lengthPtr)
727         *lengthPtr = len;
728
729     h->flags &= ~HEADERFLAG_SORTED;
730     headerSort(h);
731
732     return (void *) ei;
733
734 errxit:
735     ei = _free(ei);
736     return (void *) ei;
737 }
738
739 void * headerUnload(Header h)
740 {
741     size_t length;
742     void * uh = doHeaderUnload(h, &length);
743     return uh;
744 }
745
746 /**
747  * Find matching (tag,type) entry in header.
748  * @param h             header
749  * @param tag           entry tag
750  * @param type          entry type
751  * @return              header entry
752  */
753 static
754 indexEntry findEntry(Header h, rpmTag tag, rpmTagType type)
755 {
756     indexEntry entry, entry2, last;
757     struct indexEntry_s key;
758
759     if (h == NULL) return NULL;
760     if (!(h->flags & HEADERFLAG_SORTED)) headerSort(h);
761
762     key.info.tag = tag;
763
764     entry2 = entry = 
765         bsearch(&key, h->index, h->indexUsed, sizeof(*h->index), indexCmp);
766     if (entry == NULL)
767         return NULL;
768
769     if (type == RPM_NULL_TYPE)
770         return entry;
771
772     /* look backwards */
773     while (entry->info.tag == tag && entry->info.type != type &&
774            entry > h->index) entry--;
775
776     if (entry->info.tag == tag && entry->info.type == type)
777         return entry;
778
779     last = h->index + h->indexUsed;
780     /* FIX: entry2 = entry. Code looks bogus as well. */
781     while (entry2->info.tag == tag && entry2->info.type != type &&
782            entry2 < last) entry2++;
783
784     if (entry->info.tag == tag && entry->info.type == type)
785         return entry;
786
787     return NULL;
788 }
789
790 int headerRemoveEntry(Header h, rpmTag tag)
791 {
792     indexEntry last = h->index + h->indexUsed;
793     indexEntry entry, first;
794     int ne;
795
796     entry = findEntry(h, tag, RPM_NULL_TYPE);
797     if (!entry) return 1;
798
799     /* Make sure entry points to the first occurence of this tag. */
800     while (entry > h->index && (entry - 1)->info.tag == tag)  
801         entry--;
802
803     /* Free data for tags being removed. */
804     for (first = entry; first < last; first++) {
805         rpm_data_t data;
806         if (first->info.tag != tag)
807             break;
808         data = first->data;
809         first->data = NULL;
810         first->length = 0;
811         if (ENTRY_IN_REGION(first))
812             continue;
813         data = _free(data);
814     }
815
816     ne = (first - entry);
817     if (ne > 0) {
818         h->indexUsed -= ne;
819         ne = last - first;
820         if (ne > 0)
821             memmove(entry, first, (ne * sizeof(*entry)));
822     }
823
824     return 0;
825 }
826
827 Header headerLoad(void * uh)
828 {
829     int32_t * ei = (int32_t *) uh;
830     int32_t il = ntohl(ei[0]);          /* index length */
831     int32_t dl = ntohl(ei[1]);          /* data length */
832     size_t pvlen = sizeof(il) + sizeof(dl) +
833                (il * sizeof(struct entryInfo_s)) + dl;
834     void * pv = uh;
835     Header h = NULL;
836     entryInfo pe;
837     unsigned char * dataStart;
838     unsigned char * dataEnd;
839     indexEntry entry; 
840     int rdlen;
841     int i;
842
843     /* Sanity checks on header intro. */
844     if (hdrchkTags(il) || hdrchkData(dl))
845         goto errxit;
846
847     ei = (int32_t *) pv;
848     pe = (entryInfo) &ei[2];
849     dataStart = (unsigned char *) (pe + il);
850     dataEnd = dataStart + dl;
851
852     h = xcalloc(1, sizeof(*h));
853     h->blob = uh;
854     h->indexAlloced = il + 1;
855     h->indexUsed = il;
856     h->index = xcalloc(h->indexAlloced, sizeof(*h->index));
857     h->flags |= HEADERFLAG_SORTED;
858     h->nrefs = 0;
859     h = headerLink(h);
860
861     entry = h->index;
862     i = 0;
863     if (!(htonl(pe->tag) < HEADER_I18NTABLE)) {
864         h->flags |= HEADERFLAG_LEGACY;
865         entry->info.type = REGION_TAG_TYPE;
866         entry->info.tag = HEADER_IMAGE;
867         entry->info.count = REGION_TAG_COUNT;
868         entry->info.offset = ((unsigned char *)pe - dataStart); /* negative offset */
869
870         entry->data = pe;
871         entry->length = pvlen - sizeof(il) - sizeof(dl);
872         rdlen = regionSwab(entry+1, il, 0, pe, dataStart, dataEnd, entry->info.offset);
873 #if 0   /* XXX don't check, the 8/98 i18n bug fails here. */
874         if (rdlen != dl)
875             goto errxit;
876 #endif
877         entry->rdlen = rdlen;
878         entry++;
879         h->indexUsed++;
880     } else {
881         int32_t rdl;
882         int32_t ril;
883
884         h->flags &= ~HEADERFLAG_LEGACY;
885
886         entry->info.type = htonl(pe->type);
887         entry->info.count = htonl(pe->count);
888
889         if (hdrchkType(entry->info.type))
890             goto errxit;
891         if (hdrchkTags(entry->info.count))
892             goto errxit;
893
894         {   int off = ntohl(pe->offset);
895
896             if (hdrchkData(off))
897                 goto errxit;
898             if (off) {
899                 size_t nb = REGION_TAG_COUNT;
900                 int32_t stei[nb];
901                 /* XXX Hmm, why the copy? */
902                 memcpy(&stei, dataStart + off, nb);
903                 rdl = -ntohl(stei[2]);  /* negative offset */
904                 ril = rdl/sizeof(*pe);
905                 if (hdrchkTags(ril) || hdrchkData(rdl))
906                     goto errxit;
907                 entry->info.tag = htonl(pe->tag);
908             } else {
909                 ril = il;
910                 rdl = (ril * sizeof(struct entryInfo_s));
911                 entry->info.tag = HEADER_IMAGE;
912             }
913         }
914         entry->info.offset = -rdl;      /* negative offset */
915
916         entry->data = pe;
917         entry->length = pvlen - sizeof(il) - sizeof(dl);
918         rdlen = regionSwab(entry+1, ril-1, 0, pe+1, dataStart, dataEnd, entry->info.offset);
919         if (rdlen < 0)
920             goto errxit;
921         entry->rdlen = rdlen;
922
923         if (ril < h->indexUsed) {
924             indexEntry newEntry = entry + ril;
925             int ne = (h->indexUsed - ril);
926             int rid = entry->info.offset+1;
927             int rc;
928
929             /* Load dribble entries from region. */
930             rc = regionSwab(newEntry, ne, 0, pe+ril, dataStart, dataEnd, rid);
931             if (rc < 0)
932                 goto errxit;
933             rdlen += rc;
934
935           { indexEntry firstEntry = newEntry;
936             int save = h->indexUsed;
937             int j;
938
939             /* Dribble entries replace duplicate region entries. */
940             h->indexUsed -= ne;
941             for (j = 0; j < ne; j++, newEntry++) {
942                 (void) headerRemoveEntry(h, newEntry->info.tag);
943                 if (newEntry->info.tag == HEADER_BASENAMES)
944                     (void) headerRemoveEntry(h, HEADER_OLDFILENAMES);
945             }
946
947             /* If any duplicate entries were replaced, move new entries down. */
948             if (h->indexUsed < (save - ne)) {
949                 memmove(h->index + h->indexUsed, firstEntry,
950                         (ne * sizeof(*entry)));
951             }
952             h->indexUsed += ne;
953           }
954         }
955     }
956
957     h->flags &= ~HEADERFLAG_SORTED;
958     headerSort(h);
959
960     return h;
961
962 errxit:
963     if (h) {
964         h->index = _free(h->index);
965         h = _free(h);
966     }
967     return h;
968 }
969
970 Header headerReload(Header h, rpmTag tag)
971 {
972     Header nh;
973     size_t length;
974     void * uh = doHeaderUnload(h, &length);
975
976     h = headerFree(h);
977     if (uh == NULL)
978         return NULL;
979     nh = headerLoad(uh);
980     if (nh == NULL) {
981         uh = _free(uh);
982         return NULL;
983     }
984     if (nh->flags & HEADERFLAG_ALLOCATED)
985         uh = _free(uh);
986     nh->flags |= HEADERFLAG_ALLOCATED;
987     if (ENTRY_IS_REGION(nh->index)) {
988         if (tag == HEADER_SIGNATURES || tag == HEADER_IMMUTABLE)
989             nh->index[0].info.tag = tag;
990     }
991     return nh;
992 }
993
994 Header headerCopyLoad(const void * uh)
995 {
996     int32_t * ei = (int32_t *) uh;
997     int32_t il = ntohl(ei[0]);          /* index length */
998     int32_t dl = ntohl(ei[1]);          /* data length */
999     size_t pvlen = sizeof(il) + sizeof(dl) +
1000                         (il * sizeof(struct entryInfo_s)) + dl;
1001     void * nuh = NULL;
1002     Header h = NULL;
1003
1004     /* Sanity checks on header intro. */
1005     if (!(hdrchkTags(il) || hdrchkData(dl)) && pvlen < headerMaxbytes) {
1006         nuh = memcpy(xmalloc(pvlen), uh, pvlen);
1007         if ((h = headerLoad(nuh)) != NULL)
1008             h->flags |= HEADERFLAG_ALLOCATED;
1009     }
1010     if (h == NULL)
1011         nuh = _free(nuh);
1012     return h;
1013 }
1014
1015 /** \ingroup header
1016  * Read (and load) header from file handle.
1017  * @param fd            file handle
1018  * @param magicp        read (and verify) 8 bytes of (magic, 0)?
1019  * @return              header (or NULL on error)
1020  */
1021 Header headerRead(FD_t fd, enum hMagic magicp)
1022 {
1023     int32_t block[4];
1024     int32_t reserved;
1025     int32_t * ei = NULL;
1026     int32_t il;
1027     int32_t dl;
1028     int32_t magic;
1029     Header h = NULL;
1030     size_t len;
1031     int i;
1032
1033     memset(block, 0, sizeof(block));
1034     i = 2;
1035     if (magicp == HEADER_MAGIC_YES)
1036         i += 2;
1037
1038     /* FIX: cast? */
1039     if (timedRead(fd, (char *)block, i*sizeof(*block)) != (i * sizeof(*block)))
1040         goto exit;
1041
1042     i = 0;
1043
1044     if (magicp == HEADER_MAGIC_YES) {
1045         magic = block[i++];
1046         if (memcmp(&magic, header_magic, sizeof(magic)))
1047             goto exit;
1048         reserved = block[i++];
1049     }
1050     
1051     il = ntohl(block[i]);       i++;
1052     dl = ntohl(block[i]);       i++;
1053
1054     len = sizeof(il) + sizeof(dl) + (il * sizeof(struct entryInfo_s)) + dl;
1055
1056     /* Sanity checks on header intro. */
1057     if (hdrchkTags(il) || hdrchkData(dl) || len > headerMaxbytes)
1058         goto exit;
1059
1060     ei = xmalloc(len);
1061     ei[0] = htonl(il);
1062     ei[1] = htonl(dl);
1063     len -= sizeof(il) + sizeof(dl);
1064
1065     /* FIX: cast? */
1066     if (timedRead(fd, (char *)&ei[2], len) != len)
1067         goto exit;
1068     
1069     h = headerLoad(ei);
1070
1071 exit:
1072     if (h) {
1073         if (h->flags & HEADERFLAG_ALLOCATED)
1074             ei = _free(ei);
1075         h->flags |= HEADERFLAG_ALLOCATED;
1076     } else if (ei)
1077         ei = _free(ei);
1078         /* FIX: timedRead macro obscures annotation */
1079     return h;
1080 }
1081
1082 int headerWrite(FD_t fd, Header h, enum hMagic magicp)
1083 {
1084     ssize_t nb;
1085     size_t length;
1086     void * uh;
1087
1088     if (h == NULL)
1089         return 1;
1090     uh = doHeaderUnload(h, &length);
1091     if (uh == NULL)
1092         return 1;
1093     switch (magicp) {
1094     case HEADER_MAGIC_YES:
1095         nb = Fwrite(header_magic, sizeof(char), sizeof(header_magic), fd);
1096         if (nb != sizeof(header_magic))
1097             goto exit;
1098         break;
1099     case HEADER_MAGIC_NO:
1100         break;
1101     }
1102
1103     nb = Fwrite(uh, sizeof(char), length, fd);
1104
1105 exit:
1106     uh = _free(uh);
1107     return (nb == length ? 0 : 1);
1108 }
1109
1110 int headerIsEntry(Header h, rpmTag tag)
1111 {
1112                 /* FIX: h modified by sort. */
1113     return (findEntry(h, tag, RPM_NULL_TYPE) ? 1 : 0);
1114         
1115 }
1116
1117 /** \ingroup header
1118  * Retrieve data from header entry.
1119  * @todo Permit retrieval of regions other than HEADER_IMUTABLE.
1120  * @param entry         header entry
1121  * @param td            tag data container
1122  * @param minMem        string pointers refer to header memory?
1123  * @return              1 on success, otherwise error.
1124  */
1125 static int copyTdEntry(const indexEntry entry, rpmtd td, int minMem)
1126 {
1127     rpm_count_t count = entry->info.count;
1128     int rc = 1;         /* XXX 1 on success. */
1129
1130     assert(td != NULL);
1131     switch (entry->info.type) {
1132     case RPM_BIN_TYPE:
1133         /*
1134          * XXX This only works for
1135          * XXX  "sealed" HEADER_IMMUTABLE/HEADER_SIGNATURES/HEADER_IMAGE.
1136          * XXX This will *not* work for unsealed legacy HEADER_IMAGE (i.e.
1137          * XXX a legacy header freshly read, but not yet unloaded to the rpmdb).
1138          */
1139         if (ENTRY_IS_REGION(entry)) {
1140             int32_t * ei = ((int32_t *)entry->data) - 2;
1141             entryInfo pe = (entryInfo) (ei + 2);
1142             unsigned char * dataStart = (unsigned char *) (pe + ntohl(ei[0]));
1143             int32_t rdl = -entry->info.offset;  /* negative offset */
1144             int32_t ril = rdl/sizeof(*pe);
1145
1146             rdl = entry->rdlen;
1147             count = 2 * sizeof(*ei) + (ril * sizeof(*pe)) + rdl;
1148             if (entry->info.tag == HEADER_IMAGE) {
1149                 ril -= 1;
1150                 pe += 1;
1151             } else {
1152                 count += REGION_TAG_COUNT;
1153                 rdl += REGION_TAG_COUNT;
1154             }
1155
1156             td->data = xmalloc(count);
1157             ei = (int32_t *) td->data;
1158             ei[0] = htonl(ril);
1159             ei[1] = htonl(rdl);
1160
1161             pe = (entryInfo) memcpy(ei + 2, pe, (ril * sizeof(*pe)));
1162
1163             dataStart = (unsigned char *) memcpy(pe + ril, dataStart, rdl);
1164
1165             rc = regionSwab(NULL, ril, 0, pe, dataStart, dataStart + rdl, 0);
1166             /* XXX 1 on success. */
1167             rc = (rc < 0) ? 0 : 1;
1168         } else {
1169             count = entry->length;
1170             td->data = (!minMem
1171                 ? memcpy(xmalloc(count), entry->data, count)
1172                 : entry->data);
1173         }
1174         break;
1175     case RPM_STRING_TYPE:
1176         if (count == 1) {
1177             td->data = entry->data;
1178             break;
1179         }
1180     case RPM_STRING_ARRAY_TYPE:
1181     case RPM_I18NSTRING_TYPE:
1182     {   const char ** ptrEntry;
1183         int tableSize = count * sizeof(char *);
1184         char * t;
1185         int i;
1186
1187         if (minMem) {
1188             td->data = xmalloc(tableSize);
1189             ptrEntry = (const char **) td->data;
1190             t = entry->data;
1191         } else {
1192             t = xmalloc(tableSize + entry->length);
1193             td->data = (void *)t;
1194             ptrEntry = (const char **) td->data;
1195             t += tableSize;
1196             memcpy(t, entry->data, entry->length);
1197         }
1198         for (i = 0; i < count; i++) {
1199             *ptrEntry++ = t;
1200             t = strchr(t, 0);
1201             t++;
1202         }
1203     }   break;
1204
1205     default:
1206         td->data = entry->data;
1207         break;
1208     }
1209     td->type = entry->info.type;
1210     td->count = count;
1211
1212     td->flags = RPMTD_IMMUTABLE;
1213     if (entry->data != td->data) {
1214         td->flags |= RPMTD_ALLOCED;
1215     }
1216
1217     return rc;
1218 }
1219
1220 /** \ingroup header
1221  * Retrieve data from header entry.
1222  * Just a compat wrapper around copyTdEntry() until everything's converted
1223  * to new interface.
1224  * @param entry         header entry
1225  * @retval type         address of type (or NULL)
1226  * @retval p            address of data (or NULL)
1227  * @retval c            address of count (or NULL)
1228  * @param minMem        string pointers refer to header memory?
1229  * @return              1 on success, otherwise error.
1230  */
1231 static int copyEntry(const indexEntry entry,
1232                 rpmTagType * type,
1233                 rpm_data_t * p,
1234                 rpm_count_t * c,
1235                 int minMem)
1236 {
1237     struct rpmtd_s td;
1238     int rc;
1239
1240     rpmtdReset(&td);
1241     rc = copyTdEntry(entry, &td, minMem);
1242     TDWRAP();
1243     return rc;
1244 }
1245
1246 /**
1247  * Does locale match entry in header i18n table?
1248  * 
1249  * \verbatim
1250  * The range [l,le) contains the next locale to match:
1251  *    ll[_CC][.EEEEE][@dddd]
1252  * where
1253  *    ll        ISO language code (in lowercase).
1254  *    CC        (optional) ISO coutnry code (in uppercase).
1255  *    EEEEE     (optional) encoding (not really standardized).
1256  *    dddd      (optional) dialect.
1257  * \endverbatim
1258  *
1259  * @param td            header i18n table data, NUL terminated
1260  * @param l             start of locale to match
1261  * @param le            end of locale to match
1262  * @return              1 on good match, 2 on weak match, 0 on no match
1263  */
1264 static int headerMatchLocale(const char *td, const char *l, const char *le)
1265 {
1266     const char *fe;
1267
1268     /* First try a complete match. */
1269     if (strlen(td) == (le-l) && !strncmp(td, l, (le - l)))
1270         return 1;
1271
1272     /* Next, try stripping optional dialect and matching.  */
1273     for (fe = l; fe < le && *fe != '@'; fe++)
1274         {};
1275     if (fe < le && !strncmp(td, l, (fe - l)))
1276         return 1;
1277
1278     /* Next, try stripping optional codeset and matching.  */
1279     for (fe = l; fe < le && *fe != '.'; fe++)
1280         {};
1281     if (fe < le && !strncmp(td, l, (fe - l)))
1282         return 1;
1283
1284     /* Finally, try stripping optional country code and matching. */
1285     for (fe = l; fe < le && *fe != '_'; fe++)
1286         {};
1287     if (fe < le && !strncmp(td, l, (fe - l)))
1288         return 2;
1289
1290     return 0;
1291 }
1292
1293 /**
1294  * Return i18n string from header that matches locale.
1295  * @param h             header
1296  * @param entry         i18n string data
1297  * @retval td           tag data container
1298  * @return              1 always
1299  */
1300 static int copyI18NEntry(Header h, indexEntry entry, rpmtd td)
1301 {
1302     const char *lang, *l, *le;
1303     indexEntry table;
1304
1305     td->type = RPM_STRING_TYPE;
1306     td->count = 1;
1307     /* if no match, just return the first string */
1308     td->data = entry->data;
1309
1310     /* XXX Drepper sez' this is the order. */
1311     if ((lang = getenv("LANGUAGE")) == NULL &&
1312         (lang = getenv("LC_ALL")) == NULL &&
1313         (lang = getenv("LC_MESSAGES")) == NULL &&
1314         (lang = getenv("LANG")) == NULL)
1315             goto exit;
1316     
1317     if ((table = findEntry(h, HEADER_I18NTABLE, RPM_STRING_ARRAY_TYPE)) == NULL)
1318         goto exit;
1319
1320     for (l = lang; *l != '\0'; l = le) {
1321         const char *t;
1322         char *ed, *ed_weak = NULL;
1323         int langNum;
1324
1325         while (*l && *l == ':')                 /* skip leading colons */
1326             l++;
1327         if (*l == '\0')
1328             break;
1329         for (le = l; *le && *le != ':'; le++)   /* find end of this locale */
1330             {};
1331
1332         /* For each entry in the header ... */
1333         for (langNum = 0, t = table->data, ed = entry->data;
1334              langNum < entry->info.count;
1335              langNum++, t += strlen(t) + 1, ed += strlen(ed) + 1) {
1336
1337             int match = headerMatchLocale(t, l, le);
1338             if (match == 1) {
1339                 td->data = ed;
1340                 goto exit;
1341             } else if (match == 2) { 
1342                 ed_weak = ed;
1343             }
1344         }
1345         if (ed_weak) {
1346             td->data = ed_weak;
1347             goto exit;
1348         }
1349     }
1350
1351 exit:
1352     return 1;
1353 }
1354
1355 /**
1356  * Retrieve tag data from header.
1357  * @param h             header
1358  * @param tag           tag to retrieve
1359  * @retval td           tag data container
1360  * @param flags         flags to control retrieval
1361  * @return              1 on success, 0 on not found
1362  */
1363 static int intGetTdEntry(Header h, rpmTag tag, rpmtd td, headerGetFlags flags)
1364 {
1365     indexEntry entry;
1366     int rc;
1367
1368     assert(td != NULL);
1369     /* ensure clean state */
1370     rpmtdReset(td);
1371     td->tag = tag;
1372     /* First find the tag */
1373     /* FIX: h modified by sort. */
1374     entry = findEntry(h, tag, RPM_NULL_TYPE);
1375     if (entry == NULL) {
1376         /* Td is zeroed above, just return... */
1377         return 0;
1378     }
1379
1380     if (flags & HEADERGET_RAW) {
1381         rc = copyTdEntry(entry, td, (flags & HEADERGET_MINMEM));
1382     } else {
1383         switch (entry->info.type) {
1384         case RPM_I18NSTRING_TYPE:
1385             rc = copyI18NEntry(h, entry, td);
1386             break;
1387         default:
1388             rc = copyTdEntry(entry, td, (flags & HEADERGET_MINMEM));
1389             break;
1390         }
1391     }
1392
1393     /* XXX 1 on success */
1394     return ((rc == 1) ? 1 : 0);
1395 }
1396
1397 void * headerFreeTag(Header h, rpm_data_t data, rpmTagType type)
1398 {
1399     if (data) {
1400         if (type == RPM_FORCEFREE_TYPE ||
1401             type == RPM_STRING_ARRAY_TYPE ||
1402             type == RPM_I18NSTRING_TYPE ||
1403             type == RPM_BIN_TYPE)
1404                 data = _free(data);
1405     }
1406     return NULL;
1407 }
1408
1409 /* 
1410  * XXX temporary kludgery until tag extensions have been converted to 
1411  * take rpmtd as argument
1412  */
1413 static int intGetTagExt(Header h, rpmTag tag, rpmtd td, headerTagTagFunction tagfunc)
1414 {
1415     int rc;
1416     rpmtdReset(td);
1417     rc = tagfunc(h, td);
1418     td->tag = tag;
1419     /* XXX extension returns are reversed, ugh */
1420     return rc ? 0 : 1; 
1421 }
1422
1423 int headerGet(Header h, rpmTag tag, rpmtd td, headerGetFlags flags)
1424 {
1425     int rc;
1426     headerTagTagFunction tagfunc = NULL;
1427
1428     assert(td != NULL);
1429
1430     if (flags & HEADERGET_EXT) {
1431         tagfunc = rpmHeaderTagFunc(tag);
1432     }
1433         
1434     if (tagfunc) {
1435         rc = intGetTagExt(h, tag, td, tagfunc);
1436     } else {
1437         rc = intGetTdEntry(h, tag, td, flags);
1438     }
1439
1440     assert(tag == td->tag);
1441     return rc;
1442 }
1443
1444 static int headerGetWrap(Header h, rpmTag tag,
1445                 rpmTagType * type,
1446                 rpm_data_t * p,
1447                 rpm_count_t * c,
1448                 headerGetFlags flags)
1449 {
1450     struct rpmtd_s td;
1451     int rc;
1452
1453     rc = headerGet(h, tag, &td, flags);
1454     TDWRAP();
1455     return rc;
1456 }
1457
1458 int headerGetEntry(Header h, rpmTag tag,
1459                         rpmTagType * type,
1460                         rpm_data_t * p,
1461                         rpm_count_t * c)
1462 {
1463     return headerGetWrap(h, tag, type, p, c, HEADERGET_DEFAULT);
1464 }
1465
1466 int headerGetEntryMinMemory(Header h, rpmTag tag,
1467                         rpmTagType * type,
1468                         rpm_data_t * p,
1469                         rpm_count_t * c)
1470 {
1471     return headerGetWrap(h, tag, type, (rpm_data_t) p, c, HEADERGET_MINMEM);
1472 }
1473
1474 int headerGetRawEntry(Header h, rpmTag tag, rpmTagType * type, rpm_data_t * p,
1475                 rpm_count_t * c)
1476 {
1477     indexEntry entry;
1478     int rc;
1479
1480     if (p == NULL) return headerIsEntry(h, tag);
1481
1482     /* First find the tag */
1483                 /* FIX: h modified by sort. */
1484     entry = findEntry(h, tag, RPM_NULL_TYPE);
1485     if (!entry) {
1486         if (p) *p = NULL;
1487         if (c) *c = 0;
1488         return 0;
1489     }
1490
1491     rc = copyEntry(entry, type, p, c, 0);
1492
1493     /* XXX 1 on success */
1494     return ((rc == 1) ? 1 : 0);
1495 }
1496
1497 /**
1498  */
1499 static void copyData(rpmTagType type, rpm_data_t dstPtr, 
1500                 rpm_constdata_t srcPtr, rpm_count_t cnt, int dataLength)
1501 {
1502     switch (type) {
1503     case RPM_STRING_ARRAY_TYPE:
1504     case RPM_I18NSTRING_TYPE:
1505     {   const char ** av = (const char **) srcPtr;
1506         char * t = dstPtr;
1507
1508         while (cnt-- > 0 && dataLength > 0) {
1509             const char * s;
1510             if ((s = *av++) == NULL)
1511                 continue;
1512             do {
1513                 *t++ = *s++;
1514             } while (s[-1] && --dataLength > 0);
1515         }
1516     }   break;
1517
1518     default:
1519         memmove(dstPtr, srcPtr, dataLength);
1520         break;
1521     }
1522 }
1523
1524 /**
1525  * Return (malloc'ed) copy of entry data.
1526  * @param type          entry data type
1527  * @param p             entry data
1528  * @param c             entry item count
1529  * @retval lengthPtr    no. bytes in returned data
1530  * @return              (malloc'ed) copy of entry data, NULL on error
1531  */
1532 static void *
1533 grabData(rpmTagType type, rpm_constdata_t p, rpm_count_t c, int * lengthPtr)
1534 {
1535     rpm_data_t data = NULL;
1536     int length;
1537
1538     length = dataLength(type, p, c, 0, NULL);
1539     if (length > 0) {
1540         data = xmalloc(length);
1541         copyData(type, data, p, c, length);
1542     }
1543
1544     if (lengthPtr)
1545         *lengthPtr = length;
1546     return data;
1547 }
1548
1549 int headerAddEntry(Header h, rpmTag tag, rpmTagType type, 
1550                         rpm_constdata_t p, rpm_count_t c)
1551 {
1552     indexEntry entry;
1553     rpm_data_t data;
1554     int length;
1555
1556     /* Count must always be >= 1 for headerAddEntry. */
1557     if (c <= 0)
1558         return 0;
1559
1560     if (hdrchkType(type))
1561         return 0;
1562     if (hdrchkData(c))
1563         return 0;
1564
1565     length = 0;
1566     data = grabData(type, p, c, &length);
1567     if (data == NULL || length <= 0)
1568         return 0;
1569
1570     /* Allocate more index space if necessary */
1571     if (h->indexUsed == h->indexAlloced) {
1572         h->indexAlloced += INDEX_MALLOC_SIZE;
1573         h->index = xrealloc(h->index, h->indexAlloced * sizeof(*h->index));
1574     }
1575
1576     /* Fill in the index */
1577     entry = h->index + h->indexUsed;
1578     entry->info.tag = tag;
1579     entry->info.type = type;
1580     entry->info.count = c;
1581     entry->info.offset = 0;
1582     entry->data = data;
1583     entry->length = length;
1584
1585     if (h->indexUsed > 0 && tag < h->index[h->indexUsed-1].info.tag)
1586         h->flags &= ~HEADERFLAG_SORTED;
1587     h->indexUsed++;
1588
1589     return 1;
1590 }
1591
1592 int headerAppendEntry(Header h, rpmTag tag, rpmTagType type,
1593                 rpm_constdata_t p, rpm_count_t c)
1594 {
1595     indexEntry entry;
1596     int length;
1597
1598     if (type == RPM_STRING_TYPE || type == RPM_I18NSTRING_TYPE) {
1599         /* we can't do this */
1600         return 0;
1601     }
1602
1603     /* Find the tag entry in the header. */
1604     entry = findEntry(h, tag, type);
1605     if (!entry)
1606         return 0;
1607
1608     length = dataLength(type, p, c, 0, NULL);
1609     if (length < 0)
1610         return 0;
1611
1612     if (ENTRY_IN_REGION(entry)) {
1613         char * t = xmalloc(entry->length + length);
1614         memcpy(t, entry->data, entry->length);
1615         entry->data = t;
1616         entry->info.offset = 0;
1617     } else
1618         entry->data = xrealloc(entry->data, entry->length + length);
1619
1620     copyData(type, ((char *) entry->data) + entry->length, p, c, length);
1621
1622     entry->length += length;
1623
1624     entry->info.count += c;
1625
1626     return 1;
1627 }
1628
1629 int headerAddOrAppendEntry(Header h, rpmTag tag, rpmTagType type,
1630                 rpm_constdata_t p, rpm_count_t c)
1631 {
1632     return (findEntry(h, tag, type)
1633         ? headerAppendEntry(h, tag, type, p, c)
1634         : headerAddEntry(h, tag, type, p, c));
1635 }
1636
1637 int headerPut(Header h, rpmtd td, headerPutFlags flags)
1638 {
1639     int rc;
1640     
1641     assert(td != NULL);
1642     if (flags & HEADERPUT_APPEND) {
1643         rc = headerAddOrAppendEntry(h, td->tag, td->type, td->data, td->count);
1644     } else {
1645         rc = headerAddEntry(h, td->tag, td->type, td->data, td->count);
1646     }
1647     return rc;
1648 }
1649
1650 int headerAddI18NString(Header h, rpmTag tag, const char * string,
1651                 const char * lang)
1652 {
1653     indexEntry table, entry;
1654     const char ** strArray;
1655     int length;
1656     int ghosts;
1657     rpm_count_t i, langNum;
1658     char * buf;
1659
1660     table = findEntry(h, HEADER_I18NTABLE, RPM_STRING_ARRAY_TYPE);
1661     entry = findEntry(h, tag, RPM_I18NSTRING_TYPE);
1662
1663     if (!table && entry)
1664         return 0;               /* this shouldn't ever happen!! */
1665
1666     if (!table && !entry) {
1667         const char * charArray[2];
1668         rpm_count_t count = 0;
1669         if (!lang || (lang[0] == 'C' && lang[1] == '\0')) {
1670             charArray[count++] = "C";
1671         } else {
1672             charArray[count++] = "C";
1673             charArray[count++] = lang;
1674         }
1675         if (!headerAddEntry(h, HEADER_I18NTABLE, RPM_STRING_ARRAY_TYPE, 
1676                         &charArray, count))
1677             return 0;
1678         table = findEntry(h, HEADER_I18NTABLE, RPM_STRING_ARRAY_TYPE);
1679     }
1680
1681     if (!table)
1682         return 0;
1683     if (!lang) lang = "C";
1684
1685     {   const char * l = table->data;
1686         for (langNum = 0; langNum < table->info.count; langNum++) {
1687             if (!strcmp(l, lang)) break;
1688             l += strlen(l) + 1;
1689         }
1690     }
1691
1692     if (langNum >= table->info.count) {
1693         length = strlen(lang) + 1;
1694         if (ENTRY_IN_REGION(table)) {
1695             char * t = xmalloc(table->length + length);
1696             memcpy(t, table->data, table->length);
1697             table->data = t;
1698             table->info.offset = 0;
1699         } else
1700             table->data = xrealloc(table->data, table->length + length);
1701         memmove(((char *)table->data) + table->length, lang, length);
1702         table->length += length;
1703         table->info.count++;
1704     }
1705
1706     if (!entry) {
1707         int rc;
1708         strArray = xmalloc(sizeof(*strArray) * (langNum + 1));
1709         for (i = 0; i < langNum; i++)
1710             strArray[i] = "";
1711         strArray[langNum] = string;
1712         rc = headerAddEntry(h, tag, RPM_I18NSTRING_TYPE, strArray, langNum + 1);
1713         free(strArray);
1714         return rc;
1715     } else if (langNum >= entry->info.count) {
1716         ghosts = langNum - entry->info.count;
1717         
1718         length = strlen(string) + 1 + ghosts;
1719         if (ENTRY_IN_REGION(entry)) {
1720             char * t = xmalloc(entry->length + length);
1721             memcpy(t, entry->data, entry->length);
1722             entry->data = t;
1723             entry->info.offset = 0;
1724         } else
1725             entry->data = xrealloc(entry->data, entry->length + length);
1726
1727         memset(((char *)entry->data) + entry->length, '\0', ghosts);
1728         memmove(((char *)entry->data) + entry->length + ghosts, string, strlen(string)+1);
1729
1730         entry->length += length;
1731         entry->info.count = langNum + 1;
1732     } else {
1733         char *b, *be, *e, *ee, *t;
1734         size_t bn, sn, en;
1735
1736         /* Set beginning/end pointers to previous data */
1737         b = be = e = ee = entry->data;
1738         for (i = 0; i < table->info.count; i++) {
1739             if (i == langNum)
1740                 be = ee;
1741             ee += strlen(ee) + 1;
1742             if (i == langNum)
1743                 e  = ee;
1744         }
1745
1746         /* Get storage for new buffer */
1747         bn = (be-b);
1748         sn = strlen(string) + 1;
1749         en = (ee-e);
1750         length = bn + sn + en;
1751         t = buf = xmalloc(length);
1752
1753         /* Copy values into new storage */
1754         memcpy(t, b, bn);
1755         t += bn;
1756         memcpy(t, string, sn);
1757         t += sn;
1758         memcpy(t, e, en);
1759         t += en;
1760
1761         /* Replace i18N string array */
1762         entry->length -= strlen(be) + 1;
1763         entry->length += sn;
1764         
1765         if (ENTRY_IN_REGION(entry)) {
1766             entry->info.offset = 0;
1767         } else
1768             entry->data = _free(entry->data);
1769         entry->data = buf;
1770     }
1771
1772     return 0;
1773 }
1774
1775 int headerModifyEntry(Header h, rpmTag tag, rpmTagType type,
1776                         rpm_constdata_t p, rpm_count_t c)
1777 {
1778     indexEntry entry;
1779     rpm_data_t oldData;
1780     rpm_data_t data;
1781     int length;
1782
1783     /* First find the tag */
1784     entry = findEntry(h, tag, type);
1785     if (!entry)
1786         return 0;
1787
1788     length = 0;
1789     data = grabData(type, p, c, &length);
1790     if (data == NULL || length <= 0)
1791         return 0;
1792
1793     /* make sure entry points to the first occurence of this tag */
1794     while (entry > h->index && (entry - 1)->info.tag == tag)  
1795         entry--;
1796
1797     /* free after we've grabbed the new data in case the two are intertwined;
1798        that's a bad idea but at least we won't break */
1799     oldData = entry->data;
1800
1801     entry->info.count = c;
1802     entry->info.type = type;
1803     entry->data = data;
1804     entry->length = length;
1805
1806     if (ENTRY_IN_REGION(entry)) {
1807         entry->info.offset = 0;
1808     } else
1809         oldData = _free(oldData);
1810
1811     return 1;
1812 }
1813
1814 /**
1815  * Header tag iterator data structure.
1816  */
1817 struct headerIterator_s {
1818     Header h;           /*!< Header being iterated. */
1819     int next_index;     /*!< Next tag index. */
1820 };
1821
1822 HeaderIterator headerFreeIterator(HeaderIterator hi)
1823 {
1824     if (hi != NULL) {
1825         hi->h = headerFree(hi->h);
1826         hi = _free(hi);
1827     }
1828     return hi;
1829 }
1830
1831 HeaderIterator headerInitIterator(Header h)
1832 {
1833     HeaderIterator hi = xmalloc(sizeof(*hi));
1834
1835     headerSort(h);
1836
1837     hi->h = headerLink(h);
1838     hi->next_index = 0;
1839     return hi;
1840 }
1841
1842 int headerNext(HeaderIterator hi, rpmtd td)
1843 {
1844     Header h = hi->h;
1845     int slot = hi->next_index;
1846     indexEntry entry = NULL;
1847     int rc;
1848
1849     assert(td != NULL);
1850     rpmtdReset(td);
1851
1852     for (slot = hi->next_index; slot < h->indexUsed; slot++) {
1853         entry = h->index + slot;
1854         if (!ENTRY_IS_REGION(entry))
1855             break;
1856     }
1857     hi->next_index = slot;
1858     if (entry == NULL || slot >= h->indexUsed)
1859         return 0;
1860
1861         /* LCL: no clue */
1862     hi->next_index++;
1863
1864     td->tag = entry->info.tag;
1865
1866     rc = copyTdEntry(entry, td, 0);
1867
1868     /* XXX 1 on success */
1869     return ((rc == 1) ? 1 : 0);
1870 }
1871
1872 int headerNextIterator(HeaderIterator hi,
1873                 rpmTag * tag,
1874                 rpmTagType * type,
1875                 rpm_data_t * p,
1876                 rpm_count_t * c)
1877 {
1878     struct rpmtd_s td;
1879     int rc;
1880
1881     rc = headerNext(hi, &td);
1882     if (tag)
1883         *tag = td.tag;
1884     TDWRAP();
1885     return rc;
1886 }
1887
1888 /** \ingroup header
1889  * Duplicate a header.
1890  * @param h             header
1891  * @return              new header instance
1892  */
1893 Header headerCopy(Header h)
1894 {
1895     Header nh = headerNew();
1896     HeaderIterator hi;
1897     struct rpmtd_s td;
1898    
1899     hi = headerInitIterator(h);
1900     while (headerNext(hi, &td)) {
1901         if (rpmtdCount(&td) > 0) {
1902             (void) headerPut(nh, &td, HEADERPUT_DEFAULT);
1903         }
1904         rpmtdFreeData(&td);
1905     }
1906     hi = headerFreeIterator(hi);
1907
1908     return headerReload(nh, HEADER_IMAGE);
1909 }
1910
1911 void headerCopyTags(Header headerFrom, Header headerTo, 
1912                     const rpmTag * tagstocopy)
1913 {
1914     const rpmTag * p;
1915     struct rpmtd_s td;
1916
1917     if (headerFrom == headerTo)
1918         return;
1919
1920     for (p = tagstocopy; *p != 0; p++) {
1921         if (headerIsEntry(headerTo, *p))
1922             continue;
1923         if (!headerGet(headerFrom, *p, &td, HEADERGET_MINMEM))
1924             continue;
1925         (void) headerPut(headerTo, &td, HEADERPUT_DEFAULT);
1926         rpmtdFreeData(&td);
1927     }
1928 }
1929
1930 void * headerFreeData(rpm_data_t data, rpmTagType type)
1931 {
1932     if (data) {
1933         if (type == RPM_FORCEFREE_TYPE ||
1934             type == RPM_STRING_ARRAY_TYPE ||
1935             type == RPM_I18NSTRING_TYPE ||
1936             type == RPM_BIN_TYPE)
1937                 free(data); /* XXX _free() */
1938     }
1939     return NULL;
1940 }