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