db77d2f5b46a3b1843419d40284bea93c18b1195
[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 swap_bytes = false;
71 static uint8_t readbuf[TFFS_SECTOR_SIZE];
72 static uint8_t oobbuf[TFFS_SECTOR_OOB_SIZE];
73 static uint32_t blocksize;
74 static int mtdfd;
75 struct tffs_sectors *sectors;
76
77 struct tffs_sectors {
78 uint32_t num_sectors;
79 uint8_t sectors[0];
80 };
81
82 static inline void sector_mark_bad(int num)
83 {
84 sectors->sectors[num / 8] &= ~(0x80 >> (num % 8));
85 };
86
87 static inline uint8_t sector_get_good(int num)
88 {
89 return sectors->sectors[num / 8] & 0x80 >> (num % 8);
90 };
91
92 struct tffs_entry_segment {
93 uint32_t len;
94 void *val;
95 };
96
97 struct tffs_entry {
98 uint32_t len;
99 void *val;
100 };
101
102 struct tffs_name_table_entry {
103 uint32_t id;
104 char *val;
105 };
106
107 struct tffs_key_name_table {
108 uint32_t size;
109 struct tffs_name_table_entry *entries;
110 };
111
112 static inline uint8_t read_uint8(void *buf, ptrdiff_t off)
113 {
114 return *(uint8_t *)(buf + off);
115 }
116
117 static inline uint32_t read_uint32(void *buf, ptrdiff_t off)
118 {
119 uint32_t tmp = *(uint32_t *)(buf + off);
120 if (swap_bytes) {
121 tmp = be32toh(tmp);
122 }
123 return tmp;
124 }
125
126 static inline uint64_t read_uint64(void *buf, ptrdiff_t off)
127 {
128 uint64_t tmp = *(uint64_t *)(buf + off);
129 if (swap_bytes) {
130 tmp = be64toh(tmp);
131 }
132 return tmp;
133 }
134
135 static int read_sector(off_t pos)
136 {
137 if (pread(mtdfd, readbuf, TFFS_SECTOR_SIZE, pos) != TFFS_SECTOR_SIZE) {
138 return -1;
139 }
140
141 return 0;
142 }
143
144 static int read_sectoroob(off_t pos)
145 {
146 struct mtd_oob_buf oob = {
147 .start = pos,
148 .length = TFFS_SECTOR_OOB_SIZE,
149 .ptr = oobbuf
150 };
151
152 if (ioctl(mtdfd, MEMREADOOB, &oob) < 0) {
153 return -1;
154 }
155
156 return 0;
157 }
158
159 static inline uint32_t get_walk_size(uint32_t entry_len)
160 {
161 return (entry_len + 3) & ~0x03;
162 }
163
164 static void print_entry_value(const struct tffs_entry *entry)
165 {
166 /* These are NOT NULL terminated. */
167 fwrite(entry->val, 1, entry->len, stdout);
168 }
169
170 static int find_entry(uint32_t id, struct tffs_entry *entry)
171 {
172 uint32_t rev = 0;
173 uint32_t num_segments = 0;
174 struct tffs_entry_segment *segments = NULL;
175
176 off_t pos = 0;
177 uint8_t block_end = 0;
178 for (uint32_t sector = 0; sector < sectors->num_sectors; sector++, pos += TFFS_SECTOR_SIZE) {
179 if (block_end) {
180 if (pos % blocksize == 0) {
181 block_end = 0;
182 }
183 } else if (sector_get_good(sector)) {
184 if (read_sectoroob(pos) || read_sector(pos)) {
185 fprintf(stderr, "ERROR: sector isn't readable, but has been previously!\n");
186 exit(EXIT_FAILURE);
187 }
188 uint32_t oob_id = read_uint32(oobbuf, 0x02);
189 uint32_t oob_len = read_uint32(oobbuf, 0x06);
190 uint32_t oob_rev = read_uint32(oobbuf, 0x0a);
191 uint32_t read_id = read_uint32(readbuf, 0x00);
192 uint32_t read_len = read_uint32(readbuf, 0x04);
193 uint32_t read_rev = read_uint32(readbuf, 0x0c);
194 if (oob_id != read_id || oob_len != read_len || oob_rev != read_rev) {
195 fprintf(stderr, "Warning: sector has inconsistent metadata\n");
196 continue;
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 (strncmp(name, name_filter, strlen(name)) == 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_sectoroob(pos)) {
364 return 0;
365 }
366 if (read_uint8(oobbuf, 0x00) != 0xff) {
367 /* block is bad */
368 return 0;
369 }
370 if (read_uint8(oobbuf, 0x01) != 0xff) {
371 /* sector is bad */
372 return 0;
373 }
374 return 1;
375 }
376
377 static int check_block(off_t pos, uint32_t sector)
378 {
379 if (!check_sector(pos)) {
380 return 0;
381 }
382 if (read_sector(pos)) {
383 return 0;
384 }
385 if (read_uint64(readbuf, 0x00) != TFFS_BLOCK_HEADER_MAGIC) {
386 fprintf(stderr, "Warning: block without magic header. Skipping block\n");
387 return 0;
388 }
389 if (read_uint32(readbuf, 0x0c) != TFFS_SECTORS_PER_PAGE) {
390 fprintf(stderr, "Warning: block with wrong number of sectors per page. Skipping block\n");
391 return 0;
392 }
393
394 uint32_t num_hdr_bad = read_uint32(readbuf, 0x0c);
395 for (uint32_t i = 0; i < num_hdr_bad; i++) {
396 uint32_t bad = sector + read_uint64(readbuf, 0x1c + sizeof(uint64_t)*i);
397 sector_mark_bad(bad);
398 }
399
400 return 1;
401 }
402
403 static int scan_mtd(void)
404 {
405 struct mtd_info_user info;
406
407 if (ioctl(mtdfd, MEMGETINFO, &info)) {
408 return 0;
409 }
410
411 blocksize = info.erasesize;
412
413 sectors = malloc(sizeof(*sectors) + (info.size / TFFS_SECTOR_SIZE + 7) / 8);
414 if (sectors == NULL) {
415 fprintf(stderr, "ERROR: memory allocation failed!\n");
416 exit(EXIT_FAILURE);
417 }
418 sectors->num_sectors = info.size / TFFS_SECTOR_SIZE;
419 memset(sectors->sectors, 0xff, (info.size / TFFS_SECTOR_SIZE + 7) / 8);
420
421 uint32_t sector = 0, valid_blocks = 0;
422 uint8_t block_ok = 0;
423 for (off_t pos = 0; pos < info.size; sector++, pos += TFFS_SECTOR_SIZE) {
424 if (pos % info.erasesize == 0) {
425 block_ok = check_block(pos, sector);
426 /* first sector of the block contains metadata
427 => handle it like a bad sector */
428 sector_mark_bad(sector);
429 if (block_ok) {
430 valid_blocks++;
431 }
432 } else if (!block_ok || !sector_get_good(sector) || !check_sector(pos)) {
433 sector_mark_bad(sector);
434 }
435 }
436
437 return valid_blocks;
438 }
439
440 static void usage(int status)
441 {
442 FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
443
444 fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
445 fprintf(stream,
446 "\n"
447 "Options:\n"
448 " -a list all key value pairs found in the TFFS file/device\n"
449 " -d <mtd> inspect the TFFS on mtd device <mtd>\n"
450 " -h show this screen\n"
451 " -l list all supported keys\n"
452 " -n <key name> display the value of the given key\n"
453 );
454
455 exit(status);
456 }
457
458 static void parse_options(int argc, char *argv[])
459 {
460 while (1) {
461 int c;
462
463 c = getopt(argc, argv, "abd:hln:");
464 if (c == -1)
465 break;
466
467 switch (c) {
468 case 'a':
469 show_all = true;
470 name_filter = NULL;
471 print_all_key_names = false;
472 break;
473 case 'b':
474 swap_bytes = 1;
475 break;
476 case 'd':
477 mtddev = optarg;
478 break;
479 case 'h':
480 usage(EXIT_SUCCESS);
481 break;
482 case 'l':
483 print_all_key_names = true;
484 show_all = false;
485 name_filter = NULL;
486 break;
487 case 'n':
488 name_filter = optarg;
489 show_all = false;
490 print_all_key_names = false;
491 break;
492 default:
493 usage(EXIT_FAILURE);
494 break;
495 }
496 }
497
498 if (!mtddev) {
499 fprintf(stderr, "ERROR: No input file (-d <file>) given!\n");
500 usage(EXIT_FAILURE);
501 }
502
503 if (!show_all && !name_filter && !print_all_key_names) {
504 fprintf(stderr,
505 "ERROR: either -l, -a or -n <key name> is required!\n");
506 usage(EXIT_FAILURE);
507 }
508 }
509
510 int main(int argc, char *argv[])
511 {
512 int ret = EXIT_FAILURE;
513 struct tffs_entry name_table;
514 struct tffs_key_name_table key_names;
515
516 progname = basename(argv[0]);
517
518 parse_options(argc, argv);
519
520 mtdfd = open(mtddev, O_RDONLY);
521 if (mtdfd < 0) {
522 fprintf(stderr, "ERROR: Failed to open tffs device %s\n",
523 mtddev);
524 goto out;
525 }
526
527 if (!scan_mtd()) {
528 fprintf(stderr, "ERROR: Parsing blocks from tffs device %s failed\n", mtddev);
529 fprintf(stderr, " Is byte-swapping (-b) required?\n");
530 goto out_close;
531 }
532
533 if (!find_entry(TFFS_ID_TABLE_NAME, &name_table)) {
534 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
535 mtddev);
536 goto out_free_sectors;
537 }
538
539 parse_key_names(&name_table, &key_names);
540 if (key_names.size < 1) {
541 fprintf(stderr, "ERROR: No name table found on tffs device %s\n",
542 mtddev);
543 goto out_free_entry;
544 }
545
546 if (print_all_key_names) {
547 show_all_key_names(&key_names);
548 ret = EXIT_SUCCESS;
549 } else if (show_all) {
550 ret = show_all_key_value_pairs(&key_names);
551 } else {
552 ret = show_matching_key_value(&key_names);
553 }
554
555 free(key_names.entries);
556 out_free_entry:
557 free(name_table.val);
558 out_free_sectors:
559 free(sectors);
560 out_close:
561 close(mtdfd);
562 out:
563 return ret;
564 }