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