forked from sargon/ddhcpd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tools.c
93 lines (69 loc) · 2.11 KB
/
tools.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "tools.h"
#include "logger.h"
#include <string.h>
#include <getopt.h>
#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>
ATTR_NONNULL_ALL void addr_add(struct in_addr* subnet, struct in_addr* result, int add) {
struct in_addr addr;
memcpy(&addr, subnet, sizeof(struct in_addr));
addr.s_addr = ntohl(addr.s_addr);
addr.s_addr += (in_addr_t)add;
addr.s_addr = htonl(addr.s_addr);
memcpy(result, &addr, sizeof(struct in_addr));
}
dhcp_option* parse_option() {
//size_t optlen = strlen(optarg);
char* len_s = strchr(optarg, ':');
if (!len_s) {
ERROR("parse_option(...): Malformed dhcp option '%s'\n", optarg);
exit(1);
}
len_s++[0] = '\0';
char* payload_s = strchr(len_s, ':');
if (!payload_s) {
ERROR("parse_option(...): Malformed dhcp option '%s'\n", optarg);
exit(1);
}
payload_s++[0] = '\0';
uint8_t len = (uint8_t)atoi(len_s);
uint8_t code = (uint8_t)atoi(optarg);
dhcp_option* option = (dhcp_option*) malloc(sizeof(dhcp_option));
if (!option) {
ERROR("parse_option(...): Failed to allocate memory for dhcp option '%s'\n", optarg);
exit(1);
}
option->code = code;
option->len = len;
option->payload = calloc(len, 1);
if (!option->payload) {
ERROR("parse_option(...): Failed to allocate memory for dhcp option payload '%s'\n", optarg);
free(option);
exit(1);
}
for (int i = 0 ; i < len; i++) {
char* next_payload_s = strchr(payload_s, '.');
if (!next_payload_s && (i + 1 < len)) {
ERROR("parse_option(...): Malformed dhcp option '%s': too little payload\n", optarg);
exit(1);
}
if (i + 1 < len) {
next_payload_s++[0] = '\0';
}
uint8_t payload = (uint8_t)strtoul(payload_s, NULL, 0);
option->payload[i] = payload;
payload_s = next_payload_s;
}
return option;
}
ATTR_NONNULL_ALL char* hwaddr2c(uint8_t* hwaddr) {
char* str = calloc(18, 1);
if (!str) {
FATAL("hwaddr2c(...): Failed to allocate buffer.\n");
return NULL;
}
snprintf(str, 18, "%02X:%02X:%02X:%02X:%02X:%02X",
hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);
return str;
}