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