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