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