Fresh pull from upstream
[librecmc/librecmc.git] / tools / firmware-utils / src / mktplinkfw2.c
1 /*
2  * Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
3  *
4  * This tool was based on:
5  *   TP-Link WR941 V2 firmware checksum fixing tool.
6  *   Copyright (C) 2008,2009 Wang Jian <lark@linux.net.cn>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License version 2 as published
10  * by the Free Software Foundation.
11  *
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdint.h>
17 #include <string.h>
18 #include <unistd.h>     /* for unlink() */
19 #include <libgen.h>
20 #include <getopt.h>     /* for getopt() */
21 #include <stdarg.h>
22 #include <errno.h>
23 #include <stdbool.h>
24 #include <endian.h>
25 #include <sys/stat.h>
26
27 #include <arpa/inet.h>
28 #include <netinet/in.h>
29
30 #include "md5.h"
31
32 #define ALIGN(x,a) ({ typeof(a) __a = (a); (((x) + __a - 1) & ~(__a - 1)); })
33
34 #define MD5SUM_LEN      16
35
36 struct file_info {
37         char            *file_name;     /* name of the file */
38         uint32_t        file_size;      /* length of the file */
39 };
40
41 struct fw_header {
42         uint32_t        version;        /* 0x00: header version */
43         char            fw_version[48]; /* 0x04: fw version string */
44         uint32_t        hw_id;          /* 0x34: hardware id */
45         uint32_t        hw_rev;         /* 0x38: FIXME: hardware revision? */
46         uint32_t        unk1;           /* 0x3c: 0x00000000 */
47         uint8_t         md5sum1[MD5SUM_LEN]; /* 0x40 */
48         uint32_t        unk2;           /* 0x50: 0x00000000 */
49         uint8_t         md5sum2[MD5SUM_LEN]; /* 0x54 */
50         uint32_t        unk3;           /* 0x64: 0xffffffff */
51
52         uint32_t        kernel_la;      /* 0x68: kernel load address */
53         uint32_t        kernel_ep;      /* 0x6c: kernel entry point */
54         uint32_t        fw_length;      /* 0x70: total length of the image */
55         uint32_t        kernel_ofs;     /* 0x74: kernel data offset */
56         uint32_t        kernel_len;     /* 0x78: kernel data length */
57         uint32_t        rootfs_ofs;     /* 0x7c: rootfs data offset */
58         uint32_t        rootfs_len;     /* 0x80: rootfs data length */
59         uint32_t        boot_ofs;       /* 0x84: FIXME: seems to be unused */
60         uint32_t        boot_len;       /* 0x88: FIXME: seems to be unused */
61         uint16_t        unk4;           /* 0x8c: 0x55aa */
62         uint8_t         sver_hi;        /* 0x8e */
63         uint8_t         sver_lo;        /* 0x8f */
64         uint8_t         unk5;           /* 0x90: magic: 0xa5 */
65         uint8_t         ver_hi;         /* 0x91 */
66         uint8_t         ver_mid;        /* 0x92 */
67         uint8_t         ver_lo;         /* 0x93 */
68         uint8_t         pad[364];
69 } __attribute__ ((packed));
70
71 struct flash_layout {
72         char            *id;
73         uint32_t        fw_max_len;
74         uint32_t        kernel_la;
75         uint32_t        kernel_ep;
76         uint32_t        rootfs_ofs;
77 };
78
79 struct board_info {
80         char            *id;
81         uint32_t        hw_id;
82         uint32_t        hw_rev;
83         char            *layout_id;
84         uint32_t        hdr_ver;
85         bool            endian_swap;
86 };
87
88 /*
89  * Globals
90  */
91 static char *ofname;
92 static char *progname;
93 static char *vendor = "TP-LINK Technologies";
94 static char *version = "ver. 1.0";
95 static char *fw_ver = "0.0.0";
96 static char *sver = "1.0";
97 static uint32_t hdr_ver = 2;
98
99 static char *board_id;
100 static struct board_info *board;
101 static char *layout_id;
102 static struct flash_layout *layout;
103 static char *opt_hw_id;
104 static uint32_t hw_id;
105 static char *opt_hw_rev;
106 static uint32_t hw_rev;
107 static int fw_ver_lo;
108 static int fw_ver_mid;
109 static int fw_ver_hi;
110 static int sver_lo;
111 static int sver_hi;
112 static struct file_info kernel_info;
113 static uint32_t kernel_la = 0;
114 static uint32_t kernel_ep = 0;
115 static uint32_t kernel_len = 0;
116 static struct file_info rootfs_info;
117 static uint32_t rootfs_ofs = 0;
118 static uint32_t rootfs_align;
119 static struct file_info boot_info;
120 static int combined;
121 static int strip_padding;
122 static int add_jffs2_eof;
123 static unsigned char jffs2_eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
124
125 static struct file_info inspect_info;
126 static int extract = 0;
127 static bool endian_swap = false;
128
129 char md5salt_normal[MD5SUM_LEN] = {
130         0xdc, 0xd7, 0x3a, 0xa5, 0xc3, 0x95, 0x98, 0xfb,
131         0xdc, 0xf9, 0xe7, 0xf4, 0x0e, 0xae, 0x47, 0x37,
132 };
133
134 char md5salt_boot[MD5SUM_LEN] = {
135         0x8c, 0xef, 0x33, 0x5b, 0xd5, 0xc5, 0xce, 0xfa,
136         0xa7, 0x9c, 0x28, 0xda, 0xb2, 0xe9, 0x0f, 0x42,
137 };
138
139 static struct flash_layout layouts[] = {
140         {
141                 .id             = "8Mltq",
142                 .fw_max_len     = 0x7a0000,
143                 .kernel_la      = 0x80002000,
144                 .kernel_ep      = 0x80002000,
145                 .rootfs_ofs     = 0x140000,
146         }, {
147                 .id             = "16Mltq",
148                 .fw_max_len     = 0xf90000,
149                 .kernel_la      = 0x80002000,
150                 .kernel_ep      = 0x800061b0,
151                 .rootfs_ofs     = 0x140000,
152         }, {
153                 .id             = "8Mmtk",
154                 .fw_max_len     = 0x7a0000,
155                 .kernel_la      = 0x80000000,
156                 .kernel_ep      = 0x80000000,
157                 .rootfs_ofs     = 0x140000,
158         }, {
159                 .id             = "8MLmtk",
160                 .fw_max_len     = 0x7b0000,
161                 .kernel_la      = 0x80000000,
162                 .kernel_ep      = 0x80000000,
163                 .rootfs_ofs     = 0x140000,
164         }, {
165                 /* terminating entry */
166         }
167 };
168
169 static struct board_info boards[] = {
170         {
171                 .id             = "TD-W8970v1",
172                 .hw_id          = 0x89700001,
173                 .hw_rev         = 1,
174                 .layout_id      = "8Mltq",
175         }, {
176                 .id             = "TD-W8980v1",
177                 .hw_id          = 0x89800001,
178                 .hw_rev         = 14,
179                 .layout_id      = "8Mltq",
180         }, {
181                 .id             = "ArcherC20i",
182                 .hw_id          = 0xc2000001,
183                 .hw_rev         = 58,
184                 .layout_id      = "8Mmtk",
185                 .hdr_ver        = 3,
186                 .endian_swap    = true,
187         }, {
188                 .id             = "ArcherVR200V",
189                 .hw_id          = 0x73b70801,
190                 .hw_rev         = 0x2f,
191                 .layout_id      = "16Mltq",
192                 .hdr_ver        = 2,
193         }, {
194                 .id             = "ArcherC50",
195                 .hw_id          = 0xc7500001,
196                 .hw_rev         = 69,
197                 .layout_id      = "8Mmtk",
198                 .hdr_ver        = 3,
199                 .endian_swap    = true,
200         }, {
201                 .id             = "ArcherMR200",
202                 .hw_id          = 0xd7500001,
203                 .hw_rev         = 0x4a,
204                 .layout_id      = "8MLmtk",
205                 .hdr_ver        = 3,
206                 .endian_swap    = true,
207         }, {
208                 /* terminating entry */
209         }
210 };
211
212 /*
213  * Message macros
214  */
215 #define ERR(fmt, ...) do { \
216         fflush(0); \
217         fprintf(stderr, "[%s] *** error: " fmt "\n", \
218                         progname, ## __VA_ARGS__ ); \
219 } while (0)
220
221 #define ERRS(fmt, ...) do { \
222         int save = errno; \
223         fflush(0); \
224         fprintf(stderr, "[%s] *** error: " fmt ": %s\n", \
225                         progname, ## __VA_ARGS__, strerror(save)); \
226 } while (0)
227
228 #define DBG(fmt, ...) do { \
229         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
230 } while (0)
231
232 static struct board_info *find_board(char *id)
233 {
234         struct board_info *ret;
235         struct board_info *board;
236
237         ret = NULL;
238         for (board = boards; board->id != NULL; board++){
239                 if (strcasecmp(id, board->id) == 0) {
240                         ret = board;
241                         break;
242                 }
243         };
244
245         return ret;
246 }
247
248 static struct board_info *find_board_by_hwid(uint32_t hw_id)
249 {
250         struct board_info *board;
251
252         for (board = boards; board->id != NULL; board++) {
253                 if (hw_id == board->hw_id)
254                         return board;
255         };
256
257         return NULL;
258 }
259
260 static struct flash_layout *find_layout(char *id)
261 {
262         struct flash_layout *ret;
263         struct flash_layout *l;
264
265         ret = NULL;
266         for (l = layouts; l->id != NULL; l++){
267                 if (strcasecmp(id, l->id) == 0) {
268                         ret = l;
269                         break;
270                 }
271         };
272
273         return ret;
274 }
275
276 static void usage(int status)
277 {
278         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
279         struct board_info *board;
280
281         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
282         fprintf(stream,
283 "\n"
284 "Options:\n"
285 "  -B <board>      create image for the board specified with <board>\n"
286 "  -c              use combined kernel image\n"
287 "  -E <ep>         overwrite kernel entry point with <ep> (hexval prefixed with 0x)\n"
288 "  -L <la>         overwrite kernel load address with <la> (hexval prefixed with 0x)\n"
289 "  -H <hwid>       use hardware id specified with <hwid>\n"
290 "  -W <hwrev>      use hardware revision specified with <hwrev>\n"
291 "  -F <id>         use flash layout specified with <id>\n"
292 "  -k <file>       read kernel image from the file <file>\n"
293 "  -r <file>       read rootfs image from the file <file>\n"
294 "  -a <align>      align the rootfs start on an <align> bytes boundary\n"
295 "  -R <offset>     overwrite rootfs offset with <offset> (hexval prefixed with 0x)\n"
296 "  -o <file>       write output to the file <file>\n"
297 "  -s              strip padding from the end of the image\n"
298 "  -j              add jffs2 end-of-filesystem markers\n"
299 "  -V <version>    set image version to <version>\n"
300 "  -v <version>    set firmware version to <version>\n"
301 "  -y <version>    set secondary version to <version>\n"
302 "  -i <file>       inspect given firmware file <file>\n"
303 "  -x              extract kernel and rootfs while inspecting (requires -i)\n"
304 "  -h              show this screen\n"
305         );
306
307         exit(status);
308 }
309
310 static int get_md5(char *data, int size, char *md5)
311 {
312         MD5_CTX ctx;
313
314         MD5_Init(&ctx);
315         MD5_Update(&ctx, data, size);
316         MD5_Final(md5, &ctx);
317 }
318
319 static int get_file_stat(struct file_info *fdata)
320 {
321         struct stat st;
322         int res;
323
324         if (fdata->file_name == NULL)
325                 return 0;
326
327         res = stat(fdata->file_name, &st);
328         if (res){
329                 ERRS("stat failed on %s", fdata->file_name);
330                 return res;
331         }
332
333         fdata->file_size = st.st_size;
334         return 0;
335 }
336
337 static int read_to_buf(struct file_info *fdata, char *buf)
338 {
339         FILE *f;
340         int ret = EXIT_FAILURE;
341
342         f = fopen(fdata->file_name, "r");
343         if (f == NULL) {
344                 ERRS("could not open \"%s\" for reading", fdata->file_name);
345                 goto out;
346         }
347
348         errno = 0;
349         fread(buf, fdata->file_size, 1, f);
350         if (errno != 0) {
351                 ERRS("unable to read from file \"%s\"", fdata->file_name);
352                 goto out_close;
353         }
354
355         ret = EXIT_SUCCESS;
356
357  out_close:
358         fclose(f);
359  out:
360         return ret;
361 }
362
363 static int check_options(void)
364 {
365         int ret;
366
367         if (inspect_info.file_name) {
368                 ret = get_file_stat(&inspect_info);
369                 if (ret)
370                         return ret;
371
372                 return 0;
373         } else if (extract) {
374                 ERR("no firmware for inspection specified");
375                 return -1;
376         }
377
378         if (board_id == NULL && opt_hw_id == NULL) {
379                 ERR("either board or hardware id must be specified");
380                 return -1;
381         }
382
383         if (board_id) {
384                 board = find_board(board_id);
385                 if (board == NULL) {
386                         ERR("unknown/unsupported board id \"%s\"", board_id);
387                         return -1;
388                 }
389                 if (layout_id == NULL)
390                         layout_id = board->layout_id;
391
392                 hw_id = board->hw_id;
393                 hw_rev = board->hw_rev;
394                 if (board->hdr_ver)
395                         hdr_ver = board->hdr_ver;
396                 endian_swap = board->endian_swap;
397         } else {
398                 if (layout_id == NULL) {
399                         ERR("flash layout is not specified");
400                         return -1;
401                 }
402                 hw_id = strtoul(opt_hw_id, NULL, 0);
403
404                 if (opt_hw_rev)
405                         hw_rev = strtoul(opt_hw_rev, NULL, 0);
406                 else
407                         hw_rev = 1;
408         }
409
410         layout = find_layout(layout_id);
411         if (layout == NULL) {
412                 ERR("unknown flash layout \"%s\"", layout_id);
413                 return -1;
414         }
415
416         if (!kernel_la)
417                 kernel_la = layout->kernel_la;
418         if (!kernel_ep)
419                 kernel_ep = layout->kernel_ep;
420         if (!rootfs_ofs)
421                 rootfs_ofs = layout->rootfs_ofs;
422
423         if (kernel_info.file_name == NULL) {
424                 ERR("no kernel image specified");
425                 return -1;
426         }
427
428         ret = get_file_stat(&kernel_info);
429         if (ret)
430                 return ret;
431
432         kernel_len = kernel_info.file_size;
433
434         if (combined) {
435                 if (kernel_info.file_size >
436                     layout->fw_max_len - sizeof(struct fw_header)) {
437                         ERR("kernel image is too big");
438                         return -1;
439                 }
440         } else {
441                 if (rootfs_info.file_name == NULL) {
442                         ERR("no rootfs image specified");
443                         return -1;
444                 }
445
446                 ret = get_file_stat(&rootfs_info);
447                 if (ret)
448                         return ret;
449
450                 if (rootfs_align) {
451                         kernel_len += sizeof(struct fw_header);
452                         kernel_len = ALIGN(kernel_len, rootfs_align);
453                         kernel_len -= sizeof(struct fw_header);
454
455                         DBG("kernel length aligned to %u", kernel_len);
456
457                         if (kernel_len + rootfs_info.file_size >
458                             layout->fw_max_len - sizeof(struct fw_header)) {
459                                 ERR("images are too big");
460                                 return -1;
461                         }
462                 } else {
463                         if (kernel_info.file_size >
464                             rootfs_ofs - sizeof(struct fw_header)) {
465                                 ERR("kernel image is too big");
466                                 return -1;
467                         }
468
469                         if (rootfs_info.file_size >
470                             (layout->fw_max_len - rootfs_ofs)) {
471                                 ERR("rootfs image is too big");
472                                 return -1;
473                         }
474                 }
475         }
476
477         if (ofname == NULL) {
478                 ERR("no output file specified");
479                 return -1;
480         }
481
482         ret = sscanf(fw_ver, "%d.%d.%d", &fw_ver_hi, &fw_ver_mid, &fw_ver_lo);
483         if (ret != 3) {
484                 ERR("invalid firmware version '%s'", fw_ver);
485                 return -1;
486         }
487
488         ret = sscanf(sver, "%d.%d", &sver_hi, &sver_lo);
489         if (ret != 2) {
490                 ERR("invalid secondary version '%s'", sver);
491                 return -1;
492         }
493
494         return 0;
495 }
496
497 static void fill_header(char *buf, int len)
498 {
499         struct fw_header *hdr = (struct fw_header *)buf;
500         unsigned ver_len;
501
502         memset(hdr, '\xff', sizeof(struct fw_header));
503
504         hdr->version = htonl(bswap_32(hdr_ver));
505         ver_len = strlen(version);
506         if (ver_len > (sizeof(hdr->fw_version) - 1))
507                 ver_len = sizeof(hdr->fw_version) - 1;
508
509         memcpy(hdr->fw_version, version, ver_len);
510         hdr->fw_version[ver_len] = 0;
511
512         hdr->hw_id = htonl(hw_id);
513         hdr->hw_rev = htonl(hw_rev);
514
515         if (boot_info.file_size == 0) {
516                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(hdr->md5sum1));
517                 hdr->boot_ofs = htonl(0);
518                 hdr->boot_len = htonl(0);
519         } else {
520                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(hdr->md5sum1));
521                 hdr->boot_ofs = htonl(rootfs_ofs + rootfs_info.file_size);
522                 hdr->boot_len = htonl(rootfs_info.file_size);
523         }
524
525         hdr->kernel_la = htonl(kernel_la);
526         hdr->kernel_ep = htonl(kernel_ep);
527         hdr->fw_length = htonl(layout->fw_max_len);
528         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
529         hdr->kernel_len = htonl(kernel_len);
530         if (!combined) {
531                 hdr->rootfs_ofs = htonl(rootfs_ofs);
532                 hdr->rootfs_len = htonl(rootfs_info.file_size);
533         }
534
535         hdr->boot_ofs = htonl(0);
536         hdr->boot_len = htonl(boot_info.file_size);
537
538         hdr->unk1 = htonl(0);
539         hdr->unk2 = htonl(0);
540         hdr->unk3 = htonl(0xffffffff);
541         hdr->unk4 = htons(0x55aa);
542         hdr->unk5 = 0xa5;
543
544         hdr->sver_hi = sver_hi;
545         hdr->sver_lo = sver_lo;
546
547         hdr->ver_hi = fw_ver_hi;
548         hdr->ver_mid = fw_ver_mid;
549         hdr->ver_lo = fw_ver_lo;
550
551         if (endian_swap) {
552                 hdr->kernel_la = bswap_32(hdr->kernel_la);
553                 hdr->kernel_ep = bswap_32(hdr->kernel_ep);
554         }
555
556         get_md5(buf, len, hdr->md5sum1);
557 }
558
559 static int pad_jffs2(char *buf, int currlen)
560 {
561         int len;
562         uint32_t pad_mask;
563
564         len = currlen;
565         pad_mask = (64 * 1024);
566         while ((len < layout->fw_max_len) && (pad_mask != 0)) {
567                 uint32_t mask;
568                 int i;
569
570                 for (i = 10; i < 32; i++) {
571                         mask = 1 << i;
572                         if (pad_mask & mask)
573                                 break;
574                 }
575
576                 len = ALIGN(len, mask);
577
578                 for (i = 10; i < 32; i++) {
579                         mask = 1 << i;
580                         if ((len & (mask - 1)) == 0)
581                                 pad_mask &= ~mask;
582                 }
583
584                 for (i = 0; i < sizeof(jffs2_eof_mark); i++)
585                         buf[len + i] = jffs2_eof_mark[i];
586
587                 len += sizeof(jffs2_eof_mark);
588         }
589
590         return len;
591 }
592
593 static int write_fw(char *data, int len)
594 {
595         FILE *f;
596         int ret = EXIT_FAILURE;
597
598         f = fopen(ofname, "w");
599         if (f == NULL) {
600                 ERRS("could not open \"%s\" for writing", ofname);
601                 goto out;
602         }
603
604         errno = 0;
605         fwrite(data, len, 1, f);
606         if (errno) {
607                 ERRS("unable to write output file");
608                 goto out_flush;
609         }
610
611         DBG("firmware file \"%s\" completed", ofname);
612
613         ret = EXIT_SUCCESS;
614
615  out_flush:
616         fflush(f);
617         fclose(f);
618         if (ret != EXIT_SUCCESS) {
619                 unlink(ofname);
620         }
621  out:
622         return ret;
623 }
624
625 static int build_fw(void)
626 {
627         int buflen;
628         char *buf;
629         char *p;
630         int ret = EXIT_FAILURE;
631         int writelen = 0;
632
633         buflen = layout->fw_max_len;
634
635         buf = malloc(buflen);
636         if (!buf) {
637                 ERR("no memory for buffer\n");
638                 goto out;
639         }
640
641         memset(buf, 0xff, buflen);
642         p = buf + sizeof(struct fw_header);
643         ret = read_to_buf(&kernel_info, p);
644         if (ret)
645                 goto out_free_buf;
646
647         writelen = sizeof(struct fw_header) + kernel_len;
648
649         if (!combined) {
650                 if (rootfs_align)
651                         p = buf + writelen;
652                 else
653                         p = buf + rootfs_ofs;
654
655                 ret = read_to_buf(&rootfs_info, p);
656                 if (ret)
657                         goto out_free_buf;
658
659                 if (rootfs_align)
660                         writelen += rootfs_info.file_size;
661                 else
662                         writelen = rootfs_ofs + rootfs_info.file_size;
663
664                 if (add_jffs2_eof)
665                         writelen = pad_jffs2(buf, writelen);
666         }
667
668         if (!strip_padding)
669                 writelen = buflen;
670
671         fill_header(buf, writelen);
672         ret = write_fw(buf, writelen);
673         if (ret)
674                 goto out_free_buf;
675
676         ret = EXIT_SUCCESS;
677
678  out_free_buf:
679         free(buf);
680  out:
681         return ret;
682 }
683
684 /* Helper functions to inspect_fw() representing different output formats */
685 static inline void inspect_fw_pstr(char *label, char *str)
686 {
687         printf("%-23s: %s\n", label, str);
688 }
689
690 static inline void inspect_fw_phex(char *label, uint32_t val)
691 {
692         printf("%-23s: 0x%08x\n", label, val);
693 }
694
695 static inline void inspect_fw_phexpost(char *label,
696                                        uint32_t val, char *post)
697 {
698         printf("%-23s: 0x%08x (%s)\n", label, val, post);
699 }
700
701 static inline void inspect_fw_phexdef(char *label,
702                                       uint32_t val, uint32_t defval)
703 {
704         printf("%-23s: 0x%08x                  ", label, val);
705
706         if (val == defval)
707                 printf("(== OpenWrt default)\n");
708         else
709                 printf("(OpenWrt default: 0x%08x)\n", defval);
710 }
711
712 static inline void inspect_fw_phexexp(char *label,
713                                       uint32_t val, uint32_t expval)
714 {
715         printf("%-23s: 0x%08x ", label, val);
716
717         if (val == expval)
718                 printf("(ok)\n");
719         else
720                 printf("(expected: 0x%08x)\n", expval);
721 }
722
723 static inline void inspect_fw_phexdec(char *label, uint32_t val)
724 {
725         printf("%-23s: 0x%08x / %8u bytes\n", label, val, val);
726 }
727
728 static inline void inspect_fw_phexdecdef(char *label,
729                                          uint32_t val, uint32_t defval)
730 {
731         printf("%-23s: 0x%08x / %8u bytes ", label, val, val);
732
733         if (val == defval)
734                 printf("(== OpenWrt default)\n");
735         else
736                 printf("(OpenWrt default: 0x%08x)\n", defval);
737 }
738
739 static inline void inspect_fw_pmd5sum(char *label, uint8_t *val, char *text)
740 {
741         int i;
742
743         printf("%-23s:", label);
744         for (i=0; i<MD5SUM_LEN; i++)
745                 printf(" %02x", val[i]);
746         printf(" %s\n", text);
747 }
748
749 static int inspect_fw(void)
750 {
751         char *buf;
752         struct fw_header *hdr;
753         uint8_t md5sum[MD5SUM_LEN];
754         struct board_info *board;
755         int ret = EXIT_FAILURE;
756
757         buf = malloc(inspect_info.file_size);
758         if (!buf) {
759                 ERR("no memory for buffer!\n");
760                 goto out;
761         }
762
763         ret = read_to_buf(&inspect_info, buf);
764         if (ret)
765                 goto out_free_buf;
766         hdr = (struct fw_header *)buf;
767
768         inspect_fw_pstr("File name", inspect_info.file_name);
769         inspect_fw_phexdec("File size", inspect_info.file_size);
770
771         switch(bswap_32(ntohl(hdr->version))) {
772         case 2:
773         case 3:
774                 break;
775         default:
776                 ERR("file does not seem to have V2/V3 header!\n");
777                 goto out_free_buf;
778         }
779
780         inspect_fw_phexdec("Version 2 Header size", sizeof(struct fw_header));
781
782         if (ntohl(hdr->unk1) != 0)
783                 inspect_fw_phexdec("Unknown value 1", hdr->unk1);
784
785         memcpy(md5sum, hdr->md5sum1, sizeof(md5sum));
786         if (ntohl(hdr->boot_len) == 0)
787                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(md5sum));
788         else
789                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(md5sum));
790         get_md5(buf, inspect_info.file_size, hdr->md5sum1);
791
792         if (memcmp(md5sum, hdr->md5sum1, sizeof(md5sum))) {
793                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(*ERROR*)");
794                 inspect_fw_pmd5sum("          --> expected", hdr->md5sum1, "");
795         } else {
796                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(ok)");
797         }
798         if (ntohl(hdr->unk2) != 0)
799                 inspect_fw_phexdec("Unknown value 2", hdr->unk2);
800         inspect_fw_pmd5sum("Header MD5Sum2", hdr->md5sum2,
801                            "(purpose yet unknown, unchecked here)");
802
803         if (ntohl(hdr->unk3) != 0xffffffff)
804                 inspect_fw_phexdec("Unknown value 3", hdr->unk3);
805
806         if (ntohs(hdr->unk4) != 0x55aa)
807                 inspect_fw_phexdec("Unknown value 4", hdr->unk4);
808
809         if (hdr->unk5 != 0xa5)
810                 inspect_fw_phexdec("Unknown value 5", hdr->unk5);
811
812         printf("\n");
813
814         inspect_fw_pstr("Firmware version", hdr->fw_version);
815
816         board = find_board_by_hwid(ntohl(hdr->hw_id));
817         if (board) {
818                 layout = find_layout(board->layout_id);
819                 inspect_fw_phexpost("Hardware ID",
820                                     ntohl(hdr->hw_id), board->id);
821                 inspect_fw_phexexp("Hardware Revision",
822                                    ntohl(hdr->hw_rev), board->hw_rev);
823         } else {
824                 inspect_fw_phexpost("Hardware ID",
825                                     ntohl(hdr->hw_id), "unknown");
826                 inspect_fw_phex("Hardware Revision",
827                                 ntohl(hdr->hw_rev));
828         }
829
830         printf("%-23s: %d.%d.%d-%d.%d\n", "Software version",
831                hdr->ver_hi, hdr->ver_mid, hdr->ver_lo,
832                hdr->sver_hi, hdr->sver_lo);
833
834         printf("\n");
835
836         inspect_fw_phexdec("Kernel data offset",
837                            ntohl(hdr->kernel_ofs));
838         inspect_fw_phexdec("Kernel data length",
839                            ntohl(hdr->kernel_len));
840         if (board) {
841                 inspect_fw_phexdef("Kernel load address",
842                                    ntohl(hdr->kernel_la),
843                                    layout ? layout->kernel_la : 0xffffffff);
844                 inspect_fw_phexdef("Kernel entry point",
845                                    ntohl(hdr->kernel_ep),
846                                    layout ? layout->kernel_ep : 0xffffffff);
847                 inspect_fw_phexdecdef("Rootfs data offset",
848                                       ntohl(hdr->rootfs_ofs),
849                                       layout ? layout->rootfs_ofs : 0xffffffff);
850         } else {
851                 inspect_fw_phex("Kernel load address",
852                                 ntohl(hdr->kernel_la));
853                 inspect_fw_phex("Kernel entry point",
854                                 ntohl(hdr->kernel_ep));
855                 inspect_fw_phexdec("Rootfs data offset",
856                                    ntohl(hdr->rootfs_ofs));
857         }
858         inspect_fw_phexdec("Rootfs data length",
859                            ntohl(hdr->rootfs_len));
860         inspect_fw_phexdec("Boot loader data offset",
861                            ntohl(hdr->boot_ofs));
862         inspect_fw_phexdec("Boot loader data length",
863                            ntohl(hdr->boot_len));
864         inspect_fw_phexdec("Total firmware length",
865                            ntohl(hdr->fw_length));
866
867         if (extract) {
868                 FILE *fp;
869                 char *filename;
870
871                 printf("\n");
872
873                 filename = malloc(strlen(inspect_info.file_name) + 8);
874                 sprintf(filename, "%s-kernel", inspect_info.file_name);
875                 printf("Extracting kernel to \"%s\"...\n", filename);
876                 fp = fopen(filename, "w");
877                 if (fp) {
878                         if (!fwrite(buf + ntohl(hdr->kernel_ofs),
879                                     ntohl(hdr->kernel_len), 1, fp)) {
880                                 ERR("error in fwrite(): %s", strerror(errno));
881                         }
882                         fclose(fp);
883                 } else {
884                         ERR("error in fopen(): %s", strerror(errno));
885                 }
886                 free(filename);
887
888                 filename = malloc(strlen(inspect_info.file_name) + 8);
889                 sprintf(filename, "%s-rootfs", inspect_info.file_name);
890                 printf("Extracting rootfs to \"%s\"...\n", filename);
891                 fp = fopen(filename, "w");
892                 if (fp) {
893                         if (!fwrite(buf + ntohl(hdr->rootfs_ofs),
894                                     ntohl(hdr->rootfs_len), 1, fp)) {
895                                 ERR("error in fwrite(): %s", strerror(errno));
896                         }
897                         fclose(fp);
898                 } else {
899                         ERR("error in fopen(): %s", strerror(errno));
900                 }
901                 free(filename);
902         }
903
904  out_free_buf:
905         free(buf);
906  out:
907         return ret;
908 }
909
910 int main(int argc, char *argv[])
911 {
912         int ret = EXIT_FAILURE;
913         int err;
914
915         FILE *outfile;
916
917         progname = basename(argv[0]);
918
919         while ( 1 ) {
920                 int c;
921
922                 c = getopt(argc, argv, "a:B:H:E:F:L:V:N:W:ci:k:r:R:o:xhsjv:y:T:e");
923                 if (c == -1)
924                         break;
925
926                 switch (c) {
927                 case 'a':
928                         sscanf(optarg, "0x%x", &rootfs_align);
929                         break;
930                 case 'B':
931                         board_id = optarg;
932                         break;
933                 case 'H':
934                         opt_hw_id = optarg;
935                         break;
936                 case 'E':
937                         sscanf(optarg, "0x%x", &kernel_ep);
938                         break;
939                 case 'F':
940                         layout_id = optarg;
941                         break;
942                 case 'W':
943                         opt_hw_rev = optarg;
944                         break;
945                 case 'L':
946                         sscanf(optarg, "0x%x", &kernel_la);
947                         break;
948                 case 'V':
949                         version = optarg;
950                         break;
951                 case 'v':
952                         fw_ver = optarg;
953                         break;
954                 case 'y':
955                         sver = optarg;
956                         break;
957                 case 'N':
958                         vendor = optarg;
959                         break;
960                 case 'c':
961                         combined++;
962                         break;
963                 case 'k':
964                         kernel_info.file_name = optarg;
965                         break;
966                 case 'r':
967                         rootfs_info.file_name = optarg;
968                         break;
969                 case 'R':
970                         sscanf(optarg, "0x%x", &rootfs_ofs);
971                         break;
972                 case 'o':
973                         ofname = optarg;
974                         break;
975                 case 's':
976                         strip_padding = 1;
977                         break;
978                 case 'i':
979                         inspect_info.file_name = optarg;
980                         break;
981                 case 'j':
982                         add_jffs2_eof = 1;
983                         break;
984                 case 'x':
985                         extract = 1;
986                         break;
987                 case 'T':
988                         hdr_ver = atoi(optarg);
989                         break;
990                 case 'e':
991                         endian_swap = true;
992                         break;
993                 case 'h':
994                         usage(EXIT_SUCCESS);
995                         break;
996                 default:
997                         usage(EXIT_FAILURE);
998                         break;
999                 }
1000         }
1001
1002         ret = check_options();
1003         if (ret)
1004                 goto out;
1005
1006         if (!inspect_info.file_name)
1007                 ret = build_fw();
1008         else
1009                 ret = inspect_fw();
1010
1011  out:
1012         return ret;
1013 }
1014