29b4a5d2e5f220ed206c34688ba5a0bd105b4a4b
[openwrt/staging/hauke.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 static uint32_t num_sectors;
77 static uint8_t *sectors;
78
79 static inline void sector_mark_bad(int num)
80 {
81 sectors[num / 8] &= ~(0x80 >> (num % 8));
82 };
83
84 static inline uint8_t sector_get_good(int num)
85 {
86 return sectors[num / 8] & 0x80 >> (num % 8);
87 };
88
89 struct tffs_entry_segment {
90 uint32_t len;
91 void *val;
92 };
93
94 struct tffs_entry {
95 uint32_t len;
96 void *val;
97 };
98
99 struct tffs_name_table_entry {
100 uint32_t id;
101 char *val;
102 };
103
104 struct tffs_key_name_table {
105 uint32_t size;
106 struct tffs_name_table_entry *entries;
107 };
108
109 static inline uint8_t read_uint8(void *buf, ptrdiff_t off)
110 {
111 return *(uint8_t *)(buf + off);
112 }
113
114 static inline uint32_t read_uint32(void *buf, ptrdiff_t off)
115 {
116 uint32_t tmp = *(uint32_t *)(buf + off);
117 if (swap_bytes) {
118 tmp = be32toh(tmp);
119 }
120 return tmp;
121 }
122
123 static inline uint64_t read_uint64(void *buf, ptrdiff_t off)
124 {
125 uint64_t tmp = *(uint64_t *)(buf + off);
126 if (swap_bytes) {
127 tmp = be64toh(tmp);
128 }
129 return tmp;
130 }
131
132 static int read_sector(off_t pos)
133 {
134 if (pread(mtdfd, readbuf, TFFS_SECTOR_SIZE, pos) != TFFS_SECTOR_SIZE) {
135 return -1;
136 }
137
138 return 0;
139 }
140
141 static int read_sectoroob(off_t pos)
142 {
143 struct mtd_oob_buf oob = {
144 .start = pos,
145 .length = TFFS_SECTOR_OOB_SIZE,
146 .ptr = oobbuf
147 };
148
149 if (ioctl(mtdfd, MEMREADOOB, &oob) < 0) {
150 return -1;
151 }
152
153 return 0;
154 }
155
156 static inline uint32_t get_walk_size(uint32_t entry_len)
157 {
158 return (entry_len + 3) & ~0x03;
159 }
160
161 static void print_entry_value(const struct tffs_entry *entry)
162 {
163 /* These are NOT NULL terminated. */
164 fwrite(entry->val, 1, entry->len, stdout);
165 }
166
167 static int find_entry(uint32_t id, struct tffs_entry *entry)
168 {
169 uint32_t rev = 0;
170 uint32_t num_segments = 0;
171 struct tffs_entry_segment *segments = NULL;
172
173 off_t pos = 0;
174 uint8_t block_end = 0;
175 for (uint32_t sector = 0; sector < num_sectors; sector++, pos += TFFS_SECTOR_SIZE) {
176 if (block_end) {
177 if (pos % blocksize == 0) {
178 block_end = 0;
179 }
180 } else if (sector_get_good(sector)) {
181 if (read_sectoroob(pos) || read_sector(pos)) {
182 fprintf(stderr, "ERROR: sector isn't readable, but has been previously!\n");
183 exit(EXIT_FAILURE);
184 }
185 uint32_t read_id = read_uint32(readbuf, 0x00);
186 uint32_t read_len = read_uint32(readbuf, 0x04);
187 uint32_t read_rev = read_uint32(readbuf, 0x0c);
188 if (read_oob_sector_health) {
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
193 if (oob_id != read_id || oob_len != read_len || oob_rev != read_rev) {
194 fprintf(stderr, "Warning: sector has inconsistent metadata\n");
195 continue;
196 }
197 }
198 if (read_id == TFFS_ID_END) {
199 /* no more entries in this block */
200 block_end = 1;
201 continue;
202 }
203 if (read_len > TFFS_MAXIMUM_SEGMENT_SIZE) {
204 fprintf(stderr, "Warning: segment is longer than possible\n");
205 continue;
206 }
207 if (read_id == id) {
208 if (read_rev < rev) {
209 /* obsolete revision => ignore this */
210 continue;
211 }
212 if (read_rev > rev) {
213 /* newer revision => clear old data */
214 for (uint32_t i = 0; i < num_segments; i++) {
215 free(segments[i].val);
216 }
217 free (segments);
218 rev = read_rev;
219 num_segments = 0;
220 segments = NULL;
221 }
222
223 uint32_t seg = read_uint32(readbuf, 0x10);
224
225 if (seg == TFFS_SEGMENT_CLEARED) {
226 continue;
227 }
228
229 uint32_t next_seg = read_uint32(readbuf, 0x14);
230
231 uint32_t new_num_segs = next_seg == 0 ? seg + 1 : next_seg + 1;
232 if (new_num_segs > num_segments) {
233 segments = realloc(segments, new_num_segs * sizeof(struct tffs_entry_segment));
234 memset(segments + (num_segments * sizeof(struct tffs_entry_segment)), 0x0,
235 (new_num_segs - num_segments) * sizeof(struct tffs_entry_segment));
236 num_segments = new_num_segs;
237 }
238 segments[seg].len = read_len;
239 segments[seg].val = malloc(read_len);
240 memcpy(segments[seg].val, readbuf + TFFS_ENTRY_HEADER_SIZE, read_len);
241 }
242 }
243 }
244
245 if (num_segments == 0) {
246 return 0;
247 }
248
249 assert (segments != NULL);
250
251 uint32_t len = 0;
252 for (uint32_t i = 0; i < num_segments; i++) {
253 if (segments[i].val == NULL) {
254 /* missing segment */
255 return 0;
256 }
257
258 len += segments[i].len;
259 }
260
261 void *p = malloc(len);
262 entry->val = p;
263 entry->len = len;
264 for (uint32_t i = 0; i < num_segments; i++) {
265 memcpy(p, segments[i].val, segments[i].len);
266 p += segments[i].len;
267 }
268
269 return 1;
270 }
271
272 static void parse_key_names(struct tffs_entry *names_entry,
273 struct tffs_key_name_table *key_names)
274 {
275 uint32_t pos = 0, i = 0;
276 struct tffs_name_table_entry *name_item;
277
278 key_names->entries = NULL;
279
280 do {
281 key_names->entries = realloc(key_names->entries,
282 sizeof(struct tffs_name_table_entry) * (i + 1));
283 if (key_names->entries == NULL) {
284 fprintf(stderr, "ERROR: memory allocation failed!\n");
285 exit(EXIT_FAILURE);
286 }
287 name_item = &key_names->entries[i];
288
289 name_item->id = read_uint32(names_entry->val, pos);
290 pos += sizeof(uint32_t);
291 name_item->val = strdup((const char *)(names_entry->val + pos));
292
293 /*
294 * There is no "length" field because the string values are
295 * simply NULL-terminated -> strlen() gives us the size.
296 */
297 pos += get_walk_size(strlen(name_item->val) + 1);
298
299 ++i;
300 } while (pos < names_entry->len);
301
302 key_names->size = i;
303 }
304
305 static void show_all_key_names(struct tffs_key_name_table *key_names)
306 {
307 for (uint32_t i = 0; i < key_names->size; i++)
308 printf("%s\n", key_names->entries[i].val);
309 }
310
311 static int show_all_key_value_pairs(struct tffs_key_name_table *key_names)
312 {
313 uint8_t has_value = 0;
314 struct tffs_entry tmp;
315
316 for (uint32_t i = 0; i < key_names->size; i++) {
317 if (find_entry(key_names->entries[i].id, &tmp)) {
318 printf("%s=", (const char *)key_names->entries[i].val);
319 print_entry_value(&tmp);
320 printf("\n");
321 has_value++;
322 free(tmp.val);
323 }
324 }
325
326 if (!has_value) {
327 fprintf(stderr, "ERROR: no values found!\n");
328 return EXIT_FAILURE;
329 }
330
331 return EXIT_SUCCESS;
332 }
333
334 static int show_matching_key_value(struct tffs_key_name_table *key_names)
335 {
336 struct tffs_entry tmp;
337 const char *name;
338
339 for (uint32_t i = 0; i < key_names->size; i++) {
340 name = key_names->entries[i].val;
341
342 if (strcmp(name, name_filter) == 0) {
343 if (find_entry(key_names->entries[i].id, &tmp)) {
344 print_entry_value(&tmp);
345 printf("\n");
346 free(tmp.val);
347 return EXIT_SUCCESS;
348 } else {
349 fprintf(stderr,
350 "ERROR: no value found for name %s!\n",
351 name);
352 return EXIT_FAILURE;
353 }
354 }
355 }
356
357 fprintf(stderr, "ERROR: Unknown key name %s!\n", name_filter);
358 return EXIT_FAILURE;
359 }
360
361 static int check_sector(off_t pos)
362 {
363 if (!read_oob_sector_health) {
364 return 1;
365 }
366 if (read_sectoroob(pos)) {
367 return 0;
368 }
369 if (read_uint8(oobbuf, 0x00) != 0xff) {
370 /* block is bad */
371 return 0;
372 }
373 if (read_uint8(oobbuf, 0x01) != 0xff) {
374 /* sector is bad */
375 return 0;
376 }
377 return 1;
378 }
379
380 static int check_block(off_t pos, uint32_t sector)
381 {
382 if (!check_sector(pos)) {
383 return 0;
384 }
385 if (read_sector(pos)) {
386 return 0;
387 }
388 if (read_uint64(readbuf, 0x00) != TFFS_BLOCK_HEADER_MAGIC) {
389 fprintf(stderr, "Warning: block without magic header. Skipping block\n");
390 return 0;
391 }
392 if (read_uint32(readbuf, 0x0c) != TFFS_SECTORS_PER_PAGE) {
393 fprintf(stderr, "Warning: block with wrong number of sectors per page. Skipping block\n");
394 return 0;
395 }
396
397 uint32_t num_hdr_bad = read_uint32(readbuf, 0x0c);
398 for (uint32_t i = 0; i < num_hdr_bad; i++) {
399 uint32_t bad = sector + read_uint64(readbuf, 0x1c + sizeof(uint64_t)*i);
400 sector_mark_bad(bad);
401 }
402
403 return 1;
404 }
405
406 static int scan_mtd(void)
407 {
408 struct mtd_info_user info;
409
410 if (ioctl(mtdfd, MEMGETINFO, &info)) {
411 return 0;
412 }
413
414 blocksize = info.erasesize;
415
416 num_sectors = info.size / TFFS_SECTOR_SIZE;
417 sectors = malloc((num_sectors + 7) / 8);
418 if (sectors == NULL) {
419 fprintf(stderr, "ERROR: memory allocation failed!\n");
420 exit(EXIT_FAILURE);
421 }
422 memset(sectors, 0xff, (num_sectors + 7) / 8);
423
424 uint32_t sector = 0, valid_blocks = 0;
425 uint8_t block_ok = 0;
426 for (off_t pos = 0; pos < info.size; sector++, pos += TFFS_SECTOR_SIZE) {
427 if (pos % info.erasesize == 0) {
428 block_ok = check_block(pos, sector);
429 /* first sector of the block contains metadata
430 => handle it like a bad sector */
431 sector_mark_bad(sector);
432 if (block_ok) {
433 valid_blocks++;
434 }
435 } else if (!block_ok || !sector_get_good(sector) || !check_sector(pos)) {
436 sector_mark_bad(sector);
437 }
438 }
439
440 return valid_blocks;
441 }
442
443 static void usage(int status)
444 {
445 FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
446
447 fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
448 fprintf(stream,
449 "\n"
450 "Options:\n"
451 " -a list all key value pairs found in the TFFS file/device\n"
452 " -d <mtd> inspect the TFFS on mtd device <mtd>\n"
453 " -h show this screen\n"
454 " -l list all supported keys\n"
455 " -n <key name> display the value of the given key\n"
456 " -o read OOB information about sector health\n"
457 );
458
459 exit(status);
460 }
461
462 static void parse_options(int argc, char *argv[])
463 {
464 while (1) {
465 int c;
466
467 c = getopt(argc, argv, "abd:hln:o");
468 if (c == -1)
469 break;
470
471 switch (c) {
472 case 'a':
473 show_all = true;
474 name_filter = NULL;
475 print_all_key_names = false;
476 break;
477 case 'b':
478 swap_bytes = 1;
479 break;
480 case 'd':
481 mtddev = optarg;
482 break;
483 case 'h':
484 usage(EXIT_SUCCESS);
485 break;
486 case 'l':
487 print_all_key_names = true;
488 show_all = false;
489 name_filter = NULL;
490 break;
491 case 'n':
492 name_filter = optarg;
493 show_all = false;
494 print_all_key_names = false;
495 break;
496 case 'o':
497 read_oob_sector_health = true;
498 break;
499 default:
500 usage(EXIT_FAILURE);
501 break;
502 }
503 }
504
505 if (!mtddev) {
506 fprintf(stderr, "ERROR: No input file (-d <file>) given!\n");
507 usage(EXIT_FAILURE);
508 }
509
510 if (!show_all && !name_filter && !print_all_key_names) {
511 fprintf(stderr,
512 "ERROR: either -l, -a or -n <key name> is required!\n");
513 usage(EXIT_FAILURE);
514 }
515 }
516
517 int main(int argc, char *argv[])
518 {
519 int ret = EXIT_FAILURE;
520 struct tffs_entry name_table;
521 struct tffs_key_name_table key_names;
522
523 progname = basename(argv[0]);
524
525 parse_options(argc, argv);
526
527 mtdfd = open(mtddev, O_RDONLY);
528 if (mtdfd < 0) {
529 fprintf(stderr, "ERROR: Failed to open tffs device %s\n",
530 mtddev);
531 goto out;
532 }
533
534 if (!scan_mtd()) {
535 fprintf(stderr, "ERROR: Parsing blocks from tffs device %s failed\n", mtddev);
536 fprintf(stderr, " Is byte-swapping (-b) required?\n");
537 goto out_close;
538 }
539
540 if (!find_entry(TFFS_ID_TABLE_NAME, &name_table)) {
541 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
542 mtddev);
543 goto out_free_sectors;
544 }
545
546 parse_key_names(&name_table, &key_names);
547 if (key_names.size < 1) {
548 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
549 mtddev);
550 goto out_free_entry;
551 }
552
553 if (print_all_key_names) {
554 show_all_key_names(&key_names);
555 ret = EXIT_SUCCESS;
556 } else if (show_all) {
557 ret = show_all_key_value_pairs(&key_names);
558 } else {
559 ret = show_matching_key_value(&key_names);
560 }
561
562 free(key_names.entries);
563 out_free_entry:
564 free(name_table.val);
565 out_free_sectors:
566 free(sectors);
567 out_close:
568 close(mtdfd);
569 out:
570 return ret;
571 }