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