firmware-utils: replace GPL 2.0 boilerplate/reference with SPDX
[openwrt/staging/ldir.git] / tools / firmware-utils / src / mkdhpimg.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (c) 2016 FUKAUMI Naoki <naobsd@gmail.com>
4 */
5
6 #include <sys/stat.h>
7 #include <err.h>
8 #include <fcntl.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14
15 #include "buffalo-lib.h"
16
17 #define DHP_HEADER_SIZE 20
18
19 static char *progname;
20
21 static void
22 usage(void)
23 {
24
25 fprintf(stderr, "usage: %s <in> <out>\n", progname);
26 exit(EXIT_FAILURE);
27 }
28
29 int
30 main(int argc, char *argv[])
31 {
32 struct stat in_st;
33 size_t size;
34 uint32_t crc;
35 int in, out;
36 uint8_t *buf;
37
38 progname = argv[0];
39
40 if (argc != 3)
41 usage();
42
43 if ((in = open(argv[1], O_RDONLY)) == -1)
44 err(EXIT_FAILURE, "%s", argv[1]);
45
46 if (fstat(in, &in_st) == -1)
47 err(EXIT_FAILURE, "%s", argv[1]);
48
49 size = DHP_HEADER_SIZE + in_st.st_size;
50
51 if ((buf = malloc(size)) == NULL)
52 err(EXIT_FAILURE, "malloc");
53
54 memset(buf, 0, DHP_HEADER_SIZE);
55 buf[0x0] = 0x62;
56 buf[0x1] = 0x67;
57 buf[0x2] = 0x6e;
58 buf[0xb] = 0xb1;
59 buf[0xc] = (size >> 24) & 0xff;
60 buf[0xd] = (size >> 16) & 0xff;
61 buf[0xe] = (size >> 8) & 0xff;
62 buf[0xf] = size & 0xff;
63
64 read(in, &buf[DHP_HEADER_SIZE], in_st.st_size);
65 close(in);
66
67 crc = buffalo_crc(buf, size);
68 buf[0x10] = (crc >> 24) & 0xff;
69 buf[0x11] = (crc >> 16) & 0xff;
70 buf[0x12] = (crc >> 8) & 0xff;
71 buf[0x13] = crc & 0xff;
72
73 if ((out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1)
74 err(EXIT_FAILURE, "%s", argv[2]);
75 write(out, buf, size);
76 close(out);
77
78 free(buf);
79
80 return EXIT_SUCCESS;
81 }