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