udhcp: handle errors in read_staticlease
[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  * Licensed under GPLv2, see file LICENSE in this tarball for details.
7  */
8
9 #include <netinet/ether.h>
10
11 #include "common.h"
12 #include "dhcpd.h"
13
14 #if BB_LITTLE_ENDIAN
15 static inline uint64_t hton64(uint64_t v)
16 {
17         return (((uint64_t)htonl(v)) << 32) | htonl(v >> 32);
18 }
19 #else
20 #define hton64(v) (v)
21 #endif
22 #define ntoh64(v) hton64(v)
23
24 /* on these functions, make sure your datatype matches */
25 static int FAST_FUNC read_nip(const char *line, void *arg)
26 {
27         len_and_sockaddr *lsa;
28
29         lsa = host_and_af2sockaddr(line, 0, AF_INET);
30         if (!lsa)
31                 return 0;
32         *(uint32_t*)arg = lsa->u.sin.sin_addr.s_addr;
33         free(lsa);
34         return 1;
35 }
36
37 static int FAST_FUNC read_str(const char *line, void *arg)
38 {
39         char **dest = arg;
40
41         free(*dest);
42         *dest = xstrdup(line);
43         return 1;
44 }
45
46 static int FAST_FUNC read_u32(const char *line, void *arg)
47 {
48         *(uint32_t*)arg = bb_strtou32(line, NULL, 10);
49         return errno == 0;
50 }
51
52 static int read_yn(const char *line, void *arg)
53 {
54         char *dest = arg;
55
56         if (strcasecmp("yes", line) == 0) {
57                 *dest = 1;
58                 return 1;
59         }
60         if (strcasecmp("no", line) == 0) {
61                 *dest = 0;
62                 return 1;
63         }
64         return 0;
65 }
66
67 /* find option 'code' in opt_list */
68 struct option_set* FAST_FUNC find_option(struct option_set *opt_list, uint8_t code)
69 {
70         while (opt_list && opt_list->data[OPT_CODE] < code)
71                 opt_list = opt_list->next;
72
73         if (opt_list && opt_list->data[OPT_CODE] == code)
74                 return opt_list;
75         return NULL;
76 }
77
78 /* add an option to the opt_list */
79 static NOINLINE void attach_option(
80                 struct option_set **opt_list,
81                 const struct dhcp_option *option,
82                 char *buffer,
83                 int length)
84 {
85         struct option_set *existing, *new, **curr;
86 #if ENABLE_FEATURE_UDHCP_RFC3397
87         char *allocated = NULL;
88 #endif
89
90         existing = find_option(*opt_list, option->code);
91         if (!existing) {
92                 log2("Attaching option %02x to list", option->code);
93 #if ENABLE_FEATURE_UDHCP_RFC3397
94                 if ((option->flags & OPTION_TYPE_MASK) == OPTION_STR1035) {
95                         /* reuse buffer and length for RFC1035-formatted string */
96                         allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);
97                 }
98 #endif
99                 /* make a new option */
100                 new = xmalloc(sizeof(*new));
101                 new->data = xmalloc(length + OPT_DATA);
102                 new->data[OPT_CODE] = option->code;
103                 new->data[OPT_LEN] = length;
104                 memcpy(new->data + OPT_DATA, buffer, length);
105
106                 curr = opt_list;
107                 while (*curr && (*curr)->data[OPT_CODE] < option->code)
108                         curr = &(*curr)->next;
109
110                 new->next = *curr;
111                 *curr = new;
112                 goto ret;
113         }
114
115         if (option->flags & OPTION_LIST) {
116                 unsigned old_len;
117
118                 /* add it to an existing option */
119                 log1("Attaching option %02x to existing member of list", option->code);
120                 old_len = existing->data[OPT_LEN];
121 #if ENABLE_FEATURE_UDHCP_RFC3397
122                 if ((option->flags & OPTION_TYPE_MASK) == OPTION_STR1035) {
123                         /* reuse buffer and length for RFC1035-formatted string */
124                         allocated = buffer = (char *)dname_enc(existing->data + OPT_DATA, old_len, buffer, &length);
125                 }
126 #endif
127                 if (old_len + length < 255) {
128                         /* actually 255 is ok too, but adding a space can overlow it */
129
130                         existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
131                         if ((option->flags & OPTION_TYPE_MASK) == OPTION_STRING) {
132                                 /* add space separator between STRING options in a list */
133                                 existing->data[OPT_DATA + old_len] = ' ';
134                                 old_len++;
135                         }
136                         memcpy(existing->data + OPT_DATA + old_len, buffer, length);
137                         existing->data[OPT_LEN] = old_len + length;
138                 } /* else, ignore the data, we could put this in a second option in the future */
139         } /* else, ignore the new data */
140
141  ret: ;
142 #if ENABLE_FEATURE_UDHCP_RFC3397
143         free(allocated);
144 #endif
145 }
146
147 /* read a dhcp option and add it to opt_list */
148 static int FAST_FUNC read_opt(const char *const_line, void *arg)
149 {
150         struct option_set **opt_list = arg;
151         char *opt, *val, *endptr;
152         char *line;
153         const struct dhcp_option *option;
154         int retval, length, idx;
155         char buffer[8] ALIGNED(4);
156         uint16_t *result_u16 = (uint16_t *) buffer;
157         uint32_t *result_u32 = (uint32_t *) buffer;
158
159         /* Cheat, the only *const* line possible is "" */
160         line = (char *) const_line;
161         opt = strtok(line, " \t=");
162         if (!opt)
163                 return 0;
164
165         idx = index_in_strings(dhcp_option_strings, opt); /* NB: was strcasecmp! */
166         if (idx < 0)
167                 return 0;
168         option = &dhcp_options[idx];
169
170         retval = 0;
171         do {
172                 val = strtok(NULL, ", \t");
173                 if (!val)
174                         break;
175                 length = dhcp_option_lengths[option->flags & OPTION_TYPE_MASK];
176                 retval = 0;
177                 opt = buffer; /* new meaning for variable opt */
178                 switch (option->flags & OPTION_TYPE_MASK) {
179                 case OPTION_IP:
180                         retval = read_nip(val, buffer);
181                         break;
182                 case OPTION_IP_PAIR:
183                         retval = read_nip(val, buffer);
184                         val = strtok(NULL, ", \t/-");
185                         if (!val)
186                                 retval = 0;
187                         if (retval)
188                                 retval = read_nip(val, buffer + 4);
189                         break;
190                 case OPTION_STRING:
191 #if ENABLE_FEATURE_UDHCP_RFC3397
192                 case OPTION_STR1035:
193 #endif
194                         length = strnlen(val, 254);
195                         if (length > 0) {
196                                 opt = val;
197                                 retval = 1;
198                         }
199                         break;
200                 case OPTION_BOOLEAN:
201                         retval = read_yn(val, buffer);
202                         break;
203                 case OPTION_U8:
204                         buffer[0] = strtoul(val, &endptr, 0);
205                         retval = (endptr[0] == '\0');
206                         break;
207                 /* htonX are macros in older libc's, using temp var
208                  * in code below for safety */
209                 /* TODO: use bb_strtoX? */
210                 case OPTION_U16: {
211                         unsigned long tmp = strtoul(val, &endptr, 0);
212                         *result_u16 = htons(tmp);
213                         retval = (endptr[0] == '\0' /*&& tmp < 0x10000*/);
214                         break;
215                 }
216                 case OPTION_S16: {
217                         long tmp = strtol(val, &endptr, 0);
218                         *result_u16 = htons(tmp);
219                         retval = (endptr[0] == '\0');
220                         break;
221                 }
222                 case OPTION_U32: {
223                         unsigned long tmp = strtoul(val, &endptr, 0);
224                         *result_u32 = htonl(tmp);
225                         retval = (endptr[0] == '\0');
226                         break;
227                 }
228                 case OPTION_S32: {
229                         long tmp = strtol(val, &endptr, 0);
230                         *result_u32 = htonl(tmp);
231                         retval = (endptr[0] == '\0');
232                         break;
233                 }
234                 default:
235                         break;
236                 }
237                 if (retval)
238                         attach_option(opt_list, option, opt, length);
239         } while (retval && option->flags & OPTION_LIST);
240
241         return retval;
242 }
243
244 static int FAST_FUNC read_staticlease(const char *const_line, void *arg)
245 {
246         char *line;
247         char *mac_string;
248         char *ip_string;
249         struct ether_addr mac_bytes; /* it's "struct { uint8_t mac[6]; }" */
250         uint32_t nip;
251
252         /* Read mac */
253         line = (char *) const_line;
254         mac_string = strtok_r(line, " \t", &line);
255         if (!mac_string || !ether_aton_r(mac_string, &mac_bytes))
256                 return 0;
257
258         /* Read ip */
259         ip_string = strtok_r(NULL, " \t", &line);
260         if (!ip_string || !read_nip(ip_string, &nip))
261                 return 0;
262
263         add_static_lease(arg, (uint8_t*) &mac_bytes, nip);
264
265         log_static_leases(arg);
266
267         return 1;
268 }
269
270
271 struct config_keyword {
272         const char *keyword;
273         int (*handler)(const char *line, void *var) FAST_FUNC;
274         void *var;
275         const char *def;
276 };
277
278 static const struct config_keyword keywords[] = {
279         /* keyword       handler   variable address               default */
280         {"start",        read_nip, &(server_config.start_ip),     "192.168.0.20"},
281         {"end",          read_nip, &(server_config.end_ip),       "192.168.0.254"},
282         {"interface",    read_str, &(server_config.interface),    "eth0"},
283         /* Avoid "max_leases value not sane" warning by setting default
284          * to default_end_ip - default_start_ip + 1: */
285         {"max_leases",   read_u32, &(server_config.max_leases),   "235"},
286         {"auto_time",    read_u32, &(server_config.auto_time),    "7200"},
287         {"decline_time", read_u32, &(server_config.decline_time), "3600"},
288         {"conflict_time",read_u32, &(server_config.conflict_time),"3600"},
289         {"offer_time",   read_u32, &(server_config.offer_time),   "60"},
290         {"min_lease",    read_u32, &(server_config.min_lease_sec),"60"},
291         {"lease_file",   read_str, &(server_config.lease_file),   LEASES_FILE},
292         {"pidfile",      read_str, &(server_config.pidfile),      "/var/run/udhcpd.pid"},
293         {"siaddr",       read_nip, &(server_config.siaddr_nip),   "0.0.0.0"},
294         /* keywords with no defaults must be last! */
295         {"option",       read_opt, &(server_config.options),      ""},
296         {"opt",          read_opt, &(server_config.options),      ""},
297         {"notify_file",  read_str, &(server_config.notify_file),  ""},
298         {"sname",        read_str, &(server_config.sname),        ""},
299         {"boot_file",    read_str, &(server_config.boot_file),    ""},
300         {"static_lease", read_staticlease, &(server_config.static_leases), ""},
301 };
302 enum { KWS_WITH_DEFAULTS = ARRAY_SIZE(keywords) - 6 };
303
304 void FAST_FUNC read_config(const char *file)
305 {
306         parser_t *parser;
307         const struct config_keyword *k;
308         unsigned i;
309         char *token[2];
310
311         for (i = 0; i < KWS_WITH_DEFAULTS; i++)
312                 keywords[i].handler(keywords[i].def, keywords[i].var);
313
314         parser = config_open(file);
315         while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
316                 for (k = keywords, i = 0; i < ARRAY_SIZE(keywords); k++, i++) {
317                         if (strcasecmp(token[0], k->keyword) == 0) {
318                                 if (!k->handler(token[1], k->var)) {
319                                         bb_error_msg("can't parse line %u in %s",
320                                                         parser->lineno, file);
321                                         /* reset back to the default value */
322                                         k->handler(k->def, k->var);
323                                 }
324                                 break;
325                         }
326                 }
327         }
328         config_close(parser);
329
330         server_config.start_ip = ntohl(server_config.start_ip);
331         server_config.end_ip = ntohl(server_config.end_ip);
332 }
333
334 void FAST_FUNC write_leases(void)
335 {
336         int fd;
337         unsigned i;
338         leasetime_t curr;
339         int64_t written_at;
340
341         fd = open_or_warn(server_config.lease_file, O_WRONLY|O_CREAT|O_TRUNC);
342         if (fd < 0)
343                 return;
344
345         curr = written_at = time(NULL);
346
347         written_at = hton64(written_at);
348         full_write(fd, &written_at, sizeof(written_at));
349
350         for (i = 0; i < server_config.max_leases; i++) {
351                 leasetime_t tmp_time;
352
353                 if (g_leases[i].lease_nip == 0)
354                         continue;
355
356                 /* Screw with the time in the struct, for easier writing */
357                 tmp_time = g_leases[i].expires;
358
359                 g_leases[i].expires -= curr;
360                 if ((signed_leasetime_t) g_leases[i].expires < 0)
361                         g_leases[i].expires = 0;
362                 g_leases[i].expires = htonl(g_leases[i].expires);
363
364                 /* No error check. If the file gets truncated,
365                  * we lose some leases on restart. Oh well. */
366                 full_write(fd, &g_leases[i], sizeof(g_leases[i]));
367
368                 /* Then restore it when done */
369                 g_leases[i].expires = tmp_time;
370         }
371         close(fd);
372
373         if (server_config.notify_file) {
374 // TODO: vfork-based child creation
375                 char *cmd = xasprintf("%s %s", server_config.notify_file, server_config.lease_file);
376                 system(cmd);
377                 free(cmd);
378         }
379 }
380
381 void FAST_FUNC read_leases(const char *file)
382 {
383         struct dyn_lease lease;
384         int64_t written_at, time_passed;
385         int fd;
386 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
387         unsigned i = 0;
388 #endif
389
390         fd = open_or_warn(file, O_RDONLY);
391         if (fd < 0)
392                 return;
393
394         if (full_read(fd, &written_at, sizeof(written_at)) != sizeof(written_at))
395                 goto ret;
396         written_at = ntoh64(written_at);
397
398         time_passed = time(NULL) - written_at;
399         /* Strange written_at, or lease file from old version of udhcpd
400          * which had no "written_at" field? */
401         if ((uint64_t)time_passed > 12 * 60 * 60)
402                 goto ret;
403
404         while (full_read(fd, &lease, sizeof(lease)) == sizeof(lease)) {
405 //FIXME: what if it matches some static lease?
406                 uint32_t y = ntohl(lease.lease_nip);
407                 if (y >= server_config.start_ip && y <= server_config.end_ip) {
408                         signed_leasetime_t expires = ntohl(lease.expires) - (signed_leasetime_t)time_passed;
409                         if (expires <= 0)
410                                 continue;
411                         /* NB: add_lease takes "relative time", IOW,
412                          * lease duration, not lease deadline. */
413                         if (add_lease(lease.lease_mac, lease.lease_nip,
414                                         expires,
415                                         lease.hostname, sizeof(lease.hostname)
416                                 ) == 0
417                         ) {
418                                 bb_error_msg("too many leases while loading %s", file);
419                                 break;
420                         }
421 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
422                         i++;
423 #endif
424                 }
425         }
426         log1("Read %d leases", i);
427  ret:
428         close(fd);
429 }