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