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