save a bit of code with *strchrnul = '\0' trick
[oweals/busybox.git] / networking / udhcp / files.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * files.c -- DHCP server file manipulation *
4  * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
5  */
6
7 #include <netinet/ether.h>
8
9 #include "common.h"
10 #include "dhcpd.h"
11 #include "options.h"
12
13
14 /* on these functions, make sure your datatype matches */
15 static int read_ip(const char *line, void *arg)
16 {
17         len_and_sockaddr *lsa;
18
19         lsa = host_and_af2sockaddr(line, 0, AF_INET);
20         if (!lsa)
21                 return 0;
22         *(uint32_t*)arg = lsa->sin.sin_addr.s_addr;
23         free(lsa);
24         return 1;
25 }
26
27 static int read_mac(const char *line, void *arg)
28 {
29         uint8_t *mac_bytes = arg;
30         struct ether_addr *temp_ether_addr;
31
32         temp_ether_addr = ether_aton(line);
33         if (temp_ether_addr == NULL)
34                 return 0;
35         memcpy(mac_bytes, temp_ether_addr, 6);
36         return 1;
37 }
38
39
40 static int read_str(const char *line, void *arg)
41 {
42         char **dest = arg;
43
44         free(*dest);
45         *dest = xstrdup(line);
46         return 1;
47 }
48
49
50 static int read_u32(const char *line, void *arg)
51 {
52         *(uint32_t*)arg = bb_strtou32(line, NULL, 10);
53         return errno == 0;
54 }
55
56
57 static int read_yn(const char *line, void *arg)
58 {
59         char *dest = arg;
60
61         if (!strcasecmp("yes", line)) {
62                 *dest = 1;
63                 return 1;
64         }
65         if (!strcasecmp("no", line)) {
66                 *dest = 0;
67                 return 1;
68         }
69         return 0;
70 }
71
72
73 /* find option 'code' in opt_list */
74 struct option_set *find_option(struct option_set *opt_list, uint8_t code)
75 {
76         while (opt_list && opt_list->data[OPT_CODE] < code)
77                 opt_list = opt_list->next;
78
79         if (opt_list && opt_list->data[OPT_CODE] == code)
80                 return opt_list;
81         return NULL;
82 }
83
84
85 /* add an option to the opt_list */
86 static void attach_option(struct option_set **opt_list,
87                 const struct dhcp_option *option, char *buffer, int length)
88 {
89         struct option_set *existing, *new, **curr;
90
91         existing = find_option(*opt_list, option->code);
92         if (!existing) {
93                 DEBUG("Attaching option %02x to list", option->code);
94
95 #if ENABLE_FEATURE_RFC3397
96                 if ((option->flags & TYPE_MASK) == OPTION_STR1035)
97                         /* reuse buffer and length for RFC1035-formatted string */
98                         buffer = dname_enc(NULL, 0, buffer, &length);
99 #endif
100
101                 /* make a new option */
102                 new = xmalloc(sizeof(*new));
103                 new->data = xmalloc(length + 2);
104                 new->data[OPT_CODE] = option->code;
105                 new->data[OPT_LEN] = length;
106                 memcpy(new->data + 2, buffer, length);
107
108                 curr = opt_list;
109                 while (*curr && (*curr)->data[OPT_CODE] < option->code)
110                         curr = &(*curr)->next;
111
112                 new->next = *curr;
113                 *curr = new;
114 #if ENABLE_FEATURE_RFC3397
115                 if ((option->flags & TYPE_MASK) == OPTION_STR1035 && buffer != NULL)
116                         free(buffer);
117 #endif
118                 return;
119         }
120
121         /* add it to an existing option */
122         DEBUG("Attaching option %02x to existing member of list", option->code);
123         if (option->flags & OPTION_LIST) {
124 #if ENABLE_FEATURE_RFC3397
125                 if ((option->flags & TYPE_MASK) == OPTION_STR1035)
126                         /* reuse buffer and length for RFC1035-formatted string */
127                         buffer = dname_enc(existing->data + 2,
128                                         existing->data[OPT_LEN], buffer, &length);
129 #endif
130                 if (existing->data[OPT_LEN] + length <= 255) {
131                         existing->data = xrealloc(existing->data,
132                                         existing->data[OPT_LEN] + length + 3);
133                         if ((option->flags & TYPE_MASK) == OPTION_STRING) {
134                                 /* ' ' can bring us to 256 - bad */
135                                 if (existing->data[OPT_LEN] + length >= 255)
136                                         return;
137                                 /* add space separator between STRING options in a list */
138                                 existing->data[existing->data[OPT_LEN] + 2] = ' ';
139                                 existing->data[OPT_LEN]++;
140                         }
141                         memcpy(existing->data + existing->data[OPT_LEN] + 2, buffer, length);
142                         existing->data[OPT_LEN] += length;
143                 } /* else, ignore the data, we could put this in a second option in the future */
144 #if ENABLE_FEATURE_RFC3397
145                 if ((option->flags & TYPE_MASK) == OPTION_STR1035 && buffer != NULL)
146                         free(buffer);
147 #endif
148         } /* else, ignore the new data */
149 }
150
151
152 /* read a dhcp option and add it to opt_list */
153 static int read_opt(const char *const_line, void *arg)
154 {
155         struct option_set **opt_list = arg;
156         char *opt, *val, *endptr;
157         char *line;
158         const struct dhcp_option *option;
159         int retval, length, idx;
160         char buffer[8] __attribute__((aligned(4)));
161         uint16_t *result_u16 = (uint16_t *) buffer;
162         uint32_t *result_u32 = (uint32_t *) buffer;
163
164         /* Cheat, the only const line we'll actually get is "" */
165         line = (char *) const_line;
166         opt = strtok(line, " \t=");
167         if (!opt)
168                 return 0;
169
170         idx = index_in_strings(opt, dhcp_option_strings); /* NB: was strcasecmp! */
171         if (idx < 0)
172                 return 0;
173         option = &dhcp_options[idx];
174
175         retval = 0;
176         do {
177                 val = strtok(NULL, ", \t");
178                 if (!val) break;
179                 length = dhcp_option_lengths[option->flags & TYPE_MASK];
180                 retval = 0;
181                 opt = buffer; /* new meaning for variable opt */
182                 switch (option->flags & TYPE_MASK) {
183                 case OPTION_IP:
184                         retval = read_ip(val, buffer);
185                         break;
186                 case OPTION_IP_PAIR:
187                         retval = read_ip(val, buffer);
188                         val = strtok(NULL, ", \t/-");
189                         if (!val)
190                                 retval = 0;
191                         if (retval)
192                                 retval = read_ip(val, buffer + 4);
193                         break;
194                 case OPTION_STRING:
195 #if ENABLE_FEATURE_RFC3397
196                 case OPTION_STR1035:
197 #endif
198                         length = strlen(val);
199                         if (length > 0) {
200                                 if (length > 254) length = 254;
201                                 opt = val;
202                                 retval = 1;
203                         }
204                         break;
205                 case OPTION_BOOLEAN:
206                         retval = read_yn(val, buffer);
207                         break;
208                 case OPTION_U8:
209                         buffer[0] = strtoul(val, &endptr, 0);
210                         retval = (endptr[0] == '\0');
211                         break;
212                 /* htonX are macros in older libc's, using temp var
213                  * in code below for safety */
214                 /* TODO: use bb_strtoX? */
215                 case OPTION_U16: {
216                         unsigned long tmp = strtoul(val, &endptr, 0);
217                         *result_u16 = htons(tmp);
218                         retval = (endptr[0] == '\0' /*&& tmp < 0x10000*/);
219                         break;
220                 }
221                 case OPTION_S16: {
222                         long tmp = strtol(val, &endptr, 0);
223                         *result_u16 = htons(tmp);
224                         retval = (endptr[0] == '\0');
225                         break;
226                 }
227                 case OPTION_U32: {
228                         unsigned long tmp = strtoul(val, &endptr, 0);
229                         *result_u32 = htonl(tmp);
230                         retval = (endptr[0] == '\0');
231                         break;
232                 }
233                 case OPTION_S32: {
234                         long tmp = strtol(val, &endptr, 0);
235                         *result_u32 = htonl(tmp);
236                         retval = (endptr[0] == '\0');
237                         break;
238                 }
239                 default:
240                         break;
241                 }
242                 if (retval)
243                         attach_option(opt_list, option, opt, length);
244         } while (retval && option->flags & OPTION_LIST);
245         return retval;
246 }
247
248 static int read_staticlease(const char *const_line, void *arg)
249 {
250         char *line;
251         char *mac_string;
252         char *ip_string;
253         uint8_t *mac_bytes;
254         uint32_t *ip;
255
256         /* Allocate memory for addresses */
257         mac_bytes = xmalloc(sizeof(unsigned char) * 8);
258         ip = xmalloc(sizeof(uint32_t));
259
260         /* Read mac */
261         line = (char *) const_line;
262         mac_string = strtok(line, " \t");
263         read_mac(mac_string, mac_bytes);
264
265         /* Read ip */
266         ip_string = strtok(NULL, " \t");
267         read_ip(ip_string, ip);
268
269         addStaticLease(arg, mac_bytes, ip);
270
271         if (ENABLE_FEATURE_UDHCP_DEBUG) printStaticLeases(arg);
272
273         return 1;
274 }
275
276
277 struct config_keyword {
278         const char *keyword;
279         int (*handler)(const char *line, void *var);
280         void *var;
281         const char *def;
282 };
283
284 static const struct config_keyword keywords[] = {
285         /* keyword       handler   variable address               default */
286         {"start",        read_ip,  &(server_config.start_ip),     "192.168.0.20"},
287         {"end",          read_ip,  &(server_config.end_ip),       "192.168.0.254"},
288         {"interface",    read_str, &(server_config.interface),    "eth0"},
289         {"option",       read_opt, &(server_config.options),      ""},
290         {"opt",          read_opt, &(server_config.options),      ""},
291         /* Avoid "max_leases value not sane" warning by setting default
292          * to default_end_ip - default_start_ip + 1: */
293         {"max_leases",   read_u32, &(server_config.max_leases),   "235"},
294         {"remaining",    read_yn,  &(server_config.remaining),    "yes"},
295         {"auto_time",    read_u32, &(server_config.auto_time),    "7200"},
296         {"decline_time", read_u32, &(server_config.decline_time), "3600"},
297         {"conflict_time",read_u32, &(server_config.conflict_time),"3600"},
298         {"offer_time",   read_u32, &(server_config.offer_time),   "60"},
299         {"min_lease",    read_u32, &(server_config.min_lease),    "60"},
300         {"lease_file",   read_str, &(server_config.lease_file),   LEASES_FILE},
301         {"pidfile",      read_str, &(server_config.pidfile),      "/var/run/udhcpd.pid"},
302         {"notify_file",  read_str, &(server_config.notify_file),  ""},
303         {"siaddr",       read_ip,  &(server_config.siaddr),       "0.0.0.0"},
304         {"sname",        read_str, &(server_config.sname),        ""},
305         {"boot_file",    read_str, &(server_config.boot_file),    ""},
306         {"static_lease", read_staticlease, &(server_config.static_leases), ""},
307         /* ADDME: static lease */
308 };
309
310
311 /*
312  * Domain names may have 254 chars, and string options can be 254
313  * chars long. However, 80 bytes will be enough for most, and won't
314  * hog up memory. If you have a special application, change it
315  */
316 #define READ_CONFIG_BUF_SIZE 80
317
318 int read_config(const char *file)
319 {
320         FILE *in;
321         char buffer[READ_CONFIG_BUF_SIZE], *token, *line;
322         int i, lm = 0;
323
324         for (i = 0; i < ARRAY_SIZE(keywords); i++)
325                 if (keywords[i].def[0])
326                         keywords[i].handler(keywords[i].def, keywords[i].var);
327
328         in = fopen_or_warn(file, "r");
329         if (!in) {
330                 return 0;
331         }
332
333         while (fgets(buffer, READ_CONFIG_BUF_SIZE, in)) {
334                 char debug_orig[READ_CONFIG_BUF_SIZE];
335
336                 lm++;
337                 *strchrnul(buffer, '\n') = '\0';
338                 if (ENABLE_FEATURE_UDHCP_DEBUG)
339                         strcpy(debug_orig, buffer);
340                 *strchrnul(buffer, '#') = '\0';
341
342                 token = strtok(buffer, " \t");
343                 if (!token) continue;
344                 line = strtok(NULL, "");
345                 if (!line) continue;
346
347                 /* eat leading whitespace */
348                 line = skip_whitespace(line);
349                 /* eat trailing whitespace */
350                 i = strlen(line) - 1;
351                 while (i >= 0 && isspace(line[i]))
352                         line[i--] = '\0';
353
354                 for (i = 0; i < ARRAY_SIZE(keywords); i++)
355                         if (!strcasecmp(token, keywords[i].keyword))
356                                 if (!keywords[i].handler(line, keywords[i].var)) {
357                                         bb_error_msg("cannot parse line %d of %s", lm, file);
358                                         if (ENABLE_FEATURE_UDHCP_DEBUG)
359                                                 bb_error_msg("cannot parse '%s'", debug_orig);
360                                         /* reset back to the default value */
361                                         keywords[i].handler(keywords[i].def, keywords[i].var);
362                                 }
363         }
364         fclose(in);
365
366         server_config.start_ip = ntohl(server_config.start_ip);
367         server_config.end_ip = ntohl(server_config.end_ip);
368
369         return 1;
370 }
371
372
373 void write_leases(void)
374 {
375         int fp;
376         unsigned i;
377         time_t curr = time(0);
378         unsigned long tmp_time;
379
380         fp = open3_or_warn(server_config.lease_file, O_WRONLY|O_CREAT|O_TRUNC, 0666);
381         if (fp < 0) {
382                 return;
383         }
384
385         for (i = 0; i < server_config.max_leases; i++) {
386                 if (leases[i].yiaddr != 0) {
387
388                         /* screw with the time in the struct, for easier writing */
389                         tmp_time = leases[i].expires;
390
391                         if (server_config.remaining) {
392                                 if (lease_expired(&(leases[i])))
393                                         leases[i].expires = 0;
394                                 else leases[i].expires -= curr;
395                         } /* else stick with the time we got */
396                         leases[i].expires = htonl(leases[i].expires);
397                         // FIXME: error check??
398                         full_write(fp, &leases[i], sizeof(leases[i]));
399
400                         /* then restore it when done */
401                         leases[i].expires = tmp_time;
402                 }
403         }
404         close(fp);
405
406         if (server_config.notify_file) {
407                 char *cmd = xasprintf("%s %s", server_config.notify_file, server_config.lease_file);
408                 system(cmd);
409                 free(cmd);
410         }
411 }
412
413
414 void read_leases(const char *file)
415 {
416         int fp;
417         unsigned int i = 0;
418         struct dhcpOfferedAddr lease;
419
420         fp = open_or_warn(file, O_RDONLY);
421         if (fp < 0) {
422                 return;
423         }
424
425         while (i < server_config.max_leases
426          && full_read(fp, &lease, sizeof(lease)) == sizeof(lease)
427         ) {
428                 /* ADDME: is it a static lease */
429                 uint32_t y = ntohl(lease.yiaddr);
430                 if (y >= server_config.start_ip && y <= server_config.end_ip) {
431                         lease.expires = ntohl(lease.expires);
432                         if (!server_config.remaining)
433                                 lease.expires -= time(0);
434                         if (!(add_lease(lease.chaddr, lease.yiaddr, lease.expires))) {
435                                 bb_error_msg("too many leases while loading %s", file);
436                                 break;
437                         }
438                         i++;
439                 }
440         }
441         DEBUG("Read %d leases", i);
442         close(fp);
443 }