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