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