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