1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2000-2010
4  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5  *
6  * (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
7  * Andreas Heppel <aheppel@sysgo.de>
8  */
9 
10 #include <bootstage.h>
11 #include <command.h>
12 #include <env.h>
13 #include <env_internal.h>
14 #include <log.h>
15 #include <sort.h>
16 #include <asm/global_data.h>
17 #include <linux/printk.h>
18 #include <linux/stddef.h>
19 #include <mapmem.h>
20 #include <search.h>
21 #include <errno.h>
22 #include <malloc.h>
23 #include <u-boot/crc.h>
24 #include <dm/ofnode.h>
25 #include <net.h>
26 #include <watchdog.h>
27 
28 DECLARE_GLOBAL_DATA_PTR;
29 
30 /************************************************************************
31  * Default settings to be used when no valid environment is found
32  */
33 #include <env_default.h>
34 
35 struct hsearch_data env_htab = {
36 	.change_ok = env_flags_validate,
37 };
38 
39 /*
40  * This variable is incremented each time we set an environment variable so we
41  * can be check via env_get_id() to see if the environment has changed or not.
42  * This makes it possible to reread an environment variable only if the
43  * environment was changed, typically used by networking code.
44  */
45 static int env_id = 1;
46 
env_get_id(void)47 int env_get_id(void)
48 {
49 	return env_id;
50 }
51 
env_inc_id(void)52 void env_inc_id(void)
53 {
54 	env_id++;
55 }
56 
env_do_env_set(int flag,int argc,char * const argv[],int env_flag)57 int env_do_env_set(int flag, int argc, char *const argv[], int env_flag)
58 {
59 	int   i, len;
60 	char  *name, *value, *s;
61 	struct env_entry e, *ep;
62 
63 	debug("Initial value for argc=%d\n", argc);
64 
65 #if !IS_ENABLED(CONFIG_XPL_BUILD) && IS_ENABLED(CONFIG_CMD_NVEDIT_EFI)
66 	if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'e')
67 		return do_env_set_efi(NULL, flag, --argc, ++argv);
68 #endif
69 
70 	while (argc > 1 && **(argv + 1) == '-') {
71 		char *arg = *++argv;
72 
73 		--argc;
74 		while (*++arg) {
75 			switch (*arg) {
76 			case 'f':		/* force */
77 				env_flag |= H_FORCE;
78 				break;
79 			default:
80 				return CMD_RET_USAGE;
81 			}
82 		}
83 	}
84 	debug("Final value for argc=%d\n", argc);
85 	/* Exit early if we don't have an env to apply */
86 	if (argc < 2)
87 		return 0;
88 
89 	name = argv[1];
90 
91 	if (strchr(name, '=')) {
92 		printf("## Error: illegal character '=' "
93 		       "in variable name \"%s\"\n", name);
94 		return 1;
95 	}
96 
97 	env_inc_id();
98 
99 	/* Delete only ? */
100 	if (argc < 3 || argv[2] == NULL) {
101 		int rc = hdelete_r(name, &env_htab, env_flag);
102 
103 		/* If the variable didn't exist, don't report an error */
104 		return rc && rc != -ENOENT ? 1 : 0;
105 	}
106 
107 	/*
108 	 * Insert / replace new value
109 	 */
110 	for (i = 2, len = 0; i < argc; ++i)
111 		len += strlen(argv[i]) + 1;
112 
113 	value = malloc(len);
114 	if (value == NULL) {
115 		printf("## Can't malloc %d bytes\n", len);
116 		return 1;
117 	}
118 	for (i = 2, s = value; i < argc; ++i) {
119 		char *v = argv[i];
120 
121 		while ((*s++ = *v++) != '\0')
122 			;
123 		*(s - 1) = ' ';
124 	}
125 	if (s != value)
126 		*--s = '\0';
127 
128 	e.key	= name;
129 	e.data	= value;
130 	hsearch_r(e, ENV_ENTER, &ep, &env_htab, env_flag);
131 	free(value);
132 	if (!ep) {
133 		printf("## Error inserting \"%s\" variable, errno=%d\n",
134 			name, errno);
135 		return 1;
136 	}
137 
138 	return 0;
139 }
140 
env_set(const char * varname,const char * varvalue)141 int env_set(const char *varname, const char *varvalue)
142 {
143 	const char * const argv[4] = { "setenv", varname, varvalue, NULL };
144 
145 	/* before import into hashtable */
146 	if (!(gd->flags & GD_FLG_ENV_READY))
147 		return 1;
148 
149 	if (varvalue == NULL || varvalue[0] == '\0')
150 		return env_do_env_set(0, 2, (char * const *)argv, H_PROGRAMMATIC);
151 	else
152 		return env_do_env_set(0, 3, (char * const *)argv, H_PROGRAMMATIC);
153 }
154 
155 /**
156  * Set an environment variable to an integer value
157  *
158  * @param varname	Environment variable to set
159  * @param value		Value to set it to
160  * Return: 0 if ok, 1 on error
161  */
env_set_ulong(const char * varname,ulong value)162 int env_set_ulong(const char *varname, ulong value)
163 {
164 	/* TODO: this should be unsigned */
165 	char *str = simple_itoa(value);
166 
167 	return env_set(varname, str);
168 }
169 
170 /**
171  * Set an environment variable to an value in hex
172  *
173  * @param varname	Environment variable to set
174  * @param value		Value to set it to
175  * Return: 0 if ok, 1 on error
176  */
env_set_hex(const char * varname,ulong value)177 int env_set_hex(const char *varname, ulong value)
178 {
179 	char str[17];
180 
181 	sprintf(str, "%lx", value);
182 	return env_set(varname, str);
183 }
184 
env_get_hex(const char * varname,ulong default_val)185 ulong env_get_hex(const char *varname, ulong default_val)
186 {
187 	const char *s;
188 	ulong value;
189 	char *endp;
190 
191 	s = env_get(varname);
192 	if (s)
193 		value = hextoul(s, &endp);
194 	if (!s || endp == s)
195 		return default_val;
196 
197 	return value;
198 }
199 
eth_env_get_enetaddr(const char * name,uint8_t * enetaddr)200 int eth_env_get_enetaddr(const char *name, uint8_t *enetaddr)
201 {
202 	string_to_enetaddr(env_get(name), enetaddr);
203 	return is_valid_ethaddr(enetaddr);
204 }
205 
eth_env_set_enetaddr(const char * name,const uint8_t * enetaddr)206 int eth_env_set_enetaddr(const char *name, const uint8_t *enetaddr)
207 {
208 	char buf[ARP_HLEN_ASCII + 1];
209 
210 	if (eth_env_get_enetaddr(name, (uint8_t *)buf))
211 		return -EEXIST;
212 
213 	sprintf(buf, "%pM", enetaddr);
214 
215 	return env_set(name, buf);
216 }
217 
218 /*
219  * Look up variable from environment,
220  * return address of storage for that variable,
221  * or NULL if not found
222  */
env_get(const char * name)223 char *env_get(const char *name)
224 {
225 	if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
226 		struct env_entry e, *ep;
227 
228 		schedule();
229 
230 		e.key	= name;
231 		e.data	= NULL;
232 		hsearch_r(e, ENV_FIND, &ep, &env_htab, 0);
233 
234 		return ep ? ep->data : NULL;
235 	}
236 
237 	/* restricted capabilities before import */
238 	if (env_get_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) >= 0)
239 		return (char *)(gd->env_buf);
240 
241 	return NULL;
242 }
243 
244 /*
245  * Like env_get, but prints an error if envvar isn't defined in the
246  * environment.  It always returns what env_get does, so it can be used in
247  * place of env_get without changing error handling otherwise.
248  */
from_env(const char * envvar)249 char *from_env(const char *envvar)
250 {
251 	char *ret;
252 
253 	ret = env_get(envvar);
254 
255 	if (!ret)
256 		printf("missing environment variable: %s\n", envvar);
257 
258 	return ret;
259 }
260 
env_get_from_linear(const char * env,const char * name,char * buf,unsigned len)261 static int env_get_from_linear(const char *env, const char *name, char *buf,
262 			       unsigned len)
263 {
264 	const char *p, *end;
265 	size_t name_len;
266 
267 	if (name == NULL || *name == '\0')
268 		return -1;
269 
270 	name_len = strlen(name);
271 
272 	for (p = env; *p != '\0'; p = end + 1) {
273 		const char *value;
274 		unsigned res;
275 
276 		for (end = p; *end != '\0'; ++end)
277 			if (end - env >= CONFIG_ENV_SIZE)
278 				return -1;
279 
280 		if (strncmp(name, p, name_len) || p[name_len] != '=')
281 			continue;
282 		value = &p[name_len + 1];
283 
284 		res = end - value;
285 		memcpy(buf, value, min(len, res + 1));
286 
287 		if (len <= res) {
288 			buf[len - 1] = '\0';
289 			printf("env_buf [%u bytes] too small for value of \"%s\"\n",
290 			       len, name);
291 		}
292 
293 		return res;
294 	}
295 
296 	return -1;
297 }
298 
299 /*
300  * Look up variable from environment for restricted C runtime env.
301  */
env_get_f(const char * name,char * buf,unsigned len)302 int env_get_f(const char *name, char *buf, unsigned len)
303 {
304 	const char *env;
305 
306 	if (gd->env_valid == ENV_INVALID)
307 		env = default_environment;
308 	else
309 		env = (const char *)gd->env_addr;
310 
311 	return env_get_from_linear(env, name, buf, len);
312 }
313 
314 /**
315  * Decode the integer value of an environment variable and return it.
316  *
317  * @param name		Name of environment variable
318  * @param base		Number base to use (normally 10, or 16 for hex)
319  * @param default_val	Default value to return if the variable is not
320  *			found
321  * Return: the decoded value, or default_val if not found
322  */
env_get_ulong(const char * name,int base,ulong default_val)323 ulong env_get_ulong(const char *name, int base, ulong default_val)
324 {
325 	/*
326 	 * We can use env_get() here, even before relocation, since the
327 	 * environment variable value is an integer and thus short.
328 	 */
329 	const char *str = env_get(name);
330 
331 	return str ? simple_strtoul(str, NULL, base) : default_val;
332 }
333 
334 /*
335  * Read an environment variable as a boolean
336  * Return -1 if variable does not exist (default to true)
337  */
env_get_yesno(const char * var)338 int env_get_yesno(const char *var)
339 {
340 	char *s = env_get(var);
341 
342 	if (s == NULL)
343 		return -1;
344 	return (*s == '1' || *s == 'y' || *s == 'Y' || *s == 't' || *s == 'T') ?
345 		1 : 0;
346 }
347 
env_get_autostart(void)348 bool env_get_autostart(void)
349 {
350 	return env_get_yesno("autostart") == 1;
351 }
352 
353 /*
354  * Look up the variable from the default environment
355  */
env_get_default(const char * name)356 char *env_get_default(const char *name)
357 {
358 	int ret;
359 
360 	ret = env_get_default_into(name, (char *)(gd->env_buf),
361 				   sizeof(gd->env_buf));
362 	if (ret >= 0)
363 		return (char *)(gd->env_buf);
364 
365 	return NULL;
366 }
367 
368 /*
369  * Look up the variable from the default environment and store its value in buf
370  */
env_get_default_into(const char * name,char * buf,unsigned int len)371 int env_get_default_into(const char *name, char *buf, unsigned int len)
372 {
373 	return env_get_from_linear(default_environment, name, buf, len);
374 }
375 
env_update_fdt_addr_from_bloblist(void)376 static int env_update_fdt_addr_from_bloblist(void)
377 {
378 	/*
379 	 * fdt_addr is by default used by booti, bootm and bootefi,
380 	 * thus set it to point to the fdt embedded in a bloblist if it exists.
381 	 */
382 	if (!CONFIG_IS_ENABLED(BLOBLIST) || gd->fdt_src != FDTSRC_BLOBLIST)
383 		return 0;
384 
385 	return env_set_hex("fdt_addr", (uintptr_t)map_to_sysmem(gd->fdt_blob));
386 }
387 
env_set_default(const char * s,int flags)388 void env_set_default(const char *s, int flags)
389 {
390 	if (s) {
391 		if ((flags & H_INTERACTIVE) == 0) {
392 			printf("*** Warning - %s, "
393 				"using default environment\n\n", s);
394 		} else {
395 			puts(s);
396 		}
397 	} else {
398 		debug("Using default environment\n");
399 	}
400 
401 	flags |= H_DEFAULT;
402 	if (himport_r(&env_htab, default_environment,
403 			sizeof(default_environment), '\0', flags, 0,
404 			0, NULL) == 0) {
405 		pr_err("## Error: Environment import failed: errno = %d\n",
406 		       errno);
407 		return;
408 	}
409 
410 	gd->flags |= GD_FLG_ENV_READY;
411 	gd->flags |= GD_FLG_ENV_DEFAULT;
412 
413 	/* This has to be done after GD_FLG_ENV_READY is set */
414 	if (env_update_fdt_addr_from_bloblist())
415 		pr_err("Failed to set fdt_addr to point at DTB\n");
416 }
417 
418 /* [re]set individual variables to their value in the default environment */
env_set_default_vars(int nvars,char * const vars[],int flags)419 int env_set_default_vars(int nvars, char * const vars[], int flags)
420 {
421 	/*
422 	 * Special use-case: import from default environment
423 	 * (and use \0 as a separator)
424 	 */
425 
426 	/*
427 	 * When vars are passed remove variables that are not in
428 	 * the default environment.
429 	 */
430 	if (!nvars)
431 		flags |= H_NOCLEAR;
432 
433 	flags |= H_DEFAULT;
434 	return himport_r(&env_htab, default_environment,
435 				sizeof(default_environment), '\0',
436 				flags, 0, nvars, vars);
437 }
438 
439 /*
440  * Check if CRC is valid and (if yes) import the environment.
441  * Note that "buf" may or may not be aligned.
442  */
env_import(const char * buf,int check,int flags)443 int env_import(const char *buf, int check, int flags)
444 {
445 	env_t *ep = (env_t *)buf;
446 
447 	if (check) {
448 		uint32_t crc;
449 
450 		memcpy(&crc, &ep->crc, sizeof(crc));
451 
452 		if (crc32(0, ep->data, ENV_SIZE) != crc) {
453 			env_set_default("bad CRC", 0);
454 			return -ENOMSG; /* needed for env_load() */
455 		}
456 	}
457 
458 	if (himport_r(&env_htab, (char *)ep->data, ENV_SIZE, '\0', flags, 0,
459 			0, NULL)) {
460 		gd->flags |= GD_FLG_ENV_READY;
461 
462 		/* This has to be done after GD_FLG_ENV_READY is set */
463 		return env_update_fdt_addr_from_bloblist();
464 	}
465 
466 	pr_err("Cannot import environment: errno = %d\n", errno);
467 
468 	env_set_default("import failed", 0);
469 
470 	return -EIO;
471 }
472 
473 #ifdef CONFIG_ENV_REDUNDANT
474 static unsigned char env_flags;
475 
env_check_redund(const char * buf1,int buf1_read_fail,const char * buf2,int buf2_read_fail)476 int env_check_redund(const char *buf1, int buf1_read_fail,
477 		     const char *buf2, int buf2_read_fail)
478 {
479 	int crc1_ok = 0, crc2_ok = 0;
480 	env_t *tmp_env1, *tmp_env2;
481 
482 	tmp_env1 = (env_t *)buf1;
483 	tmp_env2 = (env_t *)buf2;
484 
485 	if (buf1_read_fail && buf2_read_fail) {
486 		puts("*** Error - No Valid Environment Area found\n");
487 		return -EIO;
488 	} else if (buf1_read_fail || buf2_read_fail) {
489 		puts("*** Warning - some problems detected ");
490 		puts("reading environment; recovered successfully\n");
491 	}
492 
493 	if (!buf1_read_fail)
494 		crc1_ok = crc32(0, tmp_env1->data, ENV_SIZE) ==
495 				tmp_env1->crc;
496 	if (!buf2_read_fail)
497 		crc2_ok = crc32(0, tmp_env2->data, ENV_SIZE) ==
498 				tmp_env2->crc;
499 
500 	if (!crc1_ok && !crc2_ok) {
501 		gd->env_valid = ENV_INVALID;
502 		return -ENOMSG; /* needed for env_load() */
503 	} else if (crc1_ok && !crc2_ok) {
504 		gd->env_valid = ENV_VALID;
505 	} else if (!crc1_ok && crc2_ok) {
506 		gd->env_valid = ENV_REDUND;
507 	} else {
508 		/* both ok - check serial */
509 		if (tmp_env1->flags == 255 && tmp_env2->flags == 0)
510 			gd->env_valid = ENV_REDUND;
511 		else if (tmp_env2->flags == 255 && tmp_env1->flags == 0)
512 			gd->env_valid = ENV_VALID;
513 		else if (tmp_env1->flags > tmp_env2->flags)
514 			gd->env_valid = ENV_VALID;
515 		else if (tmp_env2->flags > tmp_env1->flags)
516 			gd->env_valid = ENV_REDUND;
517 		else /* flags are equal - almost impossible */
518 			gd->env_valid = ENV_VALID;
519 	}
520 
521 	return 0;
522 }
523 
env_import_redund(const char * buf1,int buf1_read_fail,const char * buf2,int buf2_read_fail,int flags)524 int env_import_redund(const char *buf1, int buf1_read_fail,
525 		      const char *buf2, int buf2_read_fail,
526 		      int flags)
527 {
528 	env_t *ep;
529 	int ret;
530 
531 	ret = env_check_redund(buf1, buf1_read_fail, buf2, buf2_read_fail);
532 
533 	if (ret == -EIO) {
534 		env_set_default("bad env area", 0);
535 		return -EIO;
536 	} else if (ret == -ENOMSG) {
537 		env_set_default("bad CRC", 0);
538 		return -ENOMSG;
539 	}
540 
541 	if (gd->env_valid == ENV_VALID)
542 		ep = (env_t *)buf1;
543 	else
544 		ep = (env_t *)buf2;
545 
546 	env_flags = ep->flags;
547 
548 	return env_import((char *)ep, 0, flags);
549 }
550 #endif /* CONFIG_ENV_REDUNDANT */
551 
552 /* Export the environment and generate CRC for it. */
env_export(env_t * env_out)553 int env_export(env_t *env_out)
554 {
555 	char *res;
556 	ssize_t	len;
557 
558 	res = (char *)env_out->data;
559 	len = hexport_r(&env_htab, '\0', 0, &res, ENV_SIZE, 0, NULL);
560 	if (len < 0) {
561 		pr_err("Cannot export environment: errno = %d\n", errno);
562 		return 1;
563 	}
564 
565 	env_out->crc = crc32(0, env_out->data, ENV_SIZE);
566 
567 #ifdef CONFIG_ENV_REDUNDANT
568 	env_out->flags = ++env_flags; /* increase the serial */
569 #endif
570 
571 	return 0;
572 }
573 
env_relocate(void)574 void env_relocate(void)
575 {
576 	if (gd->env_valid == ENV_INVALID) {
577 #if defined(CONFIG_ENV_IS_NOWHERE) || defined(CONFIG_XPL_BUILD)
578 		/* Environment not changable */
579 		env_set_default(NULL, 0);
580 #else
581 		bootstage_error(BOOTSTAGE_ID_NET_CHECKSUM);
582 		env_set_default("bad CRC", 0);
583 #endif
584 	} else {
585 		env_load();
586 	}
587 }
588 
589 #ifdef CONFIG_AUTO_COMPLETE
env_complete(char * var,int maxv,char * cmdv[],int bufsz,char * buf,bool dollar_comp)590 int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf,
591 		 bool dollar_comp)
592 {
593 	struct env_entry *match;
594 	int found, idx;
595 
596 	if (dollar_comp) {
597 		/*
598 		 * When doing $ completion, the first character should
599 		 * obviously be a '$'.
600 		 */
601 		if (var[0] != '$')
602 			return 0;
603 
604 		var++;
605 
606 		/*
607 		 * The second one, if present, should be a '{', as some
608 		 * configuration of the u-boot shell expand ${var} but not
609 		 * $var.
610 		 */
611 		if (var[0] == '{')
612 			var++;
613 		else if (var[0] != '\0')
614 			return 0;
615 	}
616 
617 	idx = 0;
618 	found = 0;
619 	cmdv[0] = NULL;
620 
621 	while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
622 		int vallen = strlen(match->key) + 1;
623 
624 		if (found >= maxv - 2 ||
625 		    bufsz < vallen + (dollar_comp ? 3 : 0))
626 			break;
627 
628 		cmdv[found++] = buf;
629 
630 		/* Add the '${' prefix to each var when doing $ completion. */
631 		if (dollar_comp) {
632 			strcpy(buf, "${");
633 			buf += 2;
634 			bufsz -= 3;
635 		}
636 
637 		memcpy(buf, match->key, vallen);
638 		buf += vallen;
639 		bufsz -= vallen;
640 
641 		if (dollar_comp) {
642 			/*
643 			 * This one is a bit odd: vallen already contains the
644 			 * '\0' character but we need to add the '}' suffix,
645 			 * hence the buf - 1 here. strcpy() will add the '\0'
646 			 * character just after '}'. buf is then incremented
647 			 * to account for the extra '}' we just added.
648 			 */
649 			strcpy(buf - 1, "}");
650 			buf++;
651 		}
652 	}
653 
654 	qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
655 
656 	if (idx)
657 		cmdv[found++] = dollar_comp ? "${...}" : "...";
658 
659 	cmdv[found] = NULL;
660 	return found;
661 }
662 #endif
663 
664 #ifdef CONFIG_ENV_IMPORT_FDT
env_import_fdt(void)665 void env_import_fdt(void)
666 {
667 	const char *path;
668 	struct ofprop prop;
669 	ofnode node;
670 	int res;
671 
672 	path = env_get("env_fdt_path");
673 	if (!path || !path[0])
674 		return;
675 
676 	node = ofnode_path(path);
677 	if (!ofnode_valid(node)) {
678 		printf("Warning: device tree node '%s' not found\n", path);
679 		return;
680 	}
681 
682 	for (res = ofnode_first_property(node, &prop);
683 	     !res;
684 	     res = ofnode_next_property(&prop)) {
685 		const char *name, *val;
686 
687 		val = ofprop_get_property(&prop, &name, NULL);
688 		env_set(name, val);
689 	}
690 }
691 #endif
692