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