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