Merge branch 'vendor/LIBARCHIVE'
[dragonfly.git] / sys / boot / common / commands.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
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  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/boot/common/commands.c,v 1.19 2003/08/25 23:30:41 obrien Exp $
27  */
28
29 #include <stand.h>
30 #include <string.h>
31
32 #include "bootstrap.h"
33
34 char            *command_errmsg;
35 char            command_errbuf[256];
36 int             CurrentCondition = 1;
37
38 static int page_file(char *filename);
39
40 /*
41  * Help is read from a formatted text file.
42  *
43  * Entries in the file are formatted as 
44
45 # Ttopic [Ssubtopic] Ddescription
46 help
47 text
48 here
49 #
50
51  *
52  * Note that for code simplicity's sake, the above format must be followed
53  * exactly.
54  *
55  * Subtopic entries must immediately follow the topic (this is used to
56  * produce the listing of subtopics).
57  *
58  * If no argument(s) are supplied by the user, the help for 'help' is displayed.
59  */
60 COMMAND_SET(help, "help", "detailed help", command_help);
61
62 static int
63 help_getnext(int fd, char **topic, char **subtopic, char **desc) 
64 {
65     char        line[81], *cp, *ep;
66     
67     for (;;) {
68         if (fgetstr(line, 80, fd) < 0)
69             return(0);
70         
71         if ((strlen(line) < 3) || (line[0] != '#') || (line[1] != ' '))
72             continue;
73
74         *topic = *subtopic = *desc = NULL;
75         cp = line + 2;
76         while((cp != NULL) && (*cp != 0)) {
77             ep = strchr(cp, ' ');
78             if ((*cp == 'T') && (*topic == NULL)) {
79                 if (ep != NULL)
80                     *ep++ = 0;
81                 *topic = strdup(cp + 1);
82             } else if ((*cp == 'S') && (*subtopic == NULL)) {
83                 if (ep != NULL)
84                     *ep++ = 0;
85                 *subtopic = strdup(cp + 1);
86             } else if (*cp == 'D') {
87                 *desc = strdup(cp + 1);
88                 ep = NULL;
89             }
90             cp = ep;
91         }
92         if (*topic == NULL) {
93             if (*subtopic != NULL)
94                 free(*subtopic);
95             if (*desc != NULL)
96                 free(*desc);
97             continue;
98         }
99         return(1);
100     }
101 }
102
103 static void
104 help_emitsummary(char *topic, char *subtopic, char *desc)
105 {
106     int         i;
107     
108     pager_output("    ");
109     pager_output(topic);
110     i = strlen(topic);
111     if (subtopic != NULL) {
112         pager_output(" ");
113         pager_output(subtopic);
114         i += strlen(subtopic) + 1;
115     }
116     if (desc != NULL) {
117         do {
118             pager_output(" ");
119         } while (i++ < 30);
120         pager_output(desc);
121     }
122     pager_output("\n");
123 }
124
125             
126 static int
127 command_help(int argc, char *argv[]) 
128 {
129     char        buf[81];        /* XXX buffer size? */
130     int         hfd, matched, doindex;
131     char        *topic, *subtopic, *t, *s, *d;
132
133     /* page the help text from our load path */
134     /* sprintf(buf, "%s/boot/loader.help", getenv("loaddev")); */
135     /* page the help text from our base path */
136     snprintf(buf, sizeof(buf), "%sloader.help", getenv("base"));
137     if ((hfd = open(buf, O_RDONLY)) < 0) {
138         if ((hfd = rel_open("loader.help", NULL, O_RDONLY)) < 0) {
139             printf("Verbose help not available, use '?' to list commands\n");
140             return(CMD_OK);
141         }
142     }
143
144     /* pick up request from arguments */
145     topic = subtopic = NULL;
146     switch(argc) {
147     case 3:
148         subtopic = strdup(argv[2]);
149     case 2:
150         topic = strdup(argv[1]);
151         break;
152     case 1:
153         topic = strdup("help");
154         break;
155     default:
156         command_errmsg = "usage is 'help <topic> [<subtopic>]";
157         return(CMD_ERROR);
158     }
159
160     /* magic "index" keyword */
161     doindex = !strcmp(topic, "index");
162     matched = doindex;
163     
164     /* Scan the helpfile looking for help matching the request */
165     pager_open();
166     while(help_getnext(hfd, &t, &s, &d)) {
167
168         if (doindex) {          /* dink around formatting */
169             help_emitsummary(t, s, d);
170
171         } else if (strcmp(topic, t)) {
172             /* topic mismatch */
173             if(matched)         /* nothing more on this topic, stop scanning */
174                 break;
175
176         } else {
177             /* topic matched */
178             matched = 1;
179             if (((subtopic == NULL) && (s == NULL)) ||
180                 ((subtopic != NULL) && (s != NULL) && !strcmp(subtopic, s))) {
181                 /* exact match, print text */
182                 while((fgetstr(buf, 80, hfd) >= 0) && (buf[0] != '#')) {
183                     if (pager_output(buf))
184                         break;
185                     if (pager_output("\n"))
186                         break;
187                 }
188             } else if ((subtopic == NULL) && (s != NULL)) {
189                 /* topic match, list subtopics */
190                 help_emitsummary(t, s, d);
191             }
192         }
193         free(t);
194         free(s);
195         free(d);
196     }
197     pager_close();
198     close(hfd);
199     if (!matched) {
200         sprintf(command_errbuf, "no help available for '%s'", topic);
201         free(topic);
202         if (subtopic)
203             free(subtopic);
204         return(CMD_ERROR);
205     }
206     free(topic);
207     if (subtopic)
208         free(subtopic);
209     return(CMD_OK);
210 }
211
212
213 COMMAND_SET(commandlist, "?", "list commands", command_commandlist);
214
215 static int
216 command_commandlist(int argc, char *argv[])
217 {
218     struct bootblk_command      **cmdp;
219     char str[81];
220     
221     pager_open();
222     printf("Available commands:\n");
223     SET_FOREACH(cmdp, Xcommand_set) {
224         if (((*cmdp)->c_name != NULL) && ((*cmdp)->c_desc != NULL)) {
225             snprintf(str, sizeof(str), "  %-15s  %s\n",
226                 (*cmdp)->c_name, (*cmdp)->c_desc);
227             pager_output(str);
228         }
229     }
230     pager_close();
231     return(CMD_OK);
232 }
233
234 /*
235  * XXX set/show should become set/echo if we have variable
236  * substitution happening.
237  */
238
239 COMMAND_SET(show, "show", "show variable(s)", command_show);
240
241 static int
242 command_show(int argc, char *argv[])
243 {
244     struct env_var      *ev;
245     char                *cp;
246
247     if (argc < 2) {
248         /* 
249          * With no arguments, print everything.
250          */
251         pager_open();
252         for (ev = environ; ev != NULL; ev = ev->ev_next) {
253             pager_output(ev->ev_name);
254             cp = getenv(ev->ev_name);
255             if (cp != NULL) {
256                 pager_output("=");
257                 pager_output(cp);
258             }
259             if (pager_output("\n"))
260                 break;
261         }
262         pager_close();
263     } else {
264         if ((cp = getenv(argv[1])) != NULL) {
265             printf("%s\n", cp);
266         } else {
267             sprintf(command_errbuf, "variable '%s' not found", argv[1]);
268             return(CMD_ERROR);
269         }
270     }
271     return(CMD_OK);
272 }
273
274 COMMAND_SET(set, "set", "set a variable", command_set);
275
276 static int
277 command_set(int argc, char *argv[])
278 {
279     int         err;
280     
281     if (argc != 2) {
282         command_errmsg = "wrong number of arguments";
283         return(CMD_ERROR);
284     } else {
285         if ((err = putenv(argv[1])) != 0) {
286             command_errmsg = strerror(err);
287             return(CMD_ERROR);
288         }
289     }
290     return(CMD_OK);
291 }
292
293 COMMAND_SET(unset, "unset", "unset a variable", command_unset);
294
295 static int
296 command_unset(int argc, char *argv[]) 
297 {
298     if (argc != 2) {
299         command_errmsg = "wrong number of arguments";
300         return(CMD_ERROR);
301     } else {
302         /* ignore any errors */
303         unsetenv(argv[1]);
304     }
305     return(CMD_OK);
306 }
307
308 COMMAND_SET(echo, "echo", NULL, command_echo);
309
310 static int
311 command_echo(int argc, char *argv[])
312 {
313     char        *s;
314     int         nl, ch;
315     
316     nl = 0;
317     optind = 1;
318     optreset = 1;
319     while ((ch = getopt(argc, argv, "n")) != -1) {
320         switch(ch) {
321         case 'n':
322             nl = 1;
323             break;
324         case '?':
325         default:
326             /* getopt has already reported an error */
327             return(CMD_OK);
328         }
329     }
330     argv += (optind);
331     argc -= (optind);
332
333     s = unargv(argc, argv);
334     if (s != NULL) {
335         printf("%s", s);
336         free(s);
337     }
338     if (!nl)
339         printf("\n");
340     return(CMD_OK);
341 }
342
343 /*
344  * A passable emulation of the sh(1) command of the same name.
345  */
346
347 COMMAND_SET(read, "read", NULL, command_read);
348
349 static int
350 command_read(int argc, char *argv[])
351 {
352     char        *prompt;
353     int         timeout;
354     time_t      when;
355     char        *cp;
356     char        *name;
357     char        buf[256];               /* XXX size? */
358     int         c;
359     
360     timeout = -1;
361     prompt = NULL;
362     optind = 1;
363     optreset = 1;
364     while ((c = getopt(argc, argv, "p:t:")) != -1) {
365         switch(c) {
366             
367         case 'p':
368             prompt = optarg;
369             break;
370         case 't':
371             timeout = strtol(optarg, &cp, 0);
372             if (cp == optarg) {
373                 sprintf(command_errbuf, "bad timeout '%s'", optarg);
374                 return(CMD_ERROR);
375             }
376             break;
377         default:
378             return(CMD_OK);
379         }
380     }
381
382     argv += (optind);
383     argc -= (optind);
384     name = (argc > 0) ? argv[0]: NULL;
385         
386     if (prompt != NULL)
387         printf("%s", prompt);
388     if (timeout >= 0) {
389         when = time(NULL) + timeout;
390         while (!ischar())
391             if (time(NULL) >= when)
392                 return(CMD_OK);         /* is timeout an error? */
393     }
394
395     ngets(buf, sizeof(buf));
396
397     if (name != NULL)
398         setenv(name, buf, 1);
399     return(CMD_OK);
400 }
401
402 /*
403  * File pager
404  */
405 COMMAND_SET(more, "more", "show contents of a file", command_more);
406
407 static int
408 command_more(int argc, char *argv[])
409 {
410     int         i;
411     int         res;
412     char        line[80];
413
414     res=0;
415     pager_open();
416     for (i = 1; (i < argc) && (res == 0); i++) {
417         sprintf(line, "*** FILE %s BEGIN ***\n", argv[i]);
418         if (pager_output(line))
419                 break;
420         res = page_file(argv[i]);
421         if (!res) {
422             sprintf(line, "*** FILE %s END ***\n", argv[i]);
423             res = pager_output(line);
424         }
425     }
426     pager_close();
427
428     if (res == 0)
429         return CMD_OK;
430     else
431         return CMD_ERROR;
432 }
433
434 static int
435 page_file(char *filename)
436 {
437     int result;
438     int fd;
439     char *fullpath;
440
441     if ((fd = rel_open(filename, &fullpath, O_RDONLY)) != -1) {
442         close(fd);
443         result = pager_file(fullpath);
444         free(fullpath);
445     } else {
446         result = -1;
447     }
448     if (result == -1)
449         sprintf(command_errbuf, "error showing %s", filename);
450
451     return result;
452 }   
453
454 /*
455  * List all disk-like devices
456  */
457 COMMAND_SET(lsdev, "lsdev", "list all devices", command_lsdev);
458
459 static int
460 command_lsdev(int argc, char *argv[])
461 {
462     int         verbose, ch, i;
463     char        line[80];
464     
465     verbose = 0;
466     optind = 1;
467     optreset = 1;
468     while ((ch = getopt(argc, argv, "v")) != -1) {
469         switch(ch) {
470         case 'v':
471             verbose = 1;
472             break;
473         case '?':
474         default:
475             /* getopt has already reported an error */
476             return(CMD_OK);
477         }
478     }
479     argv += (optind);
480     argc -= (optind);
481
482     pager_open();
483     for (i = 0; devsw[i] != NULL; i++) {
484         if (devsw[i]->dv_print != NULL){
485             sprintf(line, "%s devices:\n", devsw[i]->dv_name);
486             if (pager_output(line))
487                     break;
488             devsw[i]->dv_print(verbose);
489         } else {
490             sprintf(line, "%s: (unknown)\n", devsw[i]->dv_name);
491             if (pager_output(line))
492                     break;
493         }
494     }
495     pager_close();
496     return(CMD_OK);
497 }
498
499 /*
500  * CONDITIONALS
501  */
502 COMMAND_SET_COND(ifexists, "ifexists", "conditional file/dir present",
503                  command_ifexists);
504
505 struct cond {
506     char    inherit;
507     char    current;
508 };
509
510 static struct cond CondStack[32];
511 static int CondIndex;
512
513 static int
514 command_ifexists(int argc, char *argv[])
515 {
516         if (CondIndex + 1 == sizeof(CondStack)/sizeof(CondStack[0])) {
517                 sprintf(command_errbuf, "if stack too deep");
518                 return(-1);
519         } else if (argc != 2) {
520                 sprintf(command_errbuf, "ifexists requires one argument");
521                 return(-1);
522         } else {
523                 struct stat sb;
524                 struct cond *cond = &CondStack[CondIndex++];
525
526                 cond->inherit = CurrentCondition;
527
528                 if (rel_stat(argv[1], &sb)) {
529                         cond->current = 0;
530                 } else {
531                         cond->current = 1;
532                 }
533                 CurrentCondition = (cond->inherit && cond->current);
534                 return(CMD_OK);
535         }
536 }
537
538 COMMAND_SET_COND(ifset, "ifset", "conditional kenv variable present", command_ifset);
539
540 static int
541 command_ifset(int argc, char *argv[])
542 {
543         if (CondIndex + 1 == sizeof(CondStack)/sizeof(CondStack[0])) {
544                 sprintf(command_errbuf, "if stack too deep");
545                 return(-1);
546         } else if (argc != 2) {
547                 sprintf(command_errbuf, "ifset requires one argument");
548                 return(-1);
549         } else {
550                 struct cond *cond = &CondStack[CondIndex++];
551
552                 cond->inherit = CurrentCondition;
553
554                 if (getenv(argv[1])) {
555                         cond->current = 1;
556                 } else {
557                         cond->current = 0;
558                 }
559                 CurrentCondition = (cond->inherit && cond->current);
560                 return(CMD_OK);
561         }
562 }
563
564 COMMAND_SET_COND(elseifexists, "elseifexists", "conditional file/dir present",
565                  command_elseifexists);
566
567 static int
568 command_elseifexists(int argc, char *argv[])
569 {
570         if (CondIndex == 0) {
571                 sprintf(command_errbuf, "elseifexists without if");
572                 return(-1);
573         } else if (argc != 2) {
574                 sprintf(command_errbuf, "elseifexists requires one argument");
575                 return(-1);
576         } else {
577                 struct stat sb;
578                 struct cond *cond = &CondStack[CondIndex - 1];
579
580                 if (cond->inherit == 0) {
581                         CurrentCondition = 0;   /* already ran / can't run */
582                 } else if (cond->current) {
583                         cond->inherit = 0;      /* can't run any more */
584                         cond->current = 0;
585                         CurrentCondition = 0;
586                 } else {
587                         if (rel_stat(argv[1], &sb)) {
588                                 cond->current = 0;
589                         } else {
590                                 cond->current = 1;
591                         }
592                         CurrentCondition = (cond->inherit && cond->current);
593                 }
594                 return(CMD_OK);
595         }
596 }
597
598 COMMAND_SET_COND(else, "else", "conditional if/else/endif", command_else);
599
600 static int
601 command_else(int argc, char *argv[])
602 {
603         struct cond *cond;
604
605         if (CondIndex) {
606                 cond = &CondStack[CondIndex - 1];
607                 cond->current = !cond->current;
608                 CurrentCondition = (cond->inherit && cond->current);
609                 return(CMD_OK);
610         } else {
611                 sprintf(command_errbuf, "else without if");
612                 return(-1);
613         }
614 }
615
616 COMMAND_SET_COND(endif, "endif", "conditional if/else/endif", command_endif);
617
618 static int
619 command_endif(int argc, char *argv[])
620 {
621         struct cond *cond;
622
623         if (CondIndex) {
624                 --CondIndex;
625                 if (CondIndex) {
626                         cond = &CondStack[CondIndex - 1];
627                         CurrentCondition = (cond->inherit && cond->current);
628                 } else {
629                         CurrentCondition = 1;
630                 }
631                 return(CMD_OK);
632         } else {
633                 sprintf(command_errbuf, "endif without if");
634                 return(-1);
635         }
636 }