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