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