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