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