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