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