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