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