b6b274d9198c40bd03c2e24d32711357a86a2638
[oweals/busybox.git] / networking / udhcp / common.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
4  *
5  * Licensed under GPLv2, see file LICENSE in this source tree.
6  */
7 #include "common.h"
8
9 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
10 unsigned dhcp_verbose;
11 #endif
12
13 const uint8_t MAC_BCAST_ADDR[6] ALIGN2 = {
14         0xff, 0xff, 0xff, 0xff, 0xff, 0xff
15 };
16
17 /* Supported options are easily added here.
18  * See RFC2132 for more options.
19  * OPTION_REQ: these options are requested by udhcpc (unless -o).
20  */
21 const struct dhcp_optflag dhcp_optflags[] = {
22         /* flags                                    code */
23         { OPTION_IP                   | OPTION_REQ, 0x01 }, /* DHCP_SUBNET        */
24         { OPTION_S32                              , 0x02 }, /* DHCP_TIME_OFFSET   */
25         { OPTION_IP | OPTION_LIST     | OPTION_REQ, 0x03 }, /* DHCP_ROUTER        */
26 //      { OPTION_IP | OPTION_LIST                 , 0x04 }, /* DHCP_TIME_SERVER   */
27 //      { OPTION_IP | OPTION_LIST                 , 0x05 }, /* DHCP_NAME_SERVER   */
28         { OPTION_IP | OPTION_LIST     | OPTION_REQ, 0x06 }, /* DHCP_DNS_SERVER    */
29 //      { OPTION_IP | OPTION_LIST                 , 0x07 }, /* DHCP_LOG_SERVER    */
30 //      { OPTION_IP | OPTION_LIST                 , 0x08 }, /* DHCP_COOKIE_SERVER */
31         { OPTION_IP | OPTION_LIST                 , 0x09 }, /* DHCP_LPR_SERVER    */
32         { OPTION_STRING               | OPTION_REQ, 0x0c }, /* DHCP_HOST_NAME     */
33         { OPTION_U16                              , 0x0d }, /* DHCP_BOOT_SIZE     */
34         { OPTION_STRING               | OPTION_REQ, 0x0f }, /* DHCP_DOMAIN_NAME   */
35         { OPTION_IP                               , 0x10 }, /* DHCP_SWAP_SERVER   */
36         { OPTION_STRING                           , 0x11 }, /* DHCP_ROOT_PATH     */
37         { OPTION_U8                               , 0x17 }, /* DHCP_IP_TTL        */
38         { OPTION_U16                              , 0x1a }, /* DHCP_MTU           */
39         { OPTION_IP                   | OPTION_REQ, 0x1c }, /* DHCP_BROADCAST     */
40         { OPTION_IP_PAIR | OPTION_LIST            , 0x21 }, /* DHCP_ROUTES        */
41         { OPTION_STRING                           , 0x28 }, /* DHCP_NIS_DOMAIN    */
42         { OPTION_IP | OPTION_LIST                 , 0x29 }, /* DHCP_NIS_SERVER    */
43         { OPTION_IP | OPTION_LIST     | OPTION_REQ, 0x2a }, /* DHCP_NTP_SERVER    */
44         { OPTION_IP | OPTION_LIST                 , 0x2c }, /* DHCP_WINS_SERVER   */
45         { OPTION_U32                              , 0x33 }, /* DHCP_LEASE_TIME    */
46         { OPTION_IP                               , 0x36 }, /* DHCP_SERVER_ID     */
47         { OPTION_STRING                           , 0x38 }, /* DHCP_ERR_MESSAGE   */
48 //TODO: must be combined with 'sname' and 'file' handling:
49         { OPTION_STRING                           , 0x42 }, /* DHCP_TFTP_SERVER_NAME */
50         { OPTION_STRING                           , 0x43 }, /* DHCP_BOOT_FILE     */
51 //TODO: not a string, but a set of LASCII strings:
52 //      { OPTION_STRING                           , 0x4D }, /* DHCP_USER_CLASS    */
53 #if ENABLE_FEATURE_UDHCP_RFC3397
54         { OPTION_DNS_STRING | OPTION_LIST         , 0x77 }, /* DHCP_DOMAIN_SEARCH */
55         { OPTION_SIP_SERVERS                      , 0x78 }, /* DHCP_SIP_SERVERS   */
56 #endif
57         { OPTION_STATIC_ROUTES                    , 0x79 }, /* DHCP_STATIC_ROUTES */
58         { OPTION_STATIC_ROUTES                    , 0xf9 }, /* DHCP_MS_STATIC_ROUTES */
59         { OPTION_STRING                           , 0xfc }, /* DHCP_WPAD          */
60
61         /* Options below have no match in dhcp_option_strings[],
62          * are not passed to dhcpc scripts, and cannot be specified
63          * with "option XXX YYY" syntax in dhcpd config file.
64          * These entries are only used internally by udhcp[cd]
65          * to correctly encode options into packets.
66          */
67
68         { OPTION_IP                               , 0x32 }, /* DHCP_REQUESTED_IP  */
69         { OPTION_U8                               , 0x35 }, /* DHCP_MESSAGE_TYPE  */
70         { OPTION_U16                              , 0x39 }, /* DHCP_MAX_SIZE      */
71         { OPTION_STRING                           , 0x3c }, /* DHCP_VENDOR        */
72 //FIXME: handling of this option is not exactly correct:
73         { OPTION_STRING                           , 0x3d }, /* DHCP_CLIENT_ID     */
74         { 0, 0 } /* zeroed terminating entry */
75 };
76
77 /* Used for converting options from incoming packets to env variables
78  * for udhcpc stript, and for setting options for udhcpd via
79  * "opt OPTION_NAME OPTION_VALUE" directives in udhcpd.conf file.
80  */
81 /* Must match dhcp_optflags[] order */
82 const char dhcp_option_strings[] ALIGN1 =
83         "subnet" "\0"      /* DHCP_SUBNET         */
84         "timezone" "\0"    /* DHCP_TIME_OFFSET    */
85         "router" "\0"      /* DHCP_ROUTER         */
86 //      "timesrv" "\0"     /* DHCP_TIME_SERVER    */
87 //      "namesrv" "\0"     /* DHCP_NAME_SERVER    */
88         "dns" "\0"         /* DHCP_DNS_SERVER     */
89 //      "logsrv" "\0"      /* DHCP_LOG_SERVER     */
90 //      "cookiesrv" "\0"   /* DHCP_COOKIE_SERVER  */
91         "lprsrv" "\0"      /* DHCP_LPR_SERVER     */
92         "hostname" "\0"    /* DHCP_HOST_NAME      */
93         "bootsize" "\0"    /* DHCP_BOOT_SIZE      */
94         "domain" "\0"      /* DHCP_DOMAIN_NAME    */
95         "swapsrv" "\0"     /* DHCP_SWAP_SERVER    */
96         "rootpath" "\0"    /* DHCP_ROOT_PATH      */
97         "ipttl" "\0"       /* DHCP_IP_TTL         */
98         "mtu" "\0"         /* DHCP_MTU            */
99         "broadcast" "\0"   /* DHCP_BROADCAST      */
100         "routes" "\0"      /* DHCP_ROUTES         */
101         "nisdomain" "\0"   /* DHCP_NIS_DOMAIN     */
102         "nissrv" "\0"      /* DHCP_NIS_SERVER     */
103         "ntpsrv" "\0"      /* DHCP_NTP_SERVER     */
104         "wins" "\0"        /* DHCP_WINS_SERVER    */
105         "lease" "\0"       /* DHCP_LEASE_TIME     */
106         "serverid" "\0"    /* DHCP_SERVER_ID      */
107         "message" "\0"     /* DHCP_ERR_MESSAGE    */
108         "tftp" "\0"        /* DHCP_TFTP_SERVER_NAME */
109         "bootfile" "\0"    /* DHCP_BOOT_FILE      */
110 //      "userclass" "\0"   /* DHCP_USER_CLASS     */
111 #if ENABLE_FEATURE_UDHCP_RFC3397
112         "search" "\0"      /* DHCP_DOMAIN_SEARCH  */
113 // doesn't work in udhcpd.conf since OPTION_SIP_SERVERS
114 // is not handled yet by "string->option" conversion code:
115         "sipsrv" "\0"      /* DHCP_SIP_SERVERS    */
116 #endif
117 // doesn't work in udhcpd.conf since OPTION_STATIC_ROUTES
118 // is not handled yet by "string->option" conversion code:
119         "staticroutes" "\0"/* DHCP_STATIC_ROUTES  */
120         "msstaticroutes""\0"/* DHCP_MS_STATIC_ROUTES */
121         "wpad" "\0"        /* DHCP_WPAD           */
122         ;
123
124 /* Lengths of the option types in binary form.
125  * Used by:
126  * udhcp_str2optset: to determine how many bytes to allocate.
127  * xmalloc_optname_optval: to estimate string length
128  * from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
129  * is the number of elements, multiply in by one element's string width
130  * (len_of_option_as_string[opt_type]) and you know how wide string you need.
131  */
132 const uint8_t dhcp_option_lengths[] ALIGN1 = {
133         [OPTION_IP] =      4,
134         [OPTION_IP_PAIR] = 8,
135 //      [OPTION_BOOLEAN] = 1,
136         [OPTION_STRING] =  1,  /* ignored by udhcp_str2optset */
137 #if ENABLE_FEATURE_UDHCP_RFC3397
138         [OPTION_DNS_STRING] = 1,  /* ignored by both udhcp_str2optset and xmalloc_optname_optval */
139         [OPTION_SIP_SERVERS] = 1,
140 #endif
141         [OPTION_U8] =      1,
142         [OPTION_U16] =     2,
143 //      [OPTION_S16] =     2,
144         [OPTION_U32] =     4,
145         [OPTION_S32] =     4,
146         /* Just like OPTION_STRING, we use minimum length here */
147         [OPTION_STATIC_ROUTES] = 5,
148 };
149
150
151 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 2
152 static void log_option(const char *pfx, const uint8_t *opt)
153 {
154         if (dhcp_verbose >= 2) {
155                 char buf[256 * 2 + 2];
156                 *bin2hex(buf, (void*) (opt + OPT_DATA), opt[OPT_LEN]) = '\0';
157                 bb_info_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
158         }
159 }
160 #else
161 # define log_option(pfx, opt) ((void)0)
162 #endif
163
164 unsigned FAST_FUNC udhcp_option_idx(const char *name)
165 {
166         int n = index_in_strings(dhcp_option_strings, name);
167         if (n >= 0)
168                 return n;
169
170         {
171                 char buf[sizeof(dhcp_option_strings)];
172                 char *d = buf;
173                 const char *s = dhcp_option_strings;
174                 while (s < dhcp_option_strings + sizeof(dhcp_option_strings) - 2) {
175                         *d++ = (*s == '\0' ? ' ' : *s);
176                         s++;
177                 }
178                 *d = '\0';
179                 bb_error_msg_and_die("unknown option '%s', known options: %s", name, buf);
180         }
181 }
182
183 /* Get an option with bounds checking (warning, result is not aligned) */
184 uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code)
185 {
186         uint8_t *optionptr;
187         int len;
188         int rem;
189         int overload = 0;
190         enum {
191                 FILE_FIELD101  = FILE_FIELD  * 0x101,
192                 SNAME_FIELD101 = SNAME_FIELD * 0x101,
193         };
194
195         /* option bytes: [code][len][data1][data2]..[dataLEN] */
196         optionptr = packet->options;
197         rem = sizeof(packet->options);
198         while (1) {
199                 if (rem <= 0) {
200                         bb_error_msg("bad packet, malformed option field");
201                         return NULL;
202                 }
203                 if (optionptr[OPT_CODE] == DHCP_PADDING) {
204                         rem--;
205                         optionptr++;
206                         continue;
207                 }
208                 if (optionptr[OPT_CODE] == DHCP_END) {
209                         if ((overload & FILE_FIELD101) == FILE_FIELD) {
210                                 /* can use packet->file, and didn't look at it yet */
211                                 overload |= FILE_FIELD101; /* "we looked at it" */
212                                 optionptr = packet->file;
213                                 rem = sizeof(packet->file);
214                                 continue;
215                         }
216                         if ((overload & SNAME_FIELD101) == SNAME_FIELD) {
217                                 /* can use packet->sname, and didn't look at it yet */
218                                 overload |= SNAME_FIELD101; /* "we looked at it" */
219                                 optionptr = packet->sname;
220                                 rem = sizeof(packet->sname);
221                                 continue;
222                         }
223                         break;
224                 }
225                 len = 2 + optionptr[OPT_LEN];
226                 rem -= len;
227                 if (rem < 0)
228                         continue; /* complain and return NULL */
229
230                 if (optionptr[OPT_CODE] == code) {
231                         log_option("Option found", optionptr);
232                         return optionptr + OPT_DATA;
233                 }
234
235                 if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) {
236                         overload |= optionptr[OPT_DATA];
237                         /* fall through */
238                 }
239                 optionptr += len;
240         }
241
242         /* log3 because udhcpc uses it a lot - very noisy */
243         log3("Option 0x%02x not found", code);
244         return NULL;
245 }
246
247 /* Return the position of the 'end' option (no bounds checking) */
248 int FAST_FUNC udhcp_end_option(uint8_t *optionptr)
249 {
250         int i = 0;
251
252         while (optionptr[i] != DHCP_END) {
253                 if (optionptr[i] != DHCP_PADDING)
254                         i += optionptr[i + OPT_LEN] + OPT_DATA-1;
255                 i++;
256         }
257         return i;
258 }
259
260 /* Add an option (supplied in binary form) to the options.
261  * Option format: [code][len][data1][data2]..[dataLEN]
262  */
263 void FAST_FUNC udhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt)
264 {
265         unsigned len;
266         uint8_t *optionptr = packet->options;
267         unsigned end = udhcp_end_option(optionptr);
268
269         len = OPT_DATA + addopt[OPT_LEN];
270         /* end position + (option code/length + addopt length) + end option */
271         if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE) {
272 //TODO: learn how to use overflow option if we exhaust packet->options[]
273                 bb_error_msg("option 0x%02x did not fit into the packet",
274                                 addopt[OPT_CODE]);
275                 return;
276         }
277         log_option("Adding option", addopt);
278         memcpy(optionptr + end, addopt, len);
279         optionptr[end + len] = DHCP_END;
280 }
281
282 /* Add an one to four byte option to a packet */
283 void FAST_FUNC udhcp_add_simple_option(struct dhcp_packet *packet, uint8_t code, uint32_t data)
284 {
285         const struct dhcp_optflag *dh;
286
287         for (dh = dhcp_optflags; dh->code; dh++) {
288                 if (dh->code == code) {
289                         uint8_t option[6], len;
290
291                         option[OPT_CODE] = code;
292                         len = dhcp_option_lengths[dh->flags & OPTION_TYPE_MASK];
293                         option[OPT_LEN] = len;
294                         if (BB_BIG_ENDIAN)
295                                 data <<= 8 * (4 - len);
296                         /* Assignment is unaligned! */
297                         move_to_unaligned32(&option[OPT_DATA], data);
298                         udhcp_add_binary_option(packet, option);
299                         return;
300                 }
301         }
302
303         bb_error_msg("can't add option 0x%02x", code);
304 }
305
306 /* Find option 'code' in opt_list */
307 struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code)
308 {
309         while (opt_list && opt_list->data[OPT_CODE] < code)
310                 opt_list = opt_list->next;
311
312         if (opt_list && opt_list->data[OPT_CODE] == code)
313                 return opt_list;
314         return NULL;
315 }
316
317 /* Parse string to IP in network order */
318 int FAST_FUNC udhcp_str2nip(const char *str, void *arg)
319 {
320         len_and_sockaddr *lsa;
321
322         lsa = host_and_af2sockaddr(str, 0, AF_INET);
323         if (!lsa)
324                 return 0;
325         *(uint32_t*)arg = lsa->u.sin.sin_addr.s_addr;
326         free(lsa);
327         return 1;
328 }
329
330 /* udhcp_str2optset:
331  * Parse string option representation to binary form and add it to opt_list.
332  * Called to parse "udhcpc -x OPTNAME:OPTVAL"
333  * and to parse udhcpd.conf's "opt OPTNAME OPTVAL" directives.
334  */
335 /* helper for the helper */
336 static char *allocate_tempopt_if_needed(
337                 const struct dhcp_optflag *optflag,
338                 char *buffer,
339                 int *length_p)
340 {
341         char *allocated = NULL;
342         if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_BIN) {
343                 const char *end;
344                 allocated = xstrdup(buffer); /* more than enough */
345                 end = hex2bin(allocated, buffer, 255);
346                 if (errno)
347                         bb_error_msg_and_die("malformed hex string '%s'", buffer);
348                 *length_p = end - allocated;
349         }
350         return allocated;
351 }
352 /* helper: add an option to the opt_list */
353 static NOINLINE void attach_option(
354                 struct option_set **opt_list,
355                 const struct dhcp_optflag *optflag,
356                 char *buffer,
357                 int length)
358 {
359         struct option_set *existing, *new, **curr;
360         char *allocated = NULL;
361
362         existing = udhcp_find_option(*opt_list, optflag->code);
363         if (!existing) {
364                 log2("Attaching option %02x to list", optflag->code);
365                 allocated = allocate_tempopt_if_needed(optflag, buffer, &length);
366 #if ENABLE_FEATURE_UDHCP_RFC3397
367                 if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {
368                         /* reuse buffer and length for RFC1035-formatted string */
369                         allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);
370                 }
371 #endif
372                 /* make a new option */
373                 new = xmalloc(sizeof(*new));
374                 new->data = xmalloc(length + OPT_DATA);
375                 new->data[OPT_CODE] = optflag->code;
376                 new->data[OPT_LEN] = length;
377                 memcpy(new->data + OPT_DATA, buffer, length);
378
379                 curr = opt_list;
380                 while (*curr && (*curr)->data[OPT_CODE] < optflag->code)
381                         curr = &(*curr)->next;
382
383                 new->next = *curr;
384                 *curr = new;
385                 goto ret;
386         }
387
388         if (optflag->flags & OPTION_LIST) {
389                 unsigned old_len;
390
391                 /* add it to an existing option */
392                 log2("Attaching option %02x to existing member of list", optflag->code);
393                 allocated = allocate_tempopt_if_needed(optflag, buffer, &length);
394                 old_len = existing->data[OPT_LEN];
395 #if ENABLE_FEATURE_UDHCP_RFC3397
396                 if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {
397                         /* reuse buffer and length for RFC1035-formatted string */
398                         allocated = buffer = (char *)dname_enc(existing->data + OPT_DATA, old_len, buffer, &length);
399                 }
400 #endif
401                 if (old_len + length < 255) {
402                         /* actually 255 is ok too, but adding a space can overlow it */
403
404                         existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
405                         if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING) {
406                                 /* add space separator between STRING options in a list */
407                                 existing->data[OPT_DATA + old_len] = ' ';
408                                 old_len++;
409                         }
410                         memcpy(existing->data + OPT_DATA + old_len, buffer, length);
411                         existing->data[OPT_LEN] = old_len + length;
412                 } /* else, ignore the data, we could put this in a second option in the future */
413         } /* else, ignore the new data */
414
415  ret:
416         free(allocated);
417 }
418
419 int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg)
420 {
421         struct option_set **opt_list = arg;
422         char *opt, *val, *endptr;
423         char *str;
424         const struct dhcp_optflag *optflag;
425         struct dhcp_optflag bin_optflag;
426         unsigned optcode;
427         int retval, length;
428         char buffer[8] ALIGNED(4);
429         uint16_t *result_u16 = (uint16_t *) buffer;
430         uint32_t *result_u32 = (uint32_t *) buffer;
431
432         /* Cheat, the only *const* str possible is "" */
433         str = (char *) const_str;
434         opt = strtok(str, " \t=");
435         if (!opt)
436                 return 0;
437
438         optcode = bb_strtou(opt, NULL, 0);
439         if (!errno && optcode < 255) {
440                 /* Raw (numeric) option code */
441                 bin_optflag.flags = OPTION_BIN;
442                 bin_optflag.code = optcode;
443                 optflag = &bin_optflag;
444         } else {
445                 optflag = &dhcp_optflags[udhcp_option_idx(opt)];
446         }
447
448         retval = 0;
449         do {
450                 val = strtok(NULL, ", \t");
451                 if (!val)
452                         break;
453                 length = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK];
454                 retval = 0;
455                 opt = buffer; /* new meaning for variable opt */
456                 switch (optflag->flags & OPTION_TYPE_MASK) {
457                 case OPTION_IP:
458                         retval = udhcp_str2nip(val, buffer);
459                         break;
460                 case OPTION_IP_PAIR:
461                         retval = udhcp_str2nip(val, buffer);
462                         val = strtok(NULL, ", \t/-");
463                         if (!val)
464                                 retval = 0;
465                         if (retval)
466                                 retval = udhcp_str2nip(val, buffer + 4);
467                         break;
468                 case OPTION_STRING:
469 #if ENABLE_FEATURE_UDHCP_RFC3397
470                 case OPTION_DNS_STRING:
471 #endif
472                         length = strnlen(val, 254);
473                         if (length > 0) {
474                                 opt = val;
475                                 retval = 1;
476                         }
477                         break;
478 //              case OPTION_BOOLEAN: {
479 //                      static const char no_yes[] ALIGN1 = "no\0yes\0";
480 //                      buffer[0] = retval = index_in_strings(no_yes, val);
481 //                      retval++; /* 0 - bad; 1: "no" 2: "yes" */
482 //                      break;
483 //              }
484                 case OPTION_U8:
485                         buffer[0] = strtoul(val, &endptr, 0);
486                         retval = (endptr[0] == '\0');
487                         break;
488                 /* htonX are macros in older libc's, using temp var
489                  * in code below for safety */
490                 /* TODO: use bb_strtoX? */
491                 case OPTION_U16: {
492                         unsigned long tmp = strtoul(val, &endptr, 0);
493                         *result_u16 = htons(tmp);
494                         retval = (endptr[0] == '\0' /*&& tmp < 0x10000*/);
495                         break;
496                 }
497 //              case OPTION_S16: {
498 //                      long tmp = strtol(val, &endptr, 0);
499 //                      *result_u16 = htons(tmp);
500 //                      retval = (endptr[0] == '\0');
501 //                      break;
502 //              }
503                 case OPTION_U32: {
504                         unsigned long tmp = strtoul(val, &endptr, 0);
505                         *result_u32 = htonl(tmp);
506                         retval = (endptr[0] == '\0');
507                         break;
508                 }
509                 case OPTION_S32: {
510                         long tmp = strtol(val, &endptr, 0);
511                         *result_u32 = htonl(tmp);
512                         retval = (endptr[0] == '\0');
513                         break;
514                 }
515                 case OPTION_BIN: /* handled in attach_option() */
516                         opt = val;
517                         retval = 1;
518                 default:
519                         break;
520                 }
521                 if (retval)
522                         attach_option(opt_list, optflag, opt, length);
523         } while (retval && optflag->flags & OPTION_LIST);
524
525         return retval;
526 }