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