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