archive.c 11.6 KB
Newer Older
1 2 3
/* archive.c - Alpine Package Keeper (APK)
 *
 * Copyright (C) 2005-2008 Natanael Copa <n@tanael.org>
4
 * Copyright (C) 2008-2011 Timo Teräs <timo.teras@iki.fi>
5 6
 * All rights reserved.
 *
7
 * This program is free software; you can redistribute it and/or modify it
8 9 10 11 12 13 14 15 16
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation. See http://www.gnu.org/ for details.
 */

#include <stdio.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
17
#include <utime.h>
18 19 20 21
#include <string.h>
#include <unistd.h>
#include <sysexits.h>
#include <sys/wait.h>
Natanael Copa's avatar
Natanael Copa committed
22
#include <sys/stat.h>
Timo Teräs's avatar
Timo Teräs committed
23
#include <sys/xattr.h>
24
#include <sys/sysmacros.h>
25
#include <limits.h>
Natanael Copa's avatar
Natanael Copa committed
26
#include <stdint.h>
Pierre Carrier's avatar
Pierre Carrier committed
27
#include <stdlib.h>
28 29

#include "apk_defines.h"
Natanael Copa's avatar
Natanael Copa committed
30
#include "apk_print.h"
31
#include "apk_archive.h"
Timo Teräs's avatar
Timo Teräs committed
32
#include "apk_openssl.h"
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

struct tar_header {
	/* ustar header, Posix 1003.1 */
	char name[100];     /*   0-99 */
	char mode[8];       /* 100-107 */
	char uid[8];        /* 108-115 */
	char gid[8];        /* 116-123 */
	char size[12];      /* 124-135 */
	char mtime[12];     /* 136-147 */
	char chksum[8];     /* 148-155 */
	char typeflag;      /* 156-156 */
	char linkname[100]; /* 157-256 */
	char magic[8];      /* 257-264 */
	char uname[32];     /* 265-296 */
	char gname[32];     /* 297-328 */
	char devmajor[8];   /* 329-336 */
	char devminor[8];   /* 337-344 */
	char prefix[155];   /* 345-499 */
51
	char padding[12];   /* 500-511 */
52 53
};

Timo Teräs's avatar
Timo Teräs committed
54 55 56
#define GET_OCTAL(s)	get_octal(s, sizeof(s))
#define PUT_OCTAL(s,v)	put_octal(s, sizeof(s), v)

57
static unsigned int get_octal(char *s, size_t l)
58 59
{
	apk_blob_t b = APK_BLOB_PTR_LEN(s, l);
60
	return apk_blob_pull_uint(&b, 8);
61
}
62

Timo Teräs's avatar
Timo Teräs committed
63 64 65 66 67 68 69 70 71 72 73 74 75
static void put_octal(char *s, size_t l, size_t value)
{
	char *ptr = &s[l - 1];

	*(ptr--) = '\0';
	while (value != 0 && ptr >= s) {
		*(ptr--) = '0' + (value % 8);
		value /= 8;
	}
	while (ptr >= s)
		*(ptr--) = '0';
}

76
static int blob_realloc(apk_blob_t *b, size_t newsize)
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
{
	char *tmp;
	if (b->len >= newsize) return 0;
	tmp = realloc(b->ptr, newsize);
	if (!tmp) return -ENOMEM;
	b->ptr = tmp;
	b->len = newsize;
	return 0;
}

static void handle_extended_header(struct apk_file_info *fi, apk_blob_t hdr)
{
	apk_blob_t name, value;

	while (1) {
		char *start = hdr.ptr;
		unsigned int len = apk_blob_pull_uint(&hdr, 10);
		apk_blob_pull_char(&hdr, ' ');
		if (!apk_blob_split(hdr, APK_BLOB_STR("="), &name, &hdr)) break;
96
		if (len < hdr.ptr - start + 1) break;
97
		len -= hdr.ptr - start + 1;
98
		if (hdr.len < len) break;
99 100 101 102 103 104 105 106 107 108
		value = APK_BLOB_PTR_LEN(hdr.ptr, len);
		hdr = APK_BLOB_PTR_LEN(hdr.ptr+len, hdr.len-len);
		apk_blob_pull_char(&hdr, '\n');
		if (APK_BLOB_IS_NULL(hdr)) break;
		value.ptr[value.len] = 0;

		if (apk_blob_compare(name, APK_BLOB_STR("path")) == 0) {
			fi->name = value.ptr;
		} else if (apk_blob_compare(name, APK_BLOB_STR("linkpath")) == 0) {
			fi->link_target = value.ptr;
Timo Teräs's avatar
Timo Teräs committed
109 110 111 112 113 114
		} else if (apk_blob_pull_blob_match(&name, APK_BLOB_STR("SCHILY.xattr."))) {
			name.ptr[name.len] = 0;
			*apk_xattr_array_add(&fi->xattrs) = (struct apk_xattr) {
				.name = name.ptr,
				.value = value,
			};
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		} else if (apk_blob_pull_blob_match(&name, APK_BLOB_STR("APK-TOOLS.checksum."))) {
			int type = APK_CHECKSUM_NONE;
			if (apk_blob_compare(name, APK_BLOB_STR("SHA1")) == 0)
				type = APK_CHECKSUM_SHA1;
			else if (apk_blob_compare(name, APK_BLOB_STR("MD5")) == 0)
				type = APK_CHECKSUM_MD5;
			if (type > fi->csum.type) {
				fi->csum.type = type;
				apk_blob_pull_hexdump(&value, APK_BLOB_CSUM(fi->csum));
				if (APK_BLOB_IS_NULL(value)) fi->csum.type = APK_CHECKSUM_NONE;
			}
		}
	}
}

130
int apk_tar_parse(struct apk_istream *is, apk_archive_entry_parser parser,
131
		  void *ctx, struct apk_id_cache *idc)
132
{
133
	struct apk_file_info entry;
134
	struct apk_segment_istream segment;
135 136
	struct tar_header buf;
	int end = 0, r;
137 138
	size_t toskip, paxlen = 0;
	apk_blob_t pax = APK_BLOB_NULL, longname = APK_BLOB_NULL;
139
	char filename[sizeof buf.name + sizeof buf.prefix + 2];
140

141 142
	if (IS_ERR_OR_NULL(is)) return PTR_ERR(is) ?: -EINVAL;

143
	memset(&entry, 0, sizeof(entry));
144
	entry.name = buf.name;
145
	while ((r = apk_istream_read(is, &buf, 512)) == 512) {
146
		if (buf.name[0] == '\0') {
147
			if (end) break;
148 149 150 151
			end++;
			continue;
		}

152
		entry = (struct apk_file_info){
153
			.size  = GET_OCTAL(buf.size),
154 155
			.uid   = apk_resolve_uid(idc, buf.uname, GET_OCTAL(buf.uid)),
			.gid   = apk_resolve_gid(idc, buf.gname, GET_OCTAL(buf.gid)),
156
			.mode  = GET_OCTAL(buf.mode) & 07777,
157
			.mtime = GET_OCTAL(buf.mtime),
158
			.name  = entry.name,
159 160 161 162
			.uname = buf.uname,
			.gname = buf.gname,
			.device = makedev(GET_OCTAL(buf.devmajor),
					  GET_OCTAL(buf.devminor)),
Timo Teräs's avatar
Timo Teräs committed
163
			.xattrs = entry.xattrs,
164
		};
165 166 167 168 169 170
		if (buf.prefix[0] && buf.typeflag != 'x' && buf.typeflag != 'g') {
			snprintf(filename, sizeof filename, "%.*s/%.*s",
				 (int) sizeof buf.prefix, buf.prefix,
				 (int) sizeof buf.name, buf.name);
			entry.name = filename;
		}
171 172
		buf.mode[0] = 0; /* to nul terminate 100-byte buf.name */
		buf.magic[0] = 0; /* to nul terminate 100-byte buf.linkname */
Timo Teräs's avatar
Timo Teräs committed
173
		apk_xattr_array_resize(&entry.xattrs, 0);
174

175 176
		if (entry.size >= SSIZE_MAX-512) goto err;

177 178 179 180
		if (paxlen) {
			handle_extended_header(&entry, APK_BLOB_PTR_LEN(pax.ptr, paxlen));
			apk_fileinfo_hash_xattr(&entry);
		}
181

182
		toskip = (entry.size + 511) & -512;
183
		switch (buf.typeflag) {
184
		case 'L': /* GNU long name extension */
185
			if ((r = blob_realloc(&longname, entry.size+1)) != 0 ||
186
			    (r = apk_istream_read(is, longname.ptr, entry.size)) != entry.size)
187
				goto err;
188
			entry.name = longname.ptr;
Timo Teräs's avatar
Timo Teräs committed
189
			entry.name[entry.size] = 0;
190
			toskip -= entry.size;
191
			break;
192 193
		case 'K': /* GNU long link target extension - ignored */
			break;
194 195
		case '0':
		case '7': /* regular file */
196
			entry.mode |= S_IFREG;
197 198 199
			break;
		case '1': /* hard link */
			entry.mode |= S_IFREG;
200
			if (!entry.link_target) entry.link_target = buf.linkname;
201 202 203
			break;
		case '2': /* symbolic link */
			entry.mode |= S_IFLNK;
204
			if (!entry.link_target) entry.link_target = buf.linkname;
205 206 207 208
			break;
		case '3': /* char device */
			entry.mode |= S_IFCHR;
			break;
Timo Teräs's avatar
Timo Teräs committed
209
		case '4': /* block device */
210 211 212 213 214
			entry.mode |= S_IFBLK;
			break;
		case '5': /* directory */
			entry.mode |= S_IFDIR;
			break;
215 216 217
		case '6': /* fifo */
			entry.mode |= S_IFIFO;
			break;
218 219 220 221
		case 'g': /* global pax header */
			break;
		case 'x': /* file specific pax header */
			paxlen = entry.size;
222
			if ((r = blob_realloc(&pax, (paxlen + 511) & -512)) != 0 ||
223
			    (r = apk_istream_read(is, pax.ptr, paxlen)) != paxlen)
224
				goto err;
225
			toskip -= entry.size;
226
			break;
227 228 229 230
		default:
			break;
		}

231 232 233 234 235 236
		if (strnlen(entry.name, PATH_MAX) >= PATH_MAX-10 ||
		    (entry.link_target && strnlen(entry.link_target, PATH_MAX) >= PATH_MAX-10)) {
			r = -ENAMETOOLONG;
			goto err;
		}

237
		if (entry.mode & S_IFMT) {
238 239
			apk_istream_segment(&segment, is, entry.size, entry.mtime);
			r = parser(ctx, &entry, &segment.is);
240
			if (r != 0) goto err;
241
			apk_istream_close(&segment.is);
242

243
			entry.name = buf.name;
244
			toskip -= entry.size;
245
			paxlen = 0;
246 247
		}

248 249
		if (toskip && (r = apk_istream_read(is, NULL, toskip)) != toskip)
			goto err;
250
	}
251

252 253 254
	/* Read remaining end-of-archive records, to ensure we read all of
	 * the file. The underlying istream is likely doing checksumming. */
	if (r == 512) {
255
		while ((r = apk_istream_read(is, &buf, 512)) == 512) {
256
			if (buf.name[0] != 0) break;
Timo Teräs's avatar
Timo Teräs committed
257
		}
258
	}
259
	if (r == 0) goto ok;
Timo Teräs's avatar
Timo Teräs committed
260
err:
261 262 263
	/* Check that there was no partial (or non-zero) record */
	if (r >= 0) r = -EBADMSG;
ok:
264 265
	free(pax.ptr);
	free(longname.ptr);
266
	apk_fileinfo_free(&entry);
267
	apk_istream_close(is);
Timo Teräs's avatar
Timo Teräs committed
268 269 270
	return r;
}

271 272
int apk_tar_write_entry(struct apk_ostream *os, const struct apk_file_info *ae,
			const char *data)
Timo Teräs's avatar
Timo Teräs committed
273 274 275 276 277 278 279 280 281 282 283 284 285
{
	struct tar_header buf;

	memset(&buf, 0, sizeof(buf));
	if (ae != NULL) {
		const unsigned char *src;
	        int chksum, i;

		if (S_ISREG(ae->mode))
			buf.typeflag = '0';
		else
			return -1;

286
		if (ae->name != NULL)
Timo Teräs's avatar
Timo Teräs committed
287
			strlcpy(buf.name, ae->name, sizeof buf.name);
288

Timo Teräs's avatar
Timo Teräs committed
289 290
		strlcpy(buf.uname, ae->uname ?: "root", sizeof buf.uname);
		strlcpy(buf.gname, ae->gname ?: "root", sizeof buf.gname);
Timo Teräs's avatar
Timo Teräs committed
291 292 293 294 295

		PUT_OCTAL(buf.size, ae->size);
		PUT_OCTAL(buf.uid, ae->uid);
		PUT_OCTAL(buf.gid, ae->gid);
		PUT_OCTAL(buf.mode, ae->mode & 07777);
296
		PUT_OCTAL(buf.mtime, ae->mtime ?: apk_time());
Timo Teräs's avatar
Timo Teräs committed
297 298 299 300 301 302 303 304 305 306

		/* Checksum */
		strcpy(buf.magic, "ustar  ");
		memset(buf.chksum, ' ', sizeof(buf.chksum));
		src = (const unsigned char *) &buf;
		for (i = chksum = 0; i < sizeof(buf); i++)
			chksum += src[i];
	        put_octal(buf.chksum, sizeof(buf.chksum)-1, chksum);
	}

307
	if (apk_ostream_write(os, &buf, sizeof(buf)) != sizeof(buf))
Timo Teräs's avatar
Timo Teräs committed
308 309
		return -1;

310 311
	if (ae == NULL) {
		/* End-of-archive is two empty headers */
312
		if (apk_ostream_write(os, &buf, sizeof(buf)) != sizeof(buf))
313 314
			return -1;
	} else if (data != NULL) {
315
		if (apk_ostream_write(os, data, ae->size) != ae->size)
Timo Teräs's avatar
Timo Teräs committed
316
			return -1;
317
		if (apk_tar_write_padding(os, ae) != 0)
Timo Teräs's avatar
Timo Teräs committed
318 319 320
			return -1;
	}

321 322 323
	return 0;
}

324 325 326 327 328 329 330
int apk_tar_write_padding(struct apk_ostream *os, const struct apk_file_info *ae)
{
	static char padding[512];
	int pad;

	pad = 512 - (ae->size & 511);
	if (pad != 512 &&
331
	    apk_ostream_write(os, padding, pad) != pad)
332 333 334 335 336
		return -1;

	return 0;
}

337
int apk_archive_entry_extract(int atfd, const struct apk_file_info *ae,
338 339
			      const char *extract_name, const char *link_target,
			      struct apk_istream *is,
340
			      apk_progress_cb cb, void *cb_ctx)
341
{
Timo Teräs's avatar
Timo Teräs committed
342
	struct apk_xattr *xattr;
343
	const char *fn = extract_name ?: ae->name;
344
	int fd, r = -1, atflags = 0, ret = 0;
345

346
	if (unlinkat(atfd, fn, 0) != 0 && errno != ENOENT) return -errno;
347 348 349

	switch (ae->mode & S_IFMT) {
	case S_IFDIR:
350
		r = mkdirat(atfd, fn, ae->mode & 07777);
351 352
		if (r < 0 && errno != EEXIST)
			ret = -errno;
353 354 355
		break;
	case S_IFREG:
		if (ae->link_target == NULL) {
356
			int flags = O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_EXCL;
357 358

			fd = openat(atfd, fn, flags, ae->mode & 07777);
359
			if (fd < 0) {
360
				ret = -errno;
361
				break;
362
			}
363 364
			r = apk_istream_splice(is, fd, ae->size, cb, cb_ctx);
			if (r != ae->size) ret = r < 0 ? r : -ENOSPC;
365
			close(fd);
366
		} else {
367
			r = linkat(atfd, link_target ?: ae->link_target, atfd, fn, 0);
368
			if (r < 0) ret = -errno;
369 370 371
		}
		break;
	case S_IFLNK:
372
		r = symlinkat(link_target ?: ae->link_target, atfd, fn);
373
		if (r < 0) ret = -errno;
374
		atflags |= AT_SYMLINK_NOFOLLOW;
375 376 377 378
		break;
	case S_IFBLK:
	case S_IFCHR:
	case S_IFIFO:
379
		r = mknodat(atfd, fn, ae->mode, ae->device);
380
		if (r < 0) ret = -errno;
381 382
		break;
	}
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	if (ret) {
		apk_error("Failed to create %s: %s", ae->name, strerror(-ret));
		return ret;
	}

	r = fchownat(atfd, fn, ae->uid, ae->gid, atflags);
	if (r < 0) {
		apk_error("Failed to set ownership on %s: %s",
			  fn, strerror(errno));
		if (!ret) ret = -errno;
	}

	/* chown resets suid bit so we need set it again */
	if (ae->mode & 07000) {
		r = fchmodat(atfd, fn, ae->mode & 07777, atflags);
398
		if (r < 0) {
399 400
			apk_error("Failed to set file permissions "
				  "on %s: %s",
401
				  fn, strerror(errno));
402
			if (!ret) ret = -errno;
403
		}
404
	}
405

406
	/* extract xattrs */
407
	if (!S_ISLNK(ae->mode) && ae->xattrs && ae->xattrs->num) {
408 409 410 411 412 413 414
		r = 0;
		fd = openat(atfd, fn, O_RDWR);
		if (fd >= 0) {
			foreach_array_item(xattr, ae->xattrs) {
				if (fsetxattr(fd, xattr->name, xattr->value.ptr, xattr->value.len, 0) < 0) {
					r = -errno;
					if (r != -ENOTSUP) break;
Timo Teräs's avatar
Timo Teräs committed
415 416
				}
			}
417 418 419 420 421 422
			close(fd);
		} else {
			r = -errno;
		}
		if (r) {
			if (r != -ENOTSUP)
Timo Teräs's avatar
Timo Teräs committed
423
				apk_error("Failed to set xattrs on %s: %s",
424
					  fn, strerror(-r));
425
			if (!ret) ret = r;
Timo Teräs's avatar
Timo Teräs committed
426
		}
427
	}
Timo Teräs's avatar
Timo Teräs committed
428

429 430 431 432 433 434 435 436 437 438 439
	if (!S_ISLNK(ae->mode)) {
		/* preserve modification time */
		struct timespec times[2];

		times[0].tv_sec  = times[1].tv_sec  = ae->mtime;
		times[0].tv_nsec = times[1].tv_nsec = 0;
		r = utimensat(atfd, fn, times, atflags);
		if (r < 0) {
			apk_error("Failed to preserve modification time on %s: %s",
				fn, strerror(errno));
			if (!ret || ret == -ENOTSUP) ret = -errno;
440
		}
441
	}
442

443
	return ret;
444
}