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