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