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