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