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