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