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