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