ath79: add support for TP-Link Archer C6 v2
[oweals/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 <stdbool.h>
23 #include <endian.h>
24 #include <errno.h>
25 #include <sys/stat.h>
26
27 #include <arpa/inet.h>
28 #include <netinet/in.h>
29
30 #include "md5.h"
31 #include "mktplinkfw-lib.h"
32
33 #define HEADER_VERSION_V1       0x01000000
34 #define HEADER_VERSION_V2       0x02000000
35
36 struct fw_header {
37         uint32_t        version;        /* header version */
38         char            vendor_name[24];
39         char            fw_version[36];
40         uint32_t        hw_id;          /* hardware id */
41         uint32_t        hw_rev;         /* hardware revision */
42         uint32_t        region_code;    /* region code */
43         uint8_t         md5sum1[MD5SUM_LEN];
44         uint32_t        unk2;
45         uint8_t         md5sum2[MD5SUM_LEN];
46         uint32_t        unk3;
47         uint32_t        kernel_la;      /* kernel load address */
48         uint32_t        kernel_ep;      /* kernel entry point */
49         uint32_t        fw_length;      /* total length of the firmware */
50         uint32_t        kernel_ofs;     /* kernel data offset */
51         uint32_t        kernel_len;     /* kernel data length */
52         uint32_t        rootfs_ofs;     /* rootfs data offset */
53         uint32_t        rootfs_len;     /* rootfs data length */
54         uint32_t        boot_ofs;       /* bootloader data offset */
55         uint32_t        boot_len;       /* bootloader data length */
56         uint16_t        ver_hi;
57         uint16_t        ver_mid;
58         uint16_t        ver_lo;
59         uint8_t         pad[130];
60         char            region_str1[32];
61         char            region_str2[32];
62         uint8_t         pad2[160];
63 } __attribute__ ((packed));
64
65 struct fw_region {
66         char            name[4];
67         uint32_t        code;
68 };
69
70
71 /*
72  * Globals
73  */
74 char *ofname;
75 char *progname;
76 static char *vendor = "TP-LINK Technologies";
77 static char *version = "ver. 1.0";
78 static char *fw_ver = "0.0.0";
79 static uint32_t hdr_ver = HEADER_VERSION_V1;
80
81 static char *layout_id;
82 struct flash_layout *layout;
83 static char *opt_hw_id;
84 static uint32_t hw_id;
85 static char *opt_hw_rev;
86 static uint32_t hw_rev;
87 static uint32_t opt_hdr_ver = 1;
88 static char *country;
89 static const struct fw_region *region;
90 static int fw_ver_lo;
91 static int fw_ver_mid;
92 static int fw_ver_hi;
93 struct file_info kernel_info;
94 static uint32_t kernel_la = 0;
95 static uint32_t kernel_ep = 0;
96 uint32_t kernel_len = 0;
97 struct file_info rootfs_info;
98 uint32_t rootfs_ofs = 0;
99 uint32_t rootfs_align;
100 static struct file_info boot_info;
101 int combined;
102 int strip_padding;
103 int add_jffs2_eof;
104 static uint32_t fw_max_len;
105 static uint32_t reserved_space;
106
107 static struct file_info inspect_info;
108 static int extract = 0;
109 static bool endian_swap = false;
110 static bool rootfs_ofs_calc = false;
111
112 static const char md5salt_normal[MD5SUM_LEN] = {
113         0xdc, 0xd7, 0x3a, 0xa5, 0xc3, 0x95, 0x98, 0xfb,
114         0xdd, 0xf9, 0xe7, 0xf4, 0x0e, 0xae, 0x47, 0x38,
115 };
116
117 static const char md5salt_boot[MD5SUM_LEN] = {
118         0x8c, 0xef, 0x33, 0x5b, 0xd5, 0xc5, 0xce, 0xfa,
119         0xa7, 0x9c, 0x28, 0xda, 0xb2, 0xe9, 0x0f, 0x42,
120 };
121
122 static struct flash_layout layouts[] = {
123         {
124                 .id             = "4M",
125                 .fw_max_len     = 0x3c0000,
126                 .kernel_la      = 0x80060000,
127                 .kernel_ep      = 0x80060000,
128                 .rootfs_ofs     = 0x140000,
129         }, {
130                 .id             = "4Mlzma",
131                 .fw_max_len     = 0x3c0000,
132                 .kernel_la      = 0x80060000,
133                 .kernel_ep      = 0x80060000,
134                 .rootfs_ofs     = 0x100000,
135         }, {
136                 .id             = "8M",
137                 .fw_max_len     = 0x7c0000,
138                 .kernel_la      = 0x80060000,
139                 .kernel_ep      = 0x80060000,
140                 .rootfs_ofs     = 0x140000,
141         }, {
142                 .id             = "8Mlzma",
143                 .fw_max_len     = 0x7c0000,
144                 .kernel_la      = 0x80060000,
145                 .kernel_ep      = 0x80060000,
146                 .rootfs_ofs     = 0x100000,
147         }, {
148                 .id             = "16M",
149                 .fw_max_len     = 0xf80000,
150                 .kernel_la      = 0x80060000,
151                 .kernel_ep      = 0x80060000,
152                 .rootfs_ofs     = 0x140000,
153         }, {
154                 .id             = "16Mlzma",
155                 .fw_max_len     = 0xf80000,
156                 .kernel_la      = 0x80060000,
157                 .kernel_ep      = 0x80060000,
158                 .rootfs_ofs     = 0x100000,
159         }, {
160                 .id             = "16Mppc",
161                 .fw_max_len     = 0xf80000,
162                 .kernel_la      = 0x00000000 ,
163                 .kernel_ep      = 0xc0000000,
164                 .rootfs_ofs     = 0x2a0000,
165         }, {
166                 /* terminating entry */
167         }
168 };
169
170 static const struct fw_region regions[] = {
171         /* Default region (universal) uses code 0 as well */
172         {"US", 1},
173         {"EU", 0},
174         {"BR", 0},
175 };
176
177 static const struct fw_region * find_region(const char *country) {
178         size_t i;
179
180         for (i = 0; i < ARRAY_SIZE(regions); i++) {
181                 if (strcasecmp(regions[i].name, country) == 0)
182                         return &regions[i];
183         }
184
185         return NULL;
186 }
187
188 static void usage(int status)
189 {
190         fprintf(stderr, "Usage: %s [OPTIONS...]\n", progname);
191         fprintf(stderr,
192 "\n"
193 "Options:\n"
194 "  -c              use combined kernel image\n"
195 "  -e              swap endianness in kernel load address and entry point\n"
196 "  -E <ep>         overwrite kernel entry point with <ep> (hexval prefixed with 0x)\n"
197 "  -L <la>         overwrite kernel load address with <la> (hexval prefixed with 0x)\n"
198 "  -H <hwid>       use hardware id specified with <hwid>\n"
199 "  -W <hwrev>      use hardware revision specified with <hwrev>\n"
200 "  -C <country>    set region code to <country>\n"
201 "  -F <id>         use flash layout specified with <id>\n"
202 "  -k <file>       read kernel image from the file <file>\n"
203 "  -r <file>       read rootfs image from the file <file>\n"
204 "  -a <align>      align the rootfs start on an <align> bytes boundary\n"
205 "  -R <offset>     overwrite rootfs offset with <offset> (hexval prefixed with 0x)\n"
206 "  -O              calculate rootfs offset for combined images\n"
207 "  -o <file>       write output to the file <file>\n"
208 "  -s              strip padding from the end of the image\n"
209 "  -j              add jffs2 end-of-filesystem markers\n"
210 "  -N <vendor>     set image vendor to <vendor>\n"
211 "  -V <version>    set image version to <version>\n"
212 "  -v <version>    set firmware version to <version>\n"
213 "  -m <version>    set header version to <version>\n"
214 "  -i <file>       inspect given firmware file <file>\n"
215 "  -x              extract kernel and rootfs while inspecting (requires -i)\n"
216 "  -X <size>       reserve <size> bytes in the firmware image (hexval prefixed with 0x)\n"
217 "  -h              show this screen\n"
218         );
219
220         exit(status);
221 }
222
223 static int check_options(void)
224 {
225         int ret;
226         int exceed_bytes;
227
228         if (inspect_info.file_name) {
229                 ret = get_file_stat(&inspect_info);
230                 if (ret)
231                         return ret;
232
233                 return 0;
234         } else if (extract) {
235                 ERR("no firmware for inspection specified");
236                 return -1;
237         }
238
239         if (opt_hw_id == NULL) {
240                 ERR("hardware id not specified");
241                 return -1;
242         }
243         hw_id = strtoul(opt_hw_id, NULL, 0);
244
245         if (!combined && layout_id == NULL) {
246                 ERR("flash layout is not specified");
247                 return -1;
248         }
249
250         if (opt_hw_rev)
251                 hw_rev = strtoul(opt_hw_rev, NULL, 0);
252         else
253                 hw_rev = 1;
254
255         if (country) {
256                 region = find_region(country);
257                 if (!region) {
258                         ERR("unknown region code \"%s\"", country);
259                         return -1;
260                 }
261         }
262
263         if (combined) {
264                 if (!kernel_la || !kernel_ep) {
265                         ERR("kernel loading address and entry point must be specified for combined image");
266                         return -1;
267                 }
268         } else {
269                 layout = find_layout(layouts, layout_id);
270                 if (layout == NULL) {
271                         ERR("unknown flash layout \"%s\"", layout_id);
272                         return -1;
273                 }
274
275                 if (!kernel_la)
276                         kernel_la = layout->kernel_la;
277                 if (!kernel_ep)
278                         kernel_ep = layout->kernel_ep;
279                 if (!rootfs_ofs)
280                         rootfs_ofs = layout->rootfs_ofs;
281
282                 if (reserved_space > layout->fw_max_len) {
283                         ERR("reserved space is not valid");
284                         return -1;
285                 }
286         }
287
288         if (kernel_info.file_name == NULL) {
289                 ERR("no kernel image specified");
290                 return -1;
291         }
292
293         ret = get_file_stat(&kernel_info);
294         if (ret)
295                 return ret;
296
297         kernel_len = kernel_info.file_size;
298
299         if (!combined) {
300                 fw_max_len = layout->fw_max_len - reserved_space;
301
302                 if (rootfs_info.file_name == NULL) {
303                         ERR("no rootfs image specified");
304                         return -1;
305                 }
306
307                 ret = get_file_stat(&rootfs_info);
308                 if (ret)
309                         return ret;
310
311                 if (rootfs_align) {
312                         kernel_len += sizeof(struct fw_header);
313                         rootfs_ofs = ALIGN(kernel_len, rootfs_align);
314                         kernel_len -= sizeof(struct fw_header);
315
316                         DBG("rootfs offset aligned to 0x%u", rootfs_ofs);
317
318                         exceed_bytes = kernel_len + rootfs_info.file_size - (fw_max_len - sizeof(struct fw_header));
319                         if (exceed_bytes > 0) {
320                                 ERR("images are too big by %i bytes", exceed_bytes);
321                                 return -1;
322                         }
323                 } else {
324                         exceed_bytes = kernel_info.file_size - (rootfs_ofs - sizeof(struct fw_header));
325                         if (exceed_bytes > 0) {
326                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
327                                 return -1;
328                         }
329
330                         exceed_bytes = rootfs_info.file_size - (fw_max_len - rootfs_ofs);
331                         if (exceed_bytes > 0) {
332                                 ERR("rootfs image is too big by %i bytes", exceed_bytes);
333                                 return -1;
334                         }
335                 }
336         }
337
338         if (ofname == NULL) {
339                 ERR("no output file specified");
340                 return -1;
341         }
342
343         ret = sscanf(fw_ver, "%d.%d.%d", &fw_ver_hi, &fw_ver_mid, &fw_ver_lo);
344         if (ret != 3) {
345                 ERR("invalid firmware version '%s'", fw_ver);
346                 return -1;
347         }
348
349         if (opt_hdr_ver == 1) {
350                 hdr_ver = HEADER_VERSION_V1;
351         } else if (opt_hdr_ver == 2) {
352                 hdr_ver = HEADER_VERSION_V2;
353         } else {
354                 ERR("invalid header version '%u'", opt_hdr_ver);
355                 return -1;
356         }
357
358         return 0;
359 }
360
361 void fill_header(char *buf, int len)
362 {
363         struct fw_header *hdr = (struct fw_header *)buf;
364
365         memset(hdr, 0, sizeof(struct fw_header));
366
367         hdr->version = htonl(hdr_ver);
368         strncpy(hdr->vendor_name, vendor, sizeof(hdr->vendor_name));
369         strncpy(hdr->fw_version, version, sizeof(hdr->fw_version));
370         hdr->hw_id = htonl(hw_id);
371         hdr->hw_rev = htonl(hw_rev);
372
373         hdr->kernel_la = htonl(kernel_la);
374         hdr->kernel_ep = htonl(kernel_ep);
375         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
376         hdr->kernel_len = htonl(kernel_len);
377
378         if (!combined) {
379                 if (boot_info.file_size == 0)
380                         memcpy(hdr->md5sum1, md5salt_normal, sizeof(hdr->md5sum1));
381                 else
382                         memcpy(hdr->md5sum1, md5salt_boot, sizeof(hdr->md5sum1));
383
384                 hdr->fw_length = htonl(layout->fw_max_len);
385                 hdr->rootfs_ofs = htonl(rootfs_ofs);
386                 hdr->rootfs_len = htonl(rootfs_info.file_size);
387         }
388
389         if (combined && rootfs_ofs_calc) {
390                 hdr->rootfs_ofs = htonl(sizeof(struct fw_header) + kernel_len);
391         }
392
393         hdr->ver_hi = htons(fw_ver_hi);
394         hdr->ver_mid = htons(fw_ver_mid);
395         hdr->ver_lo = htons(fw_ver_lo);
396
397         if (region) {
398                 hdr->region_code = htonl(region->code);
399                 snprintf(
400                         hdr->region_str1, sizeof(hdr->region_str1), "00000000;%02X%02X%02X%02X;",
401                         region->name[0], region->name[1], region->name[2], region->name[3]
402                 );
403                 snprintf(
404                         hdr->region_str2, sizeof(hdr->region_str2), "%02X%02X%02X%02X",
405                         region->name[0], region->name[1], region->name[2], region->name[3]
406                 );
407         }
408
409         if (endian_swap) {
410                 hdr->kernel_la = bswap_32(hdr->kernel_la);
411                 hdr->kernel_ep = bswap_32(hdr->kernel_ep);
412         }
413
414         if (!combined)
415                 get_md5(buf, len, hdr->md5sum1);
416 }
417
418 static int inspect_fw(void)
419 {
420         char *buf;
421         struct fw_header *hdr;
422         uint8_t md5sum[MD5SUM_LEN];
423         int ret = EXIT_FAILURE;
424
425         buf = malloc(inspect_info.file_size);
426         if (!buf) {
427                 ERR("no memory for buffer!\n");
428                 goto out;
429         }
430
431         ret = read_to_buf(&inspect_info, buf);
432         if (ret)
433                 goto out_free_buf;
434         hdr = (struct fw_header *)buf;
435
436         inspect_fw_pstr("File name", inspect_info.file_name);
437         inspect_fw_phexdec("File size", inspect_info.file_size);
438
439         if ((ntohl(hdr->version) != HEADER_VERSION_V1) &&
440             (ntohl(hdr->version) != HEADER_VERSION_V2)) {
441                 ERR("file does not seem to have V1/V2 header!\n");
442                 goto out_free_buf;
443         }
444
445         inspect_fw_phexdec("Version 1 Header size", sizeof(struct fw_header));
446
447         memcpy(md5sum, hdr->md5sum1, sizeof(md5sum));
448         if (ntohl(hdr->boot_len) == 0)
449                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(md5sum));
450         else
451                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(md5sum));
452         get_md5(buf, inspect_info.file_size, hdr->md5sum1);
453
454         if (memcmp(md5sum, hdr->md5sum1, sizeof(md5sum))) {
455                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(*ERROR*)");
456                 inspect_fw_pmd5sum("          --> expected", hdr->md5sum1, "");
457         } else {
458                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(ok)");
459         }
460         if (ntohl(hdr->unk2) != 0)
461                 inspect_fw_phexdec("Unknown value 2", hdr->unk2);
462         inspect_fw_pmd5sum("Header MD5Sum2", hdr->md5sum2,
463                            "(purpose yet unknown, unchecked here)");
464         if (ntohl(hdr->unk3) != 0)
465                 inspect_fw_phexdec("Unknown value 3", hdr->unk3);
466
467         printf("\n");
468
469         inspect_fw_pstr("Vendor name", hdr->vendor_name);
470         inspect_fw_pstr("Firmware version", hdr->fw_version);
471         inspect_fw_phex("Hardware ID", ntohl(hdr->hw_id));
472         inspect_fw_phex("Hardware Revision", ntohl(hdr->hw_rev));
473         inspect_fw_phex("Region code", ntohl(hdr->region_code));
474
475         printf("\n");
476
477         inspect_fw_phexdec("Kernel data offset",
478                            ntohl(hdr->kernel_ofs));
479         inspect_fw_phexdec("Kernel data length",
480                            ntohl(hdr->kernel_len));
481         inspect_fw_phex("Kernel load address",
482                         ntohl(hdr->kernel_la));
483         inspect_fw_phex("Kernel entry point",
484                         ntohl(hdr->kernel_ep));
485         inspect_fw_phexdec("Rootfs data offset",
486                            ntohl(hdr->rootfs_ofs));
487         inspect_fw_phexdec("Rootfs data length",
488                            ntohl(hdr->rootfs_len));
489         inspect_fw_phexdec("Boot loader data offset",
490                            ntohl(hdr->boot_ofs));
491         inspect_fw_phexdec("Boot loader data length",
492                            ntohl(hdr->boot_len));
493         inspect_fw_phexdec("Total firmware length",
494                            ntohl(hdr->fw_length));
495
496         if (extract) {
497                 FILE *fp;
498                 char *filename;
499
500                 printf("\n");
501
502                 filename = malloc(strlen(inspect_info.file_name) + 8);
503                 sprintf(filename, "%s-kernel", inspect_info.file_name);
504                 printf("Extracting kernel to \"%s\"...\n", filename);
505                 fp = fopen(filename, "w");
506                 if (fp) {
507                         if (!fwrite(buf + ntohl(hdr->kernel_ofs),
508                                     ntohl(hdr->kernel_len), 1, fp)) {
509                                 ERR("error in fwrite(): %s", strerror(errno));
510                         }
511                         fclose(fp);
512                 } else {
513                         ERR("error in fopen(): %s", strerror(errno));
514                 }
515                 free(filename);
516
517                 filename = malloc(strlen(inspect_info.file_name) + 8);
518                 sprintf(filename, "%s-rootfs", inspect_info.file_name);
519                 printf("Extracting rootfs to \"%s\"...\n", filename);
520                 fp = fopen(filename, "w");
521                 if (fp) {
522                         if (!fwrite(buf + ntohl(hdr->rootfs_ofs),
523                                     ntohl(hdr->rootfs_len), 1, fp)) {
524                                 ERR("error in fwrite(): %s", strerror(errno));
525                         }
526                         fclose(fp);
527                 } else {
528                         ERR("error in fopen(): %s", strerror(errno));
529                 }
530                 free(filename);
531         }
532
533  out_free_buf:
534         free(buf);
535  out:
536         return ret;
537 }
538
539 int main(int argc, char *argv[])
540 {
541         int ret = EXIT_FAILURE;
542
543         progname = basename(argv[0]);
544
545         while ( 1 ) {
546                 int c;
547
548                 c = getopt(argc, argv, "a:H:E:F:L:m:V:N:W:C:ci:k:r:R:o:OxX:ehsjv:");
549                 if (c == -1)
550                         break;
551
552                 switch (c) {
553                 case 'a':
554                         sscanf(optarg, "0x%x", &rootfs_align);
555                         break;
556                 case 'H':
557                         opt_hw_id = optarg;
558                         break;
559                 case 'E':
560                         sscanf(optarg, "0x%x", &kernel_ep);
561                         break;
562                 case 'F':
563                         layout_id = optarg;
564                         break;
565                 case 'W':
566                         opt_hw_rev = optarg;
567                         break;
568                 case 'C':
569                         country = optarg;
570                         break;
571                 case 'L':
572                         sscanf(optarg, "0x%x", &kernel_la);
573                         break;
574                 case 'm':
575                         sscanf(optarg, "%u", &opt_hdr_ver);
576                         break;
577                 case 'V':
578                         version = optarg;
579                         break;
580                 case 'v':
581                         fw_ver = optarg;
582                         break;
583                 case 'N':
584                         vendor = optarg;
585                         break;
586                 case 'c':
587                         combined++;
588                         break;
589                 case 'k':
590                         kernel_info.file_name = optarg;
591                         break;
592                 case 'r':
593                         rootfs_info.file_name = optarg;
594                         break;
595                 case 'R':
596                         sscanf(optarg, "0x%x", &rootfs_ofs);
597                         break;
598                 case 'o':
599                         ofname = optarg;
600                         break;
601                 case 'O':
602                         rootfs_ofs_calc = 1;
603                         break;
604                 case 's':
605                         strip_padding = 1;
606                         break;
607                 case 'i':
608                         inspect_info.file_name = optarg;
609                         break;
610                 case 'j':
611                         add_jffs2_eof = 1;
612                         break;
613                 case 'x':
614                         extract = 1;
615                         break;
616                 case 'e':
617                         endian_swap = true;
618                         break;
619                 case 'h':
620                         usage(EXIT_SUCCESS);
621                         break;
622                 case 'X':
623                         sscanf(optarg, "0x%x", &reserved_space);
624                         break;
625                 default:
626                         usage(EXIT_FAILURE);
627                         break;
628                 }
629         }
630
631         ret = check_options();
632         if (ret)
633                 goto out;
634
635         if (!inspect_info.file_name)
636                 ret = build_fw(sizeof(struct fw_header));
637         else
638                 ret = inspect_fw();
639
640  out:
641         return ret;
642 }