403084bad61d44467a70018873c01127adc3f586
[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     size_t uc = 0;
912     void * uh = doHeaderUnload(h, &uc);
913
914     h = headerFree(h);
915     if (uh == NULL)
916         return NULL;
917     nh = headerImport(uh, uc, 0);
918     if (nh == NULL) {
919         uh = _free(uh);
920         return NULL;
921     }
922     if (ENTRY_IS_REGION(nh->index)) {
923         if (tag == RPMTAG_HEADERSIGNATURES || tag == RPMTAG_HEADERIMMUTABLE)
924             nh->index[0].info.tag = tag;
925     }
926     return nh;
927 }
928
929 Header headerLoad(void * uh)
930 {
931     return headerImport(uh, 0, 0);
932 }
933
934 Header headerCopyLoad(const void * uh)
935 {
936     /* Discards const but that's ok as we'll take a copy */
937     return headerImport((void *)uh, 0, HEADERIMPORT_COPY);
938 }
939
940 Header headerRead(FD_t fd, int magicp)
941 {
942     int32_t block[4];
943     int32_t * ei = NULL;
944     int32_t il;
945     int32_t dl;
946     Header h = NULL;
947     unsigned int len, blen;
948
949     if (magicp == HEADER_MAGIC_YES) {
950         int32_t magic;
951
952         if (Fread(block, 1, 4*sizeof(*block), fd) != 4*sizeof(*block))
953             goto exit;
954
955         magic = block[0];
956
957         if (memcmp(&magic, rpm_header_magic, sizeof(magic)))
958             goto exit;
959
960         il = ntohl(block[2]);
961         dl = ntohl(block[3]);
962     } else {
963         if (Fread(block, 1, 2*sizeof(*block), fd) != 2*sizeof(*block))
964             goto exit;
965
966         il = ntohl(block[0]);
967         dl = ntohl(block[1]);
968     }
969
970     blen = (il * sizeof(struct entryInfo_s)) + dl;
971     len = sizeof(il) + sizeof(dl) + blen;
972
973     /* Sanity checks on header intro. */
974     if (hdrchkTags(il) || hdrchkData(dl) || len > headerMaxbytes)
975         goto exit;
976
977     ei = xmalloc(len);
978     ei[0] = htonl(il);
979     ei[1] = htonl(dl);
980
981     if (Fread((char *)&ei[2], 1, blen, fd) != blen)
982         goto exit;
983     
984     h = headerImport(ei, len, 0);
985
986 exit:
987     if (h == NULL && ei != NULL) {
988         free(ei);
989     }
990     return h;
991 }
992
993 int headerWrite(FD_t fd, Header h, int magicp)
994 {
995     ssize_t nb;
996     size_t length;
997     void * uh;
998
999     uh = doHeaderUnload(h, &length);
1000     if (uh == NULL)
1001         return 1;
1002     switch (magicp) {
1003     case HEADER_MAGIC_YES:
1004         nb = Fwrite(rpm_header_magic, sizeof(uint8_t), sizeof(rpm_header_magic), fd);
1005         if (nb != sizeof(rpm_header_magic))
1006             goto exit;
1007         break;
1008     case HEADER_MAGIC_NO:
1009         break;
1010     }
1011
1012     nb = Fwrite(uh, sizeof(char), length, fd);
1013
1014 exit:
1015     free(uh);
1016     return (nb == length ? 0 : 1);
1017 }
1018
1019 int headerIsEntry(Header h, rpmTagVal tag)
1020 {
1021                 /* FIX: h modified by sort. */
1022     return (findEntry(h, tag, RPM_NULL_TYPE) ? 1 : 0);
1023         
1024 }
1025
1026 /** \ingroup header
1027  * Retrieve data from header entry.
1028  * Relevant flags (others are ignored), if neither is set allocation
1029  * behavior depends on data type(!) 
1030  *     HEADERGET_MINMEM: return pointers to header memory
1031  *     HEADERGET_ALLOC: always return malloced memory, overrides MINMEM
1032  * 
1033  * @todo Permit retrieval of regions other than HEADER_IMUTABLE.
1034  * @param entry         header entry
1035  * @param td            tag data container
1036  * @param minMem        string pointers refer to header memory?
1037  * @param flags         flags to control memory allocation
1038  * @return              1 on success, otherwise error.
1039  */
1040 static int copyTdEntry(const indexEntry entry, rpmtd td, headerGetFlags flags)
1041 {
1042     rpm_count_t count = entry->info.count;
1043     int rc = 1;         /* XXX 1 on success. */
1044     /* ALLOC overrides MINMEM */
1045     int allocMem = flags & HEADERGET_ALLOC;
1046     int minMem = allocMem ? 0 : flags & HEADERGET_MINMEM;
1047     int argvArray = (flags & HEADERGET_ARGV) ? 1 : 0;
1048
1049     assert(td != NULL);
1050     td->flags = RPMTD_IMMUTABLE;
1051     switch (entry->info.type) {
1052     case RPM_BIN_TYPE:
1053         /*
1054          * XXX This only works for
1055          * XXX  "sealed" HEADER_IMMUTABLE/HEADER_SIGNATURES/HEADER_IMAGE.
1056          * XXX This will *not* work for unsealed legacy HEADER_IMAGE (i.e.
1057          * XXX a legacy header freshly read, but not yet unloaded to the rpmdb).
1058          */
1059         if (ENTRY_IS_REGION(entry)) {
1060             int32_t * ei = ((int32_t *)entry->data) - 2;
1061             entryInfo pe = (entryInfo) (ei + 2);
1062             unsigned char * dataStart = (unsigned char *) (pe + ntohl(ei[0]));
1063             int32_t rdl = -entry->info.offset;  /* negative offset */
1064             int32_t ril = rdl/sizeof(*pe);
1065
1066             rdl = entry->rdlen;
1067             count = 2 * sizeof(*ei) + (ril * sizeof(*pe)) + rdl;
1068             if (entry->info.tag == RPMTAG_HEADERIMAGE) {
1069                 ril -= 1;
1070                 pe += 1;
1071             } else {
1072                 count += REGION_TAG_COUNT;
1073                 rdl += REGION_TAG_COUNT;
1074             }
1075
1076             td->data = xmalloc(count);
1077             ei = (int32_t *) td->data;
1078             ei[0] = htonl(ril);
1079             ei[1] = htonl(rdl);
1080
1081             pe = (entryInfo) memcpy(ei + 2, pe, (ril * sizeof(*pe)));
1082
1083             dataStart = (unsigned char *) memcpy(pe + ril, dataStart, rdl);
1084
1085             rc = regionSwab(NULL, ril, 0, pe, dataStart, dataStart + rdl, 0);
1086             /* don't return data on failure */
1087             if (rc < 0) {
1088                 td->data = _free(td->data);
1089             }
1090             /* XXX 1 on success. */
1091             rc = (rc < 0) ? 0 : 1;
1092         } else {
1093             count = entry->length;
1094             td->data = (!minMem
1095                 ? memcpy(xmalloc(count), entry->data, count)
1096                 : entry->data);
1097         }
1098         break;
1099     case RPM_STRING_TYPE:
1100         /* simple string, but fallthrough if its actually an array */
1101         if (count == 1 && !argvArray) {
1102             td->data = allocMem ? xstrdup(entry->data) : entry->data;
1103             break;
1104         }
1105     case RPM_STRING_ARRAY_TYPE:
1106     case RPM_I18NSTRING_TYPE:
1107     {   const char ** ptrEntry;
1108         int tableSize = (count + argvArray) * sizeof(char *);
1109         char * t;
1110         int i;
1111
1112         if (minMem) {
1113             td->data = xmalloc(tableSize);
1114             ptrEntry = (const char **) td->data;
1115             t = entry->data;
1116         } else {
1117             t = xmalloc(tableSize + entry->length);
1118             td->data = (void *)t;
1119             ptrEntry = (const char **) td->data;
1120             t += tableSize;
1121             memcpy(t, entry->data, entry->length);
1122         }
1123         for (i = 0; i < count; i++) {
1124             *ptrEntry++ = t;
1125             t = strchr(t, 0);
1126             t++;
1127         }
1128         if (argvArray) {
1129             *ptrEntry = NULL;
1130             td->flags |= RPMTD_ARGV;
1131         }
1132     }   break;
1133     case RPM_CHAR_TYPE:
1134     case RPM_INT8_TYPE:
1135     case RPM_INT16_TYPE:
1136     case RPM_INT32_TYPE:
1137     case RPM_INT64_TYPE:
1138         if (allocMem) {
1139             td->data = xmalloc(entry->length);
1140             memcpy(td->data, entry->data, entry->length);
1141         } else {
1142             td->data = entry->data;
1143         }
1144         break;
1145     default:
1146         /* WTH? Don't mess with unknown data types... */
1147         rc = 0;
1148         td->data = NULL;
1149         break;
1150     }
1151     td->type = entry->info.type;
1152     td->count = count;
1153
1154     if (td->data && entry->data != td->data) {
1155         td->flags |= RPMTD_ALLOCED;
1156     }
1157
1158     return rc;
1159 }
1160
1161 /**
1162  * Does locale match entry in header i18n table?
1163  * 
1164  * \verbatim
1165  * The range [l,le) contains the next locale to match:
1166  *    ll[_CC][.EEEEE][@dddd]
1167  * where
1168  *    ll        ISO language code (in lowercase).
1169  *    CC        (optional) ISO coutnry code (in uppercase).
1170  *    EEEEE     (optional) encoding (not really standardized).
1171  *    dddd      (optional) dialect.
1172  * \endverbatim
1173  *
1174  * @param td            header i18n table data, NUL terminated
1175  * @param l             start of locale to match
1176  * @param le            end of locale to match
1177  * @return              1 on good match, 2 on weak match, 0 on no match
1178  */
1179 static int headerMatchLocale(const char *td, const char *l, const char *le)
1180 {
1181     const char *fe;
1182
1183     /* First try a complete match. */
1184     if (strlen(td) == (le-l) && rstreqn(td, l, (le - l)))
1185         return 1;
1186
1187     /* Next, try stripping optional dialect and matching.  */
1188     for (fe = l; fe < le && *fe != '@'; fe++)
1189         {};
1190     if (fe < le && rstreqn(td, l, (fe - l)))
1191         return 1;
1192
1193     /* Next, try stripping optional codeset and matching.  */
1194     for (fe = l; fe < le && *fe != '.'; fe++)
1195         {};
1196     if (fe < le && rstreqn(td, l, (fe - l)))
1197         return 1;
1198
1199     /* Finally, try stripping optional country code and matching. */
1200     for (fe = l; fe < le && *fe != '_'; fe++)
1201         {};
1202     if (fe < le && rstreqn(td, l, (fe - l)))
1203         return 2;
1204
1205     return 0;
1206 }
1207
1208 /**
1209  * Return i18n string from header that matches locale.
1210  * @param h             header
1211  * @param entry         i18n string data
1212  * @retval td           tag data container
1213  * @param flags         flags to control allocation
1214  * @return              1 always
1215  */
1216 static int copyI18NEntry(Header h, indexEntry entry, rpmtd td, 
1217                                                 headerGetFlags flags)
1218 {
1219     const char *lang, *l, *le;
1220     indexEntry table;
1221
1222     td->type = RPM_STRING_TYPE;
1223     td->count = 1;
1224     /* if no match, just return the first string */
1225     td->data = entry->data;
1226
1227     /* XXX Drepper sez' this is the order. */
1228     if ((lang = getenv("LANGUAGE")) == NULL &&
1229         (lang = getenv("LC_ALL")) == NULL &&
1230         (lang = getenv("LC_MESSAGES")) == NULL &&
1231         (lang = getenv("LANG")) == NULL)
1232             goto exit;
1233     
1234     if ((table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE)) == NULL)
1235         goto exit;
1236
1237     for (l = lang; *l != '\0'; l = le) {
1238         const char *t;
1239         char *ed, *ed_weak = NULL;
1240         int langNum;
1241
1242         while (*l && *l == ':')                 /* skip leading colons */
1243             l++;
1244         if (*l == '\0')
1245             break;
1246         for (le = l; *le && *le != ':'; le++)   /* find end of this locale */
1247             {};
1248
1249         /* For each entry in the header ... */
1250         for (langNum = 0, t = table->data, ed = entry->data;
1251              langNum < entry->info.count;
1252              langNum++, t += strlen(t) + 1, ed += strlen(ed) + 1) {
1253
1254             int match = headerMatchLocale(t, l, le);
1255             if (match == 1) {
1256                 td->data = ed;
1257                 goto exit;
1258             } else if (match == 2) { 
1259                 ed_weak = ed;
1260             }
1261         }
1262         if (ed_weak) {
1263             td->data = ed_weak;
1264             goto exit;
1265         }
1266     }
1267
1268 exit:
1269     if (flags & HEADERGET_ALLOC) {
1270         td->data = xstrdup(td->data);
1271         td->flags |= RPMTD_ALLOCED;
1272     }
1273
1274     return 1;
1275 }
1276
1277 /**
1278  * Retrieve tag data from header.
1279  * @param h             header
1280  * @retval td           tag data container
1281  * @param flags         flags to control retrieval
1282  * @return              1 on success, 0 on not found
1283  */
1284 static int intGetTdEntry(Header h, rpmtd td, headerGetFlags flags)
1285 {
1286     indexEntry entry;
1287     int rc;
1288
1289     /* First find the tag */
1290     /* FIX: h modified by sort. */
1291     entry = findEntry(h, td->tag, RPM_NULL_TYPE);
1292     if (entry == NULL) {
1293         /* Td is zeroed above, just return... */
1294         return 0;
1295     }
1296
1297     if (flags & HEADERGET_RAW) {
1298         rc = copyTdEntry(entry, td, flags);
1299     } else {
1300         switch (entry->info.type) {
1301         case RPM_I18NSTRING_TYPE:
1302             rc = copyI18NEntry(h, entry, td, flags);
1303             break;
1304         default:
1305             rc = copyTdEntry(entry, td, flags);
1306             break;
1307         }
1308     }
1309
1310     /* XXX 1 on success */
1311     return ((rc == 1) ? 1 : 0);
1312 }
1313
1314 int headerGet(Header h, rpmTagVal tag, rpmtd td, headerGetFlags flags)
1315 {
1316     int rc;
1317     headerTagTagFunction tagfunc = intGetTdEntry;
1318
1319     if (td == NULL) return 0;
1320
1321     rpmtdReset(td);
1322     td->tag = tag;
1323
1324     if (flags & HEADERGET_EXT) {
1325         headerTagTagFunction extfunc = rpmHeaderTagFunc(tag);
1326         if (extfunc) tagfunc = extfunc;
1327     }
1328     rc = tagfunc(h, td, flags);
1329
1330     assert(tag == td->tag);
1331     return rc;
1332 }
1333
1334 /**
1335  */
1336 static void copyData(rpm_tagtype_t type, rpm_data_t dstPtr, 
1337                 rpm_constdata_t srcPtr, rpm_count_t cnt, int dataLength)
1338 {
1339     switch (type) {
1340     case RPM_STRING_ARRAY_TYPE:
1341     case RPM_I18NSTRING_TYPE:
1342     {   const char ** av = (const char **) srcPtr;
1343         char * t = dstPtr;
1344
1345         while (cnt-- > 0 && dataLength > 0) {
1346             const char * s;
1347             if ((s = *av++) == NULL)
1348                 continue;
1349             do {
1350                 *t++ = *s++;
1351             } while (s[-1] && --dataLength > 0);
1352         }
1353     }   break;
1354
1355     default:
1356         memmove(dstPtr, srcPtr, dataLength);
1357         break;
1358     }
1359 }
1360
1361 /**
1362  * Return (malloc'ed) copy of entry data.
1363  * @param type          entry data type
1364  * @param p             entry data
1365  * @param c             entry item count
1366  * @retval lengthPtr    no. bytes in returned data
1367  * @return              (malloc'ed) copy of entry data, NULL on error
1368  */
1369 static void *
1370 grabData(rpm_tagtype_t type, rpm_constdata_t p, rpm_count_t c, int * lengthPtr)
1371 {
1372     rpm_data_t data = NULL;
1373     int length;
1374
1375     length = dataLength(type, p, c, 0, NULL);
1376     if (length > 0) {
1377         data = xmalloc(length);
1378         copyData(type, data, p, c, length);
1379     }
1380
1381     if (lengthPtr)
1382         *lengthPtr = length;
1383     return data;
1384 }
1385
1386 static int intAddEntry(Header h, rpmtd td)
1387 {
1388     indexEntry entry;
1389     rpm_data_t data;
1390     int length;
1391
1392     /* Count must always be >= 1 for headerAddEntry. */
1393     if (td->count <= 0)
1394         return 0;
1395
1396     if (hdrchkType(td->type))
1397         return 0;
1398     if (hdrchkData(td->count))
1399         return 0;
1400
1401     length = 0;
1402     data = grabData(td->type, td->data, td->count, &length);
1403     if (data == NULL || length <= 0)
1404         return 0;
1405
1406     /* Allocate more index space if necessary */
1407     if (h->indexUsed == h->indexAlloced) {
1408         h->indexAlloced += INDEX_MALLOC_SIZE;
1409         h->index = xrealloc(h->index, h->indexAlloced * sizeof(*h->index));
1410     }
1411
1412     /* Fill in the index */
1413     entry = h->index + h->indexUsed;
1414     entry->info.tag = td->tag;
1415     entry->info.type = td->type;
1416     entry->info.count = td->count;
1417     entry->info.offset = 0;
1418     entry->data = data;
1419     entry->length = length;
1420
1421     if (h->indexUsed > 0 && td->tag < h->index[h->indexUsed-1].info.tag)
1422         h->flags &= ~HEADERFLAG_SORTED;
1423     h->indexUsed++;
1424
1425     return 1;
1426 }
1427
1428 static int intAppendEntry(Header h, rpmtd td)
1429 {
1430     indexEntry entry;
1431     int length;
1432
1433     if (td->type == RPM_STRING_TYPE || td->type == RPM_I18NSTRING_TYPE) {
1434         /* we can't do this */
1435         return 0;
1436     }
1437
1438     /* Find the tag entry in the header. */
1439     entry = findEntry(h, td->tag, td->type);
1440     if (!entry)
1441         return 0;
1442
1443     length = dataLength(td->type, td->data, td->count, 0, NULL);
1444     if (length < 0)
1445         return 0;
1446
1447     if (ENTRY_IN_REGION(entry)) {
1448         char * t = xmalloc(entry->length + length);
1449         memcpy(t, entry->data, entry->length);
1450         entry->data = t;
1451         entry->info.offset = 0;
1452     } else
1453         entry->data = xrealloc(entry->data, entry->length + length);
1454
1455     copyData(td->type, ((char *) entry->data) + entry->length, 
1456              td->data, td->count, length);
1457
1458     entry->length += length;
1459
1460     entry->info.count += td->count;
1461
1462     return 1;
1463 }
1464
1465 int headerPut(Header h, rpmtd td, headerPutFlags flags)
1466 {
1467     int rc;
1468     
1469     assert(td != NULL);
1470     if (flags & HEADERPUT_APPEND) {
1471         rc = findEntry(h, td->tag, td->type) ?
1472                 intAppendEntry(h, td) :
1473                 intAddEntry(h, td);
1474     } else {
1475         rc = intAddEntry(h, td);
1476     }
1477     return rc;
1478 }
1479
1480 int headerAddI18NString(Header h, rpmTagVal tag, const char * string,
1481                 const char * lang)
1482 {
1483     indexEntry table, entry;
1484     const char ** strArray;
1485     int length;
1486     int ghosts;
1487     rpm_count_t i, langNum;
1488     char * buf;
1489
1490     table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE);
1491     entry = findEntry(h, tag, RPM_I18NSTRING_TYPE);
1492
1493     if (!table && entry)
1494         return 0;               /* this shouldn't ever happen!! */
1495
1496     if (!table && !entry) {
1497         const char * charArray[2];
1498         rpm_count_t count = 0;
1499         struct rpmtd_s td;
1500         if (!lang || (lang[0] == 'C' && lang[1] == '\0')) {
1501             charArray[count++] = "C";
1502         } else {
1503             charArray[count++] = "C";
1504             charArray[count++] = lang;
1505         }
1506         
1507         rpmtdReset(&td);
1508         td.tag = RPMTAG_HEADERI18NTABLE;
1509         td.type = RPM_STRING_ARRAY_TYPE;
1510         td.data = (void *) charArray;
1511         td.count = count;
1512         if (!headerPut(h, &td, HEADERPUT_DEFAULT))
1513             return 0;
1514         table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE);
1515     }
1516
1517     if (!table)
1518         return 0;
1519     if (!lang) lang = "C";
1520
1521     {   const char * l = table->data;
1522         for (langNum = 0; langNum < table->info.count; langNum++) {
1523             if (rstreq(l, lang)) break;
1524             l += strlen(l) + 1;
1525         }
1526     }
1527
1528     if (langNum >= table->info.count) {
1529         length = strlen(lang) + 1;
1530         if (ENTRY_IN_REGION(table)) {
1531             char * t = xmalloc(table->length + length);
1532             memcpy(t, table->data, table->length);
1533             table->data = t;
1534             table->info.offset = 0;
1535         } else
1536             table->data = xrealloc(table->data, table->length + length);
1537         memmove(((char *)table->data) + table->length, lang, length);
1538         table->length += length;
1539         table->info.count++;
1540     }
1541
1542     if (!entry) {
1543         int rc;
1544         struct rpmtd_s td;
1545         strArray = xmalloc(sizeof(*strArray) * (langNum + 1));
1546         for (i = 0; i < langNum; i++)
1547             strArray[i] = "";
1548         strArray[langNum] = string;
1549
1550         rpmtdReset(&td);
1551         td.tag = tag;
1552         td.type = RPM_I18NSTRING_TYPE;
1553         td.data = strArray;
1554         td.count = langNum + 1;
1555         rc = headerPut(h, &td, HEADERPUT_DEFAULT);
1556         free(strArray);
1557         return rc;
1558     } else if (langNum >= entry->info.count) {
1559         ghosts = langNum - entry->info.count;
1560         
1561         length = strlen(string) + 1 + ghosts;
1562         if (ENTRY_IN_REGION(entry)) {
1563             char * t = xmalloc(entry->length + length);
1564             memcpy(t, entry->data, entry->length);
1565             entry->data = t;
1566             entry->info.offset = 0;
1567         } else
1568             entry->data = xrealloc(entry->data, entry->length + length);
1569
1570         memset(((char *)entry->data) + entry->length, '\0', ghosts);
1571         memmove(((char *)entry->data) + entry->length + ghosts, string, strlen(string)+1);
1572
1573         entry->length += length;
1574         entry->info.count = langNum + 1;
1575     } else {
1576         char *b, *be, *e, *ee, *t;
1577         size_t bn, sn, en;
1578
1579         /* Set beginning/end pointers to previous data */
1580         b = be = e = ee = entry->data;
1581         for (i = 0; i < table->info.count; i++) {
1582             if (i == langNum)
1583                 be = ee;
1584             ee += strlen(ee) + 1;
1585             if (i == langNum)
1586                 e  = ee;
1587         }
1588
1589         /* Get storage for new buffer */
1590         bn = (be-b);
1591         sn = strlen(string) + 1;
1592         en = (ee-e);
1593         length = bn + sn + en;
1594         t = buf = xmalloc(length);
1595
1596         /* Copy values into new storage */
1597         memcpy(t, b, bn);
1598         t += bn;
1599         memcpy(t, string, sn);
1600         t += sn;
1601         memcpy(t, e, en);
1602         t += en;
1603
1604         /* Replace i18N string array */
1605         entry->length -= strlen(be) + 1;
1606         entry->length += sn;
1607         
1608         if (ENTRY_IN_REGION(entry)) {
1609             entry->info.offset = 0;
1610         } else
1611             entry->data = _free(entry->data);
1612         entry->data = buf;
1613     }
1614
1615     return 0;
1616 }
1617
1618 int headerMod(Header h, rpmtd td)
1619 {
1620     indexEntry entry;
1621     rpm_data_t oldData;
1622     rpm_data_t data;
1623     int length;
1624
1625     /* First find the tag */
1626     entry = findEntry(h, td->tag, td->type);
1627     if (!entry)
1628         return 0;
1629
1630     length = 0;
1631     data = grabData(td->type, td->data, td->count, &length);
1632     if (data == NULL || length <= 0)
1633         return 0;
1634
1635     /* make sure entry points to the first occurence of this tag */
1636     while (entry > h->index && (entry - 1)->info.tag == td->tag)  
1637         entry--;
1638
1639     /* free after we've grabbed the new data in case the two are intertwined;
1640        that's a bad idea but at least we won't break */
1641     oldData = entry->data;
1642
1643     entry->info.count = td->count;
1644     entry->info.type = td->type;
1645     entry->data = data;
1646     entry->length = length;
1647
1648     if (ENTRY_IN_REGION(entry)) {
1649         entry->info.offset = 0;
1650     } else
1651         free(oldData);
1652
1653     return 1;
1654 }
1655
1656 /**
1657  * Header tag iterator data structure.
1658  */
1659 struct headerIterator_s {
1660     Header h;           /*!< Header being iterated. */
1661     int next_index;     /*!< Next tag index. */
1662 };
1663
1664 HeaderIterator headerFreeIterator(HeaderIterator hi)
1665 {
1666     if (hi != NULL) {
1667         hi->h = headerFree(hi->h);
1668         hi = _free(hi);
1669     }
1670     return NULL;
1671 }
1672
1673 HeaderIterator headerInitIterator(Header h)
1674 {
1675     HeaderIterator hi = xmalloc(sizeof(*hi));
1676
1677     headerSort(h);
1678
1679     hi->h = headerLink(h);
1680     hi->next_index = 0;
1681     return hi;
1682 }
1683
1684 static indexEntry nextIndex(HeaderIterator hi)
1685 {
1686     Header h = hi->h;
1687     int slot;
1688     indexEntry entry = NULL;
1689
1690     for (slot = hi->next_index; slot < h->indexUsed; slot++) {
1691         entry = h->index + slot;
1692         if (!ENTRY_IS_REGION(entry))
1693             break;
1694     }
1695     hi->next_index = slot;
1696     if (entry == NULL || slot >= h->indexUsed)
1697         return NULL;
1698
1699     hi->next_index++;
1700     return entry;
1701 }
1702
1703 rpmTagVal headerNextTag(HeaderIterator hi)
1704 {
1705     indexEntry entry = nextIndex(hi);
1706     return entry ? entry->info.tag : RPMTAG_NOT_FOUND;
1707 }
1708
1709 int headerNext(HeaderIterator hi, rpmtd td)
1710 {
1711     indexEntry entry = nextIndex(hi);
1712     int rc = 0;
1713
1714     rpmtdReset(td);
1715     if (entry) {
1716         td->tag = entry->info.tag;
1717         rc = copyTdEntry(entry, td, HEADERGET_DEFAULT);
1718     }
1719     return ((rc == 1) ? 1 : 0);
1720 }
1721
1722 unsigned int headerGetInstance(Header h)
1723 {
1724     return h ? h->instance : 0;
1725 }
1726
1727 void headerSetInstance(Header h, unsigned int instance)
1728 {
1729     h->instance = instance;
1730 }    
1731