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