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