xref: /netbsd-src/external/bsd/pkg_install/dist/add/perform.c (revision a5018e85e9b7d2b831d6ea80896cebd43915cdee)
1 /*	$NetBSD: perform.c,v 1.13 2024/08/26 22:41:39 wiz Exp $	*/
2 #if HAVE_CONFIG_H
3 #include "config.h"
4 #endif
5 #include <nbcompat.h>
6 #if HAVE_SYS_CDEFS_H
7 #include <sys/cdefs.h>
8 #endif
9 __RCSID("$NetBSD: perform.c,v 1.13 2024/08/26 22:41:39 wiz Exp $");
10 
11 /*-
12  * Copyright (c) 2003 Grant Beattie <grant@NetBSD.org>
13  * Copyright (c) 2005 Dieter Baron <dillo@NetBSD.org>
14  * Copyright (c) 2007 Roland Illig <rillig@NetBSD.org>
15  * Copyright (c) 2008, 2009 Joerg Sonnenberger <joerg@NetBSD.org>
16  * Copyright (c) 2010 Thomas Klausner <wiz@NetBSD.org>
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  *
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in
27  *    the documentation and/or other materials provided with the
28  *    distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
33  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
34  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
36  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
38  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
39  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
40  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  */
43 
44 #include <sys/utsname.h>
45 #include <sys/stat.h>
46 #if HAVE_ERR_H
47 #include <err.h>
48 #endif
49 #include <errno.h>
50 #if HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #include <limits.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #include <archive.h>
59 #include <archive_entry.h>
60 
61 #include "lib.h"
62 #include "add.h"
63 #include "version.h"
64 
65 struct pkg_meta {
66 	char *meta_contents;
67 	char *meta_comment;
68 	char *meta_desc;
69 	char *meta_mtree;
70 	char *meta_build_version;
71 	char *meta_build_info;
72 	char *meta_size_pkg;
73 	char *meta_size_all;
74 	char *meta_required_by;
75 	char *meta_display;
76 	char *meta_install;
77 	char *meta_deinstall;
78 	char *meta_preserve;
79 	char *meta_installed_info;
80 };
81 
82 struct pkg_task {
83 	char *pkgname;
84 
85 	const char *prefix;
86 	char *install_prefix;
87 
88 	char *logdir;
89 	char *install_logdir;
90 	char *install_logdir_real;
91 	char *other_version;
92 
93 	package_t plist;
94 
95 	struct pkg_meta meta_data;
96 
97 	struct archive *archive;
98 	struct archive_entry *entry;
99 
100 	char *buildinfo[BI_ENUM_COUNT];
101 
102 	size_t dep_length, dep_allocated;
103 	char **dependencies;
104 };
105 
106 static const struct pkg_meta_desc {
107 	size_t entry_offset;
108 	const char *entry_filename;
109 	int required_file;
110 	mode_t perm;
111 } pkg_meta_descriptors[] = {
112 	{ offsetof(struct pkg_meta, meta_contents), CONTENTS_FNAME, 1, 0644 },
113 	{ offsetof(struct pkg_meta, meta_comment), COMMENT_FNAME, 1, 0444},
114 	{ offsetof(struct pkg_meta, meta_desc), DESC_FNAME, 1, 0444},
115 	{ offsetof(struct pkg_meta, meta_install), INSTALL_FNAME, 0, 0555 },
116 	{ offsetof(struct pkg_meta, meta_deinstall), DEINSTALL_FNAME, 0, 0555 },
117 	{ offsetof(struct pkg_meta, meta_display), DISPLAY_FNAME, 0, 0444 },
118 	{ offsetof(struct pkg_meta, meta_mtree), MTREE_FNAME, 0, 0444 },
119 	{ offsetof(struct pkg_meta, meta_build_version), BUILD_VERSION_FNAME, 0, 0444 },
120 	{ offsetof(struct pkg_meta, meta_build_info), BUILD_INFO_FNAME, 0, 0444 },
121 	{ offsetof(struct pkg_meta, meta_size_pkg), SIZE_PKG_FNAME, 0, 0444 },
122 	{ offsetof(struct pkg_meta, meta_size_all), SIZE_ALL_FNAME, 0, 0444 },
123 	{ offsetof(struct pkg_meta, meta_preserve), PRESERVE_FNAME, 0, 0444 },
124 	{ offsetof(struct pkg_meta, meta_required_by), REQUIRED_BY_FNAME, 0, 0644 },
125 	{ offsetof(struct pkg_meta, meta_installed_info), INSTALLED_INFO_FNAME, 0, 0644 },
126 	{ 0, NULL, 0, 0 },
127 };
128 
129 static int pkg_do(const char *, int, int);
130 
131 static int
132 compatible_platform(const char *opsys, const char *host, const char *package)
133 {
134 	const char *loc;
135 	size_t majorlen = 0;
136 
137 	/*
138 	 * If the user has set the CHECK_OS_VERSION variable to "no" then skip any
139 	 * uname version checks and assume they know what they are doing.  This can
140 	 * be useful on OS where the kernel version is not a good indicator of
141 	 * userland compatibility, or differs but retains ABI compatibility.
142 	 */
143 	if (strcasecmp(check_os_version, "no") == 0)
144 	    return 1;
145 
146 	/* returns 1 if host and package operating system match */
147 	if (strcmp(opsys, "NetBSD") == 0) {
148 		/*
149 		 * warn about -current package on a stable release and
150 		 * the reverse
151 		 */
152 		if ((strstr(host, ".99.") != NULL &&
153 		    strstr(package, ".99.") == NULL) ||
154 		    (strstr(package, ".99.") != NULL &&
155 		    strstr(host, ".99.") == NULL)) {
156 			return 0;
157 		}
158 		/* compare the major version only */
159 		loc = strchr(host, '.');
160 		if (loc != NULL) {
161 			majorlen = loc - host;
162 			if (majorlen != (size_t)(strchr(package, '.') - package))
163 				return 0;
164 			if (strncmp(host, package, majorlen) == 0)
165 				return 1;
166 		}
167 	}
168 	if (strcmp(host, package) == 0)
169 		return 1;
170 	return 0;
171 }
172 
173 static int
174 mkdir_p(const char *path)
175 {
176 	char *p, *cur_end;
177 	int done, saved_errno;
178 	struct stat sb;
179 
180 	/*
181 	 * Handle the easy case of direct success or
182 	 * pre-existing directory first.
183 	 */
184 	if (mkdir(path, 0777) == 0)
185 		return 0;
186 	if (stat(path, &sb) == 0) {
187 		if (S_ISDIR(sb.st_mode))
188 			return 0;
189 		errno = ENOTDIR;
190 		return -1;
191 	}
192 
193 	cur_end = p = xstrdup(path);
194 
195 	for (;;) {
196 		/*
197 		 * First skip leading slashes either from / or
198 		 * from the last iteration.
199 		 */
200 		cur_end += strspn(cur_end, "/");
201 		/* Find end of actual directory name. */
202 		cur_end += strcspn(cur_end, "/");
203 
204 		/*
205 		 * Remember if this is the last component and
206 		 * overwrite / if needed.
207 		 */
208 		done = (*cur_end == '\0');
209 		*cur_end = '\0';
210 
211 		if (mkdir(p, 0777) == -1) {
212 			saved_errno = errno;
213 			if (stat(p, &sb) == 0) {
214 				if (S_ISDIR(sb.st_mode))
215 					goto pass;
216 				errno = ENOTDIR;
217 			} else {
218 				errno = saved_errno;
219 			}
220 			free(p);
221 			return -1;
222 		}
223 pass:
224 		if (done)
225 			break;
226 		*cur_end = '/';
227 	}
228 
229 	free(p);
230 	return 0;
231 }
232 
233 /*
234  * Read meta data from archive.
235  * Bail out if a required entry is missing or entries are in the wrong order.
236  */
237 static int
238 read_meta_data(struct pkg_task *pkg)
239 {
240 	const struct pkg_meta_desc *descr, *last_descr;
241 	const char *fname;
242 	char **target;
243 	int64_t size;
244 	int r, found_required;
245 
246 	found_required = 0;
247 
248 	r = ARCHIVE_OK;
249 	last_descr = 0;
250 
251 	if (pkg->entry != NULL)
252 		goto skip_header;
253 
254 	for (;;) {
255 		r = archive_read_next_header(pkg->archive, &pkg->entry);
256 		if (r != ARCHIVE_OK)
257 				break;
258 skip_header:
259 		fname = archive_entry_pathname(pkg->entry);
260 
261 		for (descr = pkg_meta_descriptors; descr->entry_filename;
262 		     ++descr) {
263 			if (strcmp(descr->entry_filename, fname) == 0)
264 				break;
265 		}
266 		if (descr->entry_filename == NULL)
267 			break;
268 
269 		if (descr->required_file)
270 			++found_required;
271 
272 		target = (char **)((char *)&pkg->meta_data +
273 		    descr->entry_offset);
274 		if (*target) {
275 			warnx("duplicate entry, package corrupt");
276 			return -1;
277 		}
278 		if (descr < last_descr) {
279 			warnx("misordered package");
280 			return -1;
281 		}
282 		last_descr = descr;
283 
284 		size = archive_entry_size(pkg->entry);
285 		if (size > SSIZE_MAX - 1) {
286 			warnx("package meta data too large to process");
287 			return -1;
288 		}
289 		*target = xmalloc(size + 1);
290 		if (archive_read_data(pkg->archive, *target, size) != size) {
291 			warnx("cannot read package meta data");
292 			return -1;
293 		}
294 		(*target)[size] = '\0';
295 	}
296 
297 	if (r != ARCHIVE_OK)
298 		pkg->entry = NULL;
299 	if (r == ARCHIVE_EOF)
300 		r = ARCHIVE_OK;
301 
302 	for (descr = pkg_meta_descriptors; descr->entry_filename; ++descr) {
303 		if (descr->required_file)
304 			--found_required;
305 	}
306 
307 	return !found_required && r == ARCHIVE_OK ? 0 : -1;
308 }
309 
310 /*
311  * Free meta data.
312  */
313 static void
314 free_meta_data(struct pkg_task *pkg)
315 {
316 	const struct pkg_meta_desc *descr;
317 	char **target;
318 
319 	for (descr = pkg_meta_descriptors; descr->entry_filename; ++descr) {
320 		target = (char **)((char *)&pkg->meta_data +
321 		    descr->entry_offset);
322 		free(*target);
323 		*target = NULL;
324 	}
325 }
326 
327 /*
328  * Parse PLIST and populate pkg.
329  */
330 static int
331 pkg_parse_plist(struct pkg_task *pkg)
332 {
333 	plist_t *p;
334 
335 	parse_plist(&pkg->plist, pkg->meta_data.meta_contents);
336 	if ((p = find_plist(&pkg->plist, PLIST_NAME)) == NULL) {
337 		warnx("Invalid PLIST: missing @name");
338 		return -1;
339 	}
340 	if (pkg->pkgname == NULL)
341 		pkg->pkgname = xstrdup(p->name);
342 	else if (strcmp(pkg->pkgname, p->name) != 0) {
343 		warnx("Signature and PLIST differ on package name");
344 		return -1;
345 	}
346 	if ((p = find_plist(&pkg->plist, PLIST_CWD)) == NULL) {
347 		warnx("Invalid PLIST: missing @cwd");
348 		return -1;
349 	}
350 
351 	if (Prefix != NULL &&
352 	    strcmp(p->name, Prefix) != 0) {
353 		size_t len;
354 
355 		delete_plist(&pkg->plist, FALSE, PLIST_CWD, NULL);
356 		add_plist_top(&pkg->plist, PLIST_CWD, Prefix);
357 		free(pkg->meta_data.meta_contents);
358 		stringify_plist(&pkg->plist, &pkg->meta_data.meta_contents, &len,
359 		    Prefix);
360 		pkg->prefix = Prefix;
361 	} else
362 		pkg->prefix = p->name;
363 
364 	if (Destdir != NULL)
365 		pkg->install_prefix = xasprintf("%s/%s", Destdir, pkg->prefix);
366 	else
367 		pkg->install_prefix = xstrdup(pkg->prefix);
368 
369 	return 0;
370 }
371 
372 /*
373  * Helper function to extract value from a string of the
374  * form key=value ending at eol.
375  */
376 static char *
377 dup_value(const char *line, const char *eol)
378 {
379 	const char *key;
380 	char *val;
381 
382 	key = strchr(line, '=');
383 	val = xmalloc(eol - key);
384 	memcpy(val, key + 1, eol - key - 1);
385 	val[eol - key - 1] = '\0';
386 	return val;
387 }
388 
389 static int
390 check_already_installed(struct pkg_task *pkg)
391 {
392 	char *filename;
393 	int fd;
394 
395 	filename = pkgdb_pkg_file(pkg->pkgname, CONTENTS_FNAME);
396 	fd = open(filename, O_RDONLY);
397 	free(filename);
398 	if (fd == -1)
399 		return 1;
400 	close(fd);
401 
402 	if (ReplaceSame) {
403 		struct stat sb;
404 
405 		pkg->install_logdir_real = pkg->install_logdir;
406 		pkg->install_logdir = xasprintf("%s.xxxxxx", pkg->install_logdir);
407 		if (stat(pkg->install_logdir, &sb) == 0) {
408 			warnx("package `%s' already has a temporary update "
409 			    "directory `%s', remove it manually",
410 			    pkg->pkgname, pkg->install_logdir);
411 			return -1;
412 		}
413 		return 1;
414 	}
415 
416 	/* We can only arrive here for explicitly requested packages. */
417 	if (!Automatic && is_automatic_installed(pkg->pkgname)) {
418 		if (Fake ||
419 		    mark_as_automatic_installed(pkg->pkgname, 0) == 0)
420 			warnx("package `%s' was already installed as "
421 			      "dependency, now marked as installed "
422 			      "manually", pkg->pkgname);
423 	} else {
424 		warnx("package `%s' already recorded as installed",
425 		      pkg->pkgname);
426 	}
427 	return 0;
428 
429 }
430 
431 static int
432 check_other_installed(struct pkg_task *pkg)
433 {
434 	FILE *f, *f_pkg;
435 	size_t len;
436 	char *pkgbase, *iter, *filename;
437 	package_t plist;
438 	plist_t *p;
439 	int status;
440 
441 	if (pkg->install_logdir_real) {
442 		pkg->other_version = xstrdup(pkg->pkgname);
443 		return 0;
444 	}
445 
446 	pkgbase = xstrdup(pkg->pkgname);
447 
448 	if ((iter = strrchr(pkgbase, '-')) == NULL) {
449 		free(pkgbase);
450 		warnx("Invalid package name %s", pkg->pkgname);
451 		return -1;
452 	}
453 	*iter = '\0';
454 	pkg->other_version = find_best_matching_installed_pkg(pkgbase, 0);
455 	free(pkgbase);
456 	if (pkg->other_version == NULL)
457 		return 0;
458 
459 	if (!Replace) {
460 		/* XXX This is redundant to the implicit conflict check. */
461 		warnx("A different version of %s is already installed: %s",
462 		    pkg->pkgname, pkg->other_version);
463 		return -1;
464 	}
465 
466 	filename = pkgdb_pkg_file(pkg->other_version, REQUIRED_BY_FNAME);
467 	errno = 0;
468 	f = fopen(filename, "r");
469 	free(filename);
470 	if (f == NULL) {
471 		if (errno == ENOENT) {
472 			/* No packages depend on this, so everything is well. */
473 			return 0;
474 		}
475 		warnx("Can't open +REQUIRED_BY of %s", pkg->other_version);
476 		return -1;
477 	}
478 
479 	status = 0;
480 
481 	while ((iter = fgetln(f, &len)) != NULL) {
482 		if (iter[len - 1] == '\n')
483 			iter[len - 1] = '\0';
484 		filename = pkgdb_pkg_file(iter, CONTENTS_FNAME);
485 		if ((f_pkg = fopen(filename, "r")) == NULL) {
486 			warnx("Can't open +CONTENTS of depending package %s",
487 			    iter);
488 			fclose(f);
489 			return -1;
490 		}
491 		read_plist(&plist, f_pkg);
492 		fclose(f_pkg);
493 		for (p = plist.head; p != NULL; p = p->next) {
494 			if (p->type == PLIST_IGNORE) {
495 				p = p->next;
496 				continue;
497 			} else if (p->type != PLIST_PKGDEP)
498 				continue;
499 			/*
500 			 * XXX This is stricter than necessary.
501 			 * XXX One pattern might be fulfilled by
502 			 * XXX a different package and still need this
503 			 * XXX one for a different pattern.
504 			 */
505 			if (pkg_match(p->name, pkg->other_version) == 0)
506 				continue;
507 			if (pkg_match(p->name, pkg->pkgname) == 1)
508 				continue; /* Both match, ok. */
509 			if (!ForceDepending) {
510 				warnx("Dependency of %s fulfilled by %s, "
511 				    "but not by %s", iter, pkg->other_version,
512 				    pkg->pkgname);
513 				status = -1;
514 			}
515 			break;
516 		}
517 		free_plist(&plist);
518 	}
519 
520 	fclose(f);
521 
522 	return status;
523 }
524 
525 /*
526  * Read package build information from meta data.
527  */
528 static int
529 read_buildinfo(struct pkg_task *pkg)
530 {
531 	const char *data, *eol, *next_line;
532 
533 	data = pkg->meta_data.meta_build_info;
534 
535 	for (; data != NULL && *data != '\0'; data = next_line) {
536 		if ((eol = strchr(data, '\n')) == NULL) {
537 			eol = data + strlen(data);
538 			next_line = eol;
539 		} else
540 			next_line = eol + 1;
541 
542 		if (strncmp(data, "OPSYS=", 6) == 0)
543 			pkg->buildinfo[BI_OPSYS] = dup_value(data, eol);
544 		else if (strncmp(data, "OS_VERSION=", 11) == 0)
545 			pkg->buildinfo[BI_OS_VERSION] = dup_value(data, eol);
546 		else if (strncmp(data, "MACHINE_ARCH=", 13) == 0)
547 			pkg->buildinfo[BI_MACHINE_ARCH] = dup_value(data, eol);
548 		else if (strncmp(data, "IGNORE_RECOMMENDED=", 19) == 0)
549 			pkg->buildinfo[BI_IGNORE_RECOMMENDED] = dup_value(data,
550 			    eol);
551 		else if (strncmp(data, "USE_ABI_DEPENDS=", 16) == 0)
552 			pkg->buildinfo[BI_USE_ABI_DEPENDS] = dup_value(data,
553 			    eol);
554 		else if (strncmp(data, "LICENSE=", 8) == 0)
555 			pkg->buildinfo[BI_LICENSE] = dup_value(data, eol);
556 		else if (strncmp(data, "PKGTOOLS_VERSION=", 17) == 0)
557 			pkg->buildinfo[BI_PKGTOOLS_VERSION] = dup_value(data,
558 			    eol);
559 	}
560 	if (pkg->buildinfo[BI_OPSYS] == NULL ||
561 	    pkg->buildinfo[BI_OS_VERSION] == NULL ||
562 	    pkg->buildinfo[BI_MACHINE_ARCH] == NULL) {
563 		warnx("Not all required build information are present.");
564 		return -1;
565 	}
566 
567 	if ((pkg->buildinfo[BI_USE_ABI_DEPENDS] != NULL &&
568 	    strcasecmp(pkg->buildinfo[BI_USE_ABI_DEPENDS], "YES") != 0) ||
569 	    (pkg->buildinfo[BI_IGNORE_RECOMMENDED] != NULL &&
570 	    strcasecmp(pkg->buildinfo[BI_IGNORE_RECOMMENDED], "NO") != 0)) {
571 		warnx("%s was built to ignore ABI dependencies", pkg->pkgname);
572 	}
573 
574 	return 0;
575 }
576 
577 /*
578  * Free buildinfo.
579  */
580 static void
581 free_buildinfo(struct pkg_task *pkg)
582 {
583 	size_t i;
584 
585 	for (i = 0; i < BI_ENUM_COUNT; ++i) {
586 		free(pkg->buildinfo[i]);
587 		pkg->buildinfo[i] = NULL;
588 	}
589 }
590 
591 /*
592  * Write meta data files to pkgdb after creating the directory.
593  */
594 static int
595 write_meta_data(struct pkg_task *pkg)
596 {
597 	const struct pkg_meta_desc *descr;
598 	char *filename, **target;
599 	size_t len;
600 	ssize_t ret;
601 	int fd;
602 
603 	if (Fake)
604 		return 0;
605 
606 	if (mkdir_p(pkg->install_logdir)) {
607 		warn("Can't create pkgdb entry: %s", pkg->install_logdir);
608 		return -1;
609 	}
610 
611 	for (descr = pkg_meta_descriptors; descr->entry_filename; ++descr) {
612 		target = (char **)((char *)&pkg->meta_data +
613 		    descr->entry_offset);
614 		if (*target == NULL)
615 			continue;
616 		filename = xasprintf("%s/%s", pkg->install_logdir,
617 		    descr->entry_filename);
618 		(void)unlink(filename);
619 		fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, descr->perm);
620 		if (fd == -1) {
621 			warn("Can't open meta data file: %s", filename);
622 			return -1;
623 		}
624 		len = strlen(*target);
625 		do {
626 			ret = write(fd, *target, len);
627 			if (ret == -1) {
628 				warn("Can't write meta data file: %s",
629 				    filename);
630 				free(filename);
631 				close(fd);
632 				return -1;
633 			}
634 			len -= ret;
635 		} while (ret > 0);
636 		if (close(fd) == -1) {
637 			warn("Can't close meta data file: %s", filename);
638 			free(filename);
639 			return -1;
640 		}
641 		free(filename);
642 	}
643 
644 	return 0;
645 }
646 
647 /*
648  * Helper function for extract_files.
649  */
650 static int
651 copy_data_to_disk(struct archive *reader, struct archive *writer,
652     const char *filename)
653 {
654 	int r;
655 	const void *buff;
656 	size_t size;
657 	off_t offset;
658 
659 	for (;;) {
660 		r = archive_read_data_block(reader, &buff, &size, &offset);
661 		if (r == ARCHIVE_EOF)
662 			return 0;
663 		if (r != ARCHIVE_OK) {
664 			warnx("Read error for %s: %s", filename,
665 			    archive_error_string(reader));
666 			return -1;
667 		}
668 		r = archive_write_data_block(writer, buff, size, offset);
669 		if (r != ARCHIVE_OK) {
670 			warnx("Write error for %s: %s", filename,
671 			    archive_error_string(writer));
672 			return -1;
673 		}
674 	}
675 }
676 
677 /*
678  * Extract package.
679  * Any misordered, missing or unlisted file in the package is an error.
680  */
681 
682 static const int extract_flags = ARCHIVE_EXTRACT_OWNER |
683     ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_UNLINK |
684     ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR;
685 
686 static int
687 extract_files(struct pkg_task *pkg)
688 {
689 	char    cmd[MaxPathSize];
690 	const char *owner, *group, *permissions;
691 	struct archive *writer;
692 	int r;
693 	plist_t *p;
694 	const char *last_file;
695 	char *fullpath;
696 
697 	if (Fake)
698 		return 0;
699 
700 	if (mkdir_p(pkg->install_prefix)) {
701 		warn("Can't create prefix: %s", pkg->install_prefix);
702 		return -1;
703 	}
704 
705 	if (!NoRecord && !pkgdb_open(ReadWrite)) {
706 		warn("Can't open pkgdb for writing");
707 		return -1;
708 	}
709 
710 	if (chdir(pkg->install_prefix) == -1) {
711 		warn("Can't change into prefix: %s", pkg->install_prefix);
712 		return -1;
713 	}
714 
715 	writer = archive_write_disk_new();
716 	archive_write_disk_set_options(writer, extract_flags);
717 	archive_write_disk_set_standard_lookup(writer);
718 
719 	owner = NULL;
720 	group = NULL;
721 	permissions = NULL;
722 	last_file = NULL;
723 
724 	r = -1;
725 
726 	for (p = pkg->plist.head; p != NULL; p = p->next) {
727 		switch (p->type) {
728 		case PLIST_FILE:
729 			last_file = p->name;
730 			if (pkg->entry == NULL) {
731 				warnx("PLIST entry not in package (%s)",
732 				    archive_entry_pathname(pkg->entry));
733 				goto out;
734 			}
735 			if (strcmp(p->name, archive_entry_pathname(pkg->entry))) {
736 				warnx("PLIST entry and package don't match (%s vs %s)",
737 				    p->name, archive_entry_pathname(pkg->entry));
738 				goto out;
739 			}
740 			fullpath = xasprintf("%s/%s", pkg->prefix, p->name);
741 			pkgdb_store(fullpath, pkg->pkgname);
742 			free(fullpath);
743 			if (Verbose)
744 				printf("%s", p->name);
745 			break;
746 
747 		case PLIST_PKGDIR:
748 			fullpath = xasprintf("%s/%s", pkg->prefix, p->name);
749 			mkdir_p(fullpath);
750 			free(fullpath);
751 			add_pkgdir(pkg->pkgname, pkg->prefix, p->name);
752 			continue;
753 
754 		case PLIST_CMD:
755 			if (format_cmd(cmd, sizeof(cmd), p->name, pkg->prefix, last_file))
756 				return -1;
757 			printf("Executing '%s'\n", cmd);
758 			if (!Fake && system(cmd))
759 				warnx("command '%s' failed", cmd); /* XXX bail out? */
760 			continue;
761 
762 		case PLIST_CHMOD:
763 			permissions = p->name;
764 			continue;
765 
766 		case PLIST_CHOWN:
767 			owner = p->name;
768 			continue;
769 
770 		case PLIST_CHGRP:
771 			group = p->name;
772 			continue;
773 
774 		case PLIST_IGNORE:
775 			p = p->next;
776 			continue;
777 
778 		default:
779 			continue;
780 		}
781 
782 		r = archive_write_header(writer, pkg->entry);
783 		if (r != ARCHIVE_OK) {
784 			warnx("Failed to write %s for %s: %s",
785 			    archive_entry_pathname(pkg->entry),
786 			    pkg->pkgname,
787 			    archive_error_string(writer));
788 			goto out;
789 		}
790 
791 		if (owner != NULL)
792 			archive_entry_set_uname(pkg->entry, owner);
793 		if (group != NULL)
794 			archive_entry_set_uname(pkg->entry, group);
795 		if (permissions != NULL) {
796 			mode_t mode;
797 
798 			mode = archive_entry_mode(pkg->entry);
799 			mode = getmode(setmode(permissions), mode);
800 			archive_entry_set_mode(pkg->entry, mode);
801 		}
802 
803 		r = copy_data_to_disk(pkg->archive, writer,
804 		    archive_entry_pathname(pkg->entry));
805 		if (r)
806 			goto out;
807 		if (Verbose)
808 			printf("\n");
809 
810 		r = archive_read_next_header(pkg->archive, &pkg->entry);
811 		if (r == ARCHIVE_EOF) {
812 			pkg->entry = NULL;
813 			continue;
814 		}
815 		if (r != ARCHIVE_OK) {
816 			warnx("Failed to read from archive for %s: %s",
817 			    pkg->pkgname,
818 			    archive_error_string(pkg->archive));
819 			goto out;
820 		}
821 	}
822 
823 	if (pkg->entry != NULL) {
824 		warnx("Package contains entries not in PLIST: %s",
825 		    archive_entry_pathname(pkg->entry));
826 		goto out;
827 	}
828 
829 	r = 0;
830 
831 out:
832 	if (!NoRecord)
833 		pkgdb_close();
834 	archive_write_free(writer);
835 
836 	return r;
837 }
838 
839 /*
840  * Register dependencies after sucessfully installing the package.
841  */
842 static void
843 pkg_register_depends(struct pkg_task *pkg)
844 {
845 	int fd;
846 	size_t text_len, i;
847 	char *required_by, *text;
848 
849 	if (Fake)
850 		return;
851 
852 	text = xasprintf("%s\n", pkg->pkgname);
853 	text_len = strlen(text);
854 
855 	for (i = 0; i < pkg->dep_length; ++i) {
856 		required_by = pkgdb_pkg_file(pkg->dependencies[i], REQUIRED_BY_FNAME);
857 
858 		fd = open(required_by, O_WRONLY | O_APPEND | O_CREAT, 0644);
859 		if (fd == -1) {
860 			warn("can't open dependency file '%s',"
861 			    "registration is incomplete!", required_by);
862 		} else if (write(fd, text, text_len) != (ssize_t)text_len) {
863 			warn("can't write to dependency file `%s'", required_by);
864 			close(fd);
865 		} else if (close(fd) == -1)
866 			warn("cannot close file %s", required_by);
867 
868 		free(required_by);
869 	}
870 
871 	free(text);
872 }
873 
874 /*
875  * Reduce the result from uname(3) to a canonical form.
876  */
877 static void
878 normalise_platform(struct utsname *host_name)
879 {
880 #ifdef NUMERIC_VERSION_ONLY
881 	size_t span;
882 
883 	span = strspn(host_name->release, "0123456789.");
884 	host_name->release[span] = '\0';
885 #endif
886 }
887 
888 /*
889  * Check build platform of the package against local host.
890  */
891 static int
892 check_platform(struct pkg_task *pkg)
893 {
894 	struct utsname host_uname;
895 	const char *effective_arch;
896 	const char *effective_opsys;
897 	const char *effective_os_version;
898 	int fatal;
899 
900 	if (OverrideOpsys != NULL && OverrideOSVersion != NULL) {
901 		effective_opsys = OverrideOpsys;
902 		effective_os_version = OverrideOSVersion;
903 	} else {
904 		if (uname(&host_uname) < 0) {
905 			if (Force) {
906 				warnx("uname() failed, continuing.");
907 				return 0;
908 			} else {
909 				warnx("uname() failed, aborting.");
910 				return -1;
911 			}
912 		}
913 
914 		normalise_platform(&host_uname);
915 		effective_opsys = OPSYS_NAME;
916 		effective_os_version = host_uname.release;
917 	}
918 
919 	if (OverrideMachine != NULL)
920 		effective_arch = OverrideMachine;
921 	else
922 		effective_arch = PKGSRC_MACHINE_ARCH;
923 
924 	/* If either the OS or arch are different, bomb */
925 	if (strcmp(effective_opsys, pkg->buildinfo[BI_OPSYS]) ||
926 	    strcmp(effective_arch, pkg->buildinfo[BI_MACHINE_ARCH]) != 0)
927 		fatal = 1;
928 	else
929 		fatal = 0;
930 
931 	if (fatal ||
932 	    compatible_platform(effective_opsys, effective_os_version,
933 				pkg->buildinfo[BI_OS_VERSION]) != 1) {
934 		warnx("Warning: package `%s' was built for a platform:",
935 		    pkg->pkgname);
936 		warnx("%s/%s %s (pkg) vs. %s/%s %s (this host)",
937 		    pkg->buildinfo[BI_OPSYS],
938 		    pkg->buildinfo[BI_MACHINE_ARCH],
939 		    pkg->buildinfo[BI_OS_VERSION],
940 		    effective_opsys,
941 		    effective_arch,
942 		    effective_os_version);
943 		if (!Force && fatal)
944 			return -1;
945 	}
946 	return 0;
947 }
948 
949 static int
950 check_pkgtools_version(struct pkg_task *pkg)
951 {
952 	const char *val = pkg->buildinfo[BI_PKGTOOLS_VERSION];
953 	int version;
954 
955 	if (val == NULL) {
956 		warnx("Warning: package `%s' lacks pkg_install version data",
957 		    pkg->pkgname);
958 		return 0;
959 	}
960 
961 	if (strlen(val) != 8 || strspn(val, "0123456789") != 8) {
962 		warnx("Warning: package `%s' contains an invalid pkg_install version",
963 		    pkg->pkgname);
964 		return Force ? 0 : -1;
965 	}
966 	version = atoi(val);
967 	if (version > PKGTOOLS_VERSION) {
968 		warnx("%s: package `%s' was built with a newer pkg_install version",
969 		    Force ? "Warning" : "Error", pkg->pkgname);
970 		return Force ? 0 : -1;
971 	}
972 	return 0;
973 }
974 
975 /*
976  * Run the install script.
977  */
978 static int
979 run_install_script(struct pkg_task *pkg, const char *argument)
980 {
981 	int ret;
982 	char *filename;
983 
984 	if (pkg->meta_data.meta_install == NULL || NoInstall)
985 		return 0;
986 
987 	if (Destdir != NULL)
988 		setenv(PKG_DESTDIR_VNAME, Destdir, 1);
989 	setenv(PKG_PREFIX_VNAME, pkg->prefix, 1);
990 	setenv(PKG_METADATA_DIR_VNAME, pkg->logdir, 1);
991 	setenv(PKG_REFCOUNT_DBDIR_VNAME, config_pkg_refcount_dbdir, 1);
992 
993 	if (Verbose)
994 		printf("Running install with %s for %s.\n", argument,
995 		    pkg->pkgname);
996 	if (Fake)
997 		return 0;
998 
999 	filename = pkgdb_pkg_file(pkg->pkgname, INSTALL_FNAME);
1000 
1001 	ret = 0;
1002 	errno = 0;
1003 	if (fcexec(pkg->install_logdir, filename, pkg->pkgname, argument,
1004 	    (void *)NULL)) {
1005 		if (errno != 0)
1006 			warn("exec of install script failed");
1007 		else
1008 			warnx("install script returned error status");
1009 		ret = -1;
1010 	}
1011 	free(filename);
1012 
1013 	return ret;
1014 }
1015 
1016 struct find_conflict_data {
1017 	const char *pkg;
1018 	const char *old_pkg;
1019 	const char *pattern;
1020 };
1021 
1022 static int
1023 check_explicit_conflict_iter(const char *cur_pkg, void *cookie)
1024 {
1025 	struct find_conflict_data *data = cookie;
1026 
1027 	if (data->old_pkg && strcmp(data->old_pkg, cur_pkg) == 0)
1028 		return 0;
1029 
1030 	warnx("Package `%s' conflicts with `%s', and `%s' is installed.",
1031 	    data->pkg, data->pattern, cur_pkg);
1032 
1033 	return 1;
1034 }
1035 
1036 static int
1037 check_explicit_conflict(struct pkg_task *pkg)
1038 {
1039 	struct find_conflict_data data;
1040 	char *installed, *installed_pattern;
1041 	plist_t *p;
1042 	int status;
1043 
1044 	status = 0;
1045 
1046 	for (p = pkg->plist.head; p != NULL; p = p->next) {
1047 		if (p->type == PLIST_IGNORE) {
1048 			p = p->next;
1049 			continue;
1050 		}
1051 		if (p->type != PLIST_PKGCFL)
1052 			continue;
1053 		data.pkg = pkg->pkgname;
1054 		data.old_pkg = pkg->other_version;
1055 		data.pattern = p->name;
1056 		status |= match_installed_pkgs(p->name,
1057 		    check_explicit_conflict_iter, &data);
1058 	}
1059 
1060 	if (some_installed_package_conflicts_with(pkg->pkgname,
1061 	    pkg->other_version, &installed, &installed_pattern)) {
1062 		warnx("Installed package `%s' conflicts with `%s' when trying to install `%s'.",
1063 			installed, installed_pattern, pkg->pkgname);
1064 		free(installed);
1065 		free(installed_pattern);
1066 		status |= -1;
1067 	}
1068 
1069 	return status;
1070 }
1071 
1072 static int
1073 check_implicit_conflict(struct pkg_task *pkg)
1074 {
1075 	plist_t *p;
1076 	char *fullpath, *existing;
1077 	int status;
1078 
1079 	if (!pkgdb_open(ReadOnly)) {
1080 #if notyet /* XXX empty pkgdb without database? */
1081 		warn("Can't open pkgdb for reading");
1082 		return -1;
1083 #else
1084 		return 0;
1085 #endif
1086 	}
1087 
1088 	status = 0;
1089 
1090 	for (p = pkg->plist.head; p != NULL; p = p->next) {
1091 		if (p->type == PLIST_IGNORE) {
1092 			p = p->next;
1093 			continue;
1094 		} else if (p->type != PLIST_FILE)
1095 			continue;
1096 
1097 		fullpath = xasprintf("%s/%s", pkg->prefix, p->name);
1098 		existing = pkgdb_retrieve(fullpath);
1099 		free(fullpath);
1100 		if (existing == NULL)
1101 			continue;
1102 		if (pkg->other_version != NULL &&
1103 		    strcmp(pkg->other_version, existing) == 0)
1104 			continue;
1105 
1106 		warnx("Conflicting PLIST with %s: %s", existing, p->name);
1107 		if (!Force) {
1108 			status = -1;
1109 			if (!Verbose)
1110 				break;
1111 		}
1112 	}
1113 
1114 	pkgdb_close();
1115 	return status;
1116 }
1117 
1118 /* check if all REQUIRES files (usually libraries) are installed */
1119 static int
1120 check_requires(struct pkg_task *pkg)
1121 {
1122 	const char *data, *eol, *next_line;
1123 	int ret = 0;
1124 
1125 	data = pkg->meta_data.meta_build_info;
1126 
1127 	for (; data != NULL && *data != '\0'; data = next_line) {
1128 		if ((eol = strchr(data, '\n')) == NULL) {
1129 			eol = data + strlen(data);
1130 			next_line = eol;
1131 		} else
1132 			next_line = eol + 1;
1133 
1134 		if (strncmp(data, "REQUIRES=", 9) == 0) {
1135 			char *library_name = dup_value(data, eol);
1136 			struct stat sb;
1137 			if (stat(library_name, &sb) != 0 || !S_ISREG(sb.st_mode)) {
1138 				warnx("Missing required library: %s", library_name);
1139 #ifdef __NetBSD__
1140 				if (strncmp(library_name, "/usr/X11R7", 10) == 0) {
1141 					warnx("Please make sure to install the X sets");
1142 				}
1143 #endif
1144 				ret = 1;
1145 			}
1146 			free(library_name);
1147 		}
1148 	}
1149 
1150 	return ret;
1151 }
1152 
1153 /*
1154  * Install a required dependency and verify its installation.
1155  */
1156 static int
1157 install_depend_pkg(const char *dep)
1158 {
1159 	/* XXX check cyclic dependencies? */
1160 	if (Fake || NoRecord) {
1161 		if (!Force) {
1162 			warnx("Missing dependency %s", dep);
1163 			return 1;
1164 		}
1165 		warnx("Missing dependency %s, continuing", dep);
1166 	}
1167 
1168 	if (pkg_do(dep, 1, 0)) {
1169 		if (!ForceDepends) {
1170 			warnx("Can't install dependency %s", dep);
1171 			return 1;
1172 		}
1173 		warnx("Can't install dependency %s, continuing", dep);
1174 	}
1175 
1176 	if (find_best_matching_installed_pkg(dep, 0) == NULL) {
1177 		if (!ForceDepends) {
1178 			warnx("Just installed dependency %s disappeared", dep);
1179 			return 1;
1180 		}
1181 		warnx("Missing dependency %s ignored", dep);
1182 	}
1183 
1184 	return 0;
1185 }
1186 
1187 static int
1188 check_dependencies(struct pkg_task *pkg)
1189 {
1190 	plist_t *p;
1191 	char *best_installed;
1192 	int status;
1193 	size_t i;
1194 
1195 	status = 0;
1196 
1197 	/*
1198 	 * Recursively handle dependencies, installing as required.
1199 	 */
1200 	for (p = pkg->plist.head; p != NULL; p = p->next) {
1201 		if (p->type == PLIST_IGNORE) {
1202 			p = p->next;
1203 			continue;
1204 		} else if (p->type != PLIST_PKGDEP)
1205 			continue;
1206 
1207 		if (find_best_matching_installed_pkg(p->name, 0) == NULL) {
1208 			if (install_depend_pkg(p->name) != 0) {
1209 				status = -1;
1210 				break;
1211 			}
1212 		}
1213 	}
1214 
1215 	/*
1216 	 * Now that all dependencies have been processed we can find the best
1217 	 * matches for pkg_register_depends() to store in our +REQUIRED_BY.
1218 	 */
1219 	for (p = pkg->plist.head; p != NULL; p = p->next) {
1220 		if (p->type == PLIST_IGNORE) {
1221 			p = p->next;
1222 			continue;
1223 		} else if (p->type != PLIST_PKGDEP)
1224 			continue;
1225 
1226 		best_installed = find_best_matching_installed_pkg(p->name, 0);
1227 		if (best_installed == NULL) {
1228 			warnx("Expected dependency %s still missing", p->name);
1229 			return -1;
1230 		}
1231 
1232 		for (i = 0; i < pkg->dep_length; ++i) {
1233 			if (strcmp(best_installed, pkg->dependencies[i]) == 0)
1234 				break;
1235 		}
1236 		if (i < pkg->dep_length) {
1237 			/* Already used as dependency, so skip it. */
1238 			free(best_installed);
1239 			continue;
1240 		}
1241 		if (pkg->dep_length + 1 >= pkg->dep_allocated) {
1242 			char **tmp;
1243 			pkg->dep_allocated = 2 * pkg->dep_allocated + 1;
1244 			pkg->dependencies = xrealloc(pkg->dependencies,
1245 			    pkg->dep_allocated * sizeof(*tmp));
1246 		}
1247 		pkg->dependencies[pkg->dep_length++] = best_installed;
1248 	}
1249 
1250 	return status;
1251 }
1252 
1253 static int
1254 preserve_meta_data_file(struct pkg_task *pkg, const char *name)
1255 {
1256 	char *old_file, *new_file;
1257 	int rv;
1258 
1259 	if (Fake)
1260 		return 0;
1261 
1262 	old_file = pkgdb_pkg_file(pkg->other_version, name);
1263 	new_file = xasprintf("%s/%s", pkg->install_logdir, name);
1264 	rv = 0;
1265 	if (rename(old_file, new_file) == -1 && errno != ENOENT) {
1266 		warn("Can't move %s from %s to %s", name, old_file, new_file);
1267 		rv = -1;
1268 	}
1269 	free(old_file);
1270 	free(new_file);
1271 	return rv;
1272 }
1273 
1274 static int
1275 start_replacing(struct pkg_task *pkg)
1276 {
1277 	int result = -1;
1278 
1279 	if (preserve_meta_data_file(pkg, REQUIRED_BY_FNAME))
1280 		return -1;
1281 
1282 	if (preserve_meta_data_file(pkg, PRESERVE_FNAME))
1283 		return -1;
1284 
1285 	if (pkg->meta_data.meta_installed_info == NULL &&
1286 	    preserve_meta_data_file(pkg, INSTALLED_INFO_FNAME))
1287 		return -1;
1288 
1289 	if (Verbose || Fake) {
1290 		printf("%s/pkg_delete -K %s -p %s%s%s '%s'\n",
1291 			BINDIR, pkgdb_get_dir(), pkg->prefix,
1292 			Destdir ? " -P ": "", Destdir ? Destdir : "",
1293 			pkg->other_version);
1294 	}
1295 	if (!Fake) {
1296 		result = fexec_skipempty(BINDIR "/pkg_delete", "-K", pkgdb_get_dir(),
1297 		    "-p", pkg->prefix,
1298 		    Destdir ? "-P": "", Destdir ? Destdir : "",
1299 		    pkg->other_version, NULL);
1300 		if (result != 0) {
1301 			warnx("command failed: %s/pkg_delete -K %s -p %s %s%s%s",
1302 			      BINDIR, pkgdb_get_dir(), pkg->prefix, Destdir ? "-P" : " ",
1303 			      Destdir ? Destdir : "", pkg->other_version);
1304 		}
1305 	}
1306 
1307 	return result;
1308 }
1309 
1310 static int check_input(const char *line, size_t len)
1311 {
1312 	if (line == NULL || len == 0)
1313 		return 1;
1314 	switch (*line) {
1315 	case 'Y':
1316 	case 'y':
1317 	case 'T':
1318 	case 't':
1319 	case '1':
1320 		return 0;
1321 	default:
1322 		return 1;
1323 	}
1324 }
1325 
1326 static int
1327 check_signature(struct pkg_task *pkg, int invalid_sig)
1328 {
1329 #ifdef BOOTSTRAP
1330 	return 0;
1331 #else
1332 	char *line;
1333 	size_t len;
1334 
1335 	if (strcasecmp(verified_installation, "never") == 0)
1336 		return 0;
1337 	if (strcasecmp(verified_installation, "always") == 0) {
1338 		if (invalid_sig)
1339 			warnx("No valid signature found, rejected");
1340 		return invalid_sig;
1341 	}
1342 	if (strcasecmp(verified_installation, "trusted") == 0) {
1343 		if (!invalid_sig)
1344 			return 0;
1345 		fprintf(stderr, "No valid signature found for %s.\n",
1346 		    pkg->pkgname);
1347 		fprintf(stderr,
1348 		    "Do you want to proceed with the installation [y/n]?\n");
1349 		line = fgetln(stdin, &len);
1350 		if (check_input(line, len)) {
1351 			fprintf(stderr, "Cancelling installation\n");
1352 			return 1;
1353 		}
1354 		return 0;
1355 	}
1356 	if (strcasecmp(verified_installation, "interactive") == 0) {
1357 		fprintf(stderr, "Do you want to proceed with "
1358 		    "the installation of %s [y/n]?\n", pkg->pkgname);
1359 		line = fgetln(stdin, &len);
1360 		if (check_input(line, len)) {
1361 			fprintf(stderr, "Cancelling installation\n");
1362 			return 1;
1363 		}
1364 		return 0;
1365 	}
1366 	warnx("Unknown value of configuration variable VERIFIED_INSTALLATION");
1367 	return 1;
1368 #endif
1369 }
1370 
1371 static int
1372 check_vulnerable(struct pkg_task *pkg)
1373 {
1374 #ifdef BOOTSTRAP
1375 	return 0;
1376 #else
1377 	static struct pkg_vulnerabilities *pv;
1378 	int require_check;
1379 	char *line;
1380 	size_t len;
1381 
1382 	if (strcasecmp(check_vulnerabilities, "never") == 0)
1383 		return 0;
1384 	else if (strcasecmp(check_vulnerabilities, "always") == 0)
1385 		require_check = 1;
1386 	else if (strcasecmp(check_vulnerabilities, "interactive") == 0)
1387 		require_check = 0;
1388 	else {
1389 		warnx("Unknown value of the configuration variable"
1390 		    "CHECK_VULNERABILITIES");
1391 		return 1;
1392 	}
1393 
1394 	if (pv == NULL) {
1395 		pv = read_pkg_vulnerabilities_file(pkg_vulnerabilities_file,
1396 		    require_check, 0);
1397 		if (pv == NULL)
1398 			return require_check;
1399 	}
1400 
1401 	if (!audit_package(pv, pkg->pkgname, NULL, 0, 2))
1402 		return 0;
1403 
1404 	if (require_check)
1405 		return 1;
1406 
1407 	fprintf(stderr, "Do you want to proceed with the installation of %s"
1408 	    " [y/n]?\n", pkg->pkgname);
1409 	line = fgetln(stdin, &len);
1410 	if (check_input(line, len)) {
1411 		fprintf(stderr, "Cancelling installation\n");
1412 		return 1;
1413 	}
1414 	return 0;
1415 #endif
1416 }
1417 
1418 static int
1419 check_license(struct pkg_task *pkg)
1420 {
1421 #ifdef BOOTSTRAP
1422 	return 0;
1423 #else
1424 	if (LicenseCheck == 0)
1425 		return 0;
1426 
1427 	if ((pkg->buildinfo[BI_LICENSE] == NULL ||
1428 	     *pkg->buildinfo[BI_LICENSE] == '\0')) {
1429 
1430 		if (LicenseCheck == 1)
1431 			return 0;
1432 		warnx("No LICENSE set for package `%s'", pkg->pkgname);
1433 		return 1;
1434 	}
1435 
1436 	switch (acceptable_license(pkg->buildinfo[BI_LICENSE])) {
1437 	case 0:
1438 		warnx("License `%s' of package `%s' is not acceptable",
1439 		    pkg->buildinfo[BI_LICENSE], pkg->pkgname);
1440 		return 1;
1441 	case 1:
1442 		return 0;
1443 	default:
1444 		warnx("Invalid LICENSE for package `%s'", pkg->pkgname);
1445 		return 1;
1446 	}
1447 #endif
1448 }
1449 
1450 /*
1451  * Install a single package.
1452  */
1453 static int
1454 pkg_do(const char *pkgpath, int mark_automatic, int top_level)
1455 {
1456 	char *archive_name;
1457 	int status, invalid_sig;
1458 	struct pkg_task *pkg;
1459 
1460 	pkg = xcalloc(1, sizeof(*pkg));
1461 
1462 	status = -1;
1463 
1464 	pkg->archive = find_archive(pkgpath, top_level, &archive_name);
1465 	if (pkg->archive == NULL) {
1466 		warnx("no pkg found for '%s', sorry.", pkgpath);
1467 		goto clean_find_archive;
1468 	}
1469 
1470 #ifndef BOOTSTRAP
1471 	invalid_sig = pkg_verify_signature(archive_name, &pkg->archive, &pkg->entry,
1472 	    &pkg->pkgname);
1473 #else
1474 	invalid_sig = 0;
1475 #endif
1476 	free(archive_name);
1477 
1478 	if (pkg->archive == NULL)
1479 		goto clean_memory;
1480 
1481 	if (read_meta_data(pkg))
1482 		goto clean_memory;
1483 
1484 	/* Parse PLIST early, so that messages can use real package name. */
1485 	if (pkg_parse_plist(pkg))
1486 		goto clean_memory;
1487 
1488 	if (check_signature(pkg, invalid_sig))
1489 		goto clean_memory;
1490 
1491 	if (read_buildinfo(pkg))
1492 		goto clean_memory;
1493 
1494 	if (check_pkgtools_version(pkg))
1495 		goto clean_memory;
1496 
1497 	if (check_vulnerable(pkg))
1498 		goto clean_memory;
1499 
1500 	if (check_license(pkg))
1501 		goto clean_memory;
1502 
1503 	if (pkg->meta_data.meta_mtree != NULL)
1504 		warnx("mtree specification in pkg `%s' ignored", pkg->pkgname);
1505 
1506 	pkg->logdir = xasprintf("%s/%s", config_pkg_dbdir, pkg->pkgname);
1507 
1508 	if (Destdir != NULL)
1509 		pkg->install_logdir = xasprintf("%s/%s", Destdir, pkg->logdir);
1510 	else
1511 		pkg->install_logdir = xstrdup(pkg->logdir);
1512 
1513 	if (NoRecord && !Fake) {
1514 		const char *tmpdir;
1515 
1516 		tmpdir = getenv("TMPDIR");
1517 		if (tmpdir == NULL)
1518 			tmpdir = "/tmp";
1519 
1520 		free(pkg->install_logdir);
1521 		pkg->install_logdir = xasprintf("%s/pkg_install.XXXXXX", tmpdir);
1522 		/* XXX pkg_add -u... */
1523 		if (mkdtemp(pkg->install_logdir) == NULL) {
1524 			warn("mkdtemp failed");
1525 			goto clean_memory;
1526 		}
1527 	}
1528 
1529 	switch (check_already_installed(pkg)) {
1530 	case 0:
1531 		status = 0;
1532 		goto clean_memory;
1533 	case 1:
1534 		break;
1535 	case -1:
1536 		goto clean_memory;
1537 	}
1538 
1539 	if (check_platform(pkg))
1540 		goto clean_memory;
1541 
1542 	if (check_other_installed(pkg))
1543 		goto clean_memory;
1544 
1545 	if (check_explicit_conflict(pkg))
1546 		goto clean_memory;
1547 
1548 	if (check_implicit_conflict(pkg))
1549 		goto clean_memory;
1550 
1551 	if (pkg->other_version != NULL) {
1552 		/*
1553 		 * Replacing an existing package.
1554 		 * Write meta-data, get rid of the old version,
1555 		 * install/update dependencies and finally extract.
1556 		 */
1557 		if (write_meta_data(pkg))
1558 			goto nuke_pkgdb;
1559 
1560 		if (start_replacing(pkg))
1561 			goto nuke_pkgdb;
1562 
1563 		if (pkg->install_logdir_real) {
1564 			rename(pkg->install_logdir, pkg->install_logdir_real);
1565 			free(pkg->install_logdir);
1566 			pkg->install_logdir = pkg->install_logdir_real;
1567 			pkg->install_logdir_real = NULL;
1568 		}
1569 
1570 		if (check_dependencies(pkg))
1571 			goto nuke_pkgdb;
1572 
1573 		if (check_requires(pkg))
1574 			goto nuke_pkgdb;
1575 	} else {
1576 		/*
1577 		 * Normal installation.
1578 		 * Install/update dependencies first and
1579 		 * write the current package to disk afterwards.
1580 		 */
1581 		if (check_dependencies(pkg))
1582 			goto clean_memory;
1583 
1584 		if (check_requires(pkg))
1585 			goto clean_memory;
1586 
1587 		if (write_meta_data(pkg))
1588 			goto nuke_pkgdb;
1589 	}
1590 
1591 	if (run_install_script(pkg, "PRE-INSTALL"))
1592 		goto nuke_pkgdb;
1593 
1594 	if (extract_files(pkg))
1595 		goto nuke_pkg;
1596 
1597 	if (run_install_script(pkg, "POST-INSTALL"))
1598 		goto nuke_pkg;
1599 
1600 	/* XXX keep +INSTALL_INFO for updates? */
1601 	/* XXX keep +PRESERVE for updates? */
1602 	if (mark_automatic)
1603 		mark_as_automatic_installed(pkg->pkgname, 1);
1604 
1605 	pkg_register_depends(pkg);
1606 
1607 	if (Verbose)
1608 		printf("Package %s registered in %s\n", pkg->pkgname, pkg->install_logdir);
1609 
1610 	if (pkg->meta_data.meta_display != NULL)
1611 		fputs(pkg->meta_data.meta_display, stdout);
1612 
1613 	status = 0;
1614 	goto clean_memory;
1615 
1616 nuke_pkg:
1617 	if (!Fake) {
1618 		if (pkg->other_version) {
1619 			warnx("Updating of %s to %s failed.",
1620 			    pkg->other_version, pkg->pkgname);
1621 			warnx("Remember to run pkg_admin rebuild-tree after fixing this.");
1622 		}
1623 		delete_package(FALSE, &pkg->plist, FALSE, Destdir);
1624 	}
1625 
1626 nuke_pkgdb:
1627 	if (!Fake) {
1628 		(void) remove_files(pkg->install_logdir, "+*");
1629 		if (recursive_remove(pkg->install_logdir, 1))
1630 			warn("Couldn't remove %s", pkg->install_logdir);
1631 		free(pkg->install_logdir_real);
1632 		free(pkg->install_logdir);
1633 		free(pkg->logdir);
1634 		pkg->install_logdir_real = NULL;
1635 		pkg->install_logdir = NULL;
1636 		pkg->logdir = NULL;
1637 	}
1638 
1639 clean_memory:
1640 	if (pkg->logdir != NULL && NoRecord && !Fake) {
1641 		if (recursive_remove(pkg->install_logdir, 1))
1642 			warn("Couldn't remove %s", pkg->install_logdir);
1643 	}
1644 	free(pkg->install_prefix);
1645 	free(pkg->install_logdir_real);
1646 	free(pkg->install_logdir);
1647 	free(pkg->logdir);
1648 	free_buildinfo(pkg);
1649 	free_plist(&pkg->plist);
1650 	free_meta_data(pkg);
1651 	if (pkg->archive)
1652 		archive_read_free(pkg->archive);
1653 	free(pkg->other_version);
1654 	free(pkg->pkgname);
1655 clean_find_archive:
1656 	free(pkg);
1657 	return status;
1658 }
1659 
1660 int
1661 pkg_perform(lpkg_head_t *pkgs)
1662 {
1663 	int     errors = 0;
1664 	lpkg_t *lpp;
1665 
1666 	while ((lpp = TAILQ_FIRST(pkgs)) != NULL) {
1667 		if (pkg_do(lpp->lp_name, Automatic, 1))
1668 			++errors;
1669 		TAILQ_REMOVE(pkgs, lpp, lp_link);
1670 		free_lpkg(lpp);
1671 	}
1672 
1673 	return errors;
1674 }
1675