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