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