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