tools: env: split fw_string_blank into skip_chars / skip_blanks
[platform/kernel/u-boot.git] / tools / env / fw_env.c
1 /*
2  * (C) Copyright 2000-2010
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * (C) Copyright 2008
6  * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
7  *
8  * SPDX-License-Identifier:     GPL-2.0+
9  */
10
11 #define _GNU_SOURCE
12
13 #include <compiler.h>
14 #include <errno.h>
15 #include <env_flags.h>
16 #include <fcntl.h>
17 #include <linux/stringify.h>
18 #include <ctype.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stddef.h>
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
28 #ifdef MTD_OLD
29 # include <stdint.h>
30 # include <linux/mtd/mtd.h>
31 #else
32 # define  __user        /* nothing */
33 # include <mtd/mtd-user.h>
34 #endif
35
36 #include "fw_env.h"
37
38 #define DIV_ROUND_UP(n, d)      (((n) + (d) - 1) / (d))
39
40 #define min(x, y) ({                            \
41         typeof(x) _min1 = (x);                  \
42         typeof(y) _min2 = (y);                  \
43         (void) (&_min1 == &_min2);              \
44         _min1 < _min2 ? _min1 : _min2; })
45
46 struct envdev_s {
47         const char *devname;            /* Device name */
48         ulong devoff;                   /* Device offset */
49         ulong env_size;                 /* environment size */
50         ulong erase_size;               /* device erase size */
51         ulong env_sectors;              /* number of environment sectors */
52         uint8_t mtd_type;               /* type of the MTD device */
53 };
54
55 static struct envdev_s envdevices[2] =
56 {
57         {
58                 .mtd_type = MTD_ABSENT,
59         }, {
60                 .mtd_type = MTD_ABSENT,
61         },
62 };
63 static int dev_current;
64
65 #define DEVNAME(i)    envdevices[(i)].devname
66 #define DEVOFFSET(i)  envdevices[(i)].devoff
67 #define ENVSIZE(i)    envdevices[(i)].env_size
68 #define DEVESIZE(i)   envdevices[(i)].erase_size
69 #define ENVSECTORS(i) envdevices[(i)].env_sectors
70 #define DEVTYPE(i)    envdevices[(i)].mtd_type
71
72 #define CUR_ENVSIZE ENVSIZE(dev_current)
73
74 #define ENV_SIZE      getenvsize()
75
76 struct env_image_single {
77         uint32_t        crc;    /* CRC32 over data bytes    */
78         char            data[];
79 };
80
81 struct env_image_redundant {
82         uint32_t        crc;    /* CRC32 over data bytes    */
83         unsigned char   flags;  /* active or obsolete */
84         char            data[];
85 };
86
87 enum flag_scheme {
88         FLAG_NONE,
89         FLAG_BOOLEAN,
90         FLAG_INCREMENTAL,
91 };
92
93 struct environment {
94         void                    *image;
95         uint32_t                *crc;
96         unsigned char           *flags;
97         char                    *data;
98         enum flag_scheme        flag_scheme;
99 };
100
101 static struct environment environment = {
102         .flag_scheme = FLAG_NONE,
103 };
104
105 static int env_aes_cbc_crypt(char *data, const int enc);
106
107 static int HaveRedundEnv = 0;
108
109 static unsigned char active_flag = 1;
110 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
111 static unsigned char obsolete_flag = 0;
112
113 #define DEFAULT_ENV_INSTANCE_STATIC
114 #include <env_default.h>
115
116 static int flash_io (int mode);
117 static char *envmatch (char * s1, char * s2);
118 static int parse_config (void);
119
120 #if defined(CONFIG_FILE)
121 static int get_config (char *);
122 #endif
123 static inline ulong getenvsize (void)
124 {
125         ulong rc = CUR_ENVSIZE - sizeof(uint32_t);
126
127         if (HaveRedundEnv)
128                 rc -= sizeof (char);
129
130         if (common_args.aes_flag)
131                 rc &= ~(AES_KEY_LENGTH - 1);
132
133         return rc;
134 }
135
136 static char *skip_chars(char *s)
137 {
138         for (; *s != '\0'; s++) {
139                 if (isblank(*s))
140                         return s;
141         }
142         return NULL;
143 }
144
145 static char *skip_blanks(char *s)
146 {
147         for (; *s != '\0'; s++) {
148                 if (!isblank(*s))
149                         return s;
150         }
151         return NULL;
152 }
153
154 /*
155  * Search the environment for a variable.
156  * Return the value, if found, or NULL, if not found.
157  */
158 char *fw_getenv (char *name)
159 {
160         char *env, *nxt;
161
162         for (env = environment.data; *env; env = nxt + 1) {
163                 char *val;
164
165                 for (nxt = env; *nxt; ++nxt) {
166                         if (nxt >= &environment.data[ENV_SIZE]) {
167                                 fprintf (stderr, "## Error: "
168                                         "environment not terminated\n");
169                                 return NULL;
170                         }
171                 }
172                 val = envmatch (name, env);
173                 if (!val)
174                         continue;
175                 return val;
176         }
177         return NULL;
178 }
179
180 /*
181  * Search the default environment for a variable.
182  * Return the value, if found, or NULL, if not found.
183  */
184 char *fw_getdefenv(char *name)
185 {
186         char *env, *nxt;
187
188         for (env = default_environment; *env; env = nxt + 1) {
189                 char *val;
190
191                 for (nxt = env; *nxt; ++nxt) {
192                         if (nxt >= &default_environment[ENV_SIZE]) {
193                                 fprintf(stderr, "## Error: "
194                                         "default environment not terminated\n");
195                                 return NULL;
196                         }
197                 }
198                 val = envmatch(name, env);
199                 if (!val)
200                         continue;
201                 return val;
202         }
203         return NULL;
204 }
205
206 int parse_aes_key(char *key, uint8_t *bin_key)
207 {
208         char tmp[5] = { '0', 'x', 0, 0, 0 };
209         unsigned long ul;
210         int i;
211
212         if (strnlen(key, 64) != 32) {
213                 fprintf(stderr,
214                         "## Error: '-a' option requires 16-byte AES key\n");
215                 return -1;
216         }
217
218         for (i = 0; i < 16; i++) {
219                 tmp[2] = key[0];
220                 tmp[3] = key[1];
221                 errno = 0;
222                 ul = strtoul(tmp, NULL, 16);
223                 if (errno) {
224                         fprintf(stderr,
225                                 "## Error: '-a' option requires valid AES key\n");
226                         return -1;
227                 }
228                 bin_key[i] = ul & 0xff;
229                 key += 2;
230         }
231         return 0;
232 }
233
234 /*
235  * Print the current definition of one, or more, or all
236  * environment variables
237  */
238 int fw_printenv (int argc, char *argv[])
239 {
240         char *env, *nxt;
241         int i, rc = 0;
242
243         if (fw_env_open())
244                 return -1;
245
246         if (argc == 0) {                /* Print all env variables  */
247                 for (env = environment.data; *env; env = nxt + 1) {
248                         for (nxt = env; *nxt; ++nxt) {
249                                 if (nxt >= &environment.data[ENV_SIZE]) {
250                                         fprintf (stderr, "## Error: "
251                                                 "environment not terminated\n");
252                                         return -1;
253                                 }
254                         }
255
256                         printf ("%s\n", env);
257                 }
258                 return 0;
259         }
260
261         if (printenv_args.name_suppress && argc != 1) {
262                 fprintf(stderr,
263                         "## Error: `-n' option requires exactly one argument\n");
264                 return -1;
265         }
266
267         for (i = 0; i < argc; ++i) {    /* print single env variables   */
268                 char *name = argv[i];
269                 char *val = NULL;
270
271                 for (env = environment.data; *env; env = nxt + 1) {
272
273                         for (nxt = env; *nxt; ++nxt) {
274                                 if (nxt >= &environment.data[ENV_SIZE]) {
275                                         fprintf (stderr, "## Error: "
276                                                 "environment not terminated\n");
277                                         return -1;
278                                 }
279                         }
280                         val = envmatch (name, env);
281                         if (val) {
282                                 if (!printenv_args.name_suppress) {
283                                         fputs (name, stdout);
284                                         putc ('=', stdout);
285                                 }
286                                 puts (val);
287                                 break;
288                         }
289                 }
290                 if (!val) {
291                         fprintf (stderr, "## Error: \"%s\" not defined\n", name);
292                         rc = -1;
293                 }
294         }
295
296         return rc;
297 }
298
299 int fw_env_close(void)
300 {
301         int ret;
302         if (common_args.aes_flag) {
303                 ret = env_aes_cbc_crypt(environment.data, 1);
304                 if (ret) {
305                         fprintf(stderr,
306                                 "Error: can't encrypt env for flash\n");
307                         return ret;
308                 }
309         }
310
311         /*
312          * Update CRC
313          */
314         *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
315
316         /* write environment back to flash */
317         if (flash_io(O_RDWR)) {
318                 fprintf(stderr,
319                         "Error: can't write fw_env to flash\n");
320                         return -1;
321         }
322
323         return 0;
324 }
325
326
327 /*
328  * Set/Clear a single variable in the environment.
329  * This is called in sequence to update the environment
330  * in RAM without updating the copy in flash after each set
331  */
332 int fw_env_write(char *name, char *value)
333 {
334         int len;
335         char *env, *nxt;
336         char *oldval = NULL;
337         int deleting, creating, overwriting;
338
339         /*
340          * search if variable with this name already exists
341          */
342         for (nxt = env = environment.data; *env; env = nxt + 1) {
343                 for (nxt = env; *nxt; ++nxt) {
344                         if (nxt >= &environment.data[ENV_SIZE]) {
345                                 fprintf(stderr, "## Error: "
346                                         "environment not terminated\n");
347                                 errno = EINVAL;
348                                 return -1;
349                         }
350                 }
351                 if ((oldval = envmatch (name, env)) != NULL)
352                         break;
353         }
354
355         deleting = (oldval && !(value && strlen(value)));
356         creating = (!oldval && (value && strlen(value)));
357         overwriting = (oldval && (value && strlen(value)));
358
359         /* check for permission */
360         if (deleting) {
361                 if (env_flags_validate_varaccess(name,
362                     ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
363                         printf("Can't delete \"%s\"\n", name);
364                         errno = EROFS;
365                         return -1;
366                 }
367         } else if (overwriting) {
368                 if (env_flags_validate_varaccess(name,
369                     ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
370                         printf("Can't overwrite \"%s\"\n", name);
371                         errno = EROFS;
372                         return -1;
373                 } else if (env_flags_validate_varaccess(name,
374                     ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
375                         const char *defval = fw_getdefenv(name);
376
377                         if (defval == NULL)
378                                 defval = "";
379                         if (strcmp(oldval, defval)
380                             != 0) {
381                                 printf("Can't overwrite \"%s\"\n", name);
382                                 errno = EROFS;
383                                 return -1;
384                         }
385                 }
386         } else if (creating) {
387                 if (env_flags_validate_varaccess(name,
388                     ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
389                         printf("Can't create \"%s\"\n", name);
390                         errno = EROFS;
391                         return -1;
392                 }
393         } else
394                 /* Nothing to do */
395                 return 0;
396
397         if (deleting || overwriting) {
398                 if (*++nxt == '\0') {
399                         *env = '\0';
400                 } else {
401                         for (;;) {
402                                 *env = *nxt++;
403                                 if ((*env == '\0') && (*nxt == '\0'))
404                                         break;
405                                 ++env;
406                         }
407                 }
408                 *++env = '\0';
409         }
410
411         /* Delete only ? */
412         if (!value || !strlen(value))
413                 return 0;
414
415         /*
416          * Append new definition at the end
417          */
418         for (env = environment.data; *env || *(env + 1); ++env);
419         if (env > environment.data)
420                 ++env;
421         /*
422          * Overflow when:
423          * "name" + "=" + "val" +"\0\0"  > CUR_ENVSIZE - (env-environment)
424          */
425         len = strlen (name) + 2;
426         /* add '=' for first arg, ' ' for all others */
427         len += strlen(value) + 1;
428
429         if (len > (&environment.data[ENV_SIZE] - env)) {
430                 fprintf (stderr,
431                         "Error: environment overflow, \"%s\" deleted\n",
432                         name);
433                 return -1;
434         }
435
436         while ((*env = *name++) != '\0')
437                 env++;
438         *env = '=';
439         while ((*++env = *value++) != '\0')
440                 ;
441
442         /* end is marked with double '\0' */
443         *++env = '\0';
444
445         return 0;
446 }
447
448 /*
449  * Deletes or sets environment variables. Returns -1 and sets errno error codes:
450  * 0      - OK
451  * EINVAL - need at least 1 argument
452  * EROFS  - certain variables ("ethaddr", "serial#") cannot be
453  *          modified or deleted
454  *
455  */
456 int fw_setenv(int argc, char *argv[])
457 {
458         int i;
459         size_t len;
460         char *name, **valv;
461         char *value = NULL;
462         int valc;
463
464         if (argc < 1) {
465                 fprintf(stderr, "## Error: variable name missing\n");
466                 errno = EINVAL;
467                 return -1;
468         }
469
470         if (fw_env_open()) {
471                 fprintf(stderr, "Error: environment not initialized\n");
472                 return -1;
473         }
474
475         name = argv[0];
476         valv = argv + 1;
477         valc = argc - 1;
478
479         if (env_flags_validate_env_set_params(name, valv, valc) < 0)
480                 return 1;
481
482         len = 0;
483         for (i = 0; i < valc; ++i) {
484                 char *val = valv[i];
485                 size_t val_len = strlen(val);
486
487                 if (value)
488                         value[len - 1] = ' ';
489                 value = realloc(value, len + val_len + 1);
490                 if (!value) {
491                         fprintf(stderr,
492                                 "Cannot malloc %zu bytes: %s\n",
493                                 len, strerror(errno));
494                         return -1;
495                 }
496
497                 memcpy(value + len, val, val_len);
498                 len += val_len;
499                 value[len++] = '\0';
500         }
501
502         fw_env_write(name, value);
503
504         free(value);
505
506         return fw_env_close();
507 }
508
509 /*
510  * Parse  a file  and configure the u-boot variables.
511  * The script file has a very simple format, as follows:
512  *
513  * Each line has a couple with name, value:
514  * <white spaces>variable_name<white spaces>variable_value
515  *
516  * Both variable_name and variable_value are interpreted as strings.
517  * Any character after <white spaces> and before ending \r\n is interpreted
518  * as variable's value (no comment allowed on these lines !)
519  *
520  * Comments are allowed if the first character in the line is #
521  *
522  * Returns -1 and sets errno error codes:
523  * 0      - OK
524  * -1     - Error
525  */
526 int fw_parse_script(char *fname)
527 {
528         FILE *fp;
529         char dump[1024];        /* Maximum line length in the file */
530         char *name;
531         char *val;
532         int lineno = 0;
533         int len;
534         int ret = 0;
535
536         if (fw_env_open()) {
537                 fprintf(stderr, "Error: environment not initialized\n");
538                 return -1;
539         }
540
541         if (strcmp(fname, "-") == 0)
542                 fp = stdin;
543         else {
544                 fp = fopen(fname, "r");
545                 if (fp == NULL) {
546                         fprintf(stderr, "I cannot open %s for reading\n",
547                                  fname);
548                         return -1;
549                 }
550         }
551
552         while (fgets(dump, sizeof(dump), fp)) {
553                 lineno++;
554                 len = strlen(dump);
555
556                 /*
557                  * Read a whole line from the file. If the line is too long
558                  * or is not terminated, reports an error and exit.
559                  */
560                 if (dump[len - 1] != '\n') {
561                         fprintf(stderr,
562                         "Line %d not corrected terminated or too long\n",
563                                 lineno);
564                         ret = -1;
565                         break;
566                 }
567
568                 /* Drop ending line feed / carriage return */
569                 while (len > 0 && (dump[len - 1] == '\n' ||
570                                 dump[len - 1] == '\r')) {
571                         dump[len - 1] = '\0';
572                         len--;
573                 }
574
575                 /* Skip comment or empty lines */
576                 if ((len == 0) || dump[0] == '#')
577                         continue;
578
579                 /*
580                  * Search for variable's name,
581                  * remove leading whitespaces
582                  */
583                 name = skip_blanks(dump);
584                 if (!name)
585                         continue;
586
587                 /* The first white space is the end of variable name */
588                 val = skip_chars(name);
589                 len = strlen(name);
590                 if (val) {
591                         *val++ = '\0';
592                         if ((val - name) < len)
593                                 val = skip_blanks(val);
594                         else
595                                 val = NULL;
596                 }
597
598 #ifdef DEBUG
599                 fprintf(stderr, "Setting %s : %s\n",
600                         name, val ? val : " removed");
601 #endif
602
603                 if (env_flags_validate_type(name, val) < 0) {
604                         ret = -1;
605                         break;
606                 }
607
608                 /*
609                  * If there is an error setting a variable,
610                  * try to save the environment and returns an error
611                  */
612                 if (fw_env_write(name, val)) {
613                         fprintf(stderr,
614                         "fw_env_write returns with error : %s\n",
615                                 strerror(errno));
616                         ret = -1;
617                         break;
618                 }
619
620         }
621
622         /* Close file if not stdin */
623         if (strcmp(fname, "-") != 0)
624                 fclose(fp);
625
626         ret |= fw_env_close();
627
628         return ret;
629
630 }
631
632 /*
633  * Test for bad block on NAND, just returns 0 on NOR, on NAND:
634  * 0    - block is good
635  * > 0  - block is bad
636  * < 0  - failed to test
637  */
638 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
639 {
640         if (mtd_type == MTD_NANDFLASH) {
641                 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
642
643                 if (badblock < 0) {
644                         perror ("Cannot read bad block mark");
645                         return badblock;
646                 }
647
648                 if (badblock) {
649 #ifdef DEBUG
650                         fprintf (stderr, "Bad block at 0x%llx, "
651                                  "skipping\n", *blockstart);
652 #endif
653                         return badblock;
654                 }
655         }
656
657         return 0;
658 }
659
660 /*
661  * Read data from flash at an offset into a provided buffer. On NAND it skips
662  * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
663  * the DEVOFFSET (dev) block. On NOR the loop is only run once.
664  */
665 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
666                            off_t offset, uint8_t mtd_type)
667 {
668         size_t blocklen;        /* erase / write length - one block on NAND,
669                                    0 on NOR */
670         size_t processed = 0;   /* progress counter */
671         size_t readlen = count; /* current read length */
672         off_t top_of_range;     /* end of the last block we may use */
673         off_t block_seek;       /* offset inside the current block to the start
674                                    of the data */
675         loff_t blockstart;      /* running start of the current block -
676                                    MEMGETBADBLOCK needs 64 bits */
677         int rc;
678
679         blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
680
681         /* Offset inside a block */
682         block_seek = offset - blockstart;
683
684         if (mtd_type == MTD_NANDFLASH) {
685                 /*
686                  * NAND: calculate which blocks we are reading. We have
687                  * to read one block at a time to skip bad blocks.
688                  */
689                 blocklen = DEVESIZE (dev);
690
691                 /*
692                  * To calculate the top of the range, we have to use the
693                  * global DEVOFFSET (dev), which can be different from offset
694                  */
695                 top_of_range = ((DEVOFFSET(dev) / blocklen) +
696                                 ENVSECTORS (dev)) * blocklen;
697
698                 /* Limit to one block for the first read */
699                 if (readlen > blocklen - block_seek)
700                         readlen = blocklen - block_seek;
701         } else {
702                 blocklen = 0;
703                 top_of_range = offset + count;
704         }
705
706         /* This only runs once on NOR flash */
707         while (processed < count) {
708                 rc = flash_bad_block (fd, mtd_type, &blockstart);
709                 if (rc < 0)             /* block test failed */
710                         return -1;
711
712                 if (blockstart + block_seek + readlen > top_of_range) {
713                         /* End of range is reached */
714                         fprintf (stderr,
715                                  "Too few good blocks within range\n");
716                         return -1;
717                 }
718
719                 if (rc) {               /* block is bad */
720                         blockstart += blocklen;
721                         continue;
722                 }
723
724                 /*
725                  * If a block is bad, we retry in the next block at the same
726                  * offset - see common/env_nand.c::writeenv()
727                  */
728                 lseek (fd, blockstart + block_seek, SEEK_SET);
729
730                 rc = read (fd, buf + processed, readlen);
731                 if (rc != readlen) {
732                         fprintf (stderr, "Read error on %s: %s\n",
733                                  DEVNAME (dev), strerror (errno));
734                         return -1;
735                 }
736 #ifdef DEBUG
737                 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
738                          rc, blockstart + block_seek, DEVNAME(dev));
739 #endif
740                 processed += readlen;
741                 readlen = min (blocklen, count - processed);
742                 block_seek = 0;
743                 blockstart += blocklen;
744         }
745
746         return processed;
747 }
748
749 /*
750  * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
751  * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
752  * erase and write the whole data at once.
753  */
754 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
755                             off_t offset, uint8_t mtd_type)
756 {
757         void *data;
758         struct erase_info_user erase;
759         size_t blocklen;        /* length of NAND block / NOR erase sector */
760         size_t erase_len;       /* whole area that can be erased - may include
761                                    bad blocks */
762         size_t erasesize;       /* erase / write length - one block on NAND,
763                                    whole area on NOR */
764         size_t processed = 0;   /* progress counter */
765         size_t write_total;     /* total size to actually write - excluding
766                                    bad blocks */
767         off_t erase_offset;     /* offset to the first erase block (aligned)
768                                    below offset */
769         off_t block_seek;       /* offset inside the erase block to the start
770                                    of the data */
771         off_t top_of_range;     /* end of the last block we may use */
772         loff_t blockstart;      /* running start of the current block -
773                                    MEMGETBADBLOCK needs 64 bits */
774         int rc;
775
776         /*
777          * For mtd devices only offset and size of the environment do matter
778          */
779         if (mtd_type == MTD_ABSENT) {
780                 blocklen = count;
781                 top_of_range = offset + count;
782                 erase_len = blocklen;
783                 blockstart = offset;
784                 block_seek = 0;
785                 write_total = blocklen;
786         } else {
787                 blocklen = DEVESIZE(dev);
788
789                 top_of_range = ((DEVOFFSET(dev) / blocklen) +
790                                         ENVSECTORS(dev)) * blocklen;
791
792                 erase_offset = (offset / blocklen) * blocklen;
793
794                 /* Maximum area we may use */
795                 erase_len = top_of_range - erase_offset;
796
797                 blockstart = erase_offset;
798                 /* Offset inside a block */
799                 block_seek = offset - erase_offset;
800
801                 /*
802                  * Data size we actually write: from the start of the block
803                  * to the start of the data, then count bytes of data, and
804                  * to the end of the block
805                  */
806                 write_total = ((block_seek + count + blocklen - 1) /
807                                                         blocklen) * blocklen;
808         }
809
810         /*
811          * Support data anywhere within erase sectors: read out the complete
812          * area to be erased, replace the environment image, write the whole
813          * block back again.
814          */
815         if (write_total > count) {
816                 data = malloc (erase_len);
817                 if (!data) {
818                         fprintf (stderr,
819                                  "Cannot malloc %zu bytes: %s\n",
820                                  erase_len, strerror (errno));
821                         return -1;
822                 }
823
824                 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
825                                      mtd_type);
826                 if (write_total != rc)
827                         return -1;
828
829 #ifdef DEBUG
830                 fprintf(stderr, "Preserving data ");
831                 if (block_seek != 0)
832                         fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
833                 if (block_seek + count != write_total) {
834                         if (block_seek != 0)
835                                 fprintf(stderr, " and ");
836                         fprintf(stderr, "0x%lx - 0x%x",
837                                 block_seek + count, write_total - 1);
838                 }
839                 fprintf(stderr, "\n");
840 #endif
841                 /* Overwrite the old environment */
842                 memcpy (data + block_seek, buf, count);
843         } else {
844                 /*
845                  * We get here, iff offset is block-aligned and count is a
846                  * multiple of blocklen - see write_total calculation above
847                  */
848                 data = buf;
849         }
850
851         if (mtd_type == MTD_NANDFLASH) {
852                 /*
853                  * NAND: calculate which blocks we are writing. We have
854                  * to write one block at a time to skip bad blocks.
855                  */
856                 erasesize = blocklen;
857         } else {
858                 erasesize = erase_len;
859         }
860
861         erase.length = erasesize;
862
863         /* This only runs once on NOR flash and SPI-dataflash */
864         while (processed < write_total) {
865                 rc = flash_bad_block (fd, mtd_type, &blockstart);
866                 if (rc < 0)             /* block test failed */
867                         return rc;
868
869                 if (blockstart + erasesize > top_of_range) {
870                         fprintf (stderr, "End of range reached, aborting\n");
871                         return -1;
872                 }
873
874                 if (rc) {               /* block is bad */
875                         blockstart += blocklen;
876                         continue;
877                 }
878
879                 if (mtd_type != MTD_ABSENT) {
880                         erase.start = blockstart;
881                         ioctl(fd, MEMUNLOCK, &erase);
882                         /* These do not need an explicit erase cycle */
883                         if (mtd_type != MTD_DATAFLASH)
884                                 if (ioctl(fd, MEMERASE, &erase) != 0) {
885                                         fprintf(stderr,
886                                                 "MTD erase error on %s: %s\n",
887                                                 DEVNAME(dev), strerror(errno));
888                                         return -1;
889                                 }
890                 }
891
892                 if (lseek (fd, blockstart, SEEK_SET) == -1) {
893                         fprintf (stderr,
894                                  "Seek error on %s: %s\n",
895                                  DEVNAME (dev), strerror (errno));
896                         return -1;
897                 }
898
899 #ifdef DEBUG
900                 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
901                         blockstart);
902 #endif
903                 if (write (fd, data + processed, erasesize) != erasesize) {
904                         fprintf (stderr, "Write error on %s: %s\n",
905                                  DEVNAME (dev), strerror (errno));
906                         return -1;
907                 }
908
909                 if (mtd_type != MTD_ABSENT)
910                         ioctl(fd, MEMLOCK, &erase);
911
912                 processed  += erasesize;
913                 block_seek = 0;
914                 blockstart += erasesize;
915         }
916
917         if (write_total > count)
918                 free (data);
919
920         return processed;
921 }
922
923 /*
924  * Set obsolete flag at offset - NOR flash only
925  */
926 static int flash_flag_obsolete (int dev, int fd, off_t offset)
927 {
928         int rc;
929         struct erase_info_user erase;
930
931         erase.start  = DEVOFFSET (dev);
932         erase.length = DEVESIZE (dev);
933         /* This relies on the fact, that obsolete_flag == 0 */
934         rc = lseek (fd, offset, SEEK_SET);
935         if (rc < 0) {
936                 fprintf (stderr, "Cannot seek to set the flag on %s \n",
937                          DEVNAME (dev));
938                 return rc;
939         }
940         ioctl (fd, MEMUNLOCK, &erase);
941         rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
942         ioctl (fd, MEMLOCK, &erase);
943         if (rc < 0)
944                 perror ("Could not set obsolete flag");
945
946         return rc;
947 }
948
949 /* Encrypt or decrypt the environment before writing or reading it. */
950 static int env_aes_cbc_crypt(char *payload, const int enc)
951 {
952         uint8_t *data = (uint8_t *)payload;
953         const int len = getenvsize();
954         uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
955         uint32_t aes_blocks;
956
957         /* First we expand the key. */
958         aes_expand_key(common_args.aes_key, key_exp);
959
960         /* Calculate the number of AES blocks to encrypt. */
961         aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
962
963         if (enc)
964                 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
965         else
966                 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
967
968         return 0;
969 }
970
971 static int flash_write (int fd_current, int fd_target, int dev_target)
972 {
973         int rc;
974
975         switch (environment.flag_scheme) {
976         case FLAG_NONE:
977                 break;
978         case FLAG_INCREMENTAL:
979                 (*environment.flags)++;
980                 break;
981         case FLAG_BOOLEAN:
982                 *environment.flags = active_flag;
983                 break;
984         default:
985                 fprintf (stderr, "Unimplemented flash scheme %u \n",
986                          environment.flag_scheme);
987                 return -1;
988         }
989
990 #ifdef DEBUG
991         fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
992                 DEVOFFSET (dev_target), DEVNAME (dev_target));
993 #endif
994
995         rc = flash_write_buf(dev_target, fd_target, environment.image,
996                               CUR_ENVSIZE, DEVOFFSET(dev_target),
997                               DEVTYPE(dev_target));
998         if (rc < 0)
999                 return rc;
1000
1001         if (environment.flag_scheme == FLAG_BOOLEAN) {
1002                 /* Have to set obsolete flag */
1003                 off_t offset = DEVOFFSET (dev_current) +
1004                         offsetof (struct env_image_redundant, flags);
1005 #ifdef DEBUG
1006                 fprintf(stderr,
1007                         "Setting obsolete flag in environment at 0x%lx on %s\n",
1008                         DEVOFFSET (dev_current), DEVNAME (dev_current));
1009 #endif
1010                 flash_flag_obsolete (dev_current, fd_current, offset);
1011         }
1012
1013         return 0;
1014 }
1015
1016 static int flash_read (int fd)
1017 {
1018         struct mtd_info_user mtdinfo;
1019         struct stat st;
1020         int rc;
1021
1022         rc = fstat(fd, &st);
1023         if (rc < 0) {
1024                 fprintf(stderr, "Cannot stat the file %s\n",
1025                         DEVNAME(dev_current));
1026                 return -1;
1027         }
1028
1029         if (S_ISCHR(st.st_mode)) {
1030                 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1031                 if (rc < 0) {
1032                         fprintf(stderr, "Cannot get MTD information for %s\n",
1033                                 DEVNAME(dev_current));
1034                         return -1;
1035                 }
1036                 if (mtdinfo.type != MTD_NORFLASH &&
1037                     mtdinfo.type != MTD_NANDFLASH &&
1038                     mtdinfo.type != MTD_DATAFLASH &&
1039                     mtdinfo.type != MTD_UBIVOLUME) {
1040                         fprintf (stderr, "Unsupported flash type %u on %s\n",
1041                                  mtdinfo.type, DEVNAME(dev_current));
1042                         return -1;
1043                 }
1044         } else {
1045                 memset(&mtdinfo, 0, sizeof(mtdinfo));
1046                 mtdinfo.type = MTD_ABSENT;
1047         }
1048
1049         DEVTYPE(dev_current) = mtdinfo.type;
1050
1051         rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1052                              DEVOFFSET (dev_current), mtdinfo.type);
1053         if (rc != CUR_ENVSIZE)
1054                 return -1;
1055
1056         return 0;
1057 }
1058
1059 static int flash_io (int mode)
1060 {
1061         int fd_current, fd_target, rc, dev_target;
1062
1063         /* dev_current: fd_current, erase_current */
1064         fd_current = open (DEVNAME (dev_current), mode);
1065         if (fd_current < 0) {
1066                 fprintf (stderr,
1067                          "Can't open %s: %s\n",
1068                          DEVNAME (dev_current), strerror (errno));
1069                 return -1;
1070         }
1071
1072         if (mode == O_RDWR) {
1073                 if (HaveRedundEnv) {
1074                         /* switch to next partition for writing */
1075                         dev_target = !dev_current;
1076                         /* dev_target: fd_target, erase_target */
1077                         fd_target = open (DEVNAME (dev_target), mode);
1078                         if (fd_target < 0) {
1079                                 fprintf (stderr,
1080                                          "Can't open %s: %s\n",
1081                                          DEVNAME (dev_target),
1082                                          strerror (errno));
1083                                 rc = -1;
1084                                 goto exit;
1085                         }
1086                 } else {
1087                         dev_target = dev_current;
1088                         fd_target = fd_current;
1089                 }
1090
1091                 rc = flash_write (fd_current, fd_target, dev_target);
1092
1093                 if (HaveRedundEnv) {
1094                         if (close (fd_target)) {
1095                                 fprintf (stderr,
1096                                         "I/O error on %s: %s\n",
1097                                         DEVNAME (dev_target),
1098                                         strerror (errno));
1099                                 rc = -1;
1100                         }
1101                 }
1102         } else {
1103                 rc = flash_read (fd_current);
1104         }
1105
1106 exit:
1107         if (close (fd_current)) {
1108                 fprintf (stderr,
1109                          "I/O error on %s: %s\n",
1110                          DEVNAME (dev_current), strerror (errno));
1111                 return -1;
1112         }
1113
1114         return rc;
1115 }
1116
1117 /*
1118  * s1 is either a simple 'name', or a 'name=value' pair.
1119  * s2 is a 'name=value' pair.
1120  * If the names match, return the value of s2, else NULL.
1121  */
1122
1123 static char *envmatch (char * s1, char * s2)
1124 {
1125         if (s1 == NULL || s2 == NULL)
1126                 return NULL;
1127
1128         while (*s1 == *s2++)
1129                 if (*s1++ == '=')
1130                         return s2;
1131         if (*s1 == '\0' && *(s2 - 1) == '=')
1132                 return s2;
1133         return NULL;
1134 }
1135
1136 /*
1137  * Prevent confusion if running from erased flash memory
1138  */
1139 int fw_env_open(void)
1140 {
1141         int crc0, crc0_ok;
1142         unsigned char flag0;
1143         void *addr0;
1144
1145         int crc1, crc1_ok;
1146         unsigned char flag1;
1147         void *addr1;
1148
1149         int ret;
1150
1151         struct env_image_single *single;
1152         struct env_image_redundant *redundant;
1153
1154         if (parse_config ())            /* should fill envdevices */
1155                 return -1;
1156
1157         addr0 = calloc(1, CUR_ENVSIZE);
1158         if (addr0 == NULL) {
1159                 fprintf(stderr,
1160                         "Not enough memory for environment (%ld bytes)\n",
1161                         CUR_ENVSIZE);
1162                 return -1;
1163         }
1164
1165         /* read environment from FLASH to local buffer */
1166         environment.image = addr0;
1167
1168         if (HaveRedundEnv) {
1169                 redundant = addr0;
1170                 environment.crc         = &redundant->crc;
1171                 environment.flags       = &redundant->flags;
1172                 environment.data        = redundant->data;
1173         } else {
1174                 single = addr0;
1175                 environment.crc         = &single->crc;
1176                 environment.flags       = NULL;
1177                 environment.data        = single->data;
1178         }
1179
1180         dev_current = 0;
1181         if (flash_io (O_RDONLY))
1182                 return -1;
1183
1184         crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1185
1186         if (common_args.aes_flag) {
1187                 ret = env_aes_cbc_crypt(environment.data, 0);
1188                 if (ret)
1189                         return ret;
1190         }
1191
1192         crc0_ok = (crc0 == *environment.crc);
1193         if (!HaveRedundEnv) {
1194                 if (!crc0_ok) {
1195                         fprintf (stderr,
1196                                 "Warning: Bad CRC, using default environment\n");
1197                         memcpy(environment.data, default_environment, sizeof default_environment);
1198                 }
1199         } else {
1200                 flag0 = *environment.flags;
1201
1202                 dev_current = 1;
1203                 addr1 = calloc(1, CUR_ENVSIZE);
1204                 if (addr1 == NULL) {
1205                         fprintf(stderr,
1206                                 "Not enough memory for environment (%ld bytes)\n",
1207                                 CUR_ENVSIZE);
1208                         return -1;
1209                 }
1210                 redundant = addr1;
1211
1212                 /*
1213                  * have to set environment.image for flash_read(), careful -
1214                  * other pointers in environment still point inside addr0
1215                  */
1216                 environment.image = addr1;
1217                 if (flash_io (O_RDONLY))
1218                         return -1;
1219
1220                 /* Check flag scheme compatibility */
1221                 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1222                     DEVTYPE(!dev_current) == MTD_NORFLASH) {
1223                         environment.flag_scheme = FLAG_BOOLEAN;
1224                 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1225                            DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1226                         environment.flag_scheme = FLAG_INCREMENTAL;
1227                 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1228                            DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1229                         environment.flag_scheme = FLAG_BOOLEAN;
1230                 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1231                            DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1232                         environment.flag_scheme = FLAG_INCREMENTAL;
1233                 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1234                            DEVTYPE(!dev_current) == MTD_ABSENT) {
1235                         environment.flag_scheme = FLAG_INCREMENTAL;
1236                 } else {
1237                         fprintf (stderr, "Incompatible flash types!\n");
1238                         return -1;
1239                 }
1240
1241                 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1242
1243                 if (common_args.aes_flag) {
1244                         ret = env_aes_cbc_crypt(redundant->data, 0);
1245                         if (ret)
1246                                 return ret;
1247                 }
1248
1249                 crc1_ok = (crc1 == redundant->crc);
1250                 flag1 = redundant->flags;
1251
1252                 if (crc0_ok && !crc1_ok) {
1253                         dev_current = 0;
1254                 } else if (!crc0_ok && crc1_ok) {
1255                         dev_current = 1;
1256                 } else if (!crc0_ok && !crc1_ok) {
1257                         fprintf (stderr,
1258                                 "Warning: Bad CRC, using default environment\n");
1259                         memcpy (environment.data, default_environment,
1260                                 sizeof default_environment);
1261                         dev_current = 0;
1262                 } else {
1263                         switch (environment.flag_scheme) {
1264                         case FLAG_BOOLEAN:
1265                                 if (flag0 == active_flag &&
1266                                     flag1 == obsolete_flag) {
1267                                         dev_current = 0;
1268                                 } else if (flag0 == obsolete_flag &&
1269                                            flag1 == active_flag) {
1270                                         dev_current = 1;
1271                                 } else if (flag0 == flag1) {
1272                                         dev_current = 0;
1273                                 } else if (flag0 == 0xFF) {
1274                                         dev_current = 0;
1275                                 } else if (flag1 == 0xFF) {
1276                                         dev_current = 1;
1277                                 } else {
1278                                         dev_current = 0;
1279                                 }
1280                                 break;
1281                         case FLAG_INCREMENTAL:
1282                                 if (flag0 == 255 && flag1 == 0)
1283                                         dev_current = 1;
1284                                 else if ((flag1 == 255 && flag0 == 0) ||
1285                                          flag0 >= flag1)
1286                                         dev_current = 0;
1287                                 else /* flag1 > flag0 */
1288                                         dev_current = 1;
1289                                 break;
1290                         default:
1291                                 fprintf (stderr, "Unknown flag scheme %u \n",
1292                                          environment.flag_scheme);
1293                                 return -1;
1294                         }
1295                 }
1296
1297                 /*
1298                  * If we are reading, we don't need the flag and the CRC any
1299                  * more, if we are writing, we will re-calculate CRC and update
1300                  * flags before writing out
1301                  */
1302                 if (dev_current) {
1303                         environment.image       = addr1;
1304                         environment.crc         = &redundant->crc;
1305                         environment.flags       = &redundant->flags;
1306                         environment.data        = redundant->data;
1307                         free (addr0);
1308                 } else {
1309                         environment.image       = addr0;
1310                         /* Other pointers are already set */
1311                         free (addr1);
1312                 }
1313 #ifdef DEBUG
1314                 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1315 #endif
1316         }
1317         return 0;
1318 }
1319
1320
1321 static int parse_config ()
1322 {
1323         struct stat st;
1324
1325 #if defined(CONFIG_FILE)
1326         /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1327         if (get_config(common_args.config_file)) {
1328                 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1329                         common_args.config_file);
1330                 return -1;
1331         }
1332 #else
1333         DEVNAME (0) = DEVICE1_NAME;
1334         DEVOFFSET (0) = DEVICE1_OFFSET;
1335         ENVSIZE (0) = ENV1_SIZE;
1336         /* Default values are: erase-size=env-size */
1337         DEVESIZE (0) = ENVSIZE (0);
1338         /* #sectors=env-size/erase-size (rounded up) */
1339         ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1340 #ifdef DEVICE1_ESIZE
1341         DEVESIZE (0) = DEVICE1_ESIZE;
1342 #endif
1343 #ifdef DEVICE1_ENVSECTORS
1344         ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1345 #endif
1346
1347 #ifdef HAVE_REDUND
1348         DEVNAME (1) = DEVICE2_NAME;
1349         DEVOFFSET (1) = DEVICE2_OFFSET;
1350         ENVSIZE (1) = ENV2_SIZE;
1351         /* Default values are: erase-size=env-size */
1352         DEVESIZE (1) = ENVSIZE (1);
1353         /* #sectors=env-size/erase-size (rounded up) */
1354         ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1355 #ifdef DEVICE2_ESIZE
1356         DEVESIZE (1) = DEVICE2_ESIZE;
1357 #endif
1358 #ifdef DEVICE2_ENVSECTORS
1359         ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1360 #endif
1361         HaveRedundEnv = 1;
1362 #endif
1363 #endif
1364         if (stat (DEVNAME (0), &st)) {
1365                 fprintf (stderr,
1366                         "Cannot access MTD device %s: %s\n",
1367                         DEVNAME (0), strerror (errno));
1368                 return -1;
1369         }
1370
1371         if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1372                 fprintf (stderr,
1373                         "Cannot access MTD device %s: %s\n",
1374                         DEVNAME (1), strerror (errno));
1375                 return -1;
1376         }
1377         return 0;
1378 }
1379
1380 #if defined(CONFIG_FILE)
1381 static int get_config (char *fname)
1382 {
1383         FILE *fp;
1384         int i = 0;
1385         int rc;
1386         char dump[128];
1387         char *devname;
1388
1389         fp = fopen (fname, "r");
1390         if (fp == NULL)
1391                 return -1;
1392
1393         while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1394                 /* Skip incomplete conversions and comment strings */
1395                 if (dump[0] == '#')
1396                         continue;
1397
1398                 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1399                              &devname,
1400                              &DEVOFFSET (i),
1401                              &ENVSIZE (i),
1402                              &DEVESIZE (i),
1403                              &ENVSECTORS (i));
1404
1405                 if (rc < 3)
1406                         continue;
1407
1408                 DEVNAME(i) = devname;
1409
1410                 if (rc < 4)
1411                         /* Assume the erase size is the same as the env-size */
1412                         DEVESIZE(i) = ENVSIZE(i);
1413
1414                 if (rc < 5)
1415                         /* Assume enough env sectors to cover the environment */
1416                         ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1417
1418                 i++;
1419         }
1420         fclose (fp);
1421
1422         HaveRedundEnv = i - 1;
1423         if (!i) {                       /* No valid entries found */
1424                 errno = EINVAL;
1425                 return -1;
1426         } else
1427                 return 0;
1428 }
1429 #endif