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