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