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