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