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