librecmc : Bump to v1.5.15
[librecmc/librecmc.git] / tools / firmware-utils / src / mksenaofw.c
1 /*
2  *
3  *  Copyright (C) 2012 OpenWrt.org
4  *  Copyright (C) 2012 Mikko Hissa <mikko.hissa@uta.fi>
5  *
6  *  This program is free software; you can redistribute it and/or modify it
7  *  under the terms of the GNU General Public License version 2 as published
8  *  by the Free Software Foundation.
9  *
10  */
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <stdarg.h>
16 #include <libgen.h>
17 #include <errno.h>
18 #include <arpa/inet.h>
19 #include <unistd.h>
20 #include "md5.h"
21
22 #define HDR_LEN                 0x60
23 #define BUF_SIZE                0x200
24 #define VERSION_SIZE            0x10
25 #define MD5_SIZE                0x10
26 #define PAD_SIZE                0x20
27
28 #define DEFAULT_BLOCK_SIZE      65535
29
30 #define DEFAULT_HEAD_VALUE      0x0
31 #define DEFAULT_VERSION         "123"
32 #define DEFAULT_MAGIC           0x12345678
33
34 typedef struct {
35         uint32_t head;
36         uint32_t vendor_id;
37         uint32_t product_id;
38         uint8_t  version[VERSION_SIZE];
39         uint32_t firmware_type;
40         uint32_t filesize;
41         uint32_t zero;
42         uint8_t  md5sum[MD5_SIZE];
43         uint8_t  pad[PAD_SIZE];
44         uint32_t chksum;
45         uint32_t magic;
46 } img_header;
47
48 typedef struct {
49         uint8_t id;
50         char * name;
51 } firmware_type;
52
53 typedef enum {
54         NONE, ENCODE, DECODE
55 } op_mode;
56
57 static firmware_type FIRMWARE_TYPES[] = {
58         { 0x00, "combo" }, /* Used for new capwap-included style header */
59         { 0x01, "bootloader" },
60         { 0x02, "kernel" },
61         { 0x03, "kernelapp" },
62         { 0x04, "apps" },
63         /* The types below this line vary by manufacturer */
64         { 0x05, "littleapps (D-Link)/factoryapps (EnGenius)" },
65         { 0x06, "sounds (D-Link)/littleapps (EnGenius)" },
66         { 0x07, "userconfig (D-Link)/appdata (EnGenius)" },
67         { 0x08, "userconfig (EnGenius)"},
68         { 0x09, "odmapps (EnGenius)"},
69         { 0x0a, "factoryapps (D-Link)" },
70         { 0x0b, "odmapps (D-Link)" },
71         { 0x0c, "langpack (D-Link)" }
72 };
73
74 #define MOD_DEFAULT 0x616C6C00
75 #define SKU_DEFAULT 0x0
76 #define DATECODE_NONE 0xFFFFFFFF
77 #define FIRMWARE_TYPE_NONE 0xFF
78
79 struct capwap_header {
80         uint32_t mod;
81         uint32_t sku;
82         uint32_t firmware_ver[3];
83         uint32_t datecode;
84         uint32_t capwap_ver[3];
85         uint32_t model_size;
86         uint8_t  model[];
87 };
88
89 static long get_file_size(const char *filename)
90 {
91         FILE *fp_file;
92         long result;
93
94         fp_file = fopen(filename, "r");
95         if (!fp_file)
96                 return -1;
97         fseek(fp_file, 0, SEEK_END);
98         result = ftell(fp_file);
99         fclose(fp_file);
100         return result;
101 }
102
103 static int header_checksum(void *data, size_t len)
104 {
105         int sum = 0; /* shouldn't this be unsigned ? */
106         size_t i;
107
108         if (data != NULL && len > 0) {
109                 for (i = 0; i < len; ++i)
110                         sum += ((unsigned char *)data)[i];
111                 return sum;
112         }
113
114         return -1;
115 }
116
117 static int md5_file(const char *filename, uint8_t *dst)
118 {
119         FILE *fp_src;
120         MD5_CTX ctx;
121         char buf[BUF_SIZE];
122         size_t bytes_read;
123
124         MD5_Init(&ctx);
125
126         fp_src = fopen(filename, "r+b");
127         if (!fp_src) {
128                 return -1;
129         }
130         while (!feof(fp_src)) {
131                 bytes_read = fread(&buf, 1, BUF_SIZE, fp_src);
132                 MD5_Update(&ctx, &buf, bytes_read);
133         }
134         fclose(fp_src);
135
136         MD5_Final(dst, &ctx);
137
138         return 0;
139 }
140
141 static int encode_image(const char *input_file_name,
142                         const char *output_file_name, img_header *header,
143                         struct capwap_header *cw_header, int block_size)
144 {
145         char buf[BUF_SIZE];
146         size_t pad_len = 0;
147         size_t bytes_avail;
148         size_t bytes_read;
149
150         FILE *fp_output;
151         FILE *fp_input;
152
153         int model_size;
154         long magic;
155         size_t i;
156
157         fp_input = fopen(input_file_name, "r+b");
158         if (!fp_input) {
159                 fprintf(stderr, "Cannot open %s !!\n", input_file_name);
160                 return -1;
161         }
162
163         fp_output = fopen(output_file_name, "w+b");
164         if (!fp_output) {
165                 fprintf(stderr, "Cannot open %s !!\n", output_file_name);
166                 fclose(fp_input);
167                 return -1;
168         }
169
170         header->filesize = get_file_size(input_file_name);
171         if (!header->filesize) {
172                 fprintf(stderr, "File %s open/size error!\n", input_file_name);
173                 fclose(fp_input);
174                 fclose(fp_output);
175                 return -1;
176         }
177         /*
178          * Zero padding
179          */
180         if (block_size > 0) {
181                 pad_len = block_size - (header->filesize % block_size);
182         }
183
184         if (md5_file(input_file_name, (uint8_t *) &header->md5sum) < 0) {
185                 fprintf(stderr, "MD5 failed on file %s\n", input_file_name);
186                 fclose(fp_input);
187                 fclose(fp_output);
188                 return -1;
189         }
190         header->zero = 0;
191         header->chksum = header_checksum(header, HDR_LEN);
192         if (cw_header) {
193                 header->chksum += header_checksum(cw_header,
194                         sizeof(struct capwap_header) + cw_header->model_size);
195         }
196
197         header->head = htonl(header->head);
198         header->vendor_id = htonl(header->vendor_id);
199         header->product_id = htonl(header->product_id);
200         header->firmware_type = htonl(header->firmware_type);
201         header->filesize = htonl(header->filesize);
202         header->chksum = htonl(header->chksum);
203         magic = header->magic;
204         header->magic = htonl(header->magic);
205
206         fwrite(header, HDR_LEN, 1, fp_output);
207
208         if (cw_header) {
209                 model_size = cw_header->model_size;
210                 cw_header->mod = htonl(cw_header->mod);
211                 cw_header->sku = htonl(cw_header->sku);
212                 cw_header->firmware_ver[0] = htonl(cw_header->firmware_ver[0]);
213                 cw_header->firmware_ver[1] = htonl(cw_header->firmware_ver[1]);
214                 cw_header->firmware_ver[2] = htonl(cw_header->firmware_ver[2]);
215                 cw_header->datecode = htonl(cw_header->datecode);
216                 cw_header->capwap_ver[0] = htonl(cw_header->capwap_ver[0]);
217                 cw_header->capwap_ver[1] = htonl(cw_header->capwap_ver[1]);
218                 cw_header->capwap_ver[2] = htonl(cw_header->capwap_ver[2]);
219                 cw_header->model_size = htonl(cw_header->model_size);
220                 fwrite(cw_header, sizeof(struct capwap_header) + model_size, 1,
221                        fp_output);
222         }
223
224         while (!feof(fp_input) || pad_len > 0) {
225
226                 if (!feof(fp_input))
227                         bytes_read = fread(&buf, 1, BUF_SIZE, fp_input);
228                 else
229                         bytes_read = 0;
230
231                 /*
232                  * No more bytes read, start padding
233                  */
234                 if (bytes_read < BUF_SIZE && pad_len > 0) {
235                         bytes_avail = BUF_SIZE - bytes_read;
236                         memset( &buf[bytes_read], 0, bytes_avail);
237                         bytes_read += bytes_avail < pad_len ? bytes_avail : pad_len;
238                         pad_len -= bytes_avail < pad_len ? bytes_avail : pad_len;
239                 }
240
241                 for (i = 0; i < bytes_read; i++)
242                         buf[i] ^= magic >> (i % 8) & 0xff;
243                 fwrite(&buf, bytes_read, 1, fp_output);
244         }
245
246         fclose(fp_input);
247         fclose(fp_output);
248         return 1;
249 }
250
251 int decode_image(const char *input_file_name, const char *output_file_name)
252 {
253         struct capwap_header cw_header;
254         char buf[BUF_SIZE];
255         img_header header;
256
257         char *pmodel = NULL;
258         FILE *fp_input;
259         FILE *fp_output;
260
261         size_t bytes_read;
262         size_t bytes_written;
263         unsigned int i;
264
265         fp_input = fopen(input_file_name, "r+b");
266         if (!fp_input) {
267                 fprintf(stderr, "Cannot open %s !!\n", input_file_name);
268                 return -1;
269         }
270
271         fp_output = fopen(output_file_name, "w+b");
272         if (!fp_output) {
273                 fprintf(stderr, "Cannot open %s !!\n", output_file_name);
274                 fclose(fp_input);
275                 return -1;
276         }
277
278         if (fread(&header, 1, HDR_LEN, fp_input) != HDR_LEN) {
279                 fprintf(stderr, "Incorrect header size reading base header!!");
280                 fclose(fp_input);
281                 fclose(fp_output);
282                 return -1;
283         }
284
285         header.head = ntohl(header.head);
286         header.vendor_id = ntohl(header.vendor_id);
287         header.product_id = ntohl(header.product_id);
288         header.firmware_type = ntohl(header.firmware_type);
289         header.filesize = ntohl(header.filesize);
290         header.chksum = ntohl(header.chksum);
291         header.magic = ntohl(header.magic);
292
293         /* read capwap header if firmware_type is zero */
294         if (header.firmware_type == 0) {
295                 if (fread(&cw_header, 1, sizeof(struct capwap_header),
296                           fp_input) != sizeof(struct capwap_header)) {
297                         fprintf(stderr, "Incorrect header size reading capwap_header!!");
298                         fclose(fp_input);
299                         fclose(fp_output);
300                         return -1;
301                 }
302                 cw_header.mod = ntohl(cw_header.mod);
303                 cw_header.sku = ntohl(cw_header.sku);
304                 cw_header.firmware_ver[0] = ntohl(cw_header.firmware_ver[0]);
305                 cw_header.firmware_ver[1] = ntohl(cw_header.firmware_ver[1]);
306                 cw_header.firmware_ver[2] = ntohl(cw_header.firmware_ver[2]);
307                 cw_header.datecode = ntohl(cw_header.datecode);
308                 cw_header.capwap_ver[0] = ntohl(cw_header.capwap_ver[0]);
309                 cw_header.capwap_ver[1] = ntohl(cw_header.capwap_ver[1]);
310                 cw_header.capwap_ver[2] = ntohl(cw_header.capwap_ver[2]);
311                 cw_header.model_size = ntohl(cw_header.model_size);
312
313                 pmodel = malloc(cw_header.model_size + 1);
314                 if (pmodel) {
315                         pmodel[cw_header.model_size] = '\0';
316                         if (fread(pmodel, 1, cw_header.model_size, fp_input) !=
317                                   cw_header.model_size) {
318                                 fprintf(stderr, "Incorrect header size reading model name!!");
319                                 fclose(fp_input);
320                                 fclose(fp_output);
321                                 return -1;
322                         }
323                 } else {
324                         fprintf(stderr, "Incorrect header size reading model name!!");
325                         fclose(fp_input);
326                         fclose(fp_output);
327                         return -1;
328                 }
329         }
330
331         bytes_written = 0;
332         while (!feof(fp_input)) {
333
334                 bytes_read = fread(&buf, 1, BUF_SIZE, fp_input);
335                 for (i = 0; i < bytes_read; i++)
336                         buf[i] ^= header.magic >> (i % 8) & 0xff;
337
338                 /*
339                  * Handle padded source file
340                  */
341                 if (bytes_written + bytes_read > header.filesize) {
342                         bytes_read = header.filesize - bytes_written;
343                         if (bytes_read > 0)
344                                 fwrite(&buf, bytes_read, 1, fp_output);
345                         break;
346                 }
347
348                 fwrite(&buf, bytes_read, 1, fp_output);
349                 bytes_written += bytes_read;
350         }
351
352         fclose(fp_input);
353         fclose(fp_output);
354
355         return 1;
356 }
357
358 static void usage(const char *progname, int status)
359 {
360         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
361         size_t i;
362
363         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
364         fprintf(stream, "\n"
365                         "Options:\n"
366                         "  -e <file>            encode image file <file>\n"
367                         "  -d <file>            decode image file <file>\n"
368                         "  -o <file>            write output to the file <file>\n"
369                         "  -t <type>            set image type to <type>\n"
370                         "                       valid image <type> values:\n");
371         for (i = 0; i < sizeof(FIRMWARE_TYPES) / sizeof(firmware_type); i++) {
372                 fprintf(stream, "                       %-5i= %s\n", FIRMWARE_TYPES[i].id,
373                                 FIRMWARE_TYPES[i].name);
374         }
375         fprintf(stream, "  -v <version>         set image version to <version>\n"
376                         "  -r <vendor>          set image vendor id to <vendor>\n"
377                         "  -p <product>         set image product id to <product>\n"
378                         "  -m <magic>           set encoding magic <magic>\n"
379                         "  -z                   enable image padding to <blocksize>\n"
380                         "  -b <blocksize>       set image <blocksize>, defaults to %u\n"
381                         "  -c <datecode>        add capwap header with <datecode> (e.g. 171101)\n"
382                         "  -w <fw_ver>          firmware version for capwap header (e.g. 3.0.1)\n"
383                         "  -x <cw_ver>          capwap firmware version for capwap header (e.g. 1.8.53)\n"
384                         "  -n <name>            model name for capwap header (e.g. ENS620EXT)\n"
385                         "  -h                   show this screen\n", DEFAULT_BLOCK_SIZE);
386         exit(status);
387 }
388
389 int main(int argc, char *argv[])
390 {
391         static const char period[2] = ".";
392         struct capwap_header cw_header;
393         img_header header;
394
395         struct capwap_header *pcw_header = NULL;
396         char *output_file = NULL;
397         char *input_file = NULL;
398         char *progname = NULL;
399         char *mod_name = NULL;
400         char *token;
401
402         op_mode mode = NONE;
403         int tmp, pad = 0;
404         int block_size;
405         size_t i;
406         int opt;
407
408         block_size = DEFAULT_BLOCK_SIZE;
409         progname = basename(argv[0]);
410
411         memset(&header, 0, sizeof(img_header));
412         header.magic = DEFAULT_MAGIC;
413         header.head = DEFAULT_HEAD_VALUE;
414         header.firmware_type = FIRMWARE_TYPE_NONE;
415         memset(&cw_header, 0, sizeof(struct capwap_header));
416         cw_header.mod = MOD_DEFAULT;
417         cw_header.sku = SKU_DEFAULT;
418         cw_header.datecode = DATECODE_NONE;
419         strncpy( (char*)&header.version, DEFAULT_VERSION, VERSION_SIZE - 1);
420
421         while ((opt = getopt(argc, argv, ":o:e:d:t:v:r:p:m:b:c:w:x:n:h?z")) != -1) {
422                 switch (opt) {
423                 case 'e':
424                         input_file = optarg;
425                         mode = ENCODE;
426                         break;
427                 case 'd':
428                         input_file = optarg;
429                         mode = DECODE;
430                         break;
431                 case 'o':
432                         output_file = optarg;
433                         break;
434                 case 't':
435                         tmp = strtol(optarg, 0, 10);
436                         for (i = 0; i < sizeof(FIRMWARE_TYPES) / sizeof(firmware_type);
437                                         i++) {
438                                 if (FIRMWARE_TYPES[i].id == tmp) {
439                                         header.firmware_type = FIRMWARE_TYPES[i].id;
440                                         break;
441                                 }
442                         }
443                         if (header.firmware_type == FIRMWARE_TYPE_NONE) {
444                                 fprintf(stderr, "Invalid firmware type \"0\"!\n");
445                                 usage(progname, EXIT_FAILURE);
446                         }
447                         break;
448                 case 'v':
449                         strncpy( (char*)&header.version, optarg,
450                                         VERSION_SIZE - 1);
451                         break;
452                 case 'r':
453                         header.vendor_id = strtol(optarg, 0, 0);
454                         break;
455                 case 'p':
456                         header.product_id = strtol(optarg, 0, 0);
457                         break;
458                 case 'm':
459                         header.magic = strtoul(optarg, 0, 16);
460                         break;
461                 case 'z':
462                         pad = 1;
463                         break;
464                 case 'b':
465                         block_size = strtol(optarg, 0, 10);
466                         break;
467                 case 'c':
468                         cw_header.datecode = strtoul(optarg, 0, 10);
469                         break;
470                 case 'w':
471                         token = strtok(optarg, period);
472                         i = 0;
473                         while (token && (i < 3)) {
474                                 cw_header.firmware_ver[i++] =
475                                         strtoul(token, 0, 10);
476                                 token = strtok(NULL, period);
477                         }
478                         break;
479                 case 'x':
480                         token = strtok(optarg, period);
481                         i = 0;
482                         while (token && (i < 3)) {
483                                 cw_header.capwap_ver[i++] =
484                                         strtoul(token, 0, 10);
485                                 token = strtok(NULL, period);
486                         }
487                         break;
488                 case 'n':
489                         mod_name = optarg;
490                         cw_header.model_size = strlen(mod_name);
491                         break;
492                 case 'h':
493                         usage(progname, EXIT_SUCCESS);
494                         break;
495                 case ':':
496                         fprintf(stderr, "Option -%c requires an operand\n", optopt);
497                         usage(progname, EXIT_FAILURE);
498                         break;
499                 case '?':
500                         fprintf(stderr, "Unrecognized option: -%c\n", optopt);
501                         usage(progname, EXIT_FAILURE);
502                         break;
503                 default:
504                         usage(progname, EXIT_FAILURE);
505                         break;
506                 }
507         }
508
509         /* Check required arguments */
510         if (mode == NONE) {
511                 fprintf(stderr, "A mode must be defined\n");
512                 usage(progname, EXIT_FAILURE);
513         }
514
515         if (input_file == NULL || output_file == NULL) {
516                 fprintf(stderr, "Input and output files must be defined\n");
517                 usage(progname, EXIT_FAILURE);
518         }
519
520         if (mode == DECODE) {
521                 if (decode_image(input_file, output_file) < 0)
522                                 return EXIT_FAILURE;
523
524                 return EXIT_SUCCESS;
525         }
526
527         if ((header.firmware_type == 0) &&
528             (cw_header.datecode == DATECODE_NONE)) {
529                 fprintf(stderr, "Firmware type must be non-zero for non-capwap images\n");
530                 usage(progname, EXIT_FAILURE);
531         }
532
533         if (header.vendor_id == 0 || header.product_id == 0) {
534                 fprintf(stderr, "Vendor ID and Product ID must be defined and non-zero\n");
535                 usage(progname, EXIT_FAILURE);
536         }
537
538         /* Check capwap header specific arguments */
539         if (cw_header.datecode != DATECODE_NONE) {
540                 if (!mod_name) {
541                         fprintf(stderr, "Capwap header specified: model name must be specified\n");
542                         usage(progname, EXIT_FAILURE);
543                 }
544                 if (!cw_header.firmware_ver[0] && !cw_header.firmware_ver[1] &&
545                         !cw_header.firmware_ver[2]) {
546                         fprintf(stderr, "Capwap header specified, fw_ver must be non-zero\n");
547                 }
548                 if (!cw_header.capwap_ver[0] && !cw_header.capwap_ver[1] &&
549                         !cw_header.capwap_ver[2]) {
550                         fprintf(stderr, "Capwap header specified, cw_ver must be non-zero\n");
551                 }
552                 pcw_header = malloc(sizeof(struct capwap_header) +
553                                         cw_header.model_size);
554                 if (pcw_header) {
555                         memcpy(pcw_header, &cw_header,
556                                 sizeof(struct capwap_header));
557                         memcpy(&(pcw_header->model), mod_name,
558                                 cw_header.model_size);
559                 } else {
560                         fprintf(stderr, "Failed to allocate memory\n");
561                         return EXIT_FAILURE;
562                 }
563         }
564
565         if (encode_image(input_file, output_file, &header, pcw_header,
566                                 pad ? block_size : 0) < 0)
567                 return EXIT_FAILURE;
568
569         return EXIT_SUCCESS;
570 }