]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_pxe.c
pxe: support absolute paths
[karo-tx-uboot.git] / common / cmd_pxe.c
1 /*
2  * Copyright 2010-2011 Calxeda, Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the Free
6  * Software Foundation; either version 2 of the License, or (at your option)
7  * any later version.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 #include <common.h>
18 #include <command.h>
19 #include <malloc.h>
20 #include <linux/string.h>
21 #include <linux/ctype.h>
22 #include <errno.h>
23 #include <linux/list.h>
24
25 #include "menu.h"
26
27 #define MAX_TFTP_PATH_LEN 127
28
29
30 /*
31  * Like getenv, but prints an error if envvar isn't defined in the
32  * environment.  It always returns what getenv does, so it can be used in
33  * place of getenv without changing error handling otherwise.
34  */
35 static char *from_env(char *envvar)
36 {
37         char *ret;
38
39         ret = getenv(envvar);
40
41         if (!ret)
42                 printf("missing environment variable: %s\n", envvar);
43
44         return ret;
45 }
46
47 /*
48  * Convert an ethaddr from the environment to the format used by pxelinux
49  * filenames based on mac addresses. Convert's ':' to '-', and adds "01-" to
50  * the beginning of the ethernet address to indicate a hardware type of
51  * Ethernet. Also converts uppercase hex characters into lowercase, to match
52  * pxelinux's behavior.
53  *
54  * Returns 1 for success, -ENOENT if 'ethaddr' is undefined in the
55  * environment, or some other value < 0 on error.
56  */
57 static int format_mac_pxe(char *outbuf, size_t outbuf_len)
58 {
59         size_t ethaddr_len;
60         char *p, *ethaddr;
61
62         ethaddr = from_env("ethaddr");
63
64         if (!ethaddr)
65                 return -ENOENT;
66
67         ethaddr_len = strlen(ethaddr);
68
69         /*
70          * ethaddr_len + 4 gives room for "01-", ethaddr, and a NUL byte at
71          * the end.
72          */
73         if (outbuf_len < ethaddr_len + 4) {
74                 printf("outbuf is too small (%d < %d)\n",
75                                 outbuf_len, ethaddr_len + 4);
76
77                 return -EINVAL;
78         }
79
80         strcpy(outbuf, "01-");
81
82         for (p = outbuf + 3; *ethaddr; ethaddr++, p++) {
83                 if (*ethaddr == ':')
84                         *p = '-';
85                 else
86                         *p = tolower(*ethaddr);
87         }
88
89         *p = '\0';
90
91         return 1;
92 }
93
94 /*
95  * Returns the directory the file specified in the bootfile env variable is
96  * in. If bootfile isn't defined in the environment, return NULL, which should
97  * be interpreted as "don't prepend anything to paths".
98  */
99 static int get_bootfile_path(const char *file_path, char *bootfile_path,
100                              size_t bootfile_path_size)
101 {
102         char *bootfile, *last_slash;
103         size_t path_len = 0;
104
105         if (file_path[0] == '/')
106                 goto ret;
107
108         bootfile = from_env("bootfile");
109
110         if (!bootfile)
111                 goto ret;
112
113         last_slash = strrchr(bootfile, '/');
114
115         if (last_slash == NULL)
116                 goto ret;
117
118         path_len = (last_slash - bootfile) + 1;
119
120         if (bootfile_path_size < path_len) {
121                 printf("bootfile_path too small. (%d < %d)\n",
122                                 bootfile_path_size, path_len);
123
124                 return -1;
125         }
126
127         strncpy(bootfile_path, bootfile, path_len);
128
129  ret:
130         bootfile_path[path_len] = '\0';
131
132         return 1;
133 }
134
135 /*
136  * As in pxelinux, paths to files referenced from files we retrieve are
137  * relative to the location of bootfile. get_relfile takes such a path and
138  * joins it with the bootfile path to get the full path to the target file. If
139  * the bootfile path is NULL, we use file_path as is.
140  *
141  * Returns 1 for success, or < 0 on error.
142  */
143 static int get_relfile(char *file_path, void *file_addr)
144 {
145         size_t path_len;
146         char relfile[MAX_TFTP_PATH_LEN+1];
147         char addr_buf[10];
148         char *tftp_argv[] = {"tftp", NULL, NULL, NULL};
149         int err;
150
151         err = get_bootfile_path(file_path, relfile, sizeof(relfile));
152
153         if (err < 0)
154                 return err;
155
156         path_len = strlen(file_path);
157         path_len += strlen(relfile);
158
159         if (path_len > MAX_TFTP_PATH_LEN) {
160                 printf("Base path too long (%s%s)\n",
161                                         relfile,
162                                         file_path);
163
164                 return -ENAMETOOLONG;
165         }
166
167         strcat(relfile, file_path);
168
169         printf("Retrieving file: %s\n", relfile);
170
171         sprintf(addr_buf, "%p", file_addr);
172
173         tftp_argv[1] = addr_buf;
174         tftp_argv[2] = relfile;
175
176         if (do_tftpb(NULL, 0, 3, tftp_argv))
177                 return -ENOENT;
178
179         return 1;
180 }
181
182 /*
183  * Retrieve the file at 'file_path' to the locate given by 'file_addr'. If
184  * 'bootfile' was specified in the environment, the path to bootfile will be
185  * prepended to 'file_path' and the resulting path will be used.
186  *
187  * Returns 1 on success, or < 0 for error.
188  */
189 static int get_pxe_file(char *file_path, void *file_addr)
190 {
191         unsigned long config_file_size;
192         char *tftp_filesize;
193         int err;
194
195         err = get_relfile(file_path, file_addr);
196
197         if (err < 0)
198                 return err;
199
200         /*
201          * the file comes without a NUL byte at the end, so find out its size
202          * and add the NUL byte.
203          */
204         tftp_filesize = from_env("filesize");
205
206         if (!tftp_filesize)
207                 return -ENOENT;
208
209         if (strict_strtoul(tftp_filesize, 16, &config_file_size) < 0)
210                 return -EINVAL;
211
212         *(char *)(file_addr + config_file_size) = '\0';
213
214         return 1;
215 }
216
217 #define PXELINUX_DIR "pxelinux.cfg/"
218
219 /*
220  * Retrieves a file in the 'pxelinux.cfg' folder. Since this uses get_pxe_file
221  * to do the hard work, the location of the 'pxelinux.cfg' folder is generated
222  * from the bootfile path, as described above.
223  *
224  * Returns 1 on success or < 0 on error.
225  */
226 static int get_pxelinux_path(char *file, void *pxefile_addr_r)
227 {
228         size_t base_len = strlen(PXELINUX_DIR);
229         char path[MAX_TFTP_PATH_LEN+1];
230
231         if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
232                 printf("path (%s%s) too long, skipping\n",
233                                 PXELINUX_DIR, file);
234                 return -ENAMETOOLONG;
235         }
236
237         sprintf(path, PXELINUX_DIR "%s", file);
238
239         return get_pxe_file(path, pxefile_addr_r);
240 }
241
242 /*
243  * Looks for a pxe file with a name based on the pxeuuid environment variable.
244  *
245  * Returns 1 on success or < 0 on error.
246  */
247 static int pxe_uuid_path(void *pxefile_addr_r)
248 {
249         char *uuid_str;
250
251         uuid_str = from_env("pxeuuid");
252
253         if (!uuid_str)
254                 return -ENOENT;
255
256         return get_pxelinux_path(uuid_str, pxefile_addr_r);
257 }
258
259 /*
260  * Looks for a pxe file with a name based on the 'ethaddr' environment
261  * variable.
262  *
263  * Returns 1 on success or < 0 on error.
264  */
265 static int pxe_mac_path(void *pxefile_addr_r)
266 {
267         char mac_str[21];
268         int err;
269
270         err = format_mac_pxe(mac_str, sizeof(mac_str));
271
272         if (err < 0)
273                 return err;
274
275         return get_pxelinux_path(mac_str, pxefile_addr_r);
276 }
277
278 /*
279  * Looks for pxe files with names based on our IP address. See pxelinux
280  * documentation for details on what these file names look like.  We match
281  * that exactly.
282  *
283  * Returns 1 on success or < 0 on error.
284  */
285 static int pxe_ipaddr_paths(void *pxefile_addr_r)
286 {
287         char ip_addr[9];
288         int mask_pos, err;
289
290         sprintf(ip_addr, "%08X", ntohl(NetOurIP));
291
292         for (mask_pos = 7; mask_pos >= 0;  mask_pos--) {
293                 err = get_pxelinux_path(ip_addr, pxefile_addr_r);
294
295                 if (err > 0)
296                         return err;
297
298                 ip_addr[mask_pos] = '\0';
299         }
300
301         return -ENOENT;
302 }
303
304 /*
305  * Entry point for the 'pxe get' command.
306  * This Follows pxelinux's rules to download a config file from a tftp server.
307  * The file is stored at the location given by the pxefile_addr_r environment
308  * variable, which must be set.
309  *
310  * UUID comes from pxeuuid env variable, if defined
311  * MAC addr comes from ethaddr env variable, if defined
312  * IP
313  *
314  * see http://syslinux.zytor.com/wiki/index.php/PXELINUX
315  *
316  * Returns 0 on success or 1 on error.
317  */
318 static int
319 do_pxe_get(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
320 {
321         char *pxefile_addr_str;
322         unsigned long pxefile_addr_r;
323         int err;
324
325         if (argc != 1)
326                 return CMD_RET_USAGE;
327
328
329         pxefile_addr_str = from_env("pxefile_addr_r");
330
331         if (!pxefile_addr_str)
332                 return 1;
333
334         err = strict_strtoul(pxefile_addr_str, 16,
335                                 (unsigned long *)&pxefile_addr_r);
336         if (err < 0)
337                 return 1;
338
339         /*
340          * Keep trying paths until we successfully get a file we're looking
341          * for.
342          */
343         if (pxe_uuid_path((void *)pxefile_addr_r) > 0
344                 || pxe_mac_path((void *)pxefile_addr_r) > 0
345                 || pxe_ipaddr_paths((void *)pxefile_addr_r) > 0
346                 || get_pxelinux_path("default", (void *)pxefile_addr_r) > 0) {
347
348                 printf("Config file found\n");
349
350                 return 0;
351         }
352
353         printf("Config file not found\n");
354
355         return 1;
356 }
357
358 /*
359  * Wrapper to make it easier to store the file at file_path in the location
360  * specified by envaddr_name. file_path will be joined to the bootfile path,
361  * if any is specified.
362  *
363  * Returns 1 on success or < 0 on error.
364  */
365 static int get_relfile_envaddr(char *file_path, char *envaddr_name)
366 {
367         unsigned long file_addr;
368         char *envaddr;
369
370         envaddr = from_env(envaddr_name);
371
372         if (!envaddr)
373                 return -ENOENT;
374
375         if (strict_strtoul(envaddr, 16, &file_addr) < 0)
376                 return -EINVAL;
377
378         return get_relfile(file_path, (void *)file_addr);
379 }
380
381 /*
382  * A note on the pxe file parser.
383  *
384  * We're parsing files that use syslinux grammar, which has a few quirks.
385  * String literals must be recognized based on context - there is no
386  * quoting or escaping support. There's also nothing to explicitly indicate
387  * when a label section completes. We deal with that by ending a label
388  * section whenever we see a line that doesn't include.
389  *
390  * As with the syslinux family, this same file format could be reused in the
391  * future for non pxe purposes. The only action it takes during parsing that
392  * would throw this off is handling of include files. It assumes we're using
393  * pxe, and does a tftp download of a file listed as an include file in the
394  * middle of the parsing operation. That could be handled by refactoring it to
395  * take a 'include file getter' function.
396  */
397
398 /*
399  * Describes a single label given in a pxe file.
400  *
401  * Create these with the 'label_create' function given below.
402  *
403  * name - the name of the menu as given on the 'menu label' line.
404  * kernel - the path to the kernel file to use for this label.
405  * append - kernel command line to use when booting this label
406  * initrd - path to the initrd to use for this label.
407  * attempted - 0 if we haven't tried to boot this label, 1 if we have.
408  * localboot - 1 if this label specified 'localboot', 0 otherwise.
409  * list - lets these form a list, which a pxe_menu struct will hold.
410  */
411 struct pxe_label {
412         char *name;
413         char *menu;
414         char *kernel;
415         char *append;
416         char *initrd;
417         int attempted;
418         int localboot;
419         struct list_head list;
420 };
421
422 /*
423  * Describes a pxe menu as given via pxe files.
424  *
425  * title - the name of the menu as given by a 'menu title' line.
426  * default_label - the name of the default label, if any.
427  * timeout - time in tenths of a second to wait for a user key-press before
428  *           booting the default label.
429  * prompt - if 0, don't prompt for a choice unless the timeout period is
430  *          interrupted.  If 1, always prompt for a choice regardless of
431  *          timeout.
432  * labels - a list of labels defined for the menu.
433  */
434 struct pxe_menu {
435         char *title;
436         char *default_label;
437         int timeout;
438         int prompt;
439         struct list_head labels;
440 };
441
442 /*
443  * Allocates memory for and initializes a pxe_label. This uses malloc, so the
444  * result must be free()'d to reclaim the memory.
445  *
446  * Returns NULL if malloc fails.
447  */
448 static struct pxe_label *label_create(void)
449 {
450         struct pxe_label *label;
451
452         label = malloc(sizeof(struct pxe_label));
453
454         if (!label)
455                 return NULL;
456
457         memset(label, 0, sizeof(struct pxe_label));
458
459         return label;
460 }
461
462 /*
463  * Free the memory used by a pxe_label, including that used by its name,
464  * kernel, append and initrd members, if they're non NULL.
465  *
466  * So - be sure to only use dynamically allocated memory for the members of
467  * the pxe_label struct, unless you want to clean it up first. These are
468  * currently only created by the pxe file parsing code.
469  */
470 static void label_destroy(struct pxe_label *label)
471 {
472         if (label->name)
473                 free(label->name);
474
475         if (label->kernel)
476                 free(label->kernel);
477
478         if (label->append)
479                 free(label->append);
480
481         if (label->initrd)
482                 free(label->initrd);
483
484         free(label);
485 }
486
487 /*
488  * Print a label and its string members if they're defined.
489  *
490  * This is passed as a callback to the menu code for displaying each
491  * menu entry.
492  */
493 static void label_print(void *data)
494 {
495         struct pxe_label *label = data;
496         const char *c = label->menu ? label->menu : label->kernel;
497
498         printf("%s:\t%s\n", label->name, c);
499
500         if (label->kernel)
501                 printf("\t\tkernel: %s\n", label->kernel);
502
503         if (label->append)
504                 printf("\t\tappend: %s\n", label->append);
505
506         if (label->initrd)
507                 printf("\t\tinitrd: %s\n", label->initrd);
508 }
509
510 /*
511  * Boot a label that specified 'localboot'. This requires that the 'localcmd'
512  * environment variable is defined. Its contents will be executed as U-boot
513  * command.  If the label specified an 'append' line, its contents will be
514  * used to overwrite the contents of the 'bootargs' environment variable prior
515  * to running 'localcmd'.
516  *
517  * Returns 1 on success or < 0 on error.
518  */
519 static int label_localboot(struct pxe_label *label)
520 {
521         char *localcmd, *dupcmd;
522         int ret;
523
524         localcmd = from_env("localcmd");
525
526         if (!localcmd)
527                 return -ENOENT;
528
529         /*
530          * dup the command to avoid any issues with the version of it existing
531          * in the environment changing during the execution of the command.
532          */
533         dupcmd = strdup(localcmd);
534
535         if (!dupcmd)
536                 return -ENOMEM;
537
538         if (label->append)
539                 setenv("bootargs", label->append);
540
541         printf("running: %s\n", dupcmd);
542
543         ret = run_command(dupcmd, 0);
544
545         free(dupcmd);
546
547         return ret;
548 }
549
550 /*
551  * Boot according to the contents of a pxe_label.
552  *
553  * If we can't boot for any reason, we return.  A successful boot never
554  * returns.
555  *
556  * The kernel will be stored in the location given by the 'kernel_addr_r'
557  * environment variable.
558  *
559  * If the label specifies an initrd file, it will be stored in the location
560  * given by the 'ramdisk_addr_r' environment variable.
561  *
562  * If the label specifies an 'append' line, its contents will overwrite that
563  * of the 'bootargs' environment variable.
564  */
565 static void label_boot(struct pxe_label *label)
566 {
567         char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
568         int bootm_argc = 3;
569
570         label_print(label);
571
572         label->attempted = 1;
573
574         if (label->localboot) {
575                 label_localboot(label);
576                 return;
577         }
578
579         if (label->kernel == NULL) {
580                 printf("No kernel given, skipping %s\n",
581                                 label->name);
582                 return;
583         }
584
585         if (label->initrd) {
586                 if (get_relfile_envaddr(label->initrd, "ramdisk_addr_r") < 0) {
587                         printf("Skipping %s for failure retrieving initrd\n",
588                                         label->name);
589                         return;
590                 }
591
592                 bootm_argv[2] = getenv("ramdisk_addr_r");
593         } else {
594                 bootm_argv[2] = "-";
595         }
596
597         if (get_relfile_envaddr(label->kernel, "kernel_addr_r") < 0) {
598                 printf("Skipping %s for failure retrieving kernel\n",
599                                 label->name);
600                 return;
601         }
602
603         if (label->append)
604                 setenv("bootargs", label->append);
605
606         bootm_argv[1] = getenv("kernel_addr_r");
607
608         /*
609          * fdt usage is optional.  If there is an fdt_addr specified, we will
610          * pass it along to bootm, and adjust argc appropriately.
611          */
612         bootm_argv[3] = getenv("fdt_addr");
613
614         if (bootm_argv[3])
615                 bootm_argc = 4;
616
617         do_bootm(NULL, 0, bootm_argc, bootm_argv);
618 }
619
620 /*
621  * Tokens for the pxe file parser.
622  */
623 enum token_type {
624         T_EOL,
625         T_STRING,
626         T_EOF,
627         T_MENU,
628         T_TITLE,
629         T_TIMEOUT,
630         T_LABEL,
631         T_KERNEL,
632         T_LINUX,
633         T_APPEND,
634         T_INITRD,
635         T_LOCALBOOT,
636         T_DEFAULT,
637         T_PROMPT,
638         T_INCLUDE,
639         T_INVALID
640 };
641
642 /*
643  * A token - given by a value and a type.
644  */
645 struct token {
646         char *val;
647         enum token_type type;
648 };
649
650 /*
651  * Keywords recognized.
652  */
653 static const struct token keywords[] = {
654         {"menu", T_MENU},
655         {"title", T_TITLE},
656         {"timeout", T_TIMEOUT},
657         {"default", T_DEFAULT},
658         {"prompt", T_PROMPT},
659         {"label", T_LABEL},
660         {"kernel", T_KERNEL},
661         {"linux", T_LINUX},
662         {"localboot", T_LOCALBOOT},
663         {"append", T_APPEND},
664         {"initrd", T_INITRD},
665         {"include", T_INCLUDE},
666         {NULL, T_INVALID}
667 };
668
669 /*
670  * Since pxe(linux) files don't have a token to identify the start of a
671  * literal, we have to keep track of when we're in a state where a literal is
672  * expected vs when we're in a state a keyword is expected.
673  */
674 enum lex_state {
675         L_NORMAL = 0,
676         L_KEYWORD,
677         L_SLITERAL
678 };
679
680 /*
681  * get_string retrieves a string from *p and stores it as a token in
682  * *t.
683  *
684  * get_string used for scanning both string literals and keywords.
685  *
686  * Characters from *p are copied into t-val until a character equal to
687  * delim is found, or a NUL byte is reached. If delim has the special value of
688  * ' ', any whitespace character will be used as a delimiter.
689  *
690  * If lower is unequal to 0, uppercase characters will be converted to
691  * lowercase in the result. This is useful to make keywords case
692  * insensitive.
693  *
694  * The location of *p is updated to point to the first character after the end
695  * of the token - the ending delimiter.
696  *
697  * On success, the new value of t->val is returned. Memory for t->val is
698  * allocated using malloc and must be free()'d to reclaim it.  If insufficient
699  * memory is available, NULL is returned.
700  */
701 static char *get_string(char **p, struct token *t, char delim, int lower)
702 {
703         char *b, *e;
704         size_t len, i;
705
706         /*
707          * b and e both start at the beginning of the input stream.
708          *
709          * e is incremented until we find the ending delimiter, or a NUL byte
710          * is reached. Then, we take e - b to find the length of the token.
711          */
712         b = e = *p;
713
714         while (*e) {
715                 if ((delim == ' ' && isspace(*e)) || delim == *e)
716                         break;
717                 e++;
718         }
719
720         len = e - b;
721
722         /*
723          * Allocate memory to hold the string, and copy it in, converting
724          * characters to lowercase if lower is != 0.
725          */
726         t->val = malloc(len + 1);
727         if (!t->val)
728                 return NULL;
729
730         for (i = 0; i < len; i++, b++) {
731                 if (lower)
732                         t->val[i] = tolower(*b);
733                 else
734                         t->val[i] = *b;
735         }
736
737         t->val[len] = '\0';
738
739         /*
740          * Update *p so the caller knows where to continue scanning.
741          */
742         *p = e;
743
744         t->type = T_STRING;
745
746         return t->val;
747 }
748
749 /*
750  * Populate a keyword token with a type and value.
751  */
752 static void get_keyword(struct token *t)
753 {
754         int i;
755
756         for (i = 0; keywords[i].val; i++) {
757                 if (!strcmp(t->val, keywords[i].val)) {
758                         t->type = keywords[i].type;
759                         break;
760                 }
761         }
762 }
763
764 /*
765  * Get the next token.  We have to keep track of which state we're in to know
766  * if we're looking to get a string literal or a keyword.
767  *
768  * *p is updated to point at the first character after the current token.
769  */
770 static void get_token(char **p, struct token *t, enum lex_state state)
771 {
772         char *c = *p;
773
774         t->type = T_INVALID;
775
776         /* eat non EOL whitespace */
777         while (isblank(*c))
778                 c++;
779
780         /*
781          * eat comments. note that string literals can't begin with #, but
782          * can contain a # after their first character.
783          */
784         if (*c == '#') {
785                 while (*c && *c != '\n')
786                         c++;
787         }
788
789         if (*c == '\n') {
790                 t->type = T_EOL;
791                 c++;
792         } else if (*c == '\0') {
793                 t->type = T_EOF;
794                 c++;
795         } else if (state == L_SLITERAL) {
796                 get_string(&c, t, '\n', 0);
797         } else if (state == L_KEYWORD) {
798                 /*
799                  * when we expect a keyword, we first get the next string
800                  * token delimited by whitespace, and then check if it
801                  * matches a keyword in our keyword list. if it does, it's
802                  * converted to a keyword token of the appropriate type, and
803                  * if not, it remains a string token.
804                  */
805                 get_string(&c, t, ' ', 1);
806                 get_keyword(t);
807         }
808
809         *p = c;
810 }
811
812 /*
813  * Increment *c until we get to the end of the current line, or EOF.
814  */
815 static void eol_or_eof(char **c)
816 {
817         while (**c && **c != '\n')
818                 (*c)++;
819 }
820
821 /*
822  * All of these parse_* functions share some common behavior.
823  *
824  * They finish with *c pointing after the token they parse, and return 1 on
825  * success, or < 0 on error.
826  */
827
828 /*
829  * Parse a string literal and store a pointer it at *dst. String literals
830  * terminate at the end of the line.
831  */
832 static int parse_sliteral(char **c, char **dst)
833 {
834         struct token t;
835         char *s = *c;
836
837         get_token(c, &t, L_SLITERAL);
838
839         if (t.type != T_STRING) {
840                 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
841                 return -EINVAL;
842         }
843
844         *dst = t.val;
845
846         return 1;
847 }
848
849 /*
850  * Parse a base 10 (unsigned) integer and store it at *dst.
851  */
852 static int parse_integer(char **c, int *dst)
853 {
854         struct token t;
855         char *s = *c;
856         unsigned long temp;
857
858         get_token(c, &t, L_SLITERAL);
859
860         if (t.type != T_STRING) {
861                 printf("Expected string: %.*s\n", (int)(*c - s), s);
862                 return -EINVAL;
863         }
864
865         if (strict_strtoul(t.val, 10, &temp) < 0) {
866                 printf("Expected unsigned integer: %s\n", t.val);
867                 return -EINVAL;
868         }
869
870         *dst = (int)temp;
871
872         free(t.val);
873
874         return 1;
875 }
876
877 static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level);
878
879 /*
880  * Parse an include statement, and retrieve and parse the file it mentions.
881  *
882  * base should point to a location where it's safe to store the file, and
883  * nest_level should indicate how many nested includes have occurred. For this
884  * include, nest_level has already been incremented and doesn't need to be
885  * incremented here.
886  */
887 static int handle_include(char **c, char *base,
888                                 struct pxe_menu *cfg, int nest_level)
889 {
890         char *include_path;
891         char *s = *c;
892         int err;
893
894         err = parse_sliteral(c, &include_path);
895
896         if (err < 0) {
897                 printf("Expected include path: %.*s\n",
898                                  (int)(*c - s), s);
899                 return err;
900         }
901
902         err = get_pxe_file(include_path, base);
903
904         if (err < 0) {
905                 printf("Couldn't retrieve %s\n", include_path);
906                 return err;
907         }
908
909         return parse_pxefile_top(base, cfg, nest_level);
910 }
911
912 /*
913  * Parse lines that begin with 'menu'.
914  *
915  * b and nest are provided to handle the 'menu include' case.
916  *
917  * b should be the address where the file currently being parsed is stored.
918  *
919  * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
920  * a file it includes, 3 when parsing a file included by that file, and so on.
921  */
922 static int parse_menu(char **c, struct pxe_menu *cfg, char *b, int nest_level)
923 {
924         struct token t;
925         char *s = *c;
926         int err = 0;
927
928         get_token(c, &t, L_KEYWORD);
929
930         switch (t.type) {
931         case T_TITLE:
932                 err = parse_sliteral(c, &cfg->title);
933
934                 break;
935
936         case T_INCLUDE:
937                 err = handle_include(c, b + strlen(b) + 1, cfg,
938                                                 nest_level + 1);
939                 break;
940
941         default:
942                 printf("Ignoring malformed menu command: %.*s\n",
943                                 (int)(*c - s), s);
944         }
945
946         if (err < 0)
947                 return err;
948
949         eol_or_eof(c);
950
951         return 1;
952 }
953
954 /*
955  * Handles parsing a 'menu line' when we're parsing a label.
956  */
957 static int parse_label_menu(char **c, struct pxe_menu *cfg,
958                                 struct pxe_label *label)
959 {
960         struct token t;
961         char *s;
962
963         s = *c;
964
965         get_token(c, &t, L_KEYWORD);
966
967         switch (t.type) {
968         case T_DEFAULT:
969                 if (cfg->default_label)
970                         free(cfg->default_label);
971
972                 cfg->default_label = strdup(label->name);
973
974                 if (!cfg->default_label)
975                         return -ENOMEM;
976
977                 break;
978         case T_LABEL:
979                 parse_sliteral(c, &label->menu);
980                 break;
981         default:
982                 printf("Ignoring malformed menu command: %.*s\n",
983                                 (int)(*c - s), s);
984         }
985
986         eol_or_eof(c);
987
988         return 0;
989 }
990
991 /*
992  * Parses a label and adds it to the list of labels for a menu.
993  *
994  * A label ends when we either get to the end of a file, or
995  * get some input we otherwise don't have a handler defined
996  * for.
997  *
998  */
999 static int parse_label(char **c, struct pxe_menu *cfg)
1000 {
1001         struct token t;
1002         char *s = *c;
1003         struct pxe_label *label;
1004         int err;
1005
1006         label = label_create();
1007         if (!label)
1008                 return -ENOMEM;
1009
1010         err = parse_sliteral(c, &label->name);
1011         if (err < 0) {
1012                 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1013                 label_destroy(label);
1014                 return -EINVAL;
1015         }
1016
1017         list_add_tail(&label->list, &cfg->labels);
1018
1019         while (1) {
1020                 s = *c;
1021                 get_token(c, &t, L_KEYWORD);
1022
1023                 err = 0;
1024                 switch (t.type) {
1025                 case T_MENU:
1026                         err = parse_label_menu(c, cfg, label);
1027                         break;
1028
1029                 case T_KERNEL:
1030                 case T_LINUX:
1031                         err = parse_sliteral(c, &label->kernel);
1032                         break;
1033
1034                 case T_APPEND:
1035                         err = parse_sliteral(c, &label->append);
1036                         break;
1037
1038                 case T_INITRD:
1039                         err = parse_sliteral(c, &label->initrd);
1040                         break;
1041
1042                 case T_LOCALBOOT:
1043                         err = parse_integer(c, &label->localboot);
1044                         break;
1045
1046                 case T_EOL:
1047                         break;
1048
1049                 default:
1050                         /*
1051                          * put the token back! we don't want it - it's the end
1052                          * of a label and whatever token this is, it's
1053                          * something for the menu level context to handle.
1054                          */
1055                         *c = s;
1056                         return 1;
1057                 }
1058
1059                 if (err < 0)
1060                         return err;
1061         }
1062 }
1063
1064 /*
1065  * This 16 comes from the limit pxelinux imposes on nested includes.
1066  *
1067  * There is no reason at all we couldn't do more, but some limit helps prevent
1068  * infinite (until crash occurs) recursion if a file tries to include itself.
1069  */
1070 #define MAX_NEST_LEVEL 16
1071
1072 /*
1073  * Entry point for parsing a menu file. nest_level indicates how many times
1074  * we've nested in includes.  It will be 1 for the top level menu file.
1075  *
1076  * Returns 1 on success, < 0 on error.
1077  */
1078 static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level)
1079 {
1080         struct token t;
1081         char *s, *b, *label_name;
1082         int err;
1083
1084         b = p;
1085
1086         if (nest_level > MAX_NEST_LEVEL) {
1087                 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1088                 return -EMLINK;
1089         }
1090
1091         while (1) {
1092                 s = p;
1093
1094                 get_token(&p, &t, L_KEYWORD);
1095
1096                 err = 0;
1097                 switch (t.type) {
1098                 case T_MENU:
1099                         err = parse_menu(&p, cfg, b, nest_level);
1100                         break;
1101
1102                 case T_TIMEOUT:
1103                         err = parse_integer(&p, &cfg->timeout);
1104                         break;
1105
1106                 case T_LABEL:
1107                         err = parse_label(&p, cfg);
1108                         break;
1109
1110                 case T_DEFAULT:
1111                         err = parse_sliteral(&p, &label_name);
1112
1113                         if (label_name) {
1114                                 if (cfg->default_label)
1115                                         free(cfg->default_label);
1116
1117                                 cfg->default_label = label_name;
1118                         }
1119
1120                         break;
1121
1122                 case T_INCLUDE:
1123                         err = handle_include(&p, b + ALIGN(strlen(b), 4), cfg,
1124                                                         nest_level + 1);
1125                         break;
1126
1127                 case T_PROMPT:
1128                         err = parse_integer(&p, &cfg->prompt);
1129                         break;
1130
1131                 case T_EOL:
1132                         break;
1133
1134                 case T_EOF:
1135                         return 1;
1136
1137                 default:
1138                         printf("Ignoring unknown command: %.*s\n",
1139                                                         (int)(p - s), s);
1140                         eol_or_eof(&p);
1141                 }
1142
1143                 if (err < 0)
1144                         return err;
1145         }
1146 }
1147
1148 /*
1149  * Free the memory used by a pxe_menu and its labels.
1150  */
1151 static void destroy_pxe_menu(struct pxe_menu *cfg)
1152 {
1153         struct list_head *pos, *n;
1154         struct pxe_label *label;
1155
1156         if (cfg->title)
1157                 free(cfg->title);
1158
1159         if (cfg->default_label)
1160                 free(cfg->default_label);
1161
1162         list_for_each_safe(pos, n, &cfg->labels) {
1163                 label = list_entry(pos, struct pxe_label, list);
1164
1165                 label_destroy(label);
1166         }
1167
1168         free(cfg);
1169 }
1170
1171 /*
1172  * Entry point for parsing a pxe file. This is only used for the top level
1173  * file.
1174  *
1175  * Returns NULL if there is an error, otherwise, returns a pointer to a
1176  * pxe_menu struct populated with the results of parsing the pxe file (and any
1177  * files it includes). The resulting pxe_menu struct can be free()'d by using
1178  * the destroy_pxe_menu() function.
1179  */
1180 static struct pxe_menu *parse_pxefile(char *menucfg)
1181 {
1182         struct pxe_menu *cfg;
1183
1184         cfg = malloc(sizeof(struct pxe_menu));
1185
1186         if (!cfg)
1187                 return NULL;
1188
1189         memset(cfg, 0, sizeof(struct pxe_menu));
1190
1191         INIT_LIST_HEAD(&cfg->labels);
1192
1193         if (parse_pxefile_top(menucfg, cfg, 1) < 0) {
1194                 destroy_pxe_menu(cfg);
1195                 return NULL;
1196         }
1197
1198         return cfg;
1199 }
1200
1201 /*
1202  * Converts a pxe_menu struct into a menu struct for use with U-boot's generic
1203  * menu code.
1204  */
1205 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1206 {
1207         struct pxe_label *label;
1208         struct list_head *pos;
1209         struct menu *m;
1210         int err;
1211
1212         /*
1213          * Create a menu and add items for all the labels.
1214          */
1215         m = menu_create(cfg->title, cfg->timeout, cfg->prompt, label_print);
1216
1217         if (!m)
1218                 return NULL;
1219
1220         list_for_each(pos, &cfg->labels) {
1221                 label = list_entry(pos, struct pxe_label, list);
1222
1223                 if (menu_item_add(m, label->name, label) != 1) {
1224                         menu_destroy(m);
1225                         return NULL;
1226                 }
1227         }
1228
1229         /*
1230          * After we've created items for each label in the menu, set the
1231          * menu's default label if one was specified.
1232          */
1233         if (cfg->default_label) {
1234                 err = menu_default_set(m, cfg->default_label);
1235                 if (err != 1) {
1236                         if (err != -ENOENT) {
1237                                 menu_destroy(m);
1238                                 return NULL;
1239                         }
1240
1241                         printf("Missing default: %s\n", cfg->default_label);
1242                 }
1243         }
1244
1245         return m;
1246 }
1247
1248 /*
1249  * Try to boot any labels we have yet to attempt to boot.
1250  */
1251 static void boot_unattempted_labels(struct pxe_menu *cfg)
1252 {
1253         struct list_head *pos;
1254         struct pxe_label *label;
1255
1256         list_for_each(pos, &cfg->labels) {
1257                 label = list_entry(pos, struct pxe_label, list);
1258
1259                 if (!label->attempted)
1260                         label_boot(label);
1261         }
1262 }
1263
1264 /*
1265  * Boot the system as prescribed by a pxe_menu.
1266  *
1267  * Use the menu system to either get the user's choice or the default, based
1268  * on config or user input.  If there is no default or user's choice,
1269  * attempted to boot labels in the order they were given in pxe files.
1270  * If the default or user's choice fails to boot, attempt to boot other
1271  * labels in the order they were given in pxe files.
1272  *
1273  * If this function returns, there weren't any labels that successfully
1274  * booted, or the user interrupted the menu selection via ctrl+c.
1275  */
1276 static void handle_pxe_menu(struct pxe_menu *cfg)
1277 {
1278         void *choice;
1279         struct menu *m;
1280         int err;
1281
1282         m = pxe_menu_to_menu(cfg);
1283         if (!m)
1284                 return;
1285
1286         err = menu_get_choice(m, &choice);
1287
1288         menu_destroy(m);
1289
1290         /*
1291          * err == 1 means we got a choice back from menu_get_choice.
1292          *
1293          * err == -ENOENT if the menu was setup to select the default but no
1294          * default was set. in that case, we should continue trying to boot
1295          * labels that haven't been attempted yet.
1296          *
1297          * otherwise, the user interrupted or there was some other error and
1298          * we give up.
1299          */
1300
1301         if (err == 1)
1302                 label_boot(choice);
1303         else if (err != -ENOENT)
1304                 return;
1305
1306         boot_unattempted_labels(cfg);
1307 }
1308
1309 /*
1310  * Boots a system using a pxe file
1311  *
1312  * Returns 0 on success, 1 on error.
1313  */
1314 static int
1315 do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1316 {
1317         unsigned long pxefile_addr_r;
1318         struct pxe_menu *cfg;
1319         char *pxefile_addr_str;
1320
1321         if (argc == 1) {
1322                 pxefile_addr_str = from_env("pxefile_addr_r");
1323                 if (!pxefile_addr_str)
1324                         return 1;
1325
1326         } else if (argc == 2) {
1327                 pxefile_addr_str = argv[1];
1328         } else {
1329                 return CMD_RET_USAGE;
1330         }
1331
1332         if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1333                 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1334                 return 1;
1335         }
1336
1337         cfg = parse_pxefile((char *)(pxefile_addr_r));
1338
1339         if (cfg == NULL) {
1340                 printf("Error parsing config file\n");
1341                 return 1;
1342         }
1343
1344         handle_pxe_menu(cfg);
1345
1346         destroy_pxe_menu(cfg);
1347
1348         return 0;
1349 }
1350
1351 static cmd_tbl_t cmd_pxe_sub[] = {
1352         U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
1353         U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
1354 };
1355
1356 int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1357 {
1358         cmd_tbl_t *cp;
1359
1360         if (argc < 2)
1361                 return CMD_RET_USAGE;
1362
1363         /* drop initial "pxe" arg */
1364         argc--;
1365         argv++;
1366
1367         cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
1368
1369         if (cp)
1370                 return cp->cmd(cmdtp, flag, argc, argv);
1371
1372         return CMD_RET_USAGE;
1373 }
1374
1375 U_BOOT_CMD(
1376         pxe, 3, 1, do_pxe,
1377         "commands to get and boot from pxe files",
1378         "get - try to retrieve a pxe file using tftp\npxe "
1379         "boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
1380 );