udhcp: pass pointer to whole packet to "add option" functions
[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 tarball for details.
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_option dhcp_options[] = {
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_STRING                           , 0x28 }, /* DHCP_NIS_DOMAIN    */
41         { OPTION_IP | OPTION_LIST                 , 0x29 }, /* DHCP_NIS_SERVER    */
42         { OPTION_IP | OPTION_LIST     | OPTION_REQ, 0x2a }, /* DHCP_NTP_SERVER    */
43         { OPTION_IP | OPTION_LIST                 , 0x2c }, /* DHCP_WINS_SERVER   */
44         { OPTION_U32                              , 0x33 }, /* DHCP_LEASE_TIME    */
45         { OPTION_IP                               , 0x36 }, /* DHCP_SERVER_ID     */
46         { OPTION_STRING                           , 0x38 }, /* DHCP_ERR_MESSAGE   */
47 //TODO: must be combined with 'sname' and 'file' handling:
48         { OPTION_STRING                           , 0x42 }, /* DHCP_TFTP_SERVER_NAME */
49         { OPTION_STRING                           , 0x43 }, /* DHCP_BOOT_FILE     */
50 //TODO: not a string, but a set of LASCII strings:
51 //      { OPTION_STRING                           , 0x4D }, /* DHCP_USER_CLASS    */
52 #if ENABLE_FEATURE_UDHCP_RFC3397
53         { OPTION_STR1035 | OPTION_LIST            , 0x77 }, /* DHCP_DOMAIN_SEARCH */
54 #endif
55         { OPTION_STATIC_ROUTES                    , 0x79 }, /* DHCP_STATIC_ROUTES */
56         { OPTION_STRING                           , 0xfc }, /* DHCP_WPAD          */
57
58         /* Options below have no match in dhcp_option_strings[],
59          * are not passed to dhcpc scripts, and cannot be specified
60          * with "option XXX YYY" syntax in dhcpd config file.
61          * These entries are only used internally by udhcp[cd]
62          * to correctly encode options into packets.
63          */
64
65         { OPTION_IP                               , 0x32 }, /* DHCP_REQUESTED_IP  */
66         { OPTION_U8                               , 0x35 }, /* DHCP_MESSAGE_TYPE  */
67         { OPTION_U16                              , 0x39 }, /* DHCP_MAX_SIZE      */
68         { OPTION_STRING                           , 0x3c }, /* DHCP_VENDOR        */
69 //FIXME: handling of this option is not exactly correct:
70         { OPTION_STRING                           , 0x3d }, /* DHCP_CLIENT_ID     */
71         { 0, 0 } /* zeroed terminating entry */
72 };
73
74 /* Used for converting options from incoming packets to env variables
75  * for udhcpc stript, and for setting options for udhcpd via
76  * "opt OPTION_NAME OPTION_VALUE" directives in udhcpd.conf file.
77  */
78 /* Must match dhcp_options[] order */
79 const char dhcp_option_strings[] ALIGN1 =
80         "subnet" "\0"      /* DHCP_SUBNET         */
81         "timezone" "\0"    /* DHCP_TIME_OFFSET    */
82         "router" "\0"      /* DHCP_ROUTER         */
83 //      "timesrv" "\0"     /* DHCP_TIME_SERVER    */
84 //      "namesrv" "\0"     /* DHCP_NAME_SERVER    */
85         "dns" "\0"         /* DHCP_DNS_SERVER     */
86 //      "logsrv" "\0"      /* DHCP_LOG_SERVER     */
87 //      "cookiesrv" "\0"   /* DHCP_COOKIE_SERVER  */
88         "lprsrv" "\0"      /* DHCP_LPR_SERVER     */
89         "hostname" "\0"    /* DHCP_HOST_NAME      */
90         "bootsize" "\0"    /* DHCP_BOOT_SIZE      */
91         "domain" "\0"      /* DHCP_DOMAIN_NAME    */
92         "swapsrv" "\0"     /* DHCP_SWAP_SERVER    */
93         "rootpath" "\0"    /* DHCP_ROOT_PATH      */
94         "ipttl" "\0"       /* DHCP_IP_TTL         */
95         "mtu" "\0"         /* DHCP_MTU            */
96         "broadcast" "\0"   /* DHCP_BROADCAST      */
97         "nisdomain" "\0"   /* DHCP_NIS_DOMAIN     */
98         "nissrv" "\0"      /* DHCP_NIS_SERVER     */
99         "ntpsrv" "\0"      /* DHCP_NTP_SERVER     */
100         "wins" "\0"        /* DHCP_WINS_SERVER    */
101         "lease" "\0"       /* DHCP_LEASE_TIME     */
102         "serverid" "\0"    /* DHCP_SERVER_ID      */
103         "message" "\0"     /* DHCP_ERR_MESSAGE    */
104         "tftp" "\0"        /* DHCP_TFTP_SERVER_NAME */
105         "bootfile" "\0"    /* DHCP_BOOT_FILE      */
106 //      "userclass" "\0"   /* DHCP_USER_CLASS     */
107 #if ENABLE_FEATURE_UDHCP_RFC3397
108         "search" "\0"      /* DHCP_DOMAIN_SEARCH  */
109 #endif
110 // "staticroutes" is only used to set udhcpc environment, it doesn't work
111 // in udhcpd.conf since OPTION_STATIC_ROUTES is not handled yet
112 // by "string->option" conversion code:
113         "staticroutes" "\0"/* DHCP_STATIC_ROUTES */
114         "wpad" "\0"        /* DHCP_WPAD          */
115         ;
116
117 /* Lengths of the different option types */
118 const uint8_t dhcp_option_lengths[] ALIGN1 = {
119         [OPTION_IP] =      4,
120         [OPTION_IP_PAIR] = 8,
121 //      [OPTION_BOOLEAN] = 1,
122         [OPTION_STRING] =  1,
123 #if ENABLE_FEATURE_UDHCP_RFC3397
124         [OPTION_STR1035] = 1,
125 #endif
126         [OPTION_U8] =      1,
127         [OPTION_U16] =     2,
128 //      [OPTION_S16] =     2,
129         [OPTION_U32] =     4,
130         [OPTION_S32] =     4,
131         /* Just like OPTION_STRING, we use minimum length here */
132         [OPTION_STATIC_ROUTES] = 5,
133 };
134
135
136 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 2
137 static void log_option(const char *pfx, const uint8_t *opt)
138 {
139         if (dhcp_verbose >= 2) {
140                 char buf[256 * 2 + 2];
141                 *bin2hex(buf, (void*) (opt + OPT_DATA), opt[OPT_LEN]) = '\0';
142                 bb_info_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
143         }
144 }
145 #else
146 # define log_option(pfx, opt) ((void)0)
147 #endif
148
149 /* get an option with bounds checking (warning, result is not aligned). */
150 uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code)
151 {
152         uint8_t *optionptr;
153         int len;
154         int rem;
155         int overload = 0;
156         enum {
157                 FILE_FIELD101  = FILE_FIELD  * 0x101,
158                 SNAME_FIELD101 = SNAME_FIELD * 0x101,
159         };
160
161         /* option bytes: [code][len][data1][data2]..[dataLEN] */
162         optionptr = packet->options;
163         rem = sizeof(packet->options);
164         while (1) {
165                 if (rem <= 0) {
166                         bb_error_msg("bad packet, malformed option field");
167                         return NULL;
168                 }
169                 if (optionptr[OPT_CODE] == DHCP_PADDING) {
170                         rem--;
171                         optionptr++;
172                         continue;
173                 }
174                 if (optionptr[OPT_CODE] == DHCP_END) {
175                         if ((overload & FILE_FIELD101) == FILE_FIELD) {
176                                 /* can use packet->file, and didn't look at it yet */
177                                 overload |= FILE_FIELD101; /* "we looked at it" */
178                                 optionptr = packet->file;
179                                 rem = sizeof(packet->file);
180                                 continue;
181                         }
182                         if ((overload & SNAME_FIELD101) == SNAME_FIELD) {
183                                 /* can use packet->sname, and didn't look at it yet */
184                                 overload |= SNAME_FIELD101; /* "we looked at it" */
185                                 optionptr = packet->sname;
186                                 rem = sizeof(packet->sname);
187                                 continue;
188                         }
189                         break;
190                 }
191                 len = 2 + optionptr[OPT_LEN];
192                 rem -= len;
193                 if (rem < 0)
194                         continue; /* complain and return NULL */
195
196                 if (optionptr[OPT_CODE] == code) {
197                         log_option("Option found", optionptr);
198                         return optionptr + OPT_DATA;
199                 }
200
201                 if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) {
202                         overload |= optionptr[OPT_DATA];
203                         /* fall through */
204                 }
205                 optionptr += len;
206         }
207
208         /* log3 because udhcpc uses it a lot - very noisy */
209         log3("Option 0x%02x not found", code);
210         return NULL;
211 }
212
213 /* return the position of the 'end' option (no bounds checking) */
214 int FAST_FUNC udhcp_end_option(uint8_t *optionptr)
215 {
216         int i = 0;
217
218         while (optionptr[i] != DHCP_END) {
219                 if (optionptr[i] != DHCP_PADDING)
220                         i += optionptr[i + OPT_LEN] + OPT_DATA-1;
221                 i++;
222         }
223         return i;
224 }
225
226 /* Add an option (supplied in binary form) to the options.
227  * Option format: [code][len][data1][data2]..[dataLEN]
228  */
229 void FAST_FUNC udhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt)
230 {
231         unsigned len;
232         uint8_t *optionptr = packet->options;
233         unsigned end = udhcp_end_option(optionptr);
234
235         len = OPT_DATA + addopt[OPT_LEN];
236         /* end position + (option code/length + addopt length) + end option */
237         if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE) {
238 //TODO: learn how to use overflow option if we exhaust packet->options[]
239                 bb_error_msg("option 0x%02x did not fit into the packet",
240                                 addopt[OPT_CODE]);
241                 return;
242         }
243         log_option("Adding option", addopt);
244         memcpy(optionptr + end, addopt, len);
245         optionptr[end + len] = DHCP_END;
246 }
247
248 /* Add an one to four byte option to a packet */
249 void FAST_FUNC udhcp_add_simple_option(struct dhcp_packet *packet, uint8_t code, uint32_t data)
250 {
251         const struct dhcp_option *dh;
252
253         for (dh = dhcp_options; dh->code; dh++) {
254                 if (dh->code == code) {
255                         uint8_t option[6], len;
256
257                         option[OPT_CODE] = code;
258                         len = dhcp_option_lengths[dh->flags & OPTION_TYPE_MASK];
259                         option[OPT_LEN] = len;
260                         if (BB_BIG_ENDIAN)
261                                 data <<= 8 * (4 - len);
262                         /* Assignment is unaligned! */
263                         move_to_unaligned32(&option[OPT_DATA], data);
264                         udhcp_add_binary_option(packet, option);
265                         return;
266                 }
267         }
268
269         bb_error_msg("can't add option 0x%02x", code);
270 }
271
272 /* Find option 'code' in opt_list */
273 struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code)
274 {
275         while (opt_list && opt_list->data[OPT_CODE] < code)
276                 opt_list = opt_list->next;
277
278         if (opt_list && opt_list->data[OPT_CODE] == code)
279                 return opt_list;
280         return NULL;
281 }
282
283 /* Parse string to IP in network order */
284 int FAST_FUNC udhcp_str2nip(const char *str, void *arg)
285 {
286         len_and_sockaddr *lsa;
287
288         lsa = host_and_af2sockaddr(str, 0, AF_INET);
289         if (!lsa)
290                 return 0;
291         *(uint32_t*)arg = lsa->u.sin.sin_addr.s_addr;
292         free(lsa);
293         return 1;
294 }
295
296 /* udhcp_str2optset:
297  * Parse string option representation to binary form
298  * and add it to opt_list
299  */
300 /* helper: add an option to the opt_list */
301 static NOINLINE void attach_option(
302                 struct option_set **opt_list,
303                 const struct dhcp_option *option,
304                 char *buffer,
305                 int length)
306 {
307         struct option_set *existing, *new, **curr;
308 #if ENABLE_FEATURE_UDHCP_RFC3397
309         char *allocated = NULL;
310 #endif
311
312         existing = udhcp_find_option(*opt_list, option->code);
313         if (!existing) {
314                 log2("Attaching option %02x to list", option->code);
315 #if ENABLE_FEATURE_UDHCP_RFC3397
316                 if ((option->flags & OPTION_TYPE_MASK) == OPTION_STR1035) {
317                         /* reuse buffer and length for RFC1035-formatted string */
318                         allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);
319                 }
320 #endif
321                 /* make a new option */
322                 new = xmalloc(sizeof(*new));
323                 new->data = xmalloc(length + OPT_DATA);
324                 new->data[OPT_CODE] = option->code;
325                 new->data[OPT_LEN] = length;
326                 memcpy(new->data + OPT_DATA, buffer, length);
327
328                 curr = opt_list;
329                 while (*curr && (*curr)->data[OPT_CODE] < option->code)
330                         curr = &(*curr)->next;
331
332                 new->next = *curr;
333                 *curr = new;
334                 goto ret;
335         }
336
337         if (option->flags & OPTION_LIST) {
338                 unsigned old_len;
339
340                 /* add it to an existing option */
341                 log1("Attaching option %02x to existing member of list", option->code);
342                 old_len = existing->data[OPT_LEN];
343 #if ENABLE_FEATURE_UDHCP_RFC3397
344                 if ((option->flags & OPTION_TYPE_MASK) == OPTION_STR1035) {
345                         /* reuse buffer and length for RFC1035-formatted string */
346                         allocated = buffer = (char *)dname_enc(existing->data + OPT_DATA, old_len, buffer, &length);
347                 }
348 #endif
349                 if (old_len + length < 255) {
350                         /* actually 255 is ok too, but adding a space can overlow it */
351
352                         existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
353                         if ((option->flags & OPTION_TYPE_MASK) == OPTION_STRING) {
354                                 /* add space separator between STRING options in a list */
355                                 existing->data[OPT_DATA + old_len] = ' ';
356                                 old_len++;
357                         }
358                         memcpy(existing->data + OPT_DATA + old_len, buffer, length);
359                         existing->data[OPT_LEN] = old_len + length;
360                 } /* else, ignore the data, we could put this in a second option in the future */
361         } /* else, ignore the new data */
362
363  ret: ;
364 #if ENABLE_FEATURE_UDHCP_RFC3397
365         free(allocated);
366 #endif
367 }
368
369 int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg)
370 {
371         struct option_set **opt_list = arg;
372         char *opt, *val, *endptr;
373         char *str;
374         const struct dhcp_option *option;
375         int retval, length, idx;
376         char buffer[8] ALIGNED(4);
377         uint16_t *result_u16 = (uint16_t *) buffer;
378         uint32_t *result_u32 = (uint32_t *) buffer;
379
380         /* Cheat, the only *const* str possible is "" */
381         str = (char *) const_str;
382         opt = strtok(str, " \t=");
383         if (!opt)
384                 return 0;
385
386         idx = index_in_strings(dhcp_option_strings, opt); /* NB: was strcasecmp! */
387         if (idx < 0)
388                 return 0;
389         option = &dhcp_options[idx];
390
391         retval = 0;
392         do {
393                 val = strtok(NULL, ", \t");
394                 if (!val)
395                         break;
396                 length = dhcp_option_lengths[option->flags & OPTION_TYPE_MASK];
397                 retval = 0;
398                 opt = buffer; /* new meaning for variable opt */
399                 switch (option->flags & OPTION_TYPE_MASK) {
400                 case OPTION_IP:
401                         retval = udhcp_str2nip(val, buffer);
402                         break;
403                 case OPTION_IP_PAIR:
404                         retval = udhcp_str2nip(val, buffer);
405                         val = strtok(NULL, ", \t/-");
406                         if (!val)
407                                 retval = 0;
408                         if (retval)
409                                 retval = udhcp_str2nip(val, buffer + 4);
410                         break;
411                 case OPTION_STRING:
412 #if ENABLE_FEATURE_UDHCP_RFC3397
413                 case OPTION_STR1035:
414 #endif
415                         length = strnlen(val, 254);
416                         if (length > 0) {
417                                 opt = val;
418                                 retval = 1;
419                         }
420                         break;
421 //              case OPTION_BOOLEAN: {
422 //                      static const char noyes[] ALIGN1 = "no\0yes\0";
423 //                      buffer[0] = retval = index_in_strings(noyes, val);
424 //                      retval++; /* 0 - bad; 1: "no" 2: "yes" */
425 //                      break;
426 //              }
427                 case OPTION_U8:
428                         buffer[0] = strtoul(val, &endptr, 0);
429                         retval = (endptr[0] == '\0');
430                         break;
431                 /* htonX are macros in older libc's, using temp var
432                  * in code below for safety */
433                 /* TODO: use bb_strtoX? */
434                 case OPTION_U16: {
435                         unsigned long tmp = strtoul(val, &endptr, 0);
436                         *result_u16 = htons(tmp);
437                         retval = (endptr[0] == '\0' /*&& tmp < 0x10000*/);
438                         break;
439                 }
440 //              case OPTION_S16: {
441 //                      long tmp = strtol(val, &endptr, 0);
442 //                      *result_u16 = htons(tmp);
443 //                      retval = (endptr[0] == '\0');
444 //                      break;
445 //              }
446                 case OPTION_U32: {
447                         unsigned long tmp = strtoul(val, &endptr, 0);
448                         *result_u32 = htonl(tmp);
449                         retval = (endptr[0] == '\0');
450                         break;
451                 }
452                 case OPTION_S32: {
453                         long tmp = strtol(val, &endptr, 0);
454                         *result_u32 = htonl(tmp);
455                         retval = (endptr[0] == '\0');
456                         break;
457                 }
458                 default:
459                         break;
460                 }
461                 if (retval)
462                         attach_option(opt_list, option, opt, length);
463         } while (retval && option->flags & OPTION_LIST);
464
465         return retval;
466 }