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