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