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