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