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