tools: firmware-utils: fix compiler warnings
[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        0x04440001
35 #define HWID_ANTMINER_S3        0x04440003
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                 /* terminating entry */
438         }
439 };
440
441 /*
442  * Message macros
443  */
444 #define ERR(fmt, ...) do { \
445         fflush(0); \
446         fprintf(stderr, "[%s] *** error: " fmt "\n", \
447                         progname, ## __VA_ARGS__ ); \
448 } while (0)
449
450 #define ERRS(fmt, ...) do { \
451         int save = errno; \
452         fflush(0); \
453         fprintf(stderr, "[%s] *** error: " fmt ": %s\n", \
454                         progname, ## __VA_ARGS__, strerror(save)); \
455 } while (0)
456
457 #define DBG(fmt, ...) do { \
458         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
459 } while (0)
460
461 static struct board_info *find_board(char *id)
462 {
463         struct board_info *ret;
464         struct board_info *board;
465
466         ret = NULL;
467         for (board = boards; board->id != NULL; board++){
468                 if (strcasecmp(id, board->id) == 0) {
469                         ret = board;
470                         break;
471                 }
472         };
473
474         return ret;
475 }
476
477 static struct board_info *find_board_by_hwid(uint32_t hw_id)
478 {
479         struct board_info *board;
480
481         for (board = boards; board->id != NULL; board++) {
482                 if (hw_id == board->hw_id)
483                         return board;
484         };
485
486         return NULL;
487 }
488
489 static struct flash_layout *find_layout(char *id)
490 {
491         struct flash_layout *ret;
492         struct flash_layout *l;
493
494         ret = NULL;
495         for (l = layouts; l->id != NULL; l++){
496                 if (strcasecmp(id, l->id) == 0) {
497                         ret = l;
498                         break;
499                 }
500         };
501
502         return ret;
503 }
504
505 static void usage(int status)
506 {
507         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
508         struct board_info *board;
509
510         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
511         fprintf(stream,
512 "\n"
513 "Options:\n"
514 "  -B <board>      create image for the board specified with <board>\n"
515 "  -c              use combined kernel image\n"
516 "  -E <ep>         overwrite kernel entry point with <ep> (hexval prefixed with 0x)\n"
517 "  -L <la>         overwrite kernel load address with <la> (hexval prefixed with 0x)\n"
518 "  -H <hwid>       use hardware id specified with <hwid>\n"
519 "  -W <hwrev>      use hardware revision specified with <hwrev>\n"
520 "  -F <id>         use flash layout specified with <id>\n"
521 "  -k <file>       read kernel image from the file <file>\n"
522 "  -r <file>       read rootfs image from the file <file>\n"
523 "  -a <align>      align the rootfs start on an <align> bytes boundary\n"
524 "  -R <offset>     overwrite rootfs offset with <offset> (hexval prefixed with 0x)\n"
525 "  -o <file>       write output to the file <file>\n"
526 "  -s              strip padding from the end of the image\n"
527 "  -S              ignore firmware size limit (only for combined images)\n"
528 "  -j              add jffs2 end-of-filesystem markers\n"
529 "  -N <vendor>     set image vendor to <vendor>\n"
530 "  -V <version>    set image version to <version>\n"
531 "  -v <version>    set firmware version to <version>\n"
532 "  -m <version>    set header version to <version>\n"
533 "  -i <file>       inspect given firmware file <file>\n"
534 "  -x              extract kernel and rootfs while inspecting (requires -i)\n"
535 "  -X <size>       reserve <size> bytes in the firmware image (hexval prefixed with 0x)\n"
536 "  -h              show this screen\n"
537         );
538
539         exit(status);
540 }
541
542 static int get_md5(char *data, int size, char *md5)
543 {
544         MD5_CTX ctx;
545
546         MD5_Init(&ctx);
547         MD5_Update(&ctx, data, size);
548         MD5_Final(md5, &ctx);
549 }
550
551 static int get_file_stat(struct file_info *fdata)
552 {
553         struct stat st;
554         int res;
555
556         if (fdata->file_name == NULL)
557                 return 0;
558
559         res = stat(fdata->file_name, &st);
560         if (res){
561                 ERRS("stat failed on %s", fdata->file_name);
562                 return res;
563         }
564
565         fdata->file_size = st.st_size;
566         return 0;
567 }
568
569 static int read_to_buf(struct file_info *fdata, char *buf)
570 {
571         FILE *f;
572         int ret = EXIT_FAILURE;
573
574         f = fopen(fdata->file_name, "r");
575         if (f == NULL) {
576                 ERRS("could not open \"%s\" for reading", fdata->file_name);
577                 goto out;
578         }
579
580         errno = 0;
581         fread(buf, fdata->file_size, 1, f);
582         if (errno != 0) {
583                 ERRS("unable to read from file \"%s\"", fdata->file_name);
584                 goto out_close;
585         }
586
587         ret = EXIT_SUCCESS;
588
589  out_close:
590         fclose(f);
591  out:
592         return ret;
593 }
594
595 static int check_options(void)
596 {
597         int ret;
598         int exceed_bytes;
599
600         if (inspect_info.file_name) {
601                 ret = get_file_stat(&inspect_info);
602                 if (ret)
603                         return ret;
604
605                 return 0;
606         } else if (extract) {
607                 ERR("no firmware for inspection specified");
608                 return -1;
609         }
610
611         if (board_id == NULL && opt_hw_id == NULL) {
612                 ERR("either board or hardware id must be specified");
613                 return -1;
614         }
615
616         if (board_id) {
617                 board = find_board(board_id);
618                 if (board == NULL) {
619                         ERR("unknown/unsupported board id \"%s\"", board_id);
620                         return -1;
621                 }
622                 if (layout_id == NULL)
623                         layout_id = board->layout_id;
624
625                 hw_id = board->hw_id;
626                 hw_rev = board->hw_rev;
627         } else {
628                 if (layout_id == NULL) {
629                         ERR("flash layout is not specified");
630                         return -1;
631                 }
632                 hw_id = strtoul(opt_hw_id, NULL, 0);
633
634                 if (opt_hw_rev)
635                         hw_rev = strtoul(opt_hw_rev, NULL, 0);
636                 else
637                         hw_rev = 1;
638         }
639
640         layout = find_layout(layout_id);
641         if (layout == NULL) {
642                 ERR("unknown flash layout \"%s\"", layout_id);
643                 return -1;
644         }
645
646         if (!kernel_la)
647                 kernel_la = layout->kernel_la;
648         if (!kernel_ep)
649                 kernel_ep = layout->kernel_ep;
650         if (!rootfs_ofs)
651                 rootfs_ofs = layout->rootfs_ofs;
652
653         if (reserved_space > layout->fw_max_len) {
654                 ERR("reserved space is not valid");
655                 return -1;
656         }
657
658         fw_max_len = layout->fw_max_len - reserved_space;
659
660         if (kernel_info.file_name == NULL) {
661                 ERR("no kernel image specified");
662                 return -1;
663         }
664
665         ret = get_file_stat(&kernel_info);
666         if (ret)
667                 return ret;
668
669         kernel_len = kernel_info.file_size;
670
671         if (combined) {
672                 exceed_bytes = kernel_info.file_size - (fw_max_len - sizeof(struct fw_header));
673                 if (exceed_bytes > 0) {
674                         if (!ignore_size) {
675                                 ERR("kernel image is too big by %i bytes", exceed_bytes);
676                                 return -1;
677                         }
678                         layout->fw_max_len = sizeof(struct fw_header) +
679                                              kernel_info.file_size +
680                                              reserved_space;
681                 }
682         } else {
683                 if (rootfs_info.file_name == NULL) {
684                         ERR("no rootfs image specified");
685                         return -1;
686                 }
687
688                 ret = get_file_stat(&rootfs_info);
689                 if (ret)
690                         return ret;
691
692                 if (rootfs_align) {
693                         kernel_len += sizeof(struct fw_header);
694                         kernel_len = ALIGN(kernel_len, rootfs_align);
695                         kernel_len -= sizeof(struct fw_header);
696
697                         DBG("kernel length aligned to %u", kernel_len);
698
699                         exceed_bytes = kernel_len + rootfs_info.file_size - (fw_max_len - sizeof(struct fw_header));
700                         if (exceed_bytes > 0) {
701                                 ERR("images are too big by %i bytes", exceed_bytes);
702                                 return -1;
703                         }
704                 } else {
705                         exceed_bytes = kernel_info.file_size - (rootfs_ofs - sizeof(struct fw_header));
706                         if (exceed_bytes > 0) {
707                                 ERR("kernel image is too big");
708                                 return -1;
709                         }
710
711                         exceed_bytes = rootfs_info.file_size - (fw_max_len - rootfs_ofs);
712                         if (exceed_bytes > 0) {
713                                 ERR("rootfs image is too big");
714                                 return -1;
715                         }
716                 }
717         }
718
719         if (ofname == NULL) {
720                 ERR("no output file specified");
721                 return -1;
722         }
723
724         ret = sscanf(fw_ver, "%d.%d.%d", &fw_ver_hi, &fw_ver_mid, &fw_ver_lo);
725         if (ret != 3) {
726                 ERR("invalid firmware version '%s'", fw_ver);
727                 return -1;
728         }
729
730         if (opt_hdr_ver == 1) {
731                 hdr_ver = HEADER_VERSION_V1;
732         } else if (opt_hdr_ver == 2) {
733                 hdr_ver = HEADER_VERSION_V2;
734         } else {
735                 ERR("invalid header version '%u'", opt_hdr_ver);
736                 return -1;
737         }
738
739         return 0;
740 }
741
742 static void fill_header(char *buf, int len)
743 {
744         struct fw_header *hdr = (struct fw_header *)buf;
745
746         memset(hdr, 0, sizeof(struct fw_header));
747
748         hdr->version = htonl(hdr_ver);
749         strncpy(hdr->vendor_name, vendor, sizeof(hdr->vendor_name));
750         strncpy(hdr->fw_version, version, sizeof(hdr->fw_version));
751         hdr->hw_id = htonl(hw_id);
752         hdr->hw_rev = htonl(hw_rev);
753
754         if (boot_info.file_size == 0)
755                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(hdr->md5sum1));
756         else
757                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(hdr->md5sum1));
758
759         hdr->kernel_la = htonl(kernel_la);
760         hdr->kernel_ep = htonl(kernel_ep);
761         hdr->fw_length = htonl(layout->fw_max_len);
762         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
763         hdr->kernel_len = htonl(kernel_len);
764         if (!combined) {
765                 hdr->rootfs_ofs = htonl(rootfs_ofs);
766                 hdr->rootfs_len = htonl(rootfs_info.file_size);
767         }
768
769         hdr->ver_hi = htons(fw_ver_hi);
770         hdr->ver_mid = htons(fw_ver_mid);
771         hdr->ver_lo = htons(fw_ver_lo);
772
773         get_md5(buf, len, hdr->md5sum1);
774 }
775
776 static int pad_jffs2(char *buf, int currlen)
777 {
778         int len;
779         uint32_t pad_mask;
780
781         len = currlen;
782         pad_mask = (64 * 1024);
783         while ((len < layout->fw_max_len) && (pad_mask != 0)) {
784                 uint32_t mask;
785                 int i;
786
787                 for (i = 10; i < 32; i++) {
788                         mask = 1 << i;
789                         if (pad_mask & mask)
790                                 break;
791                 }
792
793                 len = ALIGN(len, mask);
794
795                 for (i = 10; i < 32; i++) {
796                         mask = 1 << i;
797                         if ((len & (mask - 1)) == 0)
798                                 pad_mask &= ~mask;
799                 }
800
801                 for (i = 0; i < sizeof(jffs2_eof_mark); i++)
802                         buf[len + i] = jffs2_eof_mark[i];
803
804                 len += sizeof(jffs2_eof_mark);
805         }
806
807         return len;
808 }
809
810 static int write_fw(char *data, int len)
811 {
812         FILE *f;
813         int ret = EXIT_FAILURE;
814
815         f = fopen(ofname, "w");
816         if (f == NULL) {
817                 ERRS("could not open \"%s\" for writing", ofname);
818                 goto out;
819         }
820
821         errno = 0;
822         fwrite(data, len, 1, f);
823         if (errno) {
824                 ERRS("unable to write output file");
825                 goto out_flush;
826         }
827
828         DBG("firmware file \"%s\" completed", ofname);
829
830         ret = EXIT_SUCCESS;
831
832  out_flush:
833         fflush(f);
834         fclose(f);
835         if (ret != EXIT_SUCCESS) {
836                 unlink(ofname);
837         }
838  out:
839         return ret;
840 }
841
842 static int build_fw(void)
843 {
844         int buflen;
845         char *buf;
846         char *p;
847         int ret = EXIT_FAILURE;
848         int writelen = 0;
849
850         buflen = layout->fw_max_len;
851
852         buf = malloc(buflen);
853         if (!buf) {
854                 ERR("no memory for buffer\n");
855                 goto out;
856         }
857
858         memset(buf, 0xff, buflen);
859         p = buf + sizeof(struct fw_header);
860         ret = read_to_buf(&kernel_info, p);
861         if (ret)
862                 goto out_free_buf;
863
864         writelen = sizeof(struct fw_header) + kernel_len;
865
866         if (!combined) {
867                 if (rootfs_align)
868                         p = buf + writelen;
869                 else
870                         p = buf + rootfs_ofs;
871
872                 ret = read_to_buf(&rootfs_info, p);
873                 if (ret)
874                         goto out_free_buf;
875
876                 if (rootfs_align)
877                         writelen += rootfs_info.file_size;
878                 else
879                         writelen = rootfs_ofs + rootfs_info.file_size;
880
881                 if (add_jffs2_eof)
882                         writelen = pad_jffs2(buf, writelen);
883         }
884
885         if (!strip_padding)
886                 writelen = buflen;
887
888         fill_header(buf, writelen);
889         ret = write_fw(buf, writelen);
890         if (ret)
891                 goto out_free_buf;
892
893         ret = EXIT_SUCCESS;
894
895  out_free_buf:
896         free(buf);
897  out:
898         return ret;
899 }
900
901 /* Helper functions to inspect_fw() representing different output formats */
902 static inline void inspect_fw_pstr(char *label, char *str)
903 {
904         printf("%-23s: %s\n", label, str);
905 }
906
907 static inline void inspect_fw_phex(char *label, uint32_t val)
908 {
909         printf("%-23s: 0x%08x\n", label, val);
910 }
911
912 static inline void inspect_fw_phexpost(char *label,
913                                        uint32_t val, char *post)
914 {
915         printf("%-23s: 0x%08x (%s)\n", label, val, post);
916 }
917
918 static inline void inspect_fw_phexdef(char *label,
919                                       uint32_t val, uint32_t defval)
920 {
921         printf("%-23s: 0x%08x                  ", label, val);
922
923         if (val == defval)
924                 printf("(== OpenWrt default)\n");
925         else
926                 printf("(OpenWrt default: 0x%08x)\n", defval);
927 }
928
929 static inline void inspect_fw_phexexp(char *label,
930                                       uint32_t val, uint32_t expval)
931 {
932         printf("%-23s: 0x%08x ", label, val);
933
934         if (val == expval)
935                 printf("(ok)\n");
936         else
937                 printf("(expected: 0x%08x)\n", expval);
938 }
939
940 static inline void inspect_fw_phexdec(char *label, uint32_t val)
941 {
942         printf("%-23s: 0x%08x / %8u bytes\n", label, val, val);
943 }
944
945 static inline void inspect_fw_phexdecdef(char *label,
946                                          uint32_t val, uint32_t defval)
947 {
948         printf("%-23s: 0x%08x / %8u bytes ", label, val, val);
949
950         if (val == defval)
951                 printf("(== OpenWrt default)\n");
952         else
953                 printf("(OpenWrt default: 0x%08x)\n", defval);
954 }
955
956 static inline void inspect_fw_pmd5sum(char *label, uint8_t *val, char *text)
957 {
958         int i;
959
960         printf("%-23s:", label);
961         for (i=0; i<MD5SUM_LEN; i++)
962                 printf(" %02x", val[i]);
963         printf(" %s\n", text);
964 }
965
966 static int inspect_fw(void)
967 {
968         char *buf;
969         struct fw_header *hdr;
970         uint8_t md5sum[MD5SUM_LEN];
971         struct board_info *board;
972         int ret = EXIT_FAILURE;
973
974         buf = malloc(inspect_info.file_size);
975         if (!buf) {
976                 ERR("no memory for buffer!\n");
977                 goto out;
978         }
979
980         ret = read_to_buf(&inspect_info, buf);
981         if (ret)
982                 goto out_free_buf;
983         hdr = (struct fw_header *)buf;
984
985         inspect_fw_pstr("File name", inspect_info.file_name);
986         inspect_fw_phexdec("File size", inspect_info.file_size);
987
988         if ((ntohl(hdr->version) != HEADER_VERSION_V1) &&
989             (ntohl(hdr->version) != HEADER_VERSION_V2)) {
990                 ERR("file does not seem to have V1/V2 header!\n");
991                 goto out_free_buf;
992         }
993
994         inspect_fw_phexdec("Version 1 Header size", sizeof(struct fw_header));
995
996         if (ntohl(hdr->unk1) != 0)
997                 inspect_fw_phexdec("Unknown value 1", hdr->unk1);
998
999         memcpy(md5sum, hdr->md5sum1, sizeof(md5sum));
1000         if (ntohl(hdr->boot_len) == 0)
1001                 memcpy(hdr->md5sum1, md5salt_normal, sizeof(md5sum));
1002         else
1003                 memcpy(hdr->md5sum1, md5salt_boot, sizeof(md5sum));
1004         get_md5(buf, inspect_info.file_size, hdr->md5sum1);
1005
1006         if (memcmp(md5sum, hdr->md5sum1, sizeof(md5sum))) {
1007                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(*ERROR*)");
1008                 inspect_fw_pmd5sum("          --> expected", hdr->md5sum1, "");
1009         } else {
1010                 inspect_fw_pmd5sum("Header MD5Sum1", md5sum, "(ok)");
1011         }
1012         if (ntohl(hdr->unk2) != 0)
1013                 inspect_fw_phexdec("Unknown value 2", hdr->unk2);
1014         inspect_fw_pmd5sum("Header MD5Sum2", hdr->md5sum2,
1015                            "(purpose yet unknown, unchecked here)");
1016         if (ntohl(hdr->unk3) != 0)
1017                 inspect_fw_phexdec("Unknown value 3", hdr->unk3);
1018
1019         printf("\n");
1020
1021         inspect_fw_pstr("Vendor name", hdr->vendor_name);
1022         inspect_fw_pstr("Firmware version", hdr->fw_version);
1023         board = find_board_by_hwid(ntohl(hdr->hw_id));
1024         if (board) {
1025                 layout = find_layout(board->layout_id);
1026                 inspect_fw_phexpost("Hardware ID",
1027                                     ntohl(hdr->hw_id), board->id);
1028                 inspect_fw_phexexp("Hardware Revision",
1029                                    ntohl(hdr->hw_rev), board->hw_rev);
1030         } else {
1031                 inspect_fw_phexpost("Hardware ID",
1032                                     ntohl(hdr->hw_id), "unknown");
1033                 inspect_fw_phex("Hardware Revision",
1034                                 ntohl(hdr->hw_rev));
1035         }
1036
1037         printf("\n");
1038
1039         inspect_fw_phexdec("Kernel data offset",
1040                            ntohl(hdr->kernel_ofs));
1041         inspect_fw_phexdec("Kernel data length",
1042                            ntohl(hdr->kernel_len));
1043         if (board) {
1044                 inspect_fw_phexdef("Kernel load address",
1045                                    ntohl(hdr->kernel_la),
1046                                    layout ? layout->kernel_la : 0xffffffff);
1047                 inspect_fw_phexdef("Kernel entry point",
1048                                    ntohl(hdr->kernel_ep),
1049                                    layout ? layout->kernel_ep : 0xffffffff);
1050                 inspect_fw_phexdecdef("Rootfs data offset",
1051                                       ntohl(hdr->rootfs_ofs),
1052                                       layout ? layout->rootfs_ofs : 0xffffffff);
1053         } else {
1054                 inspect_fw_phex("Kernel load address",
1055                                 ntohl(hdr->kernel_la));
1056                 inspect_fw_phex("Kernel entry point",
1057                                 ntohl(hdr->kernel_ep));
1058                 inspect_fw_phexdec("Rootfs data offset",
1059                                    ntohl(hdr->rootfs_ofs));
1060         }
1061         inspect_fw_phexdec("Rootfs data length",
1062                            ntohl(hdr->rootfs_len));
1063         inspect_fw_phexdec("Boot loader data offset",
1064                            ntohl(hdr->boot_ofs));
1065         inspect_fw_phexdec("Boot loader data length",
1066                            ntohl(hdr->boot_len));
1067         inspect_fw_phexdec("Total firmware length",
1068                            ntohl(hdr->fw_length));
1069
1070         if (extract) {
1071                 FILE *fp;
1072                 char *filename;
1073
1074                 printf("\n");
1075
1076                 filename = malloc(strlen(inspect_info.file_name) + 8);
1077                 sprintf(filename, "%s-kernel", inspect_info.file_name);
1078                 printf("Extracting kernel to \"%s\"...\n", filename);
1079                 fp = fopen(filename, "w");
1080                 if (fp) {
1081                         if (!fwrite(buf + ntohl(hdr->kernel_ofs),
1082                                     ntohl(hdr->kernel_len), 1, fp)) {
1083                                 ERR("error in fwrite(): %s", strerror(errno));
1084                         }
1085                         fclose(fp);
1086                 } else {
1087                         ERR("error in fopen(): %s", strerror(errno));
1088                 }
1089                 free(filename);
1090
1091                 filename = malloc(strlen(inspect_info.file_name) + 8);
1092                 sprintf(filename, "%s-rootfs", inspect_info.file_name);
1093                 printf("Extracting rootfs to \"%s\"...\n", filename);
1094                 fp = fopen(filename, "w");
1095                 if (fp) {
1096                         if (!fwrite(buf + ntohl(hdr->rootfs_ofs),
1097                                     ntohl(hdr->rootfs_len), 1, fp)) {
1098                                 ERR("error in fwrite(): %s", strerror(errno));
1099                         }
1100                         fclose(fp);
1101                 } else {
1102                         ERR("error in fopen(): %s", strerror(errno));
1103                 }
1104                 free(filename);
1105         }
1106
1107  out_free_buf:
1108         free(buf);
1109  out:
1110         return ret;
1111 }
1112
1113 int main(int argc, char *argv[])
1114 {
1115         int ret = EXIT_FAILURE;
1116         int err;
1117
1118         FILE *outfile;
1119
1120         progname = basename(argv[0]);
1121
1122         while ( 1 ) {
1123                 int c;
1124
1125                 c = getopt(argc, argv, "a:B:H:E:F:L:m:V:N:W:ci:k:r:R:o:xX:hsSjv:");
1126                 if (c == -1)
1127                         break;
1128
1129                 switch (c) {
1130                 case 'a':
1131                         sscanf(optarg, "0x%x", &rootfs_align);
1132                         break;
1133                 case 'B':
1134                         board_id = optarg;
1135                         break;
1136                 case 'H':
1137                         opt_hw_id = optarg;
1138                         break;
1139                 case 'E':
1140                         sscanf(optarg, "0x%x", &kernel_ep);
1141                         break;
1142                 case 'F':
1143                         layout_id = optarg;
1144                         break;
1145                 case 'W':
1146                         opt_hw_rev = optarg;
1147                         break;
1148                 case 'L':
1149                         sscanf(optarg, "0x%x", &kernel_la);
1150                         break;
1151                 case 'm':
1152                         sscanf(optarg, "%u", &opt_hdr_ver);
1153                         break;
1154                 case 'V':
1155                         version = optarg;
1156                         break;
1157                 case 'v':
1158                         fw_ver = optarg;
1159                         break;
1160                 case 'N':
1161                         vendor = optarg;
1162                         break;
1163                 case 'c':
1164                         combined++;
1165                         break;
1166                 case 'k':
1167                         kernel_info.file_name = optarg;
1168                         break;
1169                 case 'r':
1170                         rootfs_info.file_name = optarg;
1171                         break;
1172                 case 'R':
1173                         sscanf(optarg, "0x%x", &rootfs_ofs);
1174                         break;
1175                 case 'o':
1176                         ofname = optarg;
1177                         break;
1178                 case 's':
1179                         strip_padding = 1;
1180                         break;
1181                 case 'S':
1182                         ignore_size = 1;
1183                         break;
1184                 case 'i':
1185                         inspect_info.file_name = optarg;
1186                         break;
1187                 case 'j':
1188                         add_jffs2_eof = 1;
1189                         break;
1190                 case 'x':
1191                         extract = 1;
1192                         break;
1193                 case 'h':
1194                         usage(EXIT_SUCCESS);
1195                         break;
1196                 case 'X':
1197                         sscanf(optarg, "0x%x", &reserved_space);
1198                         break;
1199                 default:
1200                         usage(EXIT_FAILURE);
1201                         break;
1202                 }
1203         }
1204
1205         ret = check_options();
1206         if (ret)
1207                 goto out;
1208
1209         if (!inspect_info.file_name)
1210                 ret = build_fw();
1211         else
1212                 ret = inspect_fw();
1213
1214  out:
1215         return ret;
1216 }
1217