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