Specifically validate region tag on header import
[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         entry->info.tag = htonl(pe->tag);
832
833         if (!ENTRY_IS_REGION(entry))
834             goto errxit;
835         if (entry->info.type != REGION_TAG_TYPE)
836             goto errxit;
837         if (entry->info.count != REGION_TAG_COUNT)
838             goto errxit;
839
840         {   int off = ntohl(pe->offset);
841
842             if (off) {
843                 size_t nb = REGION_TAG_COUNT;
844                 int32_t stei[nb];
845                 if (hdrchkRange(dl, (off + nb)))
846                     goto errxit;
847                 /* XXX Hmm, why the copy? */
848                 memcpy(&stei, dataStart + off, nb);
849                 rdl = -ntohl(stei[2]);  /* negative offset */
850                 ril = rdl/sizeof(*pe);
851                 if (hdrchkTags(ril) || hdrchkData(rdl))
852                     goto errxit;
853             } else {
854                 ril = il;
855                 rdl = (ril * sizeof(struct entryInfo_s));
856                 entry->info.tag = RPMTAG_HEADERIMAGE;
857             }
858         }
859         entry->info.offset = -rdl;      /* negative offset */
860
861         entry->data = pe;
862         entry->length = pvlen - sizeof(il) - sizeof(dl);
863         rdlen = regionSwab(entry+1, ril-1, 0, pe+1,
864                            dataStart, dataEnd, entry->info.offset, fast);
865         if (rdlen < 0)
866             goto errxit;
867         entry->rdlen = rdlen;
868
869         if (ril < h->indexUsed) {
870             indexEntry newEntry = entry + ril;
871             int ne = (h->indexUsed - ril);
872             int rid = entry->info.offset+1;
873
874             /* Load dribble entries from region. */
875             rdlen = regionSwab(newEntry, ne, rdlen, pe+ril,
876                                 dataStart, dataEnd, rid, fast);
877             if (rdlen < 0)
878                 goto errxit;
879
880           { indexEntry firstEntry = newEntry;
881             int save = h->indexUsed;
882             int j;
883
884             /* Dribble entries replace duplicate region entries. */
885             h->indexUsed -= ne;
886             for (j = 0; j < ne; j++, newEntry++) {
887                 (void) headerDel(h, newEntry->info.tag);
888                 if (newEntry->info.tag == RPMTAG_BASENAMES)
889                     (void) headerDel(h, RPMTAG_OLDFILENAMES);
890             }
891
892             /* If any duplicate entries were replaced, move new entries down. */
893             if (h->indexUsed < (save - ne)) {
894                 memmove(h->index + h->indexUsed, firstEntry,
895                         (ne * sizeof(*entry)));
896             }
897             h->indexUsed += ne;
898           }
899         }
900
901         rdlen += REGION_TAG_COUNT;
902
903         if (rdlen != dl)
904             goto errxit;
905     }
906
907     h->flags &= ~HEADERFLAG_SORTED;
908     headerSort(h);
909     h->flags |= HEADERFLAG_ALLOCATED;
910
911     return h;
912
913 errxit:
914     if (h) {
915         if (flags & HEADERIMPORT_COPY)
916             free(h->blob);
917         free(h->index);
918         free(h);
919     }
920     return NULL;
921 }
922
923 Header headerReload(Header h, rpmTagVal tag)
924 {
925     Header nh;
926     unsigned int uc = 0;
927     void * uh = headerExport(h, &uc);
928
929     h = headerFree(h);
930     if (uh == NULL)
931         return NULL;
932     nh = headerImport(uh, uc, 0);
933     if (nh == NULL) {
934         uh = _free(uh);
935         return NULL;
936     }
937     if (ENTRY_IS_REGION(nh->index)) {
938         if (tag == RPMTAG_HEADERSIGNATURES || tag == RPMTAG_HEADERIMMUTABLE)
939             nh->index[0].info.tag = tag;
940     }
941     return nh;
942 }
943
944 Header headerLoad(void * uh)
945 {
946     return headerImport(uh, 0, 0);
947 }
948
949 Header headerCopyLoad(const void * uh)
950 {
951     /* Discards const but that's ok as we'll take a copy */
952     return headerImport((void *)uh, 0, HEADERIMPORT_COPY);
953 }
954
955 Header headerRead(FD_t fd, int magicp)
956 {
957     int32_t block[4];
958     int32_t * ei = NULL;
959     int32_t il;
960     int32_t dl;
961     Header h = NULL;
962     unsigned int len, blen;
963
964     if (magicp == HEADER_MAGIC_YES) {
965         int32_t magic;
966
967         if (Fread(block, 1, 4*sizeof(*block), fd) != 4*sizeof(*block))
968             goto exit;
969
970         magic = block[0];
971
972         if (memcmp(&magic, rpm_header_magic, sizeof(magic)))
973             goto exit;
974
975         il = ntohl(block[2]);
976         dl = ntohl(block[3]);
977     } else {
978         if (Fread(block, 1, 2*sizeof(*block), fd) != 2*sizeof(*block))
979             goto exit;
980
981         il = ntohl(block[0]);
982         dl = ntohl(block[1]);
983     }
984
985     blen = (il * sizeof(struct entryInfo_s)) + dl;
986     len = sizeof(il) + sizeof(dl) + blen;
987
988     /* Sanity checks on header intro. */
989     if (hdrchkTags(il) || hdrchkData(dl) || len > headerMaxbytes)
990         goto exit;
991
992     ei = xmalloc(len);
993     ei[0] = htonl(il);
994     ei[1] = htonl(dl);
995
996     if (Fread((char *)&ei[2], 1, blen, fd) != blen)
997         goto exit;
998     
999     h = headerImport(ei, len, 0);
1000
1001 exit:
1002     if (h == NULL && ei != NULL) {
1003         free(ei);
1004     }
1005     return h;
1006 }
1007
1008 int headerWrite(FD_t fd, Header h, int magicp)
1009 {
1010     ssize_t nb;
1011     unsigned int length;
1012     void * uh;
1013
1014     uh = headerExport(h, &length);
1015     if (uh == NULL)
1016         return 1;
1017     switch (magicp) {
1018     case HEADER_MAGIC_YES:
1019         nb = Fwrite(rpm_header_magic, sizeof(uint8_t), sizeof(rpm_header_magic), fd);
1020         if (nb != sizeof(rpm_header_magic))
1021             goto exit;
1022         break;
1023     case HEADER_MAGIC_NO:
1024         break;
1025     }
1026
1027     nb = Fwrite(uh, sizeof(char), length, fd);
1028
1029 exit:
1030     free(uh);
1031     return (nb == length ? 0 : 1);
1032 }
1033
1034 int headerIsEntry(Header h, rpmTagVal tag)
1035 {
1036                 /* FIX: h modified by sort. */
1037     return (findEntry(h, tag, RPM_NULL_TYPE) ? 1 : 0);
1038         
1039 }
1040
1041 /** \ingroup header
1042  * Retrieve data from header entry.
1043  * Relevant flags (others are ignored), if neither is set allocation
1044  * behavior depends on data type(!) 
1045  *     HEADERGET_MINMEM: return pointers to header memory
1046  *     HEADERGET_ALLOC: always return malloced memory, overrides MINMEM
1047  * 
1048  * @todo Permit retrieval of regions other than HEADER_IMUTABLE.
1049  * @param entry         header entry
1050  * @param td            tag data container
1051  * @param minMem        string pointers refer to header memory?
1052  * @param flags         flags to control memory allocation
1053  * @return              1 on success, otherwise error.
1054  */
1055 static int copyTdEntry(const indexEntry entry, rpmtd td, headerGetFlags flags)
1056 {
1057     rpm_count_t count = entry->info.count;
1058     int rc = 1;         /* XXX 1 on success. */
1059     /* ALLOC overrides MINMEM */
1060     int allocMem = flags & HEADERGET_ALLOC;
1061     int minMem = allocMem ? 0 : flags & HEADERGET_MINMEM;
1062     int argvArray = (flags & HEADERGET_ARGV) ? 1 : 0;
1063
1064     assert(td != NULL);
1065     td->flags = RPMTD_IMMUTABLE;
1066     switch (entry->info.type) {
1067     case RPM_BIN_TYPE:
1068         /*
1069          * XXX This only works for
1070          * XXX  "sealed" HEADER_IMMUTABLE/HEADER_SIGNATURES/HEADER_IMAGE.
1071          * XXX This will *not* work for unsealed legacy HEADER_IMAGE (i.e.
1072          * XXX a legacy header freshly read, but not yet unloaded to the rpmdb).
1073          */
1074         if (ENTRY_IS_REGION(entry)) {
1075             int32_t * ei = ((int32_t *)entry->data) - 2;
1076             entryInfo pe = (entryInfo) (ei + 2);
1077             unsigned char * dataStart = (unsigned char *) (pe + ntohl(ei[0]));
1078             int32_t rdl = -entry->info.offset;  /* negative offset */
1079             int32_t ril = rdl/sizeof(*pe);
1080
1081             rdl = entry->rdlen;
1082             count = 2 * sizeof(*ei) + (ril * sizeof(*pe)) + rdl;
1083             if (entry->info.tag == RPMTAG_HEADERIMAGE) {
1084                 ril -= 1;
1085                 pe += 1;
1086             } else {
1087                 count += REGION_TAG_COUNT;
1088                 rdl += REGION_TAG_COUNT;
1089             }
1090
1091             td->data = xmalloc(count);
1092             ei = (int32_t *) td->data;
1093             ei[0] = htonl(ril);
1094             ei[1] = htonl(rdl);
1095
1096             pe = (entryInfo) memcpy(ei + 2, pe, (ril * sizeof(*pe)));
1097
1098             dataStart = (unsigned char *) memcpy(pe + ril, dataStart, rdl);
1099
1100             rc = regionSwab(NULL, ril, 0, pe, dataStart, dataStart + rdl, 0, 0);
1101             /* don't return data on failure */
1102             if (rc < 0) {
1103                 td->data = _free(td->data);
1104             }
1105             /* XXX 1 on success. */
1106             rc = (rc < 0) ? 0 : 1;
1107         } else {
1108             count = entry->length;
1109             td->data = (!minMem
1110                 ? memcpy(xmalloc(count), entry->data, count)
1111                 : entry->data);
1112         }
1113         break;
1114     case RPM_STRING_TYPE:
1115         /* simple string, but fallthrough if its actually an array */
1116         if (count == 1 && !argvArray) {
1117             td->data = allocMem ? xstrdup(entry->data) : entry->data;
1118             break;
1119         }
1120     case RPM_STRING_ARRAY_TYPE:
1121     case RPM_I18NSTRING_TYPE:
1122     {   const char ** ptrEntry;
1123         int tableSize = (count + argvArray) * sizeof(char *);
1124         char * t;
1125         int i;
1126
1127         if (minMem) {
1128             td->data = xmalloc(tableSize);
1129             ptrEntry = (const char **) td->data;
1130             t = entry->data;
1131         } else {
1132             t = xmalloc(tableSize + entry->length);
1133             td->data = (void *)t;
1134             ptrEntry = (const char **) td->data;
1135             t += tableSize;
1136             memcpy(t, entry->data, entry->length);
1137         }
1138         for (i = 0; i < count; i++) {
1139             *ptrEntry++ = t;
1140             t = strchr(t, 0);
1141             t++;
1142         }
1143         if (argvArray) {
1144             *ptrEntry = NULL;
1145             td->flags |= RPMTD_ARGV;
1146         }
1147     }   break;
1148     case RPM_CHAR_TYPE:
1149     case RPM_INT8_TYPE:
1150     case RPM_INT16_TYPE:
1151     case RPM_INT32_TYPE:
1152     case RPM_INT64_TYPE:
1153         if (allocMem) {
1154             td->data = xmalloc(entry->length);
1155             memcpy(td->data, entry->data, entry->length);
1156         } else {
1157             td->data = entry->data;
1158         }
1159         break;
1160     default:
1161         /* WTH? Don't mess with unknown data types... */
1162         rc = 0;
1163         td->data = NULL;
1164         break;
1165     }
1166     td->type = entry->info.type;
1167     td->count = count;
1168
1169     if (td->data && entry->data != td->data) {
1170         td->flags |= RPMTD_ALLOCED;
1171     }
1172
1173     return rc;
1174 }
1175
1176 /**
1177  * Does locale match entry in header i18n table?
1178  * 
1179  * \verbatim
1180  * The range [l,le) contains the next locale to match:
1181  *    ll[_CC][.EEEEE][@dddd]
1182  * where
1183  *    ll        ISO language code (in lowercase).
1184  *    CC        (optional) ISO coutnry code (in uppercase).
1185  *    EEEEE     (optional) encoding (not really standardized).
1186  *    dddd      (optional) dialect.
1187  * \endverbatim
1188  *
1189  * @param td            header i18n table data, NUL terminated
1190  * @param l             start of locale to match
1191  * @param le            end of locale to match
1192  * @return              1 on good match, 2 on weak match, 0 on no match
1193  */
1194 static int headerMatchLocale(const char *td, const char *l, const char *le)
1195 {
1196     const char *fe;
1197
1198     /* First try a complete match. */
1199     if (strlen(td) == (le-l) && rstreqn(td, l, (le - l)))
1200         return 1;
1201
1202     /* Next, try stripping optional dialect and matching.  */
1203     for (fe = l; fe < le && *fe != '@'; fe++)
1204         {};
1205     if (fe < le && rstreqn(td, l, (fe - l)))
1206         return 1;
1207
1208     /* Next, try stripping optional codeset and matching.  */
1209     for (fe = l; fe < le && *fe != '.'; fe++)
1210         {};
1211     if (fe < le && rstreqn(td, l, (fe - l)))
1212         return 1;
1213
1214     /* Finally, try stripping optional country code and matching. */
1215     for (fe = l; fe < le && *fe != '_'; fe++)
1216         {};
1217     if (fe < le && rstreqn(td, l, (fe - l)))
1218         return 2;
1219
1220     return 0;
1221 }
1222
1223 /**
1224  * Return i18n string from header that matches locale.
1225  * @param h             header
1226  * @param entry         i18n string data
1227  * @retval td           tag data container
1228  * @param flags         flags to control allocation
1229  * @return              1 always
1230  */
1231 static int copyI18NEntry(Header h, indexEntry entry, rpmtd td, 
1232                                                 headerGetFlags flags)
1233 {
1234     const char *lang, *l, *le;
1235     indexEntry table;
1236
1237     td->type = RPM_STRING_TYPE;
1238     td->count = 1;
1239     /* if no match, just return the first string */
1240     td->data = entry->data;
1241
1242     /* XXX Drepper sez' this is the order. */
1243     if ((lang = getenv("LANGUAGE")) == NULL &&
1244         (lang = getenv("LC_ALL")) == NULL &&
1245         (lang = getenv("LC_MESSAGES")) == NULL &&
1246         (lang = getenv("LANG")) == NULL)
1247             goto exit;
1248     
1249     if ((table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE)) == NULL)
1250         goto exit;
1251
1252     for (l = lang; *l != '\0'; l = le) {
1253         const char *t;
1254         char *ed, *ed_weak = NULL;
1255         int langNum;
1256
1257         while (*l && *l == ':')                 /* skip leading colons */
1258             l++;
1259         if (*l == '\0')
1260             break;
1261         for (le = l; *le && *le != ':'; le++)   /* find end of this locale */
1262             {};
1263
1264         /* For each entry in the header ... */
1265         for (langNum = 0, t = table->data, ed = entry->data;
1266              langNum < entry->info.count;
1267              langNum++, t += strlen(t) + 1, ed += strlen(ed) + 1) {
1268
1269             int match = headerMatchLocale(t, l, le);
1270             if (match == 1) {
1271                 td->data = ed;
1272                 goto exit;
1273             } else if (match == 2) { 
1274                 ed_weak = ed;
1275             }
1276         }
1277         if (ed_weak) {
1278             td->data = ed_weak;
1279             goto exit;
1280         }
1281     }
1282
1283 exit:
1284     if (flags & HEADERGET_ALLOC) {
1285         td->data = xstrdup(td->data);
1286         td->flags |= RPMTD_ALLOCED;
1287     }
1288
1289     return 1;
1290 }
1291
1292 /**
1293  * Retrieve tag data from header.
1294  * @param h             header
1295  * @retval td           tag data container
1296  * @param flags         flags to control retrieval
1297  * @return              1 on success, 0 on not found
1298  */
1299 static int intGetTdEntry(Header h, rpmtd td, headerGetFlags flags)
1300 {
1301     indexEntry entry;
1302     int rc;
1303
1304     /* First find the tag */
1305     /* FIX: h modified by sort. */
1306     entry = findEntry(h, td->tag, RPM_NULL_TYPE);
1307     if (entry == NULL) {
1308         /* Td is zeroed above, just return... */
1309         return 0;
1310     }
1311
1312     if (flags & HEADERGET_RAW) {
1313         rc = copyTdEntry(entry, td, flags);
1314     } else {
1315         switch (entry->info.type) {
1316         case RPM_I18NSTRING_TYPE:
1317             rc = copyI18NEntry(h, entry, td, flags);
1318             break;
1319         default:
1320             rc = copyTdEntry(entry, td, flags);
1321             break;
1322         }
1323     }
1324
1325     if (rc == 0)
1326         td->flags |= RPMTD_INVALID;
1327
1328     /* XXX 1 on success */
1329     return ((rc == 1) ? 1 : 0);
1330 }
1331
1332 int headerGet(Header h, rpmTagVal tag, rpmtd td, headerGetFlags flags)
1333 {
1334     int rc;
1335     headerTagTagFunction tagfunc = intGetTdEntry;
1336
1337     if (td == NULL) return 0;
1338
1339     rpmtdReset(td);
1340     td->tag = tag;
1341
1342     if (flags & HEADERGET_EXT) {
1343         headerTagTagFunction extfunc = rpmHeaderTagFunc(tag);
1344         if (extfunc) tagfunc = extfunc;
1345     }
1346     rc = tagfunc(h, td, flags);
1347
1348     assert(tag == td->tag);
1349     return rc;
1350 }
1351
1352 /**
1353  */
1354 static void copyData(rpm_tagtype_t type, rpm_data_t dstPtr, 
1355                 rpm_constdata_t srcPtr, rpm_count_t cnt, int dataLength)
1356 {
1357     switch (type) {
1358     case RPM_STRING_ARRAY_TYPE:
1359     case RPM_I18NSTRING_TYPE:
1360     {   const char ** av = (const char **) srcPtr;
1361         char * t = dstPtr;
1362
1363         while (cnt-- > 0 && dataLength > 0) {
1364             const char * s;
1365             if ((s = *av++) == NULL)
1366                 continue;
1367             do {
1368                 *t++ = *s++;
1369             } while (s[-1] && --dataLength > 0);
1370         }
1371     }   break;
1372
1373     default:
1374         memmove(dstPtr, srcPtr, dataLength);
1375         break;
1376     }
1377 }
1378
1379 /**
1380  * Return (malloc'ed) copy of entry data.
1381  * @param type          entry data type
1382  * @param p             entry data
1383  * @param c             entry item count
1384  * @retval lengthPtr    no. bytes in returned data
1385  * @return              (malloc'ed) copy of entry data, NULL on error
1386  */
1387 static void *
1388 grabData(rpm_tagtype_t type, rpm_constdata_t p, rpm_count_t c, int * lengthPtr)
1389 {
1390     rpm_data_t data = NULL;
1391     int length;
1392
1393     length = dataLength(type, p, c, 0, NULL);
1394     if (length > 0) {
1395         data = xmalloc(length);
1396         copyData(type, data, p, c, length);
1397     }
1398
1399     if (lengthPtr)
1400         *lengthPtr = length;
1401     return data;
1402 }
1403
1404 static int intAddEntry(Header h, rpmtd td)
1405 {
1406     indexEntry entry;
1407     rpm_data_t data;
1408     int length;
1409
1410     /* Count must always be >= 1 for headerAddEntry. */
1411     if (td->count <= 0)
1412         return 0;
1413
1414     if (hdrchkType(td->type))
1415         return 0;
1416     if (hdrchkData(td->count))
1417         return 0;
1418
1419     length = 0;
1420     data = grabData(td->type, td->data, td->count, &length);
1421     if (data == NULL || length <= 0)
1422         return 0;
1423
1424     /* Allocate more index space if necessary */
1425     if (h->indexUsed == h->indexAlloced) {
1426         h->indexAlloced += INDEX_MALLOC_SIZE;
1427         h->index = xrealloc(h->index, h->indexAlloced * sizeof(*h->index));
1428     }
1429
1430     /* Fill in the index */
1431     entry = h->index + h->indexUsed;
1432     entry->info.tag = td->tag;
1433     entry->info.type = td->type;
1434     entry->info.count = td->count;
1435     entry->info.offset = 0;
1436     entry->data = data;
1437     entry->length = length;
1438
1439     if (h->indexUsed > 0 && td->tag < h->index[h->indexUsed-1].info.tag)
1440         h->flags &= ~HEADERFLAG_SORTED;
1441     h->indexUsed++;
1442
1443     return 1;
1444 }
1445
1446 static int intAppendEntry(Header h, rpmtd td)
1447 {
1448     indexEntry entry;
1449     int length;
1450
1451     if (td->type == RPM_STRING_TYPE || td->type == RPM_I18NSTRING_TYPE) {
1452         /* we can't do this */
1453         return 0;
1454     }
1455
1456     /* Find the tag entry in the header. */
1457     entry = findEntry(h, td->tag, td->type);
1458     if (!entry)
1459         return 0;
1460
1461     length = dataLength(td->type, td->data, td->count, 0, NULL);
1462     if (length < 0)
1463         return 0;
1464
1465     if (ENTRY_IN_REGION(entry)) {
1466         char * t = xmalloc(entry->length + length);
1467         memcpy(t, entry->data, entry->length);
1468         entry->data = t;
1469         entry->info.offset = 0;
1470     } else
1471         entry->data = xrealloc(entry->data, entry->length + length);
1472
1473     copyData(td->type, ((char *) entry->data) + entry->length, 
1474              td->data, td->count, length);
1475
1476     entry->length += length;
1477
1478     entry->info.count += td->count;
1479
1480     return 1;
1481 }
1482
1483 int headerPut(Header h, rpmtd td, headerPutFlags flags)
1484 {
1485     int rc;
1486     
1487     assert(td != NULL);
1488     if (flags & HEADERPUT_APPEND) {
1489         rc = findEntry(h, td->tag, td->type) ?
1490                 intAppendEntry(h, td) :
1491                 intAddEntry(h, td);
1492     } else {
1493         rc = intAddEntry(h, td);
1494     }
1495     return rc;
1496 }
1497
1498 int headerAddI18NString(Header h, rpmTagVal tag, const char * string,
1499                 const char * lang)
1500 {
1501     indexEntry table, entry;
1502     const char ** strArray;
1503     int length;
1504     int ghosts;
1505     rpm_count_t i, langNum;
1506     char * buf;
1507
1508     table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE);
1509     entry = findEntry(h, tag, RPM_I18NSTRING_TYPE);
1510
1511     if (!table && entry)
1512         return 0;               /* this shouldn't ever happen!! */
1513
1514     if (!table && !entry) {
1515         const char * charArray[2];
1516         rpm_count_t count = 0;
1517         struct rpmtd_s td;
1518         if (!lang || (lang[0] == 'C' && lang[1] == '\0')) {
1519             charArray[count++] = "C";
1520         } else {
1521             charArray[count++] = "C";
1522             charArray[count++] = lang;
1523         }
1524         
1525         rpmtdReset(&td);
1526         td.tag = RPMTAG_HEADERI18NTABLE;
1527         td.type = RPM_STRING_ARRAY_TYPE;
1528         td.data = (void *) charArray;
1529         td.count = count;
1530         if (!headerPut(h, &td, HEADERPUT_DEFAULT))
1531             return 0;
1532         table = findEntry(h, RPMTAG_HEADERI18NTABLE, RPM_STRING_ARRAY_TYPE);
1533     }
1534
1535     if (!table)
1536         return 0;
1537     if (!lang) lang = "C";
1538
1539     {   const char * l = table->data;
1540         for (langNum = 0; langNum < table->info.count; langNum++) {
1541             if (rstreq(l, lang)) break;
1542             l += strlen(l) + 1;
1543         }
1544     }
1545
1546     if (langNum >= table->info.count) {
1547         length = strlen(lang) + 1;
1548         if (ENTRY_IN_REGION(table)) {
1549             char * t = xmalloc(table->length + length);
1550             memcpy(t, table->data, table->length);
1551             table->data = t;
1552             table->info.offset = 0;
1553         } else
1554             table->data = xrealloc(table->data, table->length + length);
1555         memmove(((char *)table->data) + table->length, lang, length);
1556         table->length += length;
1557         table->info.count++;
1558     }
1559
1560     if (!entry) {
1561         int rc;
1562         struct rpmtd_s td;
1563         strArray = xmalloc(sizeof(*strArray) * (langNum + 1));
1564         for (i = 0; i < langNum; i++)
1565             strArray[i] = "";
1566         strArray[langNum] = string;
1567
1568         rpmtdReset(&td);
1569         td.tag = tag;
1570         td.type = RPM_I18NSTRING_TYPE;
1571         td.data = strArray;
1572         td.count = langNum + 1;
1573         rc = headerPut(h, &td, HEADERPUT_DEFAULT);
1574         free(strArray);
1575         return rc;
1576     } else if (langNum >= entry->info.count) {
1577         ghosts = langNum - entry->info.count;
1578         
1579         length = strlen(string) + 1 + ghosts;
1580         if (ENTRY_IN_REGION(entry)) {
1581             char * t = xmalloc(entry->length + length);
1582             memcpy(t, entry->data, entry->length);
1583             entry->data = t;
1584             entry->info.offset = 0;
1585         } else
1586             entry->data = xrealloc(entry->data, entry->length + length);
1587
1588         memset(((char *)entry->data) + entry->length, '\0', ghosts);
1589         memmove(((char *)entry->data) + entry->length + ghosts, string, strlen(string)+1);
1590
1591         entry->length += length;
1592         entry->info.count = langNum + 1;
1593     } else {
1594         char *b, *be, *e, *ee, *t;
1595         size_t bn, sn, en;
1596
1597         /* Set beginning/end pointers to previous data */
1598         b = be = e = ee = entry->data;
1599         for (i = 0; i < table->info.count; i++) {
1600             if (i == langNum)
1601                 be = ee;
1602             ee += strlen(ee) + 1;
1603             if (i == langNum)
1604                 e  = ee;
1605         }
1606
1607         /* Get storage for new buffer */
1608         bn = (be-b);
1609         sn = strlen(string) + 1;
1610         en = (ee-e);
1611         length = bn + sn + en;
1612         t = buf = xmalloc(length);
1613
1614         /* Copy values into new storage */
1615         memcpy(t, b, bn);
1616         t += bn;
1617         memcpy(t, string, sn);
1618         t += sn;
1619         memcpy(t, e, en);
1620         t += en;
1621
1622         /* Replace i18N string array */
1623         entry->length -= strlen(be) + 1;
1624         entry->length += sn;
1625         
1626         if (ENTRY_IN_REGION(entry)) {
1627             entry->info.offset = 0;
1628         } else
1629             entry->data = _free(entry->data);
1630         entry->data = buf;
1631     }
1632
1633     return 0;
1634 }
1635
1636 int headerMod(Header h, rpmtd td)
1637 {
1638     indexEntry entry;
1639     rpm_data_t oldData;
1640     rpm_data_t data;
1641     int length;
1642
1643     /* First find the tag */
1644     entry = findEntry(h, td->tag, td->type);
1645     if (!entry)
1646         return 0;
1647
1648     length = 0;
1649     data = grabData(td->type, td->data, td->count, &length);
1650     if (data == NULL || length <= 0)
1651         return 0;
1652
1653     /* make sure entry points to the first occurence of this tag */
1654     while (entry > h->index && (entry - 1)->info.tag == td->tag)  
1655         entry--;
1656
1657     /* free after we've grabbed the new data in case the two are intertwined;
1658        that's a bad idea but at least we won't break */
1659     oldData = entry->data;
1660
1661     entry->info.count = td->count;
1662     entry->info.type = td->type;
1663     entry->data = data;
1664     entry->length = length;
1665
1666     if (ENTRY_IN_REGION(entry)) {
1667         entry->info.offset = 0;
1668     } else
1669         free(oldData);
1670
1671     return 1;
1672 }
1673
1674 /**
1675  * Header tag iterator data structure.
1676  */
1677 struct headerIterator_s {
1678     Header h;           /*!< Header being iterated. */
1679     int next_index;     /*!< Next tag index. */
1680 };
1681
1682 HeaderIterator headerFreeIterator(HeaderIterator hi)
1683 {
1684     if (hi != NULL) {
1685         hi->h = headerFree(hi->h);
1686         hi = _free(hi);
1687     }
1688     return NULL;
1689 }
1690
1691 HeaderIterator headerInitIterator(Header h)
1692 {
1693     HeaderIterator hi = xmalloc(sizeof(*hi));
1694
1695     headerSort(h);
1696
1697     hi->h = headerLink(h);
1698     hi->next_index = 0;
1699     return hi;
1700 }
1701
1702 static indexEntry nextIndex(HeaderIterator hi)
1703 {
1704     Header h = hi->h;
1705     int slot;
1706     indexEntry entry = NULL;
1707
1708     for (slot = hi->next_index; slot < h->indexUsed; slot++) {
1709         entry = h->index + slot;
1710         if (!ENTRY_IS_REGION(entry))
1711             break;
1712     }
1713     hi->next_index = slot;
1714     if (entry == NULL || slot >= h->indexUsed)
1715         return NULL;
1716
1717     hi->next_index++;
1718     return entry;
1719 }
1720
1721 rpmTagVal headerNextTag(HeaderIterator hi)
1722 {
1723     indexEntry entry = nextIndex(hi);
1724     return entry ? entry->info.tag : RPMTAG_NOT_FOUND;
1725 }
1726
1727 int headerNext(HeaderIterator hi, rpmtd td)
1728 {
1729     indexEntry entry = nextIndex(hi);
1730     int rc = 0;
1731
1732     rpmtdReset(td);
1733     if (entry) {
1734         td->tag = entry->info.tag;
1735         rc = copyTdEntry(entry, td, HEADERGET_DEFAULT);
1736     }
1737     return ((rc == 1) ? 1 : 0);
1738 }
1739
1740 unsigned int headerGetInstance(Header h)
1741 {
1742     return h ? h->instance : 0;
1743 }
1744
1745 void headerSetInstance(Header h, unsigned int instance)
1746 {
1747     h->instance = instance;
1748 }    
1749