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