]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_pxe.c
pxe: parse initrd file from append string
[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         int len;
1003         char *s = *c;
1004         struct pxe_label *label;
1005         int err;
1006
1007         label = label_create();
1008         if (!label)
1009                 return -ENOMEM;
1010
1011         err = parse_sliteral(c, &label->name);
1012         if (err < 0) {
1013                 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1014                 label_destroy(label);
1015                 return -EINVAL;
1016         }
1017
1018         list_add_tail(&label->list, &cfg->labels);
1019
1020         while (1) {
1021                 s = *c;
1022                 get_token(c, &t, L_KEYWORD);
1023
1024                 err = 0;
1025                 switch (t.type) {
1026                 case T_MENU:
1027                         err = parse_label_menu(c, cfg, label);
1028                         break;
1029
1030                 case T_KERNEL:
1031                 case T_LINUX:
1032                         err = parse_sliteral(c, &label->kernel);
1033                         break;
1034
1035                 case T_APPEND:
1036                         err = parse_sliteral(c, &label->append);
1037                         if (label->initrd)
1038                                 break;
1039                         s = strstr(label->append, "initrd=");
1040                         if (!s)
1041                                 break;
1042                         s += 7;
1043                         len = (int)(strchr(s, ' ') - s);
1044                         label->initrd = malloc(len + 1);
1045                         strncpy(label->initrd, s, len);
1046                         label->initrd[len] = '\0';
1047
1048                         break;
1049
1050                 case T_INITRD:
1051                         if (!label->initrd)
1052                                 err = parse_sliteral(c, &label->initrd);
1053                         break;
1054
1055                 case T_LOCALBOOT:
1056                         err = parse_integer(c, &label->localboot);
1057                         break;
1058
1059                 case T_EOL:
1060                         break;
1061
1062                 default:
1063                         /*
1064                          * put the token back! we don't want it - it's the end
1065                          * of a label and whatever token this is, it's
1066                          * something for the menu level context to handle.
1067                          */
1068                         *c = s;
1069                         return 1;
1070                 }
1071
1072                 if (err < 0)
1073                         return err;
1074         }
1075 }
1076
1077 /*
1078  * This 16 comes from the limit pxelinux imposes on nested includes.
1079  *
1080  * There is no reason at all we couldn't do more, but some limit helps prevent
1081  * infinite (until crash occurs) recursion if a file tries to include itself.
1082  */
1083 #define MAX_NEST_LEVEL 16
1084
1085 /*
1086  * Entry point for parsing a menu file. nest_level indicates how many times
1087  * we've nested in includes.  It will be 1 for the top level menu file.
1088  *
1089  * Returns 1 on success, < 0 on error.
1090  */
1091 static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level)
1092 {
1093         struct token t;
1094         char *s, *b, *label_name;
1095         int err;
1096
1097         b = p;
1098
1099         if (nest_level > MAX_NEST_LEVEL) {
1100                 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1101                 return -EMLINK;
1102         }
1103
1104         while (1) {
1105                 s = p;
1106
1107                 get_token(&p, &t, L_KEYWORD);
1108
1109                 err = 0;
1110                 switch (t.type) {
1111                 case T_MENU:
1112                         err = parse_menu(&p, cfg, b, nest_level);
1113                         break;
1114
1115                 case T_TIMEOUT:
1116                         err = parse_integer(&p, &cfg->timeout);
1117                         break;
1118
1119                 case T_LABEL:
1120                         err = parse_label(&p, cfg);
1121                         break;
1122
1123                 case T_DEFAULT:
1124                         err = parse_sliteral(&p, &label_name);
1125
1126                         if (label_name) {
1127                                 if (cfg->default_label)
1128                                         free(cfg->default_label);
1129
1130                                 cfg->default_label = label_name;
1131                         }
1132
1133                         break;
1134
1135                 case T_INCLUDE:
1136                         err = handle_include(&p, b + ALIGN(strlen(b), 4), cfg,
1137                                                         nest_level + 1);
1138                         break;
1139
1140                 case T_PROMPT:
1141                         err = parse_integer(&p, &cfg->prompt);
1142                         break;
1143
1144                 case T_EOL:
1145                         break;
1146
1147                 case T_EOF:
1148                         return 1;
1149
1150                 default:
1151                         printf("Ignoring unknown command: %.*s\n",
1152                                                         (int)(p - s), s);
1153                         eol_or_eof(&p);
1154                 }
1155
1156                 if (err < 0)
1157                         return err;
1158         }
1159 }
1160
1161 /*
1162  * Free the memory used by a pxe_menu and its labels.
1163  */
1164 static void destroy_pxe_menu(struct pxe_menu *cfg)
1165 {
1166         struct list_head *pos, *n;
1167         struct pxe_label *label;
1168
1169         if (cfg->title)
1170                 free(cfg->title);
1171
1172         if (cfg->default_label)
1173                 free(cfg->default_label);
1174
1175         list_for_each_safe(pos, n, &cfg->labels) {
1176                 label = list_entry(pos, struct pxe_label, list);
1177
1178                 label_destroy(label);
1179         }
1180
1181         free(cfg);
1182 }
1183
1184 /*
1185  * Entry point for parsing a pxe file. This is only used for the top level
1186  * file.
1187  *
1188  * Returns NULL if there is an error, otherwise, returns a pointer to a
1189  * pxe_menu struct populated with the results of parsing the pxe file (and any
1190  * files it includes). The resulting pxe_menu struct can be free()'d by using
1191  * the destroy_pxe_menu() function.
1192  */
1193 static struct pxe_menu *parse_pxefile(char *menucfg)
1194 {
1195         struct pxe_menu *cfg;
1196
1197         cfg = malloc(sizeof(struct pxe_menu));
1198
1199         if (!cfg)
1200                 return NULL;
1201
1202         memset(cfg, 0, sizeof(struct pxe_menu));
1203
1204         INIT_LIST_HEAD(&cfg->labels);
1205
1206         if (parse_pxefile_top(menucfg, cfg, 1) < 0) {
1207                 destroy_pxe_menu(cfg);
1208                 return NULL;
1209         }
1210
1211         return cfg;
1212 }
1213
1214 /*
1215  * Converts a pxe_menu struct into a menu struct for use with U-boot's generic
1216  * menu code.
1217  */
1218 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1219 {
1220         struct pxe_label *label;
1221         struct list_head *pos;
1222         struct menu *m;
1223         int err;
1224
1225         /*
1226          * Create a menu and add items for all the labels.
1227          */
1228         m = menu_create(cfg->title, cfg->timeout, cfg->prompt, label_print);
1229
1230         if (!m)
1231                 return NULL;
1232
1233         list_for_each(pos, &cfg->labels) {
1234                 label = list_entry(pos, struct pxe_label, list);
1235
1236                 if (menu_item_add(m, label->name, label) != 1) {
1237                         menu_destroy(m);
1238                         return NULL;
1239                 }
1240         }
1241
1242         /*
1243          * After we've created items for each label in the menu, set the
1244          * menu's default label if one was specified.
1245          */
1246         if (cfg->default_label) {
1247                 err = menu_default_set(m, cfg->default_label);
1248                 if (err != 1) {
1249                         if (err != -ENOENT) {
1250                                 menu_destroy(m);
1251                                 return NULL;
1252                         }
1253
1254                         printf("Missing default: %s\n", cfg->default_label);
1255                 }
1256         }
1257
1258         return m;
1259 }
1260
1261 /*
1262  * Try to boot any labels we have yet to attempt to boot.
1263  */
1264 static void boot_unattempted_labels(struct pxe_menu *cfg)
1265 {
1266         struct list_head *pos;
1267         struct pxe_label *label;
1268
1269         list_for_each(pos, &cfg->labels) {
1270                 label = list_entry(pos, struct pxe_label, list);
1271
1272                 if (!label->attempted)
1273                         label_boot(label);
1274         }
1275 }
1276
1277 /*
1278  * Boot the system as prescribed by a pxe_menu.
1279  *
1280  * Use the menu system to either get the user's choice or the default, based
1281  * on config or user input.  If there is no default or user's choice,
1282  * attempted to boot labels in the order they were given in pxe files.
1283  * If the default or user's choice fails to boot, attempt to boot other
1284  * labels in the order they were given in pxe files.
1285  *
1286  * If this function returns, there weren't any labels that successfully
1287  * booted, or the user interrupted the menu selection via ctrl+c.
1288  */
1289 static void handle_pxe_menu(struct pxe_menu *cfg)
1290 {
1291         void *choice;
1292         struct menu *m;
1293         int err;
1294
1295         m = pxe_menu_to_menu(cfg);
1296         if (!m)
1297                 return;
1298
1299         err = menu_get_choice(m, &choice);
1300
1301         menu_destroy(m);
1302
1303         /*
1304          * err == 1 means we got a choice back from menu_get_choice.
1305          *
1306          * err == -ENOENT if the menu was setup to select the default but no
1307          * default was set. in that case, we should continue trying to boot
1308          * labels that haven't been attempted yet.
1309          *
1310          * otherwise, the user interrupted or there was some other error and
1311          * we give up.
1312          */
1313
1314         if (err == 1)
1315                 label_boot(choice);
1316         else if (err != -ENOENT)
1317                 return;
1318
1319         boot_unattempted_labels(cfg);
1320 }
1321
1322 /*
1323  * Boots a system using a pxe file
1324  *
1325  * Returns 0 on success, 1 on error.
1326  */
1327 static int
1328 do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1329 {
1330         unsigned long pxefile_addr_r;
1331         struct pxe_menu *cfg;
1332         char *pxefile_addr_str;
1333
1334         if (argc == 1) {
1335                 pxefile_addr_str = from_env("pxefile_addr_r");
1336                 if (!pxefile_addr_str)
1337                         return 1;
1338
1339         } else if (argc == 2) {
1340                 pxefile_addr_str = argv[1];
1341         } else {
1342                 return CMD_RET_USAGE;
1343         }
1344
1345         if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1346                 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1347                 return 1;
1348         }
1349
1350         cfg = parse_pxefile((char *)(pxefile_addr_r));
1351
1352         if (cfg == NULL) {
1353                 printf("Error parsing config file\n");
1354                 return 1;
1355         }
1356
1357         handle_pxe_menu(cfg);
1358
1359         destroy_pxe_menu(cfg);
1360
1361         return 0;
1362 }
1363
1364 static cmd_tbl_t cmd_pxe_sub[] = {
1365         U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
1366         U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
1367 };
1368
1369 int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1370 {
1371         cmd_tbl_t *cp;
1372
1373         if (argc < 2)
1374                 return CMD_RET_USAGE;
1375
1376         /* drop initial "pxe" arg */
1377         argc--;
1378         argv++;
1379
1380         cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
1381
1382         if (cp)
1383                 return cp->cmd(cmdtp, flag, argc, argv);
1384
1385         return CMD_RET_USAGE;
1386 }
1387
1388 U_BOOT_CMD(
1389         pxe, 3, 1, do_pxe,
1390         "commands to get and boot from pxe files",
1391         "get - try to retrieve a pxe file using tftp\npxe "
1392         "boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
1393 );