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