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