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