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