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