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