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