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