firmware-utils: mktplinkfw: add option for endianness swap
[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
32 #define ALIGN(x,a) ({ typeof(a) __a = (a); (((x) + __a - 1) & ~(__a - 1)); })
33 #define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
34
35 #define HEADER_VERSION_V1       0x01000000
36 #define HEADER_VERSION_V2       0x02000000
37
38 #define MD5SUM_LEN      16
39
40 struct file_info {
41         char            *file_name;     /* name of the file */
42         uint32_t        file_size;      /* length of the file */
43 };
44
45 struct fw_header {
46         uint32_t        version;        /* header version */
47         char            vendor_name[24];
48         char            fw_version[36];
49         uint32_t        hw_id;          /* hardware id */
50         uint32_t        hw_rev;         /* hardware revision */
51         uint32_t        region_code;    /* region code */
52         uint8_t         md5sum1[MD5SUM_LEN];
53         uint32_t        unk2;
54         uint8_t         md5sum2[MD5SUM_LEN];
55         uint32_t        unk3;
56         uint32_t        kernel_la;      /* kernel load address */
57         uint32_t        kernel_ep;      /* kernel entry point */
58         uint32_t        fw_length;      /* total length of the firmware */
59         uint32_t        kernel_ofs;     /* kernel data offset */
60         uint32_t        kernel_len;     /* kernel data length */
61         uint32_t        rootfs_ofs;     /* rootfs data offset */
62         uint32_t        rootfs_len;     /* rootfs data length */
63         uint32_t        boot_ofs;       /* bootloader data offset */
64         uint32_t        boot_len;       /* bootloader data length */
65         uint16_t        ver_hi;
66         uint16_t        ver_mid;
67         uint16_t        ver_lo;
68         uint8_t         pad[130];
69         char            region_str1[32];
70         char            region_str2[32];
71         uint8_t         pad2[160];
72 } __attribute__ ((packed));
73
74 struct flash_layout {
75         char            *id;
76         uint32_t        fw_max_len;
77         uint32_t        kernel_la;
78         uint32_t        kernel_ep;
79         uint32_t        rootfs_ofs;
80 };
81
82 struct fw_region {
83         char            name[4];
84         uint32_t        code;
85 };
86
87
88 /*
89  * Globals
90  */
91 static char *ofname;
92 static char *progname;
93 static char *vendor = "TP-LINK Technologies";
94 static char *version = "ver. 1.0";
95 static char *fw_ver = "0.0.0";
96 static uint32_t hdr_ver = HEADER_VERSION_V1;
97
98 static char *layout_id;
99 static struct flash_layout *layout;
100 static char *opt_hw_id;
101 static uint32_t hw_id;
102 static char *opt_hw_rev;
103 static uint32_t hw_rev;
104 static uint32_t opt_hdr_ver = 1;
105 static char *country;
106 static const struct fw_region *region;
107 static int fw_ver_lo;
108 static int fw_ver_mid;
109 static int fw_ver_hi;
110 static struct file_info kernel_info;
111 static uint32_t kernel_la = 0;
112 static uint32_t kernel_ep = 0;
113 static uint32_t kernel_len = 0;
114 static struct file_info rootfs_info;
115 static uint32_t rootfs_ofs = 0;
116 static uint32_t rootfs_align;
117 static struct file_info boot_info;
118 static int combined;
119 static int strip_padding;
120 static int ignore_size;
121 static int add_jffs2_eof;
122 static unsigned char jffs2_eof_mark[4] = {0xde, 0xad, 0xc0, 0xde};
123 static uint32_t fw_max_len;
124 static uint32_t reserved_space;
125
126 static struct file_info inspect_info;
127 static int extract = 0;
128 static bool endian_swap = false;
129
130 static const char md5salt_normal[MD5SUM_LEN] = {
131         0xdc, 0xd7, 0x3a, 0xa5, 0xc3, 0x95, 0x98, 0xfb,
132         0xdd, 0xf9, 0xe7, 0xf4, 0x0e, 0xae, 0x47, 0x38,
133 };
134
135 static const char md5salt_boot[MD5SUM_LEN] = {
136         0x8c, 0xef, 0x33, 0x5b, 0xd5, 0xc5, 0xce, 0xfa,
137         0xa7, 0x9c, 0x28, 0xda, 0xb2, 0xe9, 0x0f, 0x42,
138 };
139
140 static struct flash_layout layouts[] = {
141         {
142                 .id             = "4M",
143                 .fw_max_len     = 0x3c0000,
144                 .kernel_la      = 0x80060000,
145                 .kernel_ep      = 0x80060000,
146                 .rootfs_ofs     = 0x140000,
147         }, {
148                 .id             = "4Mlzma",
149                 .fw_max_len     = 0x3c0000,
150                 .kernel_la      = 0x80060000,
151                 .kernel_ep      = 0x80060000,
152                 .rootfs_ofs     = 0x100000,
153         }, {
154                 .id             = "8M",
155                 .fw_max_len     = 0x7c0000,
156                 .kernel_la      = 0x80060000,
157                 .kernel_ep      = 0x80060000,
158                 .rootfs_ofs     = 0x140000,
159         }, {
160                 .id             = "8Mlzma",
161                 .fw_max_len     = 0x7c0000,
162                 .kernel_la      = 0x80060000,
163                 .kernel_ep      = 0x80060000,
164                 .rootfs_ofs     = 0x100000,
165         }, {
166                 .id             = "16M",
167                 .fw_max_len     = 0xf80000,
168                 .kernel_la      = 0x80060000,
169                 .kernel_ep      = 0x80060000,
170                 .rootfs_ofs     = 0x140000,
171         }, {
172                 .id             = "16Mlzma",
173                 .fw_max_len     = 0xf80000,
174                 .kernel_la      = 0x80060000,
175                 .kernel_ep      = 0x80060000,
176                 .rootfs_ofs     = 0x100000,
177         }, {
178                 .id             = "16Mppc",
179                 .fw_max_len     = 0xf80000,
180                 .kernel_la      = 0x00000000 ,
181                 .kernel_ep      = 0xc0000000,
182                 .rootfs_ofs     = 0x2a0000,
183         }, {
184                 /*
185                         Some devices (e.g. TL-WR1043 v4) use a mktplinkfw kernel image
186                         embedded in a tplink-safeloader image as os-image partition.
187
188                         We use a 1.5MB partition for the compressed kernel, which should
189                         be sufficient, but not too wasteful (the flash of the TL-WR1043 v4
190                         has 16MB in total).
191                 */
192                 .id             = "16Msafeloader",
193                 .fw_max_len     = 0x180000,
194                 .kernel_la      = 0x80060000,
195                 .kernel_ep      = 0x80060000,
196                 .rootfs_ofs     = 0,
197         }, {
198                 /* terminating entry */
199         }
200 };
201
202 static const struct fw_region regions[] = {
203         /* Default region (universal) uses code 0 as well */
204         {"US", 1},
205         {"EU", 0},
206 };
207
208 /*
209  * Message macros
210  */
211 #define ERR(fmt, ...) do { \
212         fflush(0); \
213         fprintf(stderr, "[%s] *** error: " fmt "\n", \
214                         progname, ## __VA_ARGS__ ); \
215 } while (0)
216
217 #define ERRS(fmt, ...) do { \
218         int save = errno; \
219         fflush(0); \
220         fprintf(stderr, "[%s] *** error: " fmt ": %s\n", \
221                         progname, ## __VA_ARGS__, strerror(save)); \
222 } while (0)
223
224 #define DBG(fmt, ...) do { \
225         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
226 } while (0)
227
228 static struct flash_layout *find_layout(const char *id)
229 {
230         struct flash_layout *ret;
231         struct flash_layout *l;
232
233         ret = NULL;
234         for (l = layouts; l->id != NULL; l++){
235                 if (strcasecmp(id, l->id) == 0) {
236                         ret = l;
237                         break;
238                 }
239         };
240
241         return ret;
242 }
243
244 static const struct fw_region * find_region(const char *country) {
245         size_t i;
246
247         for (i = 0; i < ARRAY_SIZE(regions); i++) {
248                 if (strcasecmp(regions[i].name, country) == 0)
249                         return &regions[i];
250         }
251
252         return NULL;
253 }
254
255 static void usage(int status)
256 {
257         fprintf(stderr, "Usage: %s [OPTIONS...]\n", progname);
258         fprintf(stderr,
259 "\n"
260 "Options:\n"
261 "  -c              use combined kernel image\n"
262 "  -e              swap endianness in kernel load address and entry point\n"
263 "  -E <ep>         overwrite kernel entry point with <ep> (hexval prefixed with 0x)\n"
264 "  -L <la>         overwrite kernel load address with <la> (hexval prefixed with 0x)\n"
265 "  -H <hwid>       use hardware id specified with <hwid>\n"
266 "  -W <hwrev>      use hardware revision specified with <hwrev>\n"
267 "  -C <country>    set region code to <country>\n"
268 "  -F <id>         use flash layout specified with <id>\n"
269 "  -k <file>       read kernel image from the file <file>\n"
270 "  -r <file>       read rootfs image from the file <file>\n"
271 "  -a <align>      align the rootfs start on an <align> bytes boundary\n"
272 "  -R <offset>     overwrite rootfs offset with <offset> (hexval prefixed with 0x)\n"
273 "  -o <file>       write output to the file <file>\n"
274 "  -s              strip padding from the end of the image\n"
275 "  -S              ignore firmware size limit (only for combined images)\n"
276 "  -j              add jffs2 end-of-filesystem markers\n"
277 "  -N <vendor>     set image vendor to <vendor>\n"
278 "  -V <version>    set image version to <version>\n"
279 "  -v <version>    set firmware version to <version>\n"
280 "  -m <version>    set header version to <version>\n"
281 "  -i <file>       inspect given firmware file <file>\n"
282 "  -x              extract kernel and rootfs while inspecting (requires -i)\n"
283 "  -X <size>       reserve <size> bytes in the firmware image (hexval prefixed with 0x)\n"
284 "  -h              show this screen\n"
285         );
286
287         exit(status);
288 }
289
290 static void get_md5(const char *data, int size, uint8_t *md5)
291 {
292         MD5_CTX ctx;
293
294         MD5_Init(&ctx);
295         MD5_Update(&ctx, data, size);
296         MD5_Final(md5, &ctx);
297 }
298
299 static int get_file_stat(struct file_info *fdata)
300 {
301         struct stat st;
302         int res;
303
304         if (fdata->file_name == NULL)
305                 return 0;
306
307         res = stat(fdata->file_name, &st);
308         if (res){
309                 ERRS("stat failed on %s", fdata->file_name);
310                 return res;
311         }
312
313         fdata->file_size = st.st_size;
314         return 0;
315 }
316
317 static int read_to_buf(const struct file_info *fdata, char *buf)
318 {
319         FILE *f;
320         int ret = EXIT_FAILURE;
321
322         f = fopen(fdata->file_name, "r");
323         if (f == NULL) {
324                 ERRS("could not open \"%s\" for reading", fdata->file_name);
325                 goto out;
326         }
327
328         errno = 0;
329         fread(buf, fdata->file_size, 1, f);
330         if (errno != 0) {
331                 ERRS("unable to read from file \"%s\"", fdata->file_name);
332                 goto out_close;
333         }
334
335         ret = EXIT_SUCCESS;
336
337  out_close:
338         fclose(f);
339  out:
340         return ret;
341 }
342
343 static int check_options(void)
344 {
345         int ret;
346         int exceed_bytes;
347
348         if (inspect_info.file_name) {
349                 ret = get_file_stat(&inspect_info);
350                 if (ret)
351                         return ret;
352
353                 return 0;
354         } else if (extract) {
355                 ERR("no firmware for inspection specified");
356                 return -1;
357         }
358
359         if (opt_hw_id == NULL) {
360                 ERR("hardware id not specified");
361                 return -1;
362         }
363         hw_id = strtoul(opt_hw_id, NULL, 0);
364
365         if (layout_id == NULL) {
366                 ERR("flash layout is not specified");
367                 return -1;
368         }
369
370         if (opt_hw_rev)
371                 hw_rev = strtoul(opt_hw_rev, NULL, 0);
372         else
373                 hw_rev = 1;
374
375         if (country) {
376                 region = find_region(country);
377                 if (!region) {
378                         ERR("unknown region code \"%s\"", country);
379                         return -1;
380                 }
381         }
382
383         layout = find_layout(layout_id);
384         if (layout == NULL) {
385                 ERR("unknown flash layout \"%s\"", layout_id);
386                 return -1;
387         }
388
389         if (!kernel_la)
390                 kernel_la = layout->kernel_la;
391         if (!kernel_ep)
392                 kernel_ep = layout->kernel_ep;
393         if (!rootfs_ofs)
394                 rootfs_ofs = layout->rootfs_ofs;
395
396         if (reserved_space > layout->fw_max_len) {
397                 ERR("reserved space is not valid");
398                 return -1;
399         }
400
401         fw_max_len = layout->fw_max_len - reserved_space;
402
403         if (kernel_info.file_name == NULL) {
404                 ERR("no kernel image specified");
405                 return -1;
406         }
407
408         ret = get_file_stat(&kernel_info);
409         if (ret)
410                 return ret;
411
412         kernel_len = kernel_info.file_size;
413
414         if (combined) {
415                 exceed_bytes = kernel_info.file_size - (fw_max_len - sizeof(struct fw_header));
416                 if (exceed_bytes > 0) {
417                         if (!ignore_size) {
418                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
419                                 return -1;
420                         }
421                         layout->fw_max_len = sizeof(struct fw_header) +
422                                              kernel_info.file_size +
423                                              reserved_space;
424                 }
425         } else {
426                 if (rootfs_info.file_name == NULL) {
427                         ERR("no rootfs image specified");
428                         return -1;
429                 }
430
431                 ret = get_file_stat(&rootfs_info);
432                 if (ret)
433                         return ret;
434
435                 if (rootfs_align) {
436                         kernel_len += sizeof(struct fw_header);
437                         kernel_len = ALIGN(kernel_len, rootfs_align);
438                         kernel_len -= sizeof(struct fw_header);
439
440                         DBG("kernel length aligned to %u", kernel_len);
441
442                         exceed_bytes = kernel_len + rootfs_info.file_size - (fw_max_len - sizeof(struct fw_header));
443                         if (exceed_bytes > 0) {
444                                 ERR("images are too big by %i bytes", exceed_bytes);
445                                 return -1;
446                         }
447                 } else {
448                         exceed_bytes = kernel_info.file_size - (rootfs_ofs - sizeof(struct fw_header));
449                         if (exceed_bytes > 0) {
450                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
451                                 return -1;
452                         }
453
454                         exceed_bytes = rootfs_info.file_size - (fw_max_len - rootfs_ofs);
455                         if (exceed_bytes > 0) {
456                                 ERR("rootfs image is too big by %i bytes", exceed_bytes);
457                                 return -1;
458                         }
459                 }
460         }
461
462         if (ofname == NULL) {
463                 ERR("no output file specified");
464                 return -1;
465         }
466
467         ret = sscanf(fw_ver, "%d.%d.%d", &fw_ver_hi, &fw_ver_mid, &fw_ver_lo);
468         if (ret != 3) {
469                 ERR("invalid firmware version '%s'", fw_ver);
470                 return -1;
471         }
472
473         if (opt_hdr_ver == 1) {
474                 hdr_ver = HEADER_VERSION_V1;
475         } else if (opt_hdr_ver == 2) {
476                 hdr_ver = HEADER_VERSION_V2;
477         } else {
478                 ERR("invalid header version '%u'", opt_hdr_ver);
479                 return -1;
480         }
481
482         return 0;
483 }
484
485 static void fill_header(char *buf, int len)
486 {
487         struct fw_header *hdr = (struct fw_header *)buf;
488
489         memset(hdr, 0, sizeof(struct fw_header));
490
491         hdr->version = htonl(hdr_ver);
492         strncpy(hdr->vendor_name, vendor, sizeof(hdr->vendor_name));
493         strncpy(hdr->fw_version, version, sizeof(hdr->fw_version));
494         hdr->hw_id = htonl(hw_id);
495         hdr->hw_rev = htonl(hw_rev);
496
497         if (boot_info.file_size == 0)
498                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(hdr->md5sum1));
499         else
500                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(hdr->md5sum1));
501
502         hdr->kernel_la = htonl(kernel_la);
503         hdr->kernel_ep = htonl(kernel_ep);
504         hdr->fw_length = htonl(layout->fw_max_len);
505         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
506         hdr->kernel_len = htonl(kernel_len);
507         if (!combined) {
508                 hdr->rootfs_ofs = htonl(rootfs_ofs);
509                 hdr->rootfs_len = htonl(rootfs_info.file_size);
510         }
511
512         hdr->ver_hi = htons(fw_ver_hi);
513         hdr->ver_mid = htons(fw_ver_mid);
514         hdr->ver_lo = htons(fw_ver_lo);
515
516         if (region) {
517                 hdr->region_code = htonl(region->code);
518                 snprintf(
519                         hdr->region_str1, sizeof(hdr->region_str1), "00000000;%02X%02X%02X%02X;",
520                         region->name[0], region->name[1], region->name[2], region->name[3]
521                 );
522                 snprintf(
523                         hdr->region_str2, sizeof(hdr->region_str2), "%02X%02X%02X%02X",
524                         region->name[0], region->name[1], region->name[2], region->name[3]
525                 );
526         }
527
528         if (endian_swap) {
529                 hdr->kernel_la = bswap_32(hdr->kernel_la);
530                 hdr->kernel_ep = bswap_32(hdr->kernel_ep);
531         }
532
533         get_md5(buf, len, hdr->md5sum1);
534 }
535
536 static int pad_jffs2(char *buf, int currlen)
537 {
538         int len;
539         uint32_t pad_mask;
540
541         len = currlen;
542         pad_mask = (64 * 1024);
543         while ((len < layout->fw_max_len) && (pad_mask != 0)) {
544                 uint32_t mask;
545                 int i;
546
547                 for (i = 10; i < 32; i++) {
548                         mask = 1 << i;
549                         if (pad_mask & mask)
550                                 break;
551                 }
552
553                 len = ALIGN(len, mask);
554
555                 for (i = 10; i < 32; i++) {
556                         mask = 1 << i;
557                         if ((len & (mask - 1)) == 0)
558                                 pad_mask &= ~mask;
559                 }
560
561                 for (i = 0; i < sizeof(jffs2_eof_mark); i++)
562                         buf[len + i] = jffs2_eof_mark[i];
563
564                 len += sizeof(jffs2_eof_mark);
565         }
566
567         return len;
568 }
569
570 static int write_fw(const char *data, int len)
571 {
572         FILE *f;
573         int ret = EXIT_FAILURE;
574
575         f = fopen(ofname, "w");
576         if (f == NULL) {
577                 ERRS("could not open \"%s\" for writing", ofname);
578                 goto out;
579         }
580
581         errno = 0;
582         fwrite(data, len, 1, f);
583         if (errno) {
584                 ERRS("unable to write output file");
585                 goto out_flush;
586         }
587
588         DBG("firmware file \"%s\" completed", ofname);
589
590         ret = EXIT_SUCCESS;
591
592  out_flush:
593         fflush(f);
594         fclose(f);
595         if (ret != EXIT_SUCCESS) {
596                 unlink(ofname);
597         }
598  out:
599         return ret;
600 }
601
602 static int build_fw(void)
603 {
604         int buflen;
605         char *buf;
606         char *p;
607         int ret = EXIT_FAILURE;
608         int writelen = 0;
609
610         buflen = layout->fw_max_len;
611
612         buf = malloc(buflen);
613         if (!buf) {
614                 ERR("no memory for buffer\n");
615                 goto out;
616         }
617
618         memset(buf, 0xff, buflen);
619         p = buf + sizeof(struct fw_header);
620         ret = read_to_buf(&kernel_info, p);
621         if (ret)
622                 goto out_free_buf;
623
624         writelen = sizeof(struct fw_header) + kernel_len;
625
626         if (!combined) {
627                 if (rootfs_align)
628                         p = buf + writelen;
629                 else
630                         p = buf + rootfs_ofs;
631
632                 ret = read_to_buf(&rootfs_info, p);
633                 if (ret)
634                         goto out_free_buf;
635
636                 if (rootfs_align)
637                         writelen += rootfs_info.file_size;
638                 else
639                         writelen = rootfs_ofs + rootfs_info.file_size;
640
641                 if (add_jffs2_eof)
642                         writelen = pad_jffs2(buf, writelen);
643         }
644
645         if (!strip_padding)
646                 writelen = buflen;
647
648         fill_header(buf, writelen);
649         ret = write_fw(buf, writelen);
650         if (ret)
651                 goto out_free_buf;
652
653         ret = EXIT_SUCCESS;
654
655  out_free_buf:
656         free(buf);
657  out:
658         return ret;
659 }
660
661 /* Helper functions to inspect_fw() representing different output formats */
662 static inline void inspect_fw_pstr(const char *label, const char *str)
663 {
664         printf("%-23s: %s\n", label, str);
665 }
666
667 static inline void inspect_fw_phex(const char *label, uint32_t val)
668 {
669         printf("%-23s: 0x%08x\n", label, val);
670 }
671
672 static inline void inspect_fw_phexdec(const char *label, uint32_t val)
673 {
674         printf("%-23s: 0x%08x / %8u bytes\n", label, val, val);
675 }
676
677 static inline void inspect_fw_pmd5sum(const char *label, const uint8_t *val, const char *text)
678 {
679         int i;
680
681         printf("%-23s:", label);
682         for (i=0; i<MD5SUM_LEN; i++)
683                 printf(" %02x", val[i]);
684         printf(" %s\n", text);
685 }
686
687 static int inspect_fw(void)
688 {
689         char *buf;
690         struct fw_header *hdr;
691         uint8_t md5sum[MD5SUM_LEN];
692         int ret = EXIT_FAILURE;
693
694         buf = malloc(inspect_info.file_size);
695         if (!buf) {
696                 ERR("no memory for buffer!\n");
697                 goto out;
698         }
699
700         ret = read_to_buf(&inspect_info, buf);
701         if (ret)
702                 goto out_free_buf;
703         hdr = (struct fw_header *)buf;
704
705         inspect_fw_pstr("File name", inspect_info.file_name);
706         inspect_fw_phexdec("File size", inspect_info.file_size);
707
708         if ((ntohl(hdr->version) != HEADER_VERSION_V1) &&
709             (ntohl(hdr->version) != HEADER_VERSION_V2)) {
710                 ERR("file does not seem to have V1/V2 header!\n");
711                 goto out_free_buf;
712         }
713
714         inspect_fw_phexdec("Version 1 Header size", sizeof(struct fw_header));
715
716         memcpy(md5sum, hdr->md5sum1, sizeof(md5sum));
717         if (ntohl(hdr->boot_len) == 0)
718                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(md5sum));
719         else
720                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(md5sum));
721         get_md5(buf, inspect_info.file_size, hdr->md5sum1);
722
723         if (memcmp(md5sum, hdr->md5sum1, sizeof(md5sum))) {
724                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(*ERROR*)");
725                 inspect_fw_pmd5sum("          --> expected", hdr->md5sum1, "");
726         } else {
727                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(ok)");
728         }
729         if (ntohl(hdr->unk2) != 0)
730                 inspect_fw_phexdec("Unknown value 2", hdr->unk2);
731         inspect_fw_pmd5sum("Header MD5Sum2", hdr->md5sum2,
732                            "(purpose yet unknown, unchecked here)");
733         if (ntohl(hdr->unk3) != 0)
734                 inspect_fw_phexdec("Unknown value 3", hdr->unk3);
735
736         printf("\n");
737
738         inspect_fw_pstr("Vendor name", hdr->vendor_name);
739         inspect_fw_pstr("Firmware version", hdr->fw_version);
740         inspect_fw_phex("Hardware ID", ntohl(hdr->hw_id));
741         inspect_fw_phex("Hardware Revision", ntohl(hdr->hw_rev));
742         inspect_fw_phex("Region code", ntohl(hdr->region_code));
743
744         printf("\n");
745
746         inspect_fw_phexdec("Kernel data offset",
747                            ntohl(hdr->kernel_ofs));
748         inspect_fw_phexdec("Kernel data length",
749                            ntohl(hdr->kernel_len));
750         inspect_fw_phex("Kernel load address",
751                         ntohl(hdr->kernel_la));
752         inspect_fw_phex("Kernel entry point",
753                         ntohl(hdr->kernel_ep));
754         inspect_fw_phexdec("Rootfs data offset",
755                            ntohl(hdr->rootfs_ofs));
756         inspect_fw_phexdec("Rootfs data length",
757                            ntohl(hdr->rootfs_len));
758         inspect_fw_phexdec("Boot loader data offset",
759                            ntohl(hdr->boot_ofs));
760         inspect_fw_phexdec("Boot loader data length",
761                            ntohl(hdr->boot_len));
762         inspect_fw_phexdec("Total firmware length",
763                            ntohl(hdr->fw_length));
764
765         if (extract) {
766                 FILE *fp;
767                 char *filename;
768
769                 printf("\n");
770
771                 filename = malloc(strlen(inspect_info.file_name) + 8);
772                 sprintf(filename, "%s-kernel", inspect_info.file_name);
773                 printf("Extracting kernel to \"%s\"...\n", filename);
774                 fp = fopen(filename, "w");
775                 if (fp) {
776                         if (!fwrite(buf + ntohl(hdr->kernel_ofs),
777                                     ntohl(hdr->kernel_len), 1, fp)) {
778                                 ERR("error in fwrite(): %s", strerror(errno));
779                         }
780                         fclose(fp);
781                 } else {
782                         ERR("error in fopen(): %s", strerror(errno));
783                 }
784                 free(filename);
785
786                 filename = malloc(strlen(inspect_info.file_name) + 8);
787                 sprintf(filename, "%s-rootfs", inspect_info.file_name);
788                 printf("Extracting rootfs to \"%s\"...\n", filename);
789                 fp = fopen(filename, "w");
790                 if (fp) {
791                         if (!fwrite(buf + ntohl(hdr->rootfs_ofs),
792                                     ntohl(hdr->rootfs_len), 1, fp)) {
793                                 ERR("error in fwrite(): %s", strerror(errno));
794                         }
795                         fclose(fp);
796                 } else {
797                         ERR("error in fopen(): %s", strerror(errno));
798                 }
799                 free(filename);
800         }
801
802  out_free_buf:
803         free(buf);
804  out:
805         return ret;
806 }
807
808 int main(int argc, char *argv[])
809 {
810         int ret = EXIT_FAILURE;
811
812         progname = basename(argv[0]);
813
814         while ( 1 ) {
815                 int c;
816
817                 c = getopt(argc, argv, "a:H:E:F:L:m:V:N:W:C:ci:k:r:R:o:xX:ehsSjv:");
818                 if (c == -1)
819                         break;
820
821                 switch (c) {
822                 case 'a':
823                         sscanf(optarg, "0x%x", &rootfs_align);
824                         break;
825                 case 'H':
826                         opt_hw_id = optarg;
827                         break;
828                 case 'E':
829                         sscanf(optarg, "0x%x", &kernel_ep);
830                         break;
831                 case 'F':
832                         layout_id = optarg;
833                         break;
834                 case 'W':
835                         opt_hw_rev = optarg;
836                         break;
837                 case 'C':
838                         country = optarg;
839                         break;
840                 case 'L':
841                         sscanf(optarg, "0x%x", &kernel_la);
842                         break;
843                 case 'm':
844                         sscanf(optarg, "%u", &opt_hdr_ver);
845                         break;
846                 case 'V':
847                         version = optarg;
848                         break;
849                 case 'v':
850                         fw_ver = optarg;
851                         break;
852                 case 'N':
853                         vendor = optarg;
854                         break;
855                 case 'c':
856                         combined++;
857                         break;
858                 case 'k':
859                         kernel_info.file_name = optarg;
860                         break;
861                 case 'r':
862                         rootfs_info.file_name = optarg;
863                         break;
864                 case 'R':
865                         sscanf(optarg, "0x%x", &rootfs_ofs);
866                         break;
867                 case 'o':
868                         ofname = optarg;
869                         break;
870                 case 's':
871                         strip_padding = 1;
872                         break;
873                 case 'S':
874                         ignore_size = 1;
875                         break;
876                 case 'i':
877                         inspect_info.file_name = optarg;
878                         break;
879                 case 'j':
880                         add_jffs2_eof = 1;
881                         break;
882                 case 'x':
883                         extract = 1;
884                         break;
885                 case 'e':
886                         endian_swap = true;
887                         break;
888                 case 'h':
889                         usage(EXIT_SUCCESS);
890                         break;
891                 case 'X':
892                         sscanf(optarg, "0x%x", &reserved_space);
893                         break;
894                 default:
895                         usage(EXIT_FAILURE);
896                         break;
897                 }
898         }
899
900         ret = check_options();
901         if (ret)
902                 goto out;
903
904         if (!inspect_info.file_name)
905                 ret = build_fw();
906         else
907                 ret = inspect_fw();
908
909  out:
910         return ret;
911 }