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