perform.c revision 179760
1/*
2 * FreeBSD install - a package for the installation and maintainance
3 * of non-core utilities.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * Jordan K. Hubbard
15 * 18 July 1993
16 *
17 * This is the main body of the add module.
18 *
19 */
20
21#include <sys/cdefs.h>
22__FBSDID("$FreeBSD: head/usr.sbin/pkg_install/add/perform.c 179760 2008-06-12 15:21:13Z flz $");
23
24#include <err.h>
25#include <paths.h>
26#include "lib.h"
27#include "add.h"
28
29#include <libgen.h>
30#include <signal.h>
31#include <sys/wait.h>
32
33static int pkg_do(char *);
34static int sanity_check(char *);
35static char LogDir[FILENAME_MAX];
36static int zapLogDir;		/* Should we delete LogDir? */
37
38int
39pkg_perform(char **pkgs)
40{
41    int i, err_cnt = 0;
42
43    signal(SIGINT, cleanup);
44    signal(SIGHUP, cleanup);
45
46    if (AddMode == SLAVE)
47	err_cnt = pkg_do(NULL);
48    else {
49	for (i = 0; pkgs[i]; i++)
50	    err_cnt += pkg_do(pkgs[i]);
51    }
52    return err_cnt;
53}
54
55static Package Plist;
56static char *Home;
57
58/*
59 * This is seriously ugly code following.  Written very fast!
60 * [And subsequently made even worse..  Sigh!  This code was just born
61 * to be hacked, I guess.. :) -jkh]
62 */
63static int
64pkg_do(char *pkg)
65{
66    char pkg_fullname[FILENAME_MAX];
67    char playpen[FILENAME_MAX];
68    char extract_contents[FILENAME_MAX];
69    char *where_to, *extract;
70    FILE *cfile;
71    int code;
72    PackingList p;
73    struct stat sb;
74    int inPlace, conflictsfound, errcode;
75    /* support for separate pre/post install scripts */
76    int new_m = 0;
77    char pre_script[FILENAME_MAX] = INSTALL_FNAME;
78    char post_script[FILENAME_MAX];
79    char pre_arg[FILENAME_MAX], post_arg[FILENAME_MAX];
80    char *conflict[2];
81    char **matched;
82
83    conflictsfound = 0;
84    code = 0;
85    zapLogDir = 0;
86    LogDir[0] = '\0';
87    strcpy(playpen, FirstPen);
88    inPlace = 0;
89
90    /* Are we coming in for a second pass, everything already extracted? */
91    if (!pkg) {
92	fgets(playpen, FILENAME_MAX, stdin);
93	playpen[strlen(playpen) - 1] = '\0'; /* pesky newline! */
94	if (chdir(playpen) == FAIL) {
95	    warnx("pkg_add in SLAVE mode can't chdir to %s", playpen);
96	    return 1;
97	}
98	read_plist(&Plist, stdin);
99	where_to = playpen;
100    }
101    /* Nope - do it now */
102    else {
103	/* Is it an ftp://foo.bar.baz/file.t[bg]z specification? */
104	if (isURL(pkg)) {
105	    if (!(Home = fileGetURL(NULL, pkg, KeepPackage))) {
106		warnx("unable to fetch '%s' by URL", pkg);
107		return 1;
108	    }
109	    where_to = Home;
110	    strcpy(pkg_fullname, pkg);
111	    cfile = fopen(CONTENTS_FNAME, "r");
112	    if (!cfile) {
113		warnx(
114		"unable to open table of contents file '%s' - not a package?",
115		CONTENTS_FNAME);
116		goto bomb;
117	    }
118	    read_plist(&Plist, cfile);
119	    fclose(cfile);
120	}
121	else {
122	    strcpy(pkg_fullname, pkg);		/*
123						 * Copy for sanity's sake,
124						 * could remove pkg_fullname
125						 */
126	    if (strcmp(pkg, "-")) {
127		if (stat(pkg_fullname, &sb) == FAIL) {
128		    warnx("can't stat package file '%s'", pkg_fullname);
129		    goto bomb;
130		}
131		sprintf(extract_contents, "--fast-read %s", CONTENTS_FNAME);
132		extract = extract_contents;
133	    }
134	    else {
135		extract = NULL;
136		sb.st_size = 100000;	/* Make up a plausible average size */
137	    }
138	    Home = make_playpen(playpen, sb.st_size * 4);
139	    if (!Home)
140		errx(1, "unable to make playpen for %lld bytes", (long long)sb.st_size * 4);
141	    where_to = Home;
142	    /* Since we can call ourselves recursively, keep notes on where we came from */
143	    if (!getenv("_TOP"))
144		setenv("_TOP", Home, 1);
145	    if (unpack(pkg_fullname, extract)) {
146		warnx(
147	"unable to extract table of contents file from '%s' - not a package?",
148		pkg_fullname);
149		goto bomb;
150	    }
151	    cfile = fopen(CONTENTS_FNAME, "r");
152	    if (!cfile) {
153		warnx(
154	"unable to open table of contents file '%s' - not a package?",
155		CONTENTS_FNAME);
156		goto bomb;
157	    }
158	    read_plist(&Plist, cfile);
159	    fclose(cfile);
160
161	    /* Extract directly rather than moving?  Oh goodie! */
162	    if (find_plist_option(&Plist, "extract-in-place")) {
163		if (Verbose)
164		    printf("Doing in-place extraction for %s\n", pkg_fullname);
165		p = find_plist(&Plist, PLIST_CWD);
166		if (p) {
167		    if (!isdir(p->name) && !Fake) {
168			if (Verbose)
169			    printf("Desired prefix of %s does not exist, creating..\n", p->name);
170			vsystem("/bin/mkdir -p %s", p->name);
171			if (chdir(p->name) == -1) {
172			    warn("unable to change directory to '%s'", p->name);
173			    goto bomb;
174			}
175		    }
176		    where_to = p->name;
177		    inPlace = 1;
178		}
179		else {
180		    warnx(
181		"no prefix specified in '%s' - this is a bad package!",
182			pkg_fullname);
183		    goto bomb;
184		}
185	    }
186
187	    /*
188	     * Apply a crude heuristic to see how much space the package will
189	     * take up once it's unpacked.  I've noticed that most packages
190	     * compress an average of 75%, so multiply by 4 for good measure.
191	     */
192
193	    if (!extract && !inPlace && min_free(playpen) < sb.st_size * 4) {
194		warnx("projected size of %lld exceeds available free space.\n"
195"Please set your PKG_TMPDIR variable to point to a location with more\n"
196		       "free space and try again", (long long)sb.st_size * 4);
197		warnx("not extracting %s\ninto %s, sorry!",
198			pkg_fullname, where_to);
199		goto bomb;
200	    }
201
202	    /* If this is a direct extract and we didn't want it, stop now */
203	    if (inPlace && Fake)
204		goto success;
205
206	    /* Finally unpack the whole mess.  If extract is null we
207	       already + did so so don't bother doing it again. */
208	    if (extract && unpack(pkg_fullname, NULL)) {
209		warnx("unable to extract '%s'!", pkg_fullname);
210		goto bomb;
211	    }
212	}
213
214	/* Check for sanity and dependencies */
215	if (sanity_check(pkg))
216	    goto bomb;
217
218	/* If we're running in MASTER mode, just output the plist and return */
219	if (AddMode == MASTER) {
220	    printf("%s\n", where_playpen());
221	    write_plist(&Plist, stdout);
222	    return 0;
223	}
224    }
225
226    /*
227     * If we have a prefix, delete the first one we see and add this
228     * one in place of it.
229     */
230    if (Prefix) {
231	delete_plist(&Plist, FALSE, PLIST_CWD, NULL);
232	add_plist_top(&Plist, PLIST_CWD, Prefix);
233    }
234
235    setenv(PKG_PREFIX_VNAME, (p = find_plist(&Plist, PLIST_CWD)) ? p->name : ".", 1);
236    /* Protect against old packages with bogus @name and origin fields */
237    if (Plist.name == NULL)
238	Plist.name = "anonymous";
239    if (Plist.origin == NULL)
240	Plist.origin = "anonymous/anonymous";
241
242    /*
243     * See if we're already registered either with the same name (the same
244     * version) or some other version with the same origin.
245     */
246    if ((isinstalledpkg(Plist.name) > 0 ||
247         matchbyorigin(Plist.origin, NULL) != NULL) && !Force) {
248	warnx("package '%s' or its older version already installed%s",
249	      Plist.name, FailOnAlreadyInstalled ? "" : " (ignored)");
250	code = FailOnAlreadyInstalled != FALSE;
251	goto success;	/* close enough for government work */
252    }
253
254    /* Now check the packing list for conflicts */
255    if (!IgnoreDeps){
256    for (p = Plist.head; p != NULL; p = p->next) {
257	if (p->type == PLIST_CONFLICTS) {
258	    int i;
259	    conflict[0] = strdup(p->name);
260	    conflict[1] = NULL;
261	    matched = matchinstalled(MATCH_GLOB, conflict, &errcode);
262	    free(conflict[0]);
263	    if (errcode == 0 && matched != NULL)
264		for (i = 0; matched[i] != NULL; i++)
265		    if (isinstalledpkg(matched[i]) > 0) {
266			warnx("package '%s' conflicts with %s", Plist.name,
267				matched[i]);
268			conflictsfound = 1;
269		    }
270
271	    continue;
272	}
273    }
274    if(conflictsfound) {
275	if(!Force) {
276	    warnx("please use pkg_delete first to remove conflicting package(s) or -f to force installation");
277	    code = 1;
278	    goto bomb;
279	} else
280	    warnx("-f specified; proceeding anyway");
281    }
282
283    /* Now check the packing list for dependencies */
284    for (p = Plist.head; p ; p = p->next) {
285	char *deporigin;
286
287	if (p->type != PLIST_PKGDEP)
288	    continue;
289	deporigin = (p->next->type == PLIST_DEPORIGIN) ? p->next->name : NULL;
290	if (Verbose) {
291	    printf("Package '%s' depends on '%s'", Plist.name, p->name);
292	    if (deporigin != NULL)
293		printf(" with '%s' origin", deporigin);
294	    printf(".\n");
295	}
296	if (isinstalledpkg(p->name) <= 0 &&
297	    !(deporigin != NULL && matchbyorigin(deporigin, NULL) != NULL)) {
298	    char path[FILENAME_MAX], *cp = NULL;
299
300	    if (!Fake) {
301		char prefixArg[2 + MAXPATHLEN]; /* "-P" + Prefix */
302		if (PrefixRecursive) {
303		    strlcpy(prefixArg, "-P", sizeof(prefixArg));
304		    strlcat(prefixArg, Prefix, sizeof(prefixArg));
305		}
306		if (!isURL(pkg) && !getenv("PKG_ADD_BASE")) {
307		    const char *ext;
308
309		    ext = strrchr(pkg_fullname, '.');
310		    if (ext == NULL)
311#if defined(__FreeBSD_version) && __FreeBSD_version >= 500039
312			ext = ".tbz";
313#else
314			ext = ".tgz";
315#endif
316		    snprintf(path, FILENAME_MAX, "%s/%s%s", getenv("_TOP"), p->name, ext);
317		    if (fexists(path))
318			cp = path;
319		    else
320			cp = fileFindByPath(pkg, p->name);
321		    if (cp) {
322			if (Verbose)
323			    printf("Loading it from %s.\n", cp);
324			if (vsystem("%s %s %s '%s'", PkgAddCmd, Verbose ? "-v " : "", PrefixRecursive ? prefixArg : "", cp)) {
325			    warnx("autoload of dependency '%s' failed%s",
326				cp, Force ? " (proceeding anyway)" : "!");
327			    if (!Force)
328				++code;
329			}
330		    }
331		    else {
332			warnx("could not find package %s %s",
333			      p->name, Force ? " (proceeding anyway)" : "!");
334			if (!Force)
335			    ++code;
336		    }
337		}
338		else if ((cp = fileGetURL(pkg, p->name, KeepPackage)) != NULL) {
339		    if (Verbose)
340			printf("Finished loading %s over FTP.\n", p->name);
341		    if (!fexists("+CONTENTS")) {
342			warnx("autoloaded package %s has no +CONTENTS file?",
343				p->name);
344			if (!Force)
345			    ++code;
346		    }
347		    else if (vsystem("(pwd; /bin/cat +CONTENTS) | %s %s %s %s -S", PkgAddCmd, Verbose ? "-v" : "", PrefixRecursive ? prefixArg : "", KeepPackage ? "-K" : "")) {
348			warnx("pkg_add of dependency '%s' failed%s",
349				p->name, Force ? " (proceeding anyway)" : "!");
350			if (!Force)
351			    ++code;
352		    }
353		    else if (Verbose)
354			printf("\t'%s' loaded successfully.\n", p->name);
355		    /* Nuke the temporary playpen */
356		    leave_playpen();
357		}
358	    }
359	    else {
360		if (Verbose)
361		    printf("and was not found%s.\n", Force ? " (proceeding anyway)" : "");
362		else
363		    printf("Package dependency %s for %s not found%s\n", p->name, pkg,
364			   Force ? " (proceeding anyway)" : "!");
365		if (!Force)
366		    ++code;
367	    }
368	}
369	else if (Verbose)
370	    printf(" - already installed.\n");
371    }
372    } /* if (!IgnoreDeps) */
373
374    if (code != 0)
375	goto bomb;
376
377    /* Look for the requirements file */
378    if (fexists(REQUIRE_FNAME)) {
379	vsystem("/bin/chmod +x %s", REQUIRE_FNAME);	/* be sure */
380	if (Verbose)
381	    printf("Running requirements file first for %s..\n", Plist.name);
382	if (!Fake && vsystem("./%s %s INSTALL", REQUIRE_FNAME, Plist.name)) {
383	    warnx("package %s fails requirements %s", pkg_fullname,
384		   Force ? "installing anyway" : "- not installed");
385	    if (!Force) {
386		code = 1;
387		goto success;	/* close enough for government work */
388	    }
389	}
390    }
391
392    /*
393     * Test whether to use the old method of passing tokens to installation
394     * scripts, and set appropriate variables..
395     */
396
397    if (fexists(POST_INSTALL_FNAME)) {
398	new_m = 1;
399	sprintf(post_script, "%s", POST_INSTALL_FNAME);
400	pre_arg[0] = '\0';
401	post_arg[0] = '\0';
402    } else {
403	if (fexists(INSTALL_FNAME)) {
404	    sprintf(post_script, "%s", INSTALL_FNAME);
405	    sprintf(pre_arg, "PRE-INSTALL");
406	    sprintf(post_arg, "POST-INSTALL");
407	}
408    }
409
410    /* If we're really installing, and have an installation file, run it */
411    if (!NoInstall && fexists(pre_script)) {
412	vsystem("/bin/chmod +x %s", pre_script);	/* make sure */
413	if (Verbose)
414	    printf("Running pre-install for %s..\n", Plist.name);
415	if (!Fake && vsystem("./%s %s %s", pre_script, Plist.name, pre_arg)) {
416	    warnx("install script returned error status");
417	    unlink(pre_script);
418	    code = 1;
419	    goto success;		/* nothing to uninstall yet */
420	}
421    }
422
423    /* Now finally extract the entire show if we're not going direct */
424    if (!inPlace && !Fake)
425	extract_plist(".", &Plist);
426
427    if (!Fake && fexists(MTREE_FNAME)) {
428	if (Verbose)
429	    printf("Running mtree for %s..\n", Plist.name);
430	p = find_plist(&Plist, PLIST_CWD);
431	if (Verbose)
432	    printf("mtree -U -f %s -d -e -p %s >%s\n", MTREE_FNAME, p ? p->name : "/", _PATH_DEVNULL);
433	if (!Fake) {
434	    if (vsystem("/usr/sbin/mtree -U -f %s -d -e -p %s >%s", MTREE_FNAME, p ? p->name : "/", _PATH_DEVNULL))
435		warnx("mtree returned a non-zero status - continuing");
436	}
437    }
438
439    /* Run the installation script one last time? */
440    if (!NoInstall && fexists(post_script)) {
441	vsystem("/bin/chmod +x %s", post_script);	/* make sure */
442	if (Verbose)
443	    printf("Running post-install for %s..\n", Plist.name);
444	if (!Fake && vsystem("./%s %s %s", post_script, Plist.name, post_arg)) {
445	    warnx("install script returned error status");
446	    unlink(post_script);
447	    code = 1;
448	    goto fail;
449	}
450    }
451
452    /* Time to record the deed? */
453    if (!NoRecord && !Fake) {
454	char contents[FILENAME_MAX];
455	char **depnames = NULL, **deporigins = NULL, ***depmatches;
456	int i, dep_count = 0;
457	FILE *contfile;
458
459	if (getuid() != 0)
460	    warnx("not running as root - trying to record install anyway");
461	sprintf(LogDir, "%s/%s", LOG_DIR, Plist.name);
462	zapLogDir = 1;
463	if (Verbose)
464	    printf("Attempting to record package into %s..\n", LogDir);
465	if (make_hierarchy(LogDir)) {
466	    warnx("can't record package into '%s', you're on your own!",
467		   LogDir);
468	    bzero(LogDir, FILENAME_MAX);
469	    code = 1;
470	    goto success;	/* close enough for government work */
471	}
472	/* Make sure pkg_info can read the entry */
473	vsystem("/bin/chmod a+rx %s", LogDir);
474	move_file(".", DESC_FNAME, LogDir);
475	move_file(".", COMMENT_FNAME, LogDir);
476	if (fexists(INSTALL_FNAME))
477	    move_file(".", INSTALL_FNAME, LogDir);
478	if (fexists(POST_INSTALL_FNAME))
479	    move_file(".", POST_INSTALL_FNAME, LogDir);
480	if (fexists(DEINSTALL_FNAME))
481	    move_file(".", DEINSTALL_FNAME, LogDir);
482	if (fexists(POST_DEINSTALL_FNAME))
483	    move_file(".", POST_DEINSTALL_FNAME, LogDir);
484	if (fexists(REQUIRE_FNAME))
485	    move_file(".", REQUIRE_FNAME, LogDir);
486	if (fexists(DISPLAY_FNAME))
487	    move_file(".", DISPLAY_FNAME, LogDir);
488	if (fexists(MTREE_FNAME))
489	    move_file(".", MTREE_FNAME, LogDir);
490	sprintf(contents, "%s/%s", LogDir, CONTENTS_FNAME);
491	contfile = fopen(contents, "w");
492	if (!contfile) {
493	    warnx("can't open new contents file '%s'! can't register pkg",
494		contents);
495	    goto success; /* can't log, but still keep pkg */
496	}
497	write_plist(&Plist, contfile);
498	fclose(contfile);
499	for (p = Plist.head; p ; p = p->next) {
500	    char *deporigin;
501
502	    if (p->type != PLIST_PKGDEP)
503		continue;
504	    deporigin = (p->next->type == PLIST_DEPORIGIN) ? p->next->name :
505							     NULL;
506	    if (Verbose) {
507		printf("Trying to record dependency on package '%s'", p->name);
508		if (deporigin != NULL)
509		    printf(" with '%s' origin", deporigin);
510		printf(".\n");
511	    }
512
513	    if (deporigin) {
514		/* Defer to origin lookup */
515		depnames = realloc(depnames, (dep_count + 1) * sizeof(*depnames));
516		depnames[dep_count] = p->name;
517		deporigins = realloc(deporigins, (dep_count + 2) * sizeof(*deporigins));
518		deporigins[dep_count] = deporigin;
519		deporigins[dep_count + 1] = NULL;
520		dep_count++;
521	    } else {
522	       /* No origin recorded, try to register on literal package name */
523	       sprintf(contents, "%s/%s/%s", LOG_DIR, p->name,
524		     REQUIRED_BY_FNAME);
525	       contfile = fopen(contents, "a");
526	       if (!contfile) {
527		  warnx("can't open dependency file '%s'!\n"
528			"dependency registration is incomplete", contents);
529	       } else {
530		  fprintf(contfile, "%s\n", Plist.name);
531		  if (fclose(contfile) == EOF) {
532		     warnx("cannot properly close file %s", contents);
533		  }
534	       }
535	    }
536	}
537	if (dep_count > 0) {
538	    depmatches = matchallbyorigin((const char **)deporigins, NULL);
539	    free(deporigins);
540	    if (!IgnoreDeps && depmatches) {
541		for (i = 0; i < dep_count; i++) {
542		    if (depmatches[i]) {
543			int j;
544			char **tmp = depmatches[i];
545			for (j = 0; tmp[j] != NULL; j++) {
546			    /* Origin looked up */
547			    sprintf(contents, "%s/%s/%s", LOG_DIR, tmp[j],
548				REQUIRED_BY_FNAME);
549			    if (depnames[i] && strcmp(depnames[i], tmp[j]) != 0)
550				warnx("warning: package '%s' requires '%s', but '%s' "
551				    "is installed", Plist.name, depnames[i], tmp[j]);
552			    contfile = fopen(contents, "a");
553			    if (!contfile) {
554				warnx("can't open dependency file '%s'!\n"
555				    "dependency registration is incomplete", contents);
556			    } else {
557				fprintf(contfile, "%s\n", Plist.name);
558				if (fclose(contfile) == EOF)
559				    warnx("cannot properly close file %s", contents);
560			    }
561			}
562		    } else if (depnames[i]) {
563			/* No package present with this origin, try literal package name */
564			sprintf(contents, "%s/%s/%s", LOG_DIR, depnames[i],
565			    REQUIRED_BY_FNAME);
566			contfile = fopen(contents, "a");
567			if (!contfile) {
568			    warnx("can't open dependency file '%s'!\n"
569				"dependency registration is incomplete", contents);
570			} else {
571			    fprintf(contfile, "%s\n", Plist.name);
572			    if (fclose(contfile) == EOF) {
573				warnx("cannot properly close file %s", contents);
574			    }
575			}
576		    }
577		}
578	    }
579	}
580	if (Verbose)
581	    printf("Package %s registered in %s\n", Plist.name, LogDir);
582    }
583
584    if ((p = find_plist(&Plist, PLIST_DISPLAY)) != NULL) {
585	FILE *fp;
586	char buf[BUFSIZ];
587
588	snprintf(buf, sizeof buf, "%s/%s", LogDir, p->name);
589	fp = fopen(buf, "r");
590	if (fp) {
591	    putc('\n', stdout);
592	    while (fgets(buf, sizeof(buf), fp))
593		fputs(buf, stdout);
594	    putc('\n', stdout);
595	    (void) fclose(fp);
596	} else {
597    	    if (!Fake) {
598		warnx("cannot open %s as display file", buf);
599	    }
600	}
601    }
602
603    goto success;
604
605 bomb:
606    code = 1;
607    goto success;
608
609 fail:
610    /* Nuke the whole (installed) show, XXX but don't clean directories */
611    if (!Fake)
612	delete_package(FALSE, FALSE, &Plist);
613
614 success:
615    /* delete the packing list contents */
616    free_plist(&Plist);
617    leave_playpen();
618    return code;
619}
620
621static int
622sanity_check(char *pkg)
623{
624    int code = 0;
625
626    if (!fexists(CONTENTS_FNAME)) {
627	warnx("package %s has no CONTENTS file!", pkg);
628	code = 1;
629    }
630    else if (!fexists(COMMENT_FNAME)) {
631	warnx("package %s has no COMMENT file!", pkg);
632	code = 1;
633    }
634    else if (!fexists(DESC_FNAME)) {
635	warnx("package %s has no DESC file!", pkg);
636	code = 1;
637    }
638    return code;
639}
640
641void
642cleanup(int sig)
643{
644    static int in_cleanup = 0;
645
646    if (!in_cleanup) {
647	in_cleanup = 1;
648    	if (sig)
649	    printf("Signal %d received, cleaning up..\n", sig);
650    	if (!Fake && zapLogDir && LogDir[0])
651	    vsystem("%s -rf %s", REMOVE_CMD, LogDir);
652    	leave_playpen();
653    }
654    if (sig)
655	exit(1);
656}
657