]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/env.c
env.c needs getopt-min.h
[z180-stamp.git] / avr / env.c
1 /*
2 * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de>
3 *
4 * SPDX-License-Identifier: GPL-2.0
5 */
6
7 #include "common.h"
8 #include <string.h>
9 #include <stdlib.h>
10 #include <stdbool.h>
11 #include <avr/eeprom.h>
12
13 #include "config.h"
14 #include "debug.h"
15 #include "xmalloc.h"
16 #include "crc.h"
17 #include "getopt-min.h"
18 #include "command.h"
19 #include "env.h"
20
21
22 #define ENV_SIZE (CONFIG_ENV_SIZE - sizeof(uint16_t) -1)
23 #define ACTIVE_FLAG 1
24 #define OBSOLETE_FLAG 0
25
26 #define ENVLIST_DELETE (1<<0)
27
28
29 /*
30 * Default Environment
31 */
32
33 #define DELIM "\0"
34
35 const FLASH char default_env[] = {
36 ENV_BAUDRATE "=" "115200" DELIM
37 ENV_BOOTDELAY "=" "3" DELIM
38 ENV_BOOTCMD "=" "pin ${pins}; loadcpm3; go ${startaddress}" DELIM
39 ENV_CPM3_SYSFILE "=" CONFIG_CPM3_SYSFILE DELIM
40 ENV_PINALIAS "=" "0:PG5,1:PG4,2:PB4,3:PB5,4:PB6,5:PB7,"
41 "6:PG3,7:PG2,8:PG1,9:PG0,10:PE7" DELIM
42 ENV_STARTADDRESS "=" "0" DELIM
43 "pins" "=" "2,8 low 9 high 3 2" DELIM
44 DELIM
45 };
46
47
48 /* EEPROM storage */
49 typedef struct environment_s {
50 uint16_t crc; /* CRC16 over data bytes */
51 uint8_t flags; /* active/obsolete flags */
52 char data[ENV_SIZE]; /* Environment data */
53 } env_t;
54
55
56 /* */
57 typedef struct env_item_s {
58 char * envvar;
59 } env_item_t;
60
61
62 static uint8_t env_valid;
63 static env_item_t env_list[CONFIG_ENVVAR_MAX];
64 static int entrycount;
65
66
67 static
68 char env_get_char(uint16_t index)
69 {
70 unsigned int off = CONFIG_ENV_OFFSET;
71 char ret;
72
73 switch (env_valid) {
74 case 2:
75 off += CONFIG_ENV_SIZE;
76 case 1:
77 ret = (char) eeprom_read_byte((const uint8_t *)off + index +
78 offsetof(env_t, data));
79 break;
80
81 default:
82 ret = default_env[index];
83 }
84
85 return ret;
86 }
87
88
89 static const FLASH char *comp_key;
90
91 static
92 int comp_env_items(const void *m1, const void *m2)
93 {
94 env_item_t *ep1 = (env_item_t *) m1;
95 env_item_t *ep2 = (env_item_t *) m2;
96
97 if (ep1 == NULL)
98 return - strcmp_P(ep2->envvar, comp_key);
99 else
100 return strcmp(ep1->envvar, ep2->envvar);
101 }
102
103
104 env_item_t *envlist_search(const MEMX char *name)
105 {
106 #ifdef __MEMX
107 if (__builtin_avr_flash_segment(name) != -1) {
108 comp_key = name;
109 return bsearch(0, env_list, entrycount,
110 sizeof(env_item_t), comp_env_items);
111 } else {
112
113 env_item_t e;
114 e.envvar = (char *) name;
115
116 return bsearch(&e, env_list, entrycount,
117 sizeof(env_item_t), comp_env_items);
118 }
119 #else
120 env_item_t e;
121 e.envvar = (char *) name;
122
123 return bsearch(&e, env_list, entrycount,
124 sizeof(env_item_t), comp_env_items);
125 #endif /* __MEMX */
126 }
127
128
129 static
130 env_item_t *envlist_enter(env_item_t *e)
131 {
132 const size_t size = sizeof(env_item_t);
133 env_item_t *ep;
134
135 ep = bsearch(e, env_list, entrycount,
136 size, comp_env_items);
137
138 if (ep == NULL) {
139 if (entrycount < CONFIG_ENVVAR_MAX) {
140
141 env_list[entrycount++] = *e;
142 qsort(env_list, entrycount, size, comp_env_items);
143 ep = bsearch(e, env_list, entrycount,
144 size, comp_env_items);
145 }
146 } else {
147 free(ep->envvar);
148 ep->envvar = e->envvar;
149 }
150
151 return ep;
152 }
153
154
155 static
156 int env_item_delete(env_item_t *ep)
157 {
158 if (entrycount == 0)
159 return -1;
160
161 free(ep->envvar);
162
163 entrycount--;
164 size_t size = sizeof(env_item_t);
165 memmove(ep, ep + 1, (env_list - ep)*size + entrycount*size);
166
167 return 0;
168 }
169
170 static
171 int envlist_delete(const MEMX char *name)
172 {
173 env_item_t *ep = envlist_search(name);
174
175 if (ep != NULL)
176 return env_item_delete(ep);
177
178 return 1;
179 }
180
181
182
183 static
184 int envlist_import(uint8_t flags)
185 {
186 uint16_t index;
187
188 int len;
189 env_item_t e;
190 char *np, c;
191 uint_fast8_t ef;
192
193 if ((flags & ENVLIST_DELETE) != 0)
194 while (entrycount != 0)
195 env_item_delete(&env_list[entrycount-1]);
196
197 for (index = 0; env_get_char(index) != '\0'; ) {
198 for (len = 0; env_get_char(index + len) != '\0'; ++len) {
199 if ((index + len) >= ENV_SIZE)
200 return -1;
201 }
202
203 np = (char *) xmalloc(len+1);
204 if (np == NULL) {
205 printf_P(PSTR("## Can't malloc %d bytes\n"), len+1);
206 return 1;
207 }
208 e.envvar = np;
209 ef = 0;
210 while ((c = env_get_char(index++)) != '\0') {
211 if (!ef && (c == '=')) {
212 *np = '\0';
213 ef = 1;
214 } else
215 *np = c;
216 np++;
217 }
218 *np = '\0';
219 envlist_enter(&e);
220 }
221
222
223 return 0;
224 }
225
226
227 static
228 uint16_t env_crc(uint16_t data_offset)
229 {
230 uint16_t crc;
231 uint16_t i;
232 char c, c0;
233
234 crc = 0xffff;
235 c = 0xff;
236 for (i = 0; !(c == 0 && c0 == 0) && i < ENV_SIZE; i++)
237 {
238 c0 = c;
239 c = eeprom_read_byte((const uint8_t *) data_offset + i);
240 crc = crc16(crc, c);
241 }
242 return crc ;
243 }
244
245
246 /**
247 * return valid env
248 */
249 static
250 int env_check_valid(void)
251 {
252 const uint16_t offset[2] = {CONFIG_ENV_OFFSET,
253 CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE};
254 uint_fast8_t flags[2], crc_ok[2];
255 int rc;
256
257 /* read FLAGS */
258 flags[0] = eeprom_read_byte ((uint8_t *) offset[0] +
259 offsetof(env_t, flags));
260 flags[1] = eeprom_read_byte ((uint8_t *) offset[1] +
261 offsetof(env_t, flags));
262
263 /* check CRC */
264 crc_ok[0] = (
265 eeprom_read_word((uint16_t *) offset[0] +
266 offsetof(env_t, crc))
267 == env_crc(offset[0] + offsetof(env_t, data))
268 );
269 crc_ok[1] = (
270 eeprom_read_word((uint16_t *) offset[1] +
271 offsetof(env_t, crc))
272 == env_crc(offset[1] + offsetof(env_t, data))
273 );
274
275 if (!crc_ok[0] && !crc_ok[1]) {
276 rc = 0;
277
278 } else if (crc_ok[0] && !crc_ok[1]) {
279 rc = 1;
280 } else if (!crc_ok[0] && crc_ok[1]) {
281 rc = 2;
282 } else {
283 /* both ok - check serial */
284 #if 1
285 if (flags[1] == ACTIVE_FLAG && flags[0] != ACTIVE_FLAG)
286 rc = 2;
287 else if (flags[1] == OBSOLETE_FLAG && flags[0] == 0xFF)
288 rc = 2;
289 else
290 rc = 1;
291 #else
292 if (flags[0] == ACTIVE_FLAG && flags[1] == OBSOLETE_FLAG)
293 rc = 1;
294 else if (flags[0] == OBSOLETE_FLAG && flags[1] == ACTIVE_FLAG)
295 rc = 2;
296 else if (flags[0] == 0xFF && flags[1] == 0)
297 rc = 2;
298 else if (flags[1] == 0xFF && flags[0] == 0)
299 rc = 1;
300 else /* flags are equal - almost impossible */
301 rc = 1;
302 #endif
303 }
304
305 return rc;
306 }
307
308
309 int env_init(void)
310 {
311 env_valid = env_check_valid();
312 if (env_valid == 0) {
313 printf_P(PSTR("*** Warning - bad CRC, "
314 "using default environment\n\n"));
315 }
316
317 envlist_import(ENVLIST_DELETE);
318 return 0;
319 }
320
321
322 char *getenv_str(const MEMX char *name)
323 {
324 env_item_t *ep;
325 char *ret = NULL;
326
327 ep = envlist_search(name);
328 if (ep != NULL)
329 ret = ep->envvar + strlen(ep->envvar) +1;
330 return ret;
331 }
332
333 static
334 int env_item_save(env_item_t *ep, uint16_t offset, int space_left)
335 {
336 int nlen, vlen;
337 char *var = ep->envvar;
338
339 nlen = strlen(var);
340 if (nlen == 0)
341 return 0;
342 vlen = strlen(var + nlen + 1);
343 if (vlen == 0)
344 return 0;
345 if (nlen + vlen + 2 > space_left)
346 return 0;
347
348 eeprom_update_block(var, (uint8_t *) offset, nlen);
349 offset += nlen;
350 eeprom_update_byte((uint8_t *) offset++, '=');
351 eeprom_update_block(var + nlen +1, (uint8_t *) offset, vlen+1);
352
353 return nlen + vlen + 2;
354 }
355
356
357 static
358 int saveenv(void)
359 {
360 unsigned int off = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
361 unsigned int off_red = CONFIG_ENV_OFFSET;
362 unsigned int pos;
363 int len, left;
364 uint16_t crc;
365 int rc = 0;
366
367 if (env_valid == 2) {
368 off = CONFIG_ENV_OFFSET;
369 off_red = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
370 }
371
372 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags), 0xff);
373
374 pos = off + offsetof(env_t, data);
375 left = ENV_SIZE - 1;
376 for (int i = 0 ; i < entrycount; i++) {
377 len = env_item_save(&env_list[i], pos, left);
378 if (len == 0) {
379 return 1;
380 }
381 pos += len;
382 left -= len;
383 }
384 /* terminate list */
385 eeprom_update_byte((uint8_t *) pos, 0);
386 crc = env_crc(off + offsetof(env_t, data));
387 eeprom_update_word((uint16_t *) off + offsetof(env_t, crc), crc);
388 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags),
389 ACTIVE_FLAG);
390
391 if (rc == 0) {
392 eeprom_update_byte((uint8_t *) off_red + offsetof(env_t, flags),
393 OBSOLETE_FLAG);
394 env_valid = (env_valid == 2) ? 1 : 2;
395 }
396
397 return rc;
398 }
399
400
401 static
402 int env_item_print(env_item_t *ep, bool mode)
403 {
404 int len;
405 char *ev = ep->envvar;
406
407 if (mode) {
408 len = printf_P(PSTR("setenv %s "), ev) - 7;
409 len += printf_P(PSTR("'%s'\n"), ev + len) - 2;
410 } else {
411 len = printf_P(PSTR("%s="), ev);
412 len += printf_P(PSTR("%s\n"), ev + len);
413 }
414 return len;
415 }
416
417
418 /*
419 * Command interface: print one or all environment variables
420 *
421 * Returns -1 in case of error, or length of printed string
422 */
423 static
424 int env_print(const MEMX char *name, bool mode)
425 {
426 int len = -1;
427
428 if (name) { /* print a single name */
429
430 env_item_t *ep = envlist_search(name);
431 if (ep != NULL)
432 len = env_item_print(ep, mode);
433
434 } else { /* print whole list */
435 len = 0;
436 for (int i = 0 ; i < entrycount; i++) {
437 len += env_item_print(&env_list[i], mode);
438 }
439 }
440 return len;
441 }
442
443
444 /**
445 * Set or delete environment variable
446 *
447 * Set a new environment variable,
448 * or replace or delete an existing one.
449 *
450 * @param flag (not used)
451 * @param argc
452 * @param argv[1] Environment variable to set or delete
453 * if no more args
454 * @param argv[2] ... Value to set it to
455 *
456 * @return 0 if ok, 1 on error
457 */
458 static
459 command_ret_t _do_env_set(int flag, int argc, char * const argv[])
460 {
461 int i, len;
462 char *name, *value, *valp, *p;
463 env_item_t e, *ep;
464
465 (void) flag;
466
467 name = argv[1];
468 value = argv[2];
469
470 if (strchr(name, '=')) {
471 printf_P(PSTR("## Error: illegal character '='"
472 "in variable name \"%s\"\n"), name);
473 return CMD_RET_FAILURE;
474 }
475 len = strlen(name);
476 if (len > CONFIG_SYS_ENV_NAMELEN) {
477 printf_P(PSTR("## Error: Variable name \"%s\" too long. "
478 "(max %d characters)\n"), name, CONFIG_SYS_ENV_NAMELEN);
479 return CMD_RET_FAILURE;
480 }
481 /*
482 env_id++;
483 */
484 /* Delete only ? */
485 if (argc < 3 || argv[2] == NULL) {
486 int rc = envlist_delete(name);
487 return rc ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
488 }
489
490 /*
491 * Insert / replace new value
492 */
493 for (i = 2, len += 1; i < argc; ++i)
494 len += strlen(argv[i]) + 1;
495
496 value = xmalloc(len);
497 if (value == NULL) {
498 printf_P(PSTR("## Can't malloc %d bytes\n"), len);
499 return CMD_RET_FAILURE;
500 }
501 strcpy(value, name);
502 valp = value + strlen(name) + 1;
503 for (i = 2, p = valp; i < argc; ++i) {
504 char *v = argv[i];
505
506 while ((*p++ = *v++) != '\0')
507 ;
508 *(p - 1) = ' ';
509 }
510 if (p != valp)
511 *--p = '\0';
512
513 e.envvar = value;
514 ep = envlist_enter(&e);
515 if (!ep) {
516 printf_P(PSTR("## Error inserting \"%s\" variable.\n"),
517 name);
518 return CMD_RET_FAILURE;
519 }
520
521 return CMD_RET_SUCCESS;
522 }
523
524 /**
525 * Set an environment variable
526 *
527 * @param varname Environment variable to set
528 * @param varvalue Value to set it to
529 * @return 0 if ok, 1 on error
530 */
531 static
532 int setenv(const MEMX char *varname, const char *varvalue)
533 {
534 int rc;
535
536 #ifdef __MEMX
537 char *tmpname = NULL;
538 if (__builtin_avr_flash_segment(varname) != -1) {
539 tmpname = malloc(strlen_P(varname)+1);
540 if (tmpname == NULL) {
541 printf_P(PSTR("setenv: Out of Memory!\n"));
542 return 1;
543 }
544 strcpy_P(tmpname, varname);
545 } else
546 tmpname = (char *) varname;
547 #endif
548
549 const char * const argv[3] = { NULL, tmpname, varvalue };
550 int argc = 3;
551
552 if (varvalue == NULL || varvalue[0] == '\0')
553 --argc;
554
555 rc = (int) _do_env_set(0, argc, (char * const *)argv);
556
557 #ifdef __MEMX
558 free(tmpname);
559 #endif
560 return rc;
561 }
562
563 /**
564 * Set an environment variable to an integer value
565 *
566 * @param name Environment variable to set
567 * @param value Value to set it to
568 * @param radix Base
569 * @return 0 if ok, 1 on error
570 */
571 static
572 int setenv_intval(const MEMX char *name, unsigned long value, int radix)
573 {
574 char buf[11];
575
576 ultoa(value, buf, radix);
577
578 return setenv(name, buf);
579 }
580
581 /**
582 * Set an environment variable to a decimal integer value
583 *
584 * @param name Environment variable to set
585 * @param value Value to set it to
586 * @return 0 if ok, 1 on error
587 */
588 int setenv_ulong(const MEMX char *name, unsigned long value)
589 {
590 return setenv_intval(name, value, 10);
591 }
592
593
594 /**
595 * Set an environment variable to a value in hex
596 *
597 * @param name Environment variable to set
598 * @param value Value to set it to
599 * @return 0 if ok, 1 on error
600 */
601 int setenv_hex(const MEMX char *name, unsigned long value)
602 {
603 return setenv_intval(name, value, 16);
604 }
605
606
607 /**
608 * Decode the integer value of an environment variable and return it.
609 *
610 * @param name Name of environemnt variable
611 * @param base Number base to use (normally 10, or 16 for hex)
612 * @param default_val Default value to return if the variable is not
613 * found
614 * @return the decoded value, or default_val if not found
615 */
616 unsigned long getenv_ulong(const MEMX char *name, int base, unsigned long default_val)
617 {
618 unsigned long value;
619 char *vp, *endp;
620
621 env_item_t *ep = envlist_search(name);
622
623 if (ep != NULL ) {
624 vp = ep->envvar + strlen(ep->envvar) +1;
625 value = strtoul(vp, &endp, base);
626 if (endp != vp)
627 return value;
628 }
629
630 return default_val;
631 }
632
633
634 /*
635 * Read an environment variable as a boolean
636 */
637 bool getenv_yesno(const MEMX char *name)
638 {
639 char *s = getenv_str(name);
640
641 if (s == NULL)
642 return false;
643
644 return strchr_P(PSTR("1yYtT"), *s) != NULL;
645
646 /*
647 return *s == '1' || *s == 'y' || *s == 'Y' || *s == 't' || *s == 'T' ?
648 1 : 0;
649 */
650 }
651
652 command_ret_t do_env_print(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
653 {
654 (void) cmdtp; (void) flag;
655
656 bool mode = 0;
657 command_ret_t rc = CMD_RET_SUCCESS;
658
659 /* reset getopt() */
660 optind = 0;
661
662 int opt;
663 while ((opt = getopt(argc, argv, PSTR("s"))) != -1) {
664 switch (opt) {
665 case 's':
666 mode = 1;
667 break;
668 default: /* '?' */
669 return CMD_RET_USAGE;
670 }
671 }
672
673 if (optind == argc) {
674 /* print all env vars */
675 int size = env_print(NULL, mode);
676 if (size < 0)
677 return CMD_RET_FAILURE;
678 if (mode == 0)
679 printf_P(PSTR("\nEnvironment size: %d/%d bytes\n"),
680 size, ENV_SIZE);
681 return CMD_RET_SUCCESS;
682 }
683
684 /* print selected env vars */
685 while (optind < argc) {
686 int rc = env_print(argv[optind], mode);
687 if (rc < 0) {
688 printf_P(PSTR("## Error: \"%s\" not defined\n"), argv[optind]);
689 rc = CMD_RET_FAILURE;
690 }
691 optind++;
692 }
693
694 return rc;
695 }
696
697
698 command_ret_t do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
699 {
700 (void) cmdtp;
701
702 if (argc < 2)
703 return CMD_RET_USAGE;
704
705 return _do_env_set(flag, argc, argv);
706 }
707
708
709 command_ret_t do_env_default(cmd_tbl_t *cmdtp, int flag,
710 int argc, char * const argv[])
711 {
712 (void) cmdtp; (void) flag; (void) argc; (void) argv;
713
714 uint8_t tmp = env_valid;
715 env_valid = 0;
716
717 /* Reset the whole environment */
718 printf_P(PSTR("## Resetting to default environment\n"));
719 envlist_import(ENVLIST_DELETE);
720
721 env_valid = tmp;
722
723 return CMD_RET_SUCCESS;
724 }
725
726
727 command_ret_t do_env_save(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
728 {
729 (void) cmdtp; (void) flag; (void) argc; (void) argv;
730
731 printf_P(PSTR("Saving Environment ...\n"));
732 return saveenv() ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
733 }
734
735
736 #if defined(CONFIG_AUTO_COMPLETE)
737 int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf)
738 {
739 ENTRY *match;
740 int found, idx;
741
742 idx = 0;
743 found = 0;
744 cmdv[0] = NULL;
745
746 while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
747 int vallen = strlen(match->key) + 1;
748
749 if (found >= maxv - 2 || bufsz < vallen)
750 break;
751
752 cmdv[found++] = buf;
753 memcpy(buf, match->key, vallen);
754 buf += vallen;
755 bufsz -= vallen;
756 }
757
758 qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
759
760 if (idx)
761 cmdv[found++] = "...";
762
763 cmdv[found] = NULL;
764 return found;
765 }
766 #endif