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