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