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