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