697b3341b2961fb1d06aba07c622155e78dd5223
[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 kenv 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 kenv 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 kenv 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", "print text ($VAR is kenv variable)", 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", "read to kenv variable", 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     if (argc > 1) {
385         command_errmsg = "wrong number of arguments";
386         return(CMD_ERROR);
387     }
388     name = (argc > 0) ? argv[0]: NULL;
389         
390     if (prompt != NULL)
391         printf("%s", prompt);
392     if (timeout >= 0) {
393         when = time(NULL) + timeout;
394         while (!ischar())
395             if (time(NULL) >= when)
396                 return(CMD_OK);         /* is timeout an error? */
397     }
398
399     ngets(buf, sizeof(buf));
400
401     if (name != NULL)
402         setenv(name, buf, 1);
403     return(CMD_OK);
404 }
405
406 /*
407  * File pager
408  */
409 COMMAND_SET(more, "more", "show contents of a file", command_more);
410
411 static int
412 command_more(int argc, char *argv[])
413 {
414     int         i;
415     int         res;
416     char        line[80];
417
418     res=0;
419     pager_open();
420     for (i = 1; (i < argc) && (res == 0); i++) {
421         sprintf(line, "*** FILE %s BEGIN ***\n", argv[i]);
422         if (pager_output(line))
423                 break;
424         res = page_file(argv[i]);
425         if (!res) {
426             sprintf(line, "*** FILE %s END ***\n", argv[i]);
427             res = pager_output(line);
428         }
429     }
430     pager_close();
431
432     if (res == 0)
433         return CMD_OK;
434     else
435         return CMD_ERROR;
436 }
437
438 static int
439 page_file(char *filename)
440 {
441     int result;
442     int fd;
443     char *fullpath;
444
445     if ((fd = rel_open(filename, &fullpath, O_RDONLY)) != -1) {
446         close(fd);
447         result = pager_file(fullpath);
448         free(fullpath);
449     } else {
450         result = -1;
451     }
452     if (result == -1)
453         sprintf(command_errbuf, "error showing %s", filename);
454
455     return result;
456 }   
457
458 /*
459  * List all disk-like devices
460  */
461 COMMAND_SET(lsdev, "lsdev", "list all devices", command_lsdev);
462
463 static int
464 command_lsdev(int argc, char *argv[])
465 {
466     int         verbose, ch, i;
467     char        line[80];
468     
469     verbose = 0;
470     optind = 1;
471     optreset = 1;
472     while ((ch = getopt(argc, argv, "v")) != -1) {
473         switch(ch) {
474         case 'v':
475             verbose = 1;
476             break;
477         case '?':
478         default:
479             /* getopt has already reported an error */
480             return(CMD_OK);
481         }
482     }
483     argv += (optind);
484     argc -= (optind);
485
486     pager_open();
487     for (i = 0; devsw[i] != NULL; i++) {
488         if (devsw[i]->dv_print != NULL){
489             sprintf(line, "%s devices:\n", devsw[i]->dv_name);
490             if (pager_output(line))
491                     break;
492             devsw[i]->dv_print(verbose);
493         } else {
494             sprintf(line, "%s: (unknown)\n", devsw[i]->dv_name);
495             if (pager_output(line))
496                     break;
497         }
498     }
499     pager_close();
500     return(CMD_OK);
501 }
502
503 /*
504  * CONDITIONALS
505  */
506 COMMAND_SET_COND(ifexists, "ifexists", "conditional file/dir present",
507                  command_ifexists);
508
509 struct cond {
510     char    inherit;
511     char    current;
512 };
513
514 static struct cond CondStack[32];
515 static int CondIndex;
516
517 static int
518 command_ifexists(int argc, char *argv[])
519 {
520         if (CondIndex + 1 == sizeof(CondStack)/sizeof(CondStack[0])) {
521                 sprintf(command_errbuf, "if stack too deep");
522                 return(-1);
523         } else if (argc != 2) {
524                 sprintf(command_errbuf, "ifexists requires one argument");
525                 return(-1);
526         } else {
527                 struct stat sb;
528                 struct cond *cond = &CondStack[CondIndex++];
529
530                 cond->inherit = CurrentCondition;
531
532                 if (rel_stat(argv[1], &sb)) {
533                         cond->current = 0;
534                 } else {
535                         cond->current = 1;
536                 }
537                 CurrentCondition = (cond->inherit && cond->current);
538                 return(CMD_OK);
539         }
540 }
541
542 COMMAND_SET_COND(ifset, "ifset", "conditional kenv variable present", command_ifset);
543
544 static int
545 command_ifset(int argc, char *argv[])
546 {
547         if (CondIndex + 1 == sizeof(CondStack)/sizeof(CondStack[0])) {
548                 sprintf(command_errbuf, "if stack too deep");
549                 return(-1);
550         } else if (argc != 2) {
551                 sprintf(command_errbuf, "ifset requires one argument");
552                 return(-1);
553         } else {
554                 struct cond *cond = &CondStack[CondIndex++];
555
556                 cond->inherit = CurrentCondition;
557
558                 if (getenv(argv[1])) {
559                         cond->current = 1;
560                 } else {
561                         cond->current = 0;
562                 }
563                 CurrentCondition = (cond->inherit && cond->current);
564                 return(CMD_OK);
565         }
566 }
567
568 COMMAND_SET_COND(elseifexists, "elseifexists", "conditional file/dir present",
569                  command_elseifexists);
570
571 static int
572 command_elseifexists(int argc, char *argv[])
573 {
574         if (CondIndex == 0) {
575                 sprintf(command_errbuf, "elseifexists without if");
576                 return(-1);
577         } else if (argc != 2) {
578                 sprintf(command_errbuf, "elseifexists requires one argument");
579                 return(-1);
580         } else {
581                 struct stat sb;
582                 struct cond *cond = &CondStack[CondIndex - 1];
583
584                 if (cond->inherit == 0) {
585                         CurrentCondition = 0;   /* already ran / can't run */
586                 } else if (cond->current) {
587                         cond->inherit = 0;      /* can't run any more */
588                         cond->current = 0;
589                         CurrentCondition = 0;
590                 } else {
591                         if (rel_stat(argv[1], &sb)) {
592                                 cond->current = 0;
593                         } else {
594                                 cond->current = 1;
595                         }
596                         CurrentCondition = (cond->inherit && cond->current);
597                 }
598                 return(CMD_OK);
599         }
600 }
601
602 COMMAND_SET_COND(else, "else", "conditional if/else/endif", command_else);
603
604 static int
605 command_else(int argc, char *argv[])
606 {
607         struct cond *cond;
608
609         if (CondIndex) {
610                 cond = &CondStack[CondIndex - 1];
611                 cond->current = !cond->current;
612                 CurrentCondition = (cond->inherit && cond->current);
613                 return(CMD_OK);
614         } else {
615                 sprintf(command_errbuf, "else without if");
616                 return(-1);
617         }
618 }
619
620 COMMAND_SET_COND(endif, "endif", "conditional if/else/endif", command_endif);
621
622 static int
623 command_endif(int argc, char *argv[])
624 {
625         struct cond *cond;
626
627         if (CondIndex) {
628                 --CondIndex;
629                 if (CondIndex) {
630                         cond = &CondStack[CondIndex - 1];
631                         CurrentCondition = (cond->inherit && cond->current);
632                 } else {
633                         CurrentCondition = 1;
634                 }
635                 return(CMD_OK);
636         } else {
637                 sprintf(command_errbuf, "endif without if");
638                 return(-1);
639         }
640 }