Fresh pull from upstream
[librecmc/librecmc.git] / tools / firmware-utils / src / mktplinkfw-kernel.c
1 /*
2  * Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
3  * Copyright (C) 2016 Tal Keren <kooolk@gmail.com>
4  *
5  * Stripped down version of the regular tplink firmware that is only used
6  * for compressing and booting the kernel.
7  *
8  * This tool was based on:
9  *   TP-Link WR941 V2 firmware checksum fixing tool.
10  *   Copyright (C) 2008,2009 Wang Jian <lark@linux.net.cn>
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License version 2 as published
14  * by the Free Software Foundation.
15  *
16  */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stdint.h>
21 #include <string.h>
22 #include <unistd.h>     /* for unlink() */
23 #include <libgen.h>
24 #include <getopt.h>     /* for getopt() */
25 #include <stdarg.h>
26 #include <errno.h>
27 #include <sys/stat.h>
28
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31
32 #define ALIGN(x,a) ({ typeof(a) __a = (a); (((x) + __a - 1) & ~(__a - 1)); })
33
34 #define HEADER_VERSION_V1       0x01000000
35
36 #define MD5SUM_LEN      16
37
38 struct file_info {
39         char            *file_name;     /* name of the file */
40         uint32_t        file_size;      /* length of the file */
41 };
42
43 struct fw_header {
44         uint32_t        version;        /* header version */
45         char            vendor_name[24];
46         char            fw_version[36];
47         uint32_t        hw_id;          /* hardware id */
48         uint32_t        hw_rev;         /* hardware revision */
49         uint32_t        unk1;
50         uint8_t         md5sum1[MD5SUM_LEN];
51         uint32_t        unk2;
52         uint8_t         md5sum2[MD5SUM_LEN];
53         uint32_t        unk3;
54         uint32_t        kernel_la;      /* kernel load address */
55         uint32_t        kernel_ep;      /* kernel entry point */
56         uint32_t        fw_length;      /* total length of the firmware */
57         uint32_t        kernel_ofs;     /* kernel data offset */
58         uint32_t        kernel_len;     /* kernel data length */
59         uint32_t        rootfs_ofs;     /* rootfs data offset */
60         uint32_t        rootfs_len;     /* rootfs data length */
61         uint32_t        boot_ofs;       /* bootloader data offset */
62         uint32_t        boot_len;       /* bootloader data length */
63         uint16_t        ver_hi;
64         uint16_t        ver_mid;
65         uint16_t        ver_lo;
66         uint8_t         pad[354];
67 } __attribute__ ((packed));
68
69
70 /*
71  * Globals
72  */
73 static char *ofname;
74 static char *progname;
75 static char *vendor = "TP-LINK Technologies";
76 static char *version = "ver. 1.0";
77 static char *fw_ver = "0.0.0";
78 static uint32_t hdr_ver = HEADER_VERSION_V1;
79
80 static char *opt_hw_id;
81 static uint32_t hw_id = 0;
82 static struct file_info kernel_info;
83 static uint32_t kernel_la = 0;
84 static uint32_t kernel_ep = 0;
85 static uint32_t kernel_len = 0;
86
87 /*
88  * Message macros
89  */
90 #define ERR(fmt, ...) do { \
91         fflush(0); \
92         fprintf(stderr, "[%s] *** error: " fmt "\n", \
93                         progname, ## __VA_ARGS__ ); \
94 } while (0)
95
96 #define ERRS(fmt, ...) do { \
97         int save = errno; \
98         fflush(0); \
99         fprintf(stderr, "[%s] *** error: " fmt ": %s\n", \
100                         progname, ## __VA_ARGS__, strerror(save)); \
101 } while (0)
102
103 #define DBG(fmt, ...) do { \
104         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
105 } while (0)
106
107 static void usage(int status)
108 {
109         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
110         struct board_info *board;
111
112         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
113         fprintf(stream,
114 "\n"
115 "Options:\n"
116 "  -E <ep>         kernel entry point with <ep> (hexval prefixed with 0x)\n"
117 "  -L <la>         kernel load address with <la> (hexval prefixed with 0x)\n"
118 "  -H <hwid>       use hardware id specified with <hwid>\n"
119 "  -k <file>       read kernel image from the file <file>\n"
120 "  -o <file>       write output to the file <file>\n"
121 "  -N <vendor>     set image vendor to <vendor>\n"
122 "  -V <version>    set image version to <version>\n"
123 "  -h              show this screen\n"
124         );
125
126         exit(status);
127 }
128
129 static int get_file_stat(struct file_info *fdata)
130 {
131         struct stat st;
132         int res;
133
134         if (fdata->file_name == NULL)
135                 return 0;
136
137         res = stat(fdata->file_name, &st);
138         if (res){
139                 ERRS("stat failed on %s", fdata->file_name);
140                 return res;
141         }
142
143         fdata->file_size = st.st_size;
144         return 0;
145 }
146
147 static int read_to_buf(struct file_info *fdata, char *buf)
148 {
149         FILE *f;
150         int ret = EXIT_FAILURE;
151
152         f = fopen(fdata->file_name, "r");
153         if (f == NULL) {
154                 ERRS("could not open \"%s\" for reading", fdata->file_name);
155                 goto out;
156         }
157
158         errno = 0;
159         fread(buf, fdata->file_size, 1, f);
160         if (errno != 0) {
161                 ERRS("unable to read from file \"%s\"", fdata->file_name);
162                 goto out_close;
163         }
164
165         ret = EXIT_SUCCESS;
166
167  out_close:
168         fclose(f);
169  out:
170         return ret;
171 }
172
173 static int check_options(void)
174 {
175         int ret;
176
177         if (opt_hw_id) {
178                 hw_id = strtoul(opt_hw_id, NULL, 0);
179         }
180
181         if (!kernel_la || !kernel_ep) {
182                 ERR("kernel loading address and entry point must be specified");
183                 return -1;
184         }
185
186         if (kernel_info.file_name == NULL) {
187                 ERR("no kernel image specified");
188                 return -1;
189         }
190
191         ret = get_file_stat(&kernel_info);
192         if (ret)
193                 return ret;
194
195         kernel_len = kernel_info.file_size;
196
197         if (ofname == NULL) {
198                 ERR("no output file specified");
199                 return -1;
200         }
201
202         return 0;
203 }
204
205 static void fill_header(char *buf)
206 {
207         struct fw_header *hdr = (struct fw_header *)buf;
208
209         memset(hdr, 0, sizeof(struct fw_header));
210
211         hdr->version = htonl(hdr_ver);
212         strncpy(hdr->vendor_name, vendor, sizeof(hdr->vendor_name));
213         strncpy(hdr->fw_version, version, sizeof(hdr->fw_version));
214
215         /**
216          * This field is ignored and not specified in stock firmware
217          * It is specified here to ensure sysupgrade hardware compatibility
218          * The hardware id of a device is in the product-info partition
219          */
220         hdr->hw_id = htonl(hw_id);
221
222         hdr->kernel_la = htonl(kernel_la);
223         hdr->kernel_ep = htonl(kernel_ep);
224
225         hdr->kernel_ofs = htonl(sizeof(struct fw_header));
226         hdr->kernel_len = htonl(kernel_len);
227 }
228
229 static int write_fw(char *data, int len)
230 {
231         FILE *f;
232         int ret = EXIT_FAILURE;
233
234         f = fopen(ofname, "w");
235         if (f == NULL) {
236                 ERRS("could not open \"%s\" for writing", ofname);
237                 goto out;
238         }
239
240         errno = 0;
241         fwrite(data, len, 1, f);
242         if (errno) {
243                 ERRS("unable to write output file");
244                 goto out_flush;
245         }
246
247         DBG("firmware file \"%s\" completed", ofname);
248
249         ret = EXIT_SUCCESS;
250
251  out_flush:
252         fflush(f);
253         fclose(f);
254         if (ret != EXIT_SUCCESS) {
255                 unlink(ofname);
256         }
257  out:
258         return ret;
259 }
260
261 static int build_fw(void)
262 {
263         int buflen;
264         char *buf;
265         char *p;
266         int ret = EXIT_FAILURE;
267
268         buflen = sizeof(struct fw_header) + kernel_len;
269         buflen = ALIGN(buflen, 0x4);
270
271         buf = malloc(buflen);
272         if (!buf) {
273                 ERR("no memory for buffer\n");
274                 goto out;
275         }
276
277         memset(buf, 0, buflen);
278         p = buf + sizeof(struct fw_header);
279         ret = read_to_buf(&kernel_info, p);
280         if (ret)
281                 goto out_free_buf;
282
283         fill_header(buf);
284         ret = write_fw(buf, buflen);
285         if (ret)
286                 goto out_free_buf;
287
288         ret = EXIT_SUCCESS;
289
290  out_free_buf:
291         free(buf);
292  out:
293         return ret;
294 }
295
296 int main(int argc, char *argv[])
297 {
298         int ret = EXIT_FAILURE;
299         int err;
300
301         FILE *outfile;
302
303         progname = basename(argv[0]);
304
305         while ( 1 ) {
306                 int c;
307
308                 c = getopt(argc, argv, "H:E:L:V:N:k:o:h");
309                 if (c == -1)
310                         break;
311
312                 switch (c) {
313                 case 'H':
314                         opt_hw_id = optarg;
315                         break;
316                 case 'E':
317                         sscanf(optarg, "0x%x", &kernel_ep);
318                         break;
319                 case 'L':
320                         sscanf(optarg, "0x%x", &kernel_la);
321                         break;
322                 case 'V':
323                         version = optarg;
324                         break;
325                 case 'N':
326                         vendor = optarg;
327                         break;
328                 case 'k':
329                         kernel_info.file_name = optarg;
330                         break;
331                 case 'o':
332                         ofname = optarg;
333                         break;
334                 case 'h':
335                         usage(EXIT_SUCCESS);
336                         break;
337                 default:
338                         usage(EXIT_FAILURE);
339                         break;
340                 }
341         }
342
343         ret = check_options();
344         if (ret)
345                 goto out;
346
347         ret = build_fw();
348
349  out:
350         return ret;
351 }
352