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