fritz-tools: add support for IPQ40xx platform
[openwrt/openwrt.git] / package / utils / fritz-tools / src / fritz_tffs_nand_read.c
1 /*
2 * A tool for reading the TFFS partitions (a name-value storage usually
3 * found in AVM Fritz!Box based devices) on nand flash.
4 *
5 * Copyright (c) 2018 Valentin Spreckels <Valentin.Spreckels@Informatik.Uni-Oldenburg.DE>
6 *
7 * Based on the fritz_tffs_read tool:
8 * Copyright (c) 2015-2016 Martin Blumenstingl <martin.blumenstingl@googlemail.com>
9 * and on the TFFS 2.0 kernel driver from AVM:
10 * Copyright (c) 2004-2007 AVM GmbH <fritzbox_info@avm.de>
11 * and the TFFS 3.0 kernel driver from AVM:
12 * Copyright (C) 2004-2014 AVM GmbH <fritzbox_info@avm.de>
13 * and the OpenWrt TFFS kernel driver:
14 * Copyright (c) 2013 John Crispin <john@phrozen.org>
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License along
27 * with this program; if not, write to the Free Software Foundation, Inc.,
28 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 */
30
31 #include <stdbool.h>
32 #include <stddef.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <stdint.h>
36 #include <string.h>
37 #include <libgen.h>
38 #include <getopt.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <endian.h>
42 #include <sys/ioctl.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <arpa/inet.h>
46 #include <mtd/mtd-user.h>
47 #include <assert.h>
48
49 #define DEFAULT_TFFS_SIZE (256 * 1024)
50
51 #define TFFS_ID_END 0xffffffff
52 #define TFFS_ID_TABLE_NAME 0x000001ff
53
54 #define TFFS_BLOCK_HEADER_MAGIC 0x41564d5f54464653ULL
55 #define TFFS_VERSION 0x0003
56 #define TFFS_ENTRY_HEADER_SIZE 0x18
57 #define TFFS_MAXIMUM_SEGMENT_SIZE (0x800 - TFFS_ENTRY_HEADER_SIZE)
58
59 #define TFFS_SECTOR_SIZE 0x0800
60 #define TFFS_SECTOR_OOB_SIZE 0x0040
61 #define TFFS_SECTORS_PER_PAGE 2
62
63 #define TFFS_SEGMENT_CLEARED 0xffffffff
64
65 static char *progname;
66 static char *mtddev;
67 static char *name_filter = NULL;
68 static bool show_all = false;
69 static bool print_all_key_names = false;
70 static bool read_oob_sector_health = false;
71 static bool swap_bytes = false;
72 static uint8_t readbuf[TFFS_SECTOR_SIZE];
73 static uint8_t oobbuf[TFFS_SECTOR_OOB_SIZE];
74 static uint32_t blocksize;
75 static int mtdfd;
76 struct tffs_sectors *sectors;
77
78 struct tffs_sectors {
79 uint32_t num_sectors;
80 uint8_t sectors[0];
81 };
82
83 static inline void sector_mark_bad(int num)
84 {
85 sectors->sectors[num / 8] &= ~(0x80 >> (num % 8));
86 };
87
88 static inline uint8_t sector_get_good(int num)
89 {
90 return sectors->sectors[num / 8] & 0x80 >> (num % 8);
91 };
92
93 struct tffs_entry_segment {
94 uint32_t len;
95 void *val;
96 };
97
98 struct tffs_entry {
99 uint32_t len;
100 void *val;
101 };
102
103 struct tffs_name_table_entry {
104 uint32_t id;
105 char *val;
106 };
107
108 struct tffs_key_name_table {
109 uint32_t size;
110 struct tffs_name_table_entry *entries;
111 };
112
113 static inline uint8_t read_uint8(void *buf, ptrdiff_t off)
114 {
115 return *(uint8_t *)(buf + off);
116 }
117
118 static inline uint32_t read_uint32(void *buf, ptrdiff_t off)
119 {
120 uint32_t tmp = *(uint32_t *)(buf + off);
121 if (swap_bytes) {
122 tmp = be32toh(tmp);
123 }
124 return tmp;
125 }
126
127 static inline uint64_t read_uint64(void *buf, ptrdiff_t off)
128 {
129 uint64_t tmp = *(uint64_t *)(buf + off);
130 if (swap_bytes) {
131 tmp = be64toh(tmp);
132 }
133 return tmp;
134 }
135
136 static int read_sector(off_t pos)
137 {
138 if (pread(mtdfd, readbuf, TFFS_SECTOR_SIZE, pos) != TFFS_SECTOR_SIZE) {
139 return -1;
140 }
141
142 return 0;
143 }
144
145 static int read_sectoroob(off_t pos)
146 {
147 struct mtd_oob_buf oob = {
148 .start = pos,
149 .length = TFFS_SECTOR_OOB_SIZE,
150 .ptr = oobbuf
151 };
152
153 if (ioctl(mtdfd, MEMREADOOB, &oob) < 0) {
154 return -1;
155 }
156
157 return 0;
158 }
159
160 static inline uint32_t get_walk_size(uint32_t entry_len)
161 {
162 return (entry_len + 3) & ~0x03;
163 }
164
165 static void print_entry_value(const struct tffs_entry *entry)
166 {
167 /* These are NOT NULL terminated. */
168 fwrite(entry->val, 1, entry->len, stdout);
169 }
170
171 static int find_entry(uint32_t id, struct tffs_entry *entry)
172 {
173 uint32_t rev = 0;
174 uint32_t num_segments = 0;
175 struct tffs_entry_segment *segments = NULL;
176
177 off_t pos = 0;
178 uint8_t block_end = 0;
179 for (uint32_t sector = 0; sector < sectors->num_sectors; sector++, pos += TFFS_SECTOR_SIZE) {
180 if (block_end) {
181 if (pos % blocksize == 0) {
182 block_end = 0;
183 }
184 } else if (sector_get_good(sector)) {
185 if (read_sectoroob(pos) || read_sector(pos)) {
186 fprintf(stderr, "ERROR: sector isn't readable, but has been previously!\n");
187 exit(EXIT_FAILURE);
188 }
189 uint32_t oob_id = read_uint32(oobbuf, 0x02);
190 uint32_t oob_len = read_uint32(oobbuf, 0x06);
191 uint32_t oob_rev = read_uint32(oobbuf, 0x0a);
192 uint32_t read_id = read_uint32(readbuf, 0x00);
193 uint32_t read_len = read_uint32(readbuf, 0x04);
194 uint32_t read_rev = read_uint32(readbuf, 0x0c);
195 if (read_oob_sector_health && (oob_id != read_id || oob_len != read_len || oob_rev != read_rev)) {
196 fprintf(stderr, "Warning: sector has inconsistent metadata\n");
197 continue;
198 }
199 if (read_id == TFFS_ID_END) {
200 /* no more entries in this block */
201 block_end = 1;
202 continue;
203 }
204 if (read_len > TFFS_MAXIMUM_SEGMENT_SIZE) {
205 fprintf(stderr, "Warning: segment is longer than possible\n");
206 continue;
207 }
208 if (read_id == id) {
209 if (read_rev < rev) {
210 /* obsolete revision => ignore this */
211 continue;
212 }
213 if (read_rev > rev) {
214 /* newer revision => clear old data */
215 for (uint32_t i = 0; i < num_segments; i++) {
216 free(segments[i].val);
217 }
218 free (segments);
219 rev = read_rev;
220 num_segments = 0;
221 segments = NULL;
222 }
223
224 uint32_t seg = read_uint32(readbuf, 0x10);
225
226 if (seg == TFFS_SEGMENT_CLEARED) {
227 continue;
228 }
229
230 uint32_t next_seg = read_uint32(readbuf, 0x14);
231
232 uint32_t new_num_segs = next_seg == 0 ? seg + 1 : next_seg + 1;
233 if (new_num_segs > num_segments) {
234 segments = realloc(segments, new_num_segs * sizeof(struct tffs_entry_segment));
235 memset(segments + (num_segments * sizeof(struct tffs_entry_segment)), 0x0,
236 (new_num_segs - num_segments) * sizeof(struct tffs_entry_segment));
237 num_segments = new_num_segs;
238 }
239 segments[seg].len = read_len;
240 segments[seg].val = malloc(read_len);
241 memcpy(segments[seg].val, readbuf + TFFS_ENTRY_HEADER_SIZE, read_len);
242 }
243 }
244 }
245
246 if (num_segments == 0) {
247 return 0;
248 }
249
250 assert (segments != NULL);
251
252 uint32_t len = 0;
253 for (uint32_t i = 0; i < num_segments; i++) {
254 if (segments[i].val == NULL) {
255 /* missing segment */
256 return 0;
257 }
258
259 len += segments[i].len;
260 }
261
262 void *p = malloc(len);
263 entry->val = p;
264 entry->len = len;
265 for (uint32_t i = 0; i < num_segments; i++) {
266 memcpy(p, segments[i].val, segments[i].len);
267 p += segments[i].len;
268 }
269
270 return 1;
271 }
272
273 static void parse_key_names(struct tffs_entry *names_entry,
274 struct tffs_key_name_table *key_names)
275 {
276 uint32_t pos = 0, i = 0;
277 struct tffs_name_table_entry *name_item;
278
279 key_names->entries = NULL;
280
281 do {
282 key_names->entries = realloc(key_names->entries,
283 sizeof(struct tffs_name_table_entry) * (i + 1));
284 if (key_names->entries == NULL) {
285 fprintf(stderr, "ERROR: memory allocation failed!\n");
286 exit(EXIT_FAILURE);
287 }
288 name_item = &key_names->entries[i];
289
290 name_item->id = read_uint32(names_entry->val, pos);
291 pos += sizeof(uint32_t);
292 name_item->val = strdup((const char *)(names_entry->val + pos));
293
294 /*
295 * There is no "length" field because the string values are
296 * simply NULL-terminated -> strlen() gives us the size.
297 */
298 pos += get_walk_size(strlen(name_item->val) + 1);
299
300 ++i;
301 } while (pos < names_entry->len);
302
303 key_names->size = i;
304 }
305
306 static void show_all_key_names(struct tffs_key_name_table *key_names)
307 {
308 for (uint32_t i = 0; i < key_names->size; i++)
309 printf("%s\n", key_names->entries[i].val);
310 }
311
312 static int show_all_key_value_pairs(struct tffs_key_name_table *key_names)
313 {
314 uint8_t has_value = 0;
315 struct tffs_entry tmp;
316
317 for (uint32_t i = 0; i < key_names->size; i++) {
318 if (find_entry(key_names->entries[i].id, &tmp)) {
319 printf("%s=", (const char *)key_names->entries[i].val);
320 print_entry_value(&tmp);
321 printf("\n");
322 has_value++;
323 free(tmp.val);
324 }
325 }
326
327 if (!has_value) {
328 fprintf(stderr, "ERROR: no values found!\n");
329 return EXIT_FAILURE;
330 }
331
332 return EXIT_SUCCESS;
333 }
334
335 static int show_matching_key_value(struct tffs_key_name_table *key_names)
336 {
337 struct tffs_entry tmp;
338 const char *name;
339
340 for (uint32_t i = 0; i < key_names->size; i++) {
341 name = key_names->entries[i].val;
342
343 if (strncmp(name, name_filter, strlen(name)) == 0) {
344 if (find_entry(key_names->entries[i].id, &tmp)) {
345 print_entry_value(&tmp);
346 printf("\n");
347 free(tmp.val);
348 return EXIT_SUCCESS;
349 } else {
350 fprintf(stderr,
351 "ERROR: no value found for name %s!\n",
352 name);
353 return EXIT_FAILURE;
354 }
355 }
356 }
357
358 fprintf(stderr, "ERROR: Unknown key name %s!\n", name_filter);
359 return EXIT_FAILURE;
360 }
361
362 static int check_sector(off_t pos)
363 {
364 if (!read_oob_sector_health) {
365 return 1;
366 }
367 if (read_sectoroob(pos)) {
368 return 0;
369 }
370 if (read_uint8(oobbuf, 0x00) != 0xff) {
371 /* block is bad */
372 return 0;
373 }
374 if (read_uint8(oobbuf, 0x01) != 0xff) {
375 /* sector is bad */
376 return 0;
377 }
378 return 1;
379 }
380
381 static int check_block(off_t pos, uint32_t sector)
382 {
383 if (!check_sector(pos)) {
384 return 0;
385 }
386 if (read_sector(pos)) {
387 return 0;
388 }
389 if (read_uint64(readbuf, 0x00) != TFFS_BLOCK_HEADER_MAGIC) {
390 fprintf(stderr, "Warning: block without magic header. Skipping block\n");
391 return 0;
392 }
393 if (read_uint32(readbuf, 0x0c) != TFFS_SECTORS_PER_PAGE) {
394 fprintf(stderr, "Warning: block with wrong number of sectors per page. Skipping block\n");
395 return 0;
396 }
397
398 uint32_t num_hdr_bad = read_uint32(readbuf, 0x0c);
399 for (uint32_t i = 0; i < num_hdr_bad; i++) {
400 uint32_t bad = sector + read_uint64(readbuf, 0x1c + sizeof(uint64_t)*i);
401 sector_mark_bad(bad);
402 }
403
404 return 1;
405 }
406
407 static int scan_mtd(void)
408 {
409 struct mtd_info_user info;
410
411 if (ioctl(mtdfd, MEMGETINFO, &info)) {
412 return 0;
413 }
414
415 blocksize = info.erasesize;
416
417 sectors = malloc(sizeof(*sectors) + (info.size / TFFS_SECTOR_SIZE + 7) / 8);
418 if (sectors == NULL) {
419 fprintf(stderr, "ERROR: memory allocation failed!\n");
420 exit(EXIT_FAILURE);
421 }
422 sectors->num_sectors = info.size / TFFS_SECTOR_SIZE;
423 memset(sectors->sectors, 0xff, (info.size / TFFS_SECTOR_SIZE + 7) / 8);
424
425 uint32_t sector = 0, valid_blocks = 0;
426 uint8_t block_ok = 0;
427 for (off_t pos = 0; pos < info.size; sector++, pos += TFFS_SECTOR_SIZE) {
428 if (pos % info.erasesize == 0) {
429 block_ok = check_block(pos, sector);
430 /* first sector of the block contains metadata
431 => handle it like a bad sector */
432 sector_mark_bad(sector);
433 if (block_ok) {
434 valid_blocks++;
435 }
436 } else if (!block_ok || !sector_get_good(sector) || !check_sector(pos)) {
437 sector_mark_bad(sector);
438 }
439 }
440
441 return valid_blocks;
442 }
443
444 static void usage(int status)
445 {
446 FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
447
448 fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
449 fprintf(stream,
450 "\n"
451 "Options:\n"
452 " -a list all key value pairs found in the TFFS file/device\n"
453 " -d <mtd> inspect the TFFS on mtd device <mtd>\n"
454 " -h show this screen\n"
455 " -l list all supported keys\n"
456 " -n <key name> display the value of the given key\n"
457 " -o read OOB information about sector health\n"
458 );
459
460 exit(status);
461 }
462
463 static void parse_options(int argc, char *argv[])
464 {
465 while (1) {
466 int c;
467
468 c = getopt(argc, argv, "abd:hln:o");
469 if (c == -1)
470 break;
471
472 switch (c) {
473 case 'a':
474 show_all = true;
475 name_filter = NULL;
476 print_all_key_names = false;
477 break;
478 case 'b':
479 swap_bytes = 1;
480 break;
481 case 'd':
482 mtddev = optarg;
483 break;
484 case 'h':
485 usage(EXIT_SUCCESS);
486 break;
487 case 'l':
488 print_all_key_names = true;
489 show_all = false;
490 name_filter = NULL;
491 break;
492 case 'n':
493 name_filter = optarg;
494 show_all = false;
495 print_all_key_names = false;
496 break;
497 case 'o':
498 read_oob_sector_health = true;
499 break;
500 default:
501 usage(EXIT_FAILURE);
502 break;
503 }
504 }
505
506 if (!mtddev) {
507 fprintf(stderr, "ERROR: No input file (-d <file>) given!\n");
508 usage(EXIT_FAILURE);
509 }
510
511 if (!show_all && !name_filter && !print_all_key_names) {
512 fprintf(stderr,
513 "ERROR: either -l, -a or -n <key name> is required!\n");
514 usage(EXIT_FAILURE);
515 }
516 }
517
518 int main(int argc, char *argv[])
519 {
520 int ret = EXIT_FAILURE;
521 struct tffs_entry name_table;
522 struct tffs_key_name_table key_names;
523
524 progname = basename(argv[0]);
525
526 parse_options(argc, argv);
527
528 mtdfd = open(mtddev, O_RDONLY);
529 if (mtdfd < 0) {
530 fprintf(stderr, "ERROR: Failed to open tffs device %s\n",
531 mtddev);
532 goto out;
533 }
534
535 if (!scan_mtd()) {
536 fprintf(stderr, "ERROR: Parsing blocks from tffs device %s failed\n", mtddev);
537 fprintf(stderr, " Is byte-swapping (-b) required?\n");
538 goto out_close;
539 }
540
541 if (!find_entry(TFFS_ID_TABLE_NAME, &name_table)) {
542 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
543 mtddev);
544 goto out_free_sectors;
545 }
546
547 parse_key_names(&name_table, &key_names);
548 if (key_names.size < 1) {
549 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
550 mtddev);
551 goto out_free_entry;
552 }
553
554 if (print_all_key_names) {
555 show_all_key_names(&key_names);
556 ret = EXIT_SUCCESS;
557 } else if (show_all) {
558 ret = show_all_key_value_pairs(&key_names);
559 } else {
560 ret = show_matching_key_value(&key_names);
561 }
562
563 free(key_names.entries);
564 out_free_entry:
565 free(name_table.val);
566 out_free_sectors:
567 free(sectors);
568 out_close:
569 close(mtdfd);
570 out:
571 return ret;
572 }