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