1/*
2 * dhcpcd - DHCP client daemon
3 * Copyright (c) 2006-2012 Roy Marples <roy@marples.name>
4 * All rights reserved
5
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <ctype.h>
29#include <errno.h>
30#include <fcntl.h>
31#include <stdlib.h>
32#include <string.h>
33#include <syslog.h>
34#include <unistd.h>
35
36#include "config.h"
37#include "common.h"
38#include "dhcp.h"
39
40#define REQUEST	(1 << 0)
41#define UINT8	(1 << 1)
42#define UINT16	(1 << 2)
43#define SINT16	(1 << 3)
44#define UINT32	(1 << 4)
45#define SINT32	(1 << 5)
46#define IPV4	(1 << 6)
47#define STRING	(1 << 7)
48#define PAIR	(1 << 8)
49#define ARRAY	(1 << 9)
50#define RFC3361	(1 << 10)
51#define RFC3397	(1 << 11)
52#define RFC3442 (1 << 12)
53#define RFC5969 (1 << 13)
54
55#define IPV4R	IPV4 | REQUEST
56
57#define DAD	"Duplicate address detected"
58
59/* Our aggregate option buffer.
60 * We ONLY use this when options are split, which for most purposes is
61 * practically never. See RFC3396 for details. */
62static uint8_t *opt_buffer;
63
64struct dhcp_opt {
65	uint8_t option;
66	int type;
67	const char *var;
68};
69
70static const struct dhcp_opt const dhcp_opts[] = {
71	{ 1,	IPV4 | REQUEST,	"subnet_mask" },
72		/* RFC 3442 states that the CSR has to come before all other
73		 * routes. For completeness, we also specify static routes,
74	 	 * then routers. */
75	{ 121,  RFC3442,	"classless_static_routes" },
76	{ 249,  RFC3442,	"ms_classless_static_routes" },
77	{ 33,	IPV4 | ARRAY | REQUEST,	"static_routes" },
78	{ 3,	IPV4 | ARRAY | REQUEST,	"routers" },
79	{ 2,	UINT32,		"time_offset" },
80	{ 4,	IPV4 | ARRAY,	"time_servers" },
81	{ 5,	IPV4 | ARRAY,	"ien116_name_servers" },
82        /* Explicitly include DNS in the list of parameters requested in the DNS request.
83         * Without this some DHCP servers may skip the DNS entries in the DHCP replies.*/
84	{ 6,	IPV4 | ARRAY | REQUEST, "domain_name_servers" },
85	{ 7,	IPV4 | ARRAY,	"log_servers" },
86	{ 8,	IPV4 | ARRAY,	"cookie_servers" },
87	{ 9, 	IPV4 | ARRAY,	"lpr_servers" },
88	{ 10,	IPV4 | ARRAY,	"impress_servers" },
89	{ 11,	IPV4 | ARRAY,	"resource_location_servers" },
90	{ 12,	STRING,		"host_name" },
91	{ 13,	UINT16,		"boot_size" },
92	{ 14,	STRING,		"merit_dump" },
93        /* Explicitly include DNS in the list of parameters requested in the DNS request.
94         * Without this some DHCP servers may skip the DNS entries in the DHCP replies.*/
95	{ 15,	STRING | REQUEST, "domain_name" },
96	{ 16,	IPV4,		"swap_server" },
97	{ 17,	STRING,		"root_path" },
98	{ 18,	STRING,		"extensions_path" },
99	{ 19,	UINT8,		"ip_forwarding" },
100	{ 20,	UINT8,		"non_local_source_routing" },
101	{ 21,	IPV4 | ARRAY,	"policy_filter" },
102	{ 22,	SINT16,		"max_dgram_reassembly" },
103	{ 23,	UINT16,		"default_ip_ttl" },
104	{ 24,	UINT32,		"path_mtu_aging_timeout" },
105	{ 25,	UINT16 | ARRAY,	"path_mtu_plateau_table" },
106	{ 26,	UINT16,		"interface_mtu" },
107	{ 27,	UINT8,		"all_subnets_local" },
108	{ 28,	IPV4 | REQUEST,	"broadcast_address" },
109	{ 29,	UINT8,		"perform_mask_discovery" },
110	{ 30,	UINT8,		"mask_supplier" },
111	{ 31,	UINT8,		"router_discovery" },
112	{ 32,	IPV4,		"router_solicitation_address" },
113	{ 34,	UINT8,		"trailer_encapsulation" },
114	{ 35, 	UINT32,		"arp_cache_timeout" },
115	{ 36,	UINT16,		"ieee802_3_encapsulation" },
116	{ 37,	UINT8,		"default_tcp_ttl" },
117	{ 38,	UINT32,		"tcp_keepalive_interval" },
118	{ 39,	UINT8,		"tcp_keepalive_garbage" },
119	{ 40,	STRING,		"nis_domain" },
120	{ 41,	IPV4 | ARRAY,	"nis_servers" },
121	{ 42,	IPV4 | ARRAY,	"ntp_servers" },
122	{ 43,	STRING,		"vendor_encapsulated_options" },
123	{ 44,	IPV4 | ARRAY,	"netbios_name_servers" },
124	{ 45,	IPV4,		"netbios_dd_server" },
125	{ 46,	UINT8,		"netbios_node_type" },
126	{ 47,	STRING,		"netbios_scope" },
127	{ 48,	IPV4 | ARRAY,	"font_servers" },
128	{ 49,	IPV4 | ARRAY,	"x_display_manager" },
129	{ 50, 	IPV4,		"dhcp_requested_address" },
130	{ 51,	UINT32 | REQUEST,	"dhcp_lease_time" },
131	{ 52,	UINT8,		"dhcp_option_overload" },
132	{ 53,	UINT8,		"dhcp_message_type" },
133	{ 54,	IPV4,		"dhcp_server_identifier" },
134	{ 55,	UINT8 | ARRAY,	"dhcp_parameter_request_list" },
135	{ 56,	STRING,		"dhcp_message" },
136	{ 57,	UINT16,		"dhcp_max_message_size" },
137	{ 58,	UINT32 | REQUEST,	"dhcp_renewal_time" },
138	{ 59,	UINT32 | REQUEST,	"dhcp_rebinding_time" },
139	{ 64,	STRING,		"nisplus_domain" },
140	{ 65,	IPV4 | ARRAY,	"nisplus_servers" },
141	{ 66,	STRING,		"tftp_server_name" },
142	{ 67,	STRING,		"bootfile_name" },
143	{ 68,	IPV4 | ARRAY,	"mobile_ip_home_agent" },
144	{ 69,	IPV4 | ARRAY,	"smtp_server" },
145	{ 70,	IPV4 | ARRAY,	"pop_server" },
146	{ 71,	IPV4 | ARRAY,	"nntp_server" },
147	{ 72,	IPV4 | ARRAY,	"www_server" },
148	{ 73,	IPV4 | ARRAY,	"finger_server" },
149	{ 74,	IPV4 | ARRAY,	"irc_server" },
150	{ 75,	IPV4 | ARRAY,	"streettalk_server" },
151	{ 76,	IPV4 | ARRAY,	"streettalk_directory_assistance_server" },
152	{ 77,	STRING,		"user_class" },
153	{ 81,	STRING | RFC3397,	"fqdn_name" },
154	{ 85,	IPV4 | ARRAY,	"nds_servers" },
155	{ 86,	STRING,		"nds_tree_name" },
156	{ 87,	STRING,		"nds_context" },
157	{ 88,	STRING | RFC3397,	"bcms_controller_names" },
158	{ 89,	IPV4 | ARRAY,	"bcms_controller_address" },
159	{ 91,	UINT32,		"client_last_transaction_time" },
160	{ 92,	IPV4 | ARRAY,	"associated_ip" },
161	{ 98,	STRING,		"uap_servers" },
162	{ 112,	IPV4 | ARRAY,	"netinfo_server_address" },
163	{ 113,	STRING,		"netinfo_server_tag" },
164	{ 114,	STRING,		"default_url" },
165	{ 118,	IPV4,		"subnet_selection" },
166	{ 119,	STRING | RFC3397,	"domain_search" },
167	{ 120,	STRING | RFC3361,	"sip_server" },
168	{ 212,  RFC5969,	"sixrd" },
169	{ 0, 0, NULL }
170};
171
172static const char *if_params[] = {
173	"interface",
174	"reason",
175	"pid",
176	"ifmetric",
177	"ifwireless",
178	"ifflags",
179	"profile",
180	"interface_order",
181	NULL
182};
183
184static const char *dhcp_params[] = {
185	"ip_address",
186	"subnet_cidr",
187	"network_number",
188	"ssid",
189	"filename",
190	"server_name",
191	NULL
192};
193
194void
195print_options(void)
196{
197	const struct dhcp_opt *opt;
198	const char **p;
199
200	for (p = if_params; *p; p++)
201		printf(" -  %s\n", *p);
202
203	for (p = dhcp_params; *p; p++)
204		printf("    %s\n", *p);
205
206	for (opt = dhcp_opts; opt->option; opt++)
207		if (opt->var)
208			printf("%03d %s\n", opt->option, opt->var);
209}
210
211int make_option_mask(uint8_t *mask, const char *opts, int add)
212{
213	char *token, *o, *p, *t;
214	const struct dhcp_opt *opt;
215	int match, n;
216
217	o = p = xstrdup(opts);
218	while ((token = strsep(&p, ", "))) {
219		if (*token == '\0')
220			continue;
221		for (opt = dhcp_opts; opt->option; opt++) {
222			if (!opt->var)
223				continue;
224			match = 0;
225			if (strcmp(opt->var, token) == 0)
226				match = 1;
227			else {
228				errno = 0;
229				n = strtol(token, &t, 0);
230				if (errno == 0 && !*t)
231					if (opt->option == n)
232						match = 1;
233			}
234			if (match) {
235				if (add == 2 && !(opt->type & IPV4)) {
236					free(o);
237					errno = EINVAL;
238					return -1;
239				}
240				if (add == 1 || add == 2)
241					add_option_mask(mask,
242					    opt->option);
243				else
244					del_option_mask(mask,
245					    opt->option);
246				break;
247			}
248		}
249		if (!opt->option) {
250			free(o);
251			errno = ENOENT;
252			return -1;
253		}
254	}
255	free(o);
256	return 0;
257}
258
259static int
260valid_length(uint8_t option, int dl, int *type)
261{
262	const struct dhcp_opt *opt;
263	ssize_t sz;
264
265	if (dl == 0)
266		return -1;
267
268	for (opt = dhcp_opts; opt->option; opt++) {
269		if (opt->option != option)
270			continue;
271
272		if (type)
273			*type = opt->type;
274		/* The size of RFC3442 and RFC5969 options is checked at a later
275		 * stage in the code */
276		if (opt->type == 0 ||
277		    opt->type & (STRING | RFC3442 | RFC5969))
278			return 0;
279		/* The code does not use SINT16 / SINT32 together with ARRAY.
280		 * It is however far easier to reason about the code if all
281		 * possible array elements are included, and also does not code
282		 * any additional CPU resources. sizeof(uintXX_t) ==
283		 * sizeof(intXX_t) can be assumed. */
284		sz = 0;
285		if (opt->type & (UINT32 | SINT32 | IPV4))
286			sz = sizeof(uint32_t);
287		else if (opt->type & (UINT16 | SINT16))
288			sz = sizeof(uint16_t);
289		else if (opt->type & UINT8)
290			sz = sizeof(uint8_t);
291		if (opt->type & ARRAY) {
292			/* The result of modulo zero is undefined. There are no
293			 * options defined in this file that do not match one of
294			 * the if-clauses above, so the following is not really
295			 * necessary. However, to avoid confusion and unexpected
296			 * behavior if the defined options are ever extended,
297			 * returning false here seems sensible. */
298			if (!sz) return -1;
299			return (dl % sz == 0) ? 0 : -1;
300		}
301		return (sz == dl) ? 0 : -1;
302	}
303
304	/* unknown option, so let it pass */
305	return 0;
306}
307
308#ifdef DEBUG_MEMORY
309static void
310free_option_buffer(void)
311{
312	free(opt_buffer);
313}
314#endif
315
316#define get_option_raw(dhcp, opt) get_option(dhcp, opt, NULL, NULL)
317static const uint8_t *
318get_option(const struct dhcp_message *dhcp, uint8_t opt, int *len, int *type)
319{
320	const uint8_t *p = dhcp->options;
321	const uint8_t *e = p + sizeof(dhcp->options);
322	uint8_t l, ol = 0;
323	uint8_t o = 0;
324	uint8_t overl = 0;
325	uint8_t *bp = NULL;
326	const uint8_t *op = NULL;
327	int bl = 0;
328
329	/* DHCP Options are in TLV format with T and L each being a single
330	 * byte.  In general, here we have p -> T, ol=p+1 -> L, op -> V.
331	 * We must make sure there is enough room to read both T and L.
332	 */
333	while (p + 1 < e) {
334		o = *p++;
335		if (o == opt) {
336			if (op) {
337				if (!opt_buffer) {
338					opt_buffer = xmalloc(sizeof(*dhcp));
339#ifdef DEBUG_MEMORY
340					atexit(free_option_buffer);
341#endif
342				}
343				if (!bp)
344					bp = opt_buffer;
345				memcpy(bp, op, ol);
346				bp += ol;
347			}
348			ol = (p + *p < e) ? *p : e - (p + 1);
349			op = p + 1;
350			bl += ol;
351		}
352		switch (o) {
353		case DHO_PAD:
354			continue;
355		case DHO_END:
356			if (overl & 1) {
357				/* bit 1 set means parse boot file */
358				overl &= ~1;
359				p = dhcp->bootfile;
360				e = p + sizeof(dhcp->bootfile);
361			} else if (overl & 2) {
362				/* bit 2 set means parse server name */
363				overl &= ~2;
364				p = dhcp->servername;
365				e = p + sizeof(dhcp->servername);
366			} else
367				goto exit;
368			break;
369		case DHO_OPTIONSOVERLOADED:
370			/* Ensure we only get this option once */
371			if (!overl)
372				overl = 0x80 | p[1];
373			break;
374		}
375		l = *p++;
376		p += l;
377	}
378
379exit:
380	if (valid_length(opt, bl, type) == -1) {
381		errno = EINVAL;
382		return NULL;
383	}
384	if (len)
385		*len = bl;
386	if (bp) {
387		memcpy(bp, op, ol);
388		return (const uint8_t *)opt_buffer;
389	}
390	if (op)
391		return op;
392	errno = ENOENT;
393	return NULL;
394}
395
396int
397get_option_addr(struct in_addr *a, const struct dhcp_message *dhcp,
398    uint8_t option)
399{
400	const uint8_t *p = get_option_raw(dhcp, option);
401
402	if (!p)
403		return -1;
404	memcpy(&a->s_addr, p, sizeof(a->s_addr));
405	return 0;
406}
407
408int
409get_option_uint32(uint32_t *i, const struct dhcp_message *dhcp, uint8_t option)
410{
411	const uint8_t *p = get_option_raw(dhcp, option);
412	uint32_t d;
413
414	if (!p)
415		return -1;
416	memcpy(&d, p, sizeof(d));
417	*i = ntohl(d);
418	return 0;
419}
420
421int
422get_option_uint16(uint16_t *i, const struct dhcp_message *dhcp, uint8_t option)
423{
424	const uint8_t *p = get_option_raw(dhcp, option);
425	uint16_t d;
426
427	if (!p)
428		return -1;
429	memcpy(&d, p, sizeof(d));
430	*i = ntohs(d);
431	return 0;
432}
433
434int
435get_option_uint8(uint8_t *i, const struct dhcp_message *dhcp, uint8_t option)
436{
437	const uint8_t *p = get_option_raw(dhcp, option);
438
439	if (!p)
440		return -1;
441	if (i)
442		*i = *(p);
443	return 0;
444}
445
446/* Decode an RFC3397 DNS search order option into a space
447 * separated string. Returns length of string (including
448 * terminating zero) or zero on error. out may be NULL
449 * to just determine output length. */
450ssize_t
451decode_rfc3397(char *out, ssize_t len, int pl, const uint8_t *p)
452{
453	const uint8_t *r, *q = p;
454	int count = 0, l, hops;
455	uint8_t ltype;
456
457	while (q - p < pl) {
458		r = NULL;
459		hops = 0;
460		/* We check we are inside our length again incase
461		 * the data is NOT terminated correctly. */
462		while ((l = *q++) && q - p < pl) {
463			ltype = l & 0xc0;
464			if (ltype == 0x80 || ltype == 0x40)
465				return 0;
466			else if (ltype == 0xc0) { /* pointer */
467				l = (l & 0x3f) << 8;
468				l |= *q++;
469				/* save source of first jump. */
470				if (!r)
471					r = q;
472				hops++;
473				if (hops > 255)
474					return 0;
475				q = p + l;
476				if (q - p >= pl)
477					return 0;
478			} else {
479				/* straightforward name segment, add with '.' */
480				count += l + 1;
481				if (out) {
482					if ((ssize_t)l + 1 > len) {
483						errno = ENOBUFS;
484						return -1;
485					}
486					memcpy(out, q, l);
487					out += l;
488					*out++ = '.';
489					len -= l;
490					len--;
491				}
492				q += l;
493			}
494		}
495		/* change last dot to space */
496		if (out)
497			*(out - 1) = ' ';
498		if (r)
499			q = r;
500	}
501
502	/* change last space to zero terminator */
503	if (out)
504		*(out - 1) = 0;
505
506	return count;
507}
508
509static ssize_t
510decode_rfc3442(char *out, ssize_t len, int pl, const uint8_t *p)
511{
512	const uint8_t *e;
513	ssize_t b, bytes = 0, ocets;
514	uint8_t cidr;
515	struct in_addr addr;
516	char *o = out;
517
518	/* Minimum is 5 -first is CIDR and a router length of 4 */
519	if (pl < 5) {
520		errno = EINVAL;
521		return -1;
522	}
523
524	e = p + pl;
525	while (p < e) {
526		cidr = *p++;
527		if (cidr > 32) {
528			errno = EINVAL;
529			return -1;
530		}
531		ocets = (cidr + 7) / 8;
532		if (!out) {
533			p += 4 + ocets;
534			bytes += ((4 * 4) * 2) + 4;
535			continue;
536		}
537		if ((((4 * 4) * 2) + 4) > len) {
538			errno = ENOBUFS;
539			return -1;
540		}
541		if (o != out) {
542			*o++ = ' ';
543			len--;
544		}
545		/* If we have ocets then we have a destination and netmask */
546		if (ocets > 0) {
547			addr.s_addr = 0;
548			memcpy(&addr.s_addr, p, ocets);
549			b = snprintf(o, len, "%s/%d", inet_ntoa(addr), cidr);
550			p += ocets;
551		} else
552			b = snprintf(o, len, "0.0.0.0/0");
553		o += b;
554		len -= b;
555
556		/* Finally, snag the router */
557		memcpy(&addr.s_addr, p, 4);
558		p += 4;
559		b = snprintf(o, len, " %s", inet_ntoa(addr));
560		o += b;
561		len -= b;
562	}
563
564	if (out)
565		return o - out;
566	return bytes;
567}
568
569static struct rt *
570decode_rfc3442_rt(int dl, const uint8_t *data)
571{
572	const uint8_t *p = data;
573	const uint8_t *e;
574	uint8_t cidr;
575	size_t ocets;
576	struct rt *routes = NULL;
577	struct rt *rt = NULL;
578
579	/* Minimum is 5 -first is CIDR and a router length of 4 */
580	if (dl < 5)
581		return NULL;
582
583	e = p + dl;
584	while (p < e) {
585		cidr = *p++;
586		if (cidr > 32) {
587			free_routes(routes);
588			errno = EINVAL;
589			return NULL;
590		}
591
592		if (rt) {
593			rt->next = xzalloc(sizeof(*rt));
594			rt = rt->next;
595		} else {
596			routes = rt = xzalloc(sizeof(*routes));
597		}
598		rt->next = NULL;
599
600		ocets = (cidr + 7) / 8;
601		/* If we have ocets then we have a destination and netmask */
602		if (ocets > 0) {
603			memcpy(&rt->dest.s_addr, p, ocets);
604			p += ocets;
605			rt->net.s_addr = htonl(~0U << (32 - cidr));
606		}
607
608		/* Finally, snag the router */
609		memcpy(&rt->gate.s_addr, p, 4);
610		p += 4;
611	}
612	return routes;
613}
614
615static char *
616decode_rfc3361(int dl, const uint8_t *data)
617{
618	uint8_t enc;
619	unsigned int l;
620	char *sip = NULL;
621	struct in_addr addr;
622	char *p;
623
624	if (dl < 2) {
625		errno = EINVAL;
626		return 0;
627	}
628
629	enc = *data++;
630	dl--;
631	switch (enc) {
632	case 0:
633		if ((l = decode_rfc3397(NULL, 0, dl, data)) > 0) {
634			sip = xmalloc(l);
635			decode_rfc3397(sip, l, dl, data);
636		}
637		break;
638	case 1:
639		if (dl == 0 || dl % 4 != 0) {
640			errno = EINVAL;
641			break;
642		}
643		addr.s_addr = INADDR_BROADCAST;
644		l = ((dl / sizeof(addr.s_addr)) * ((4 * 4) + 1)) + 1;
645		sip = p = xmalloc(l);
646		while (dl != 0) {
647			memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
648			data += sizeof(addr.s_addr);
649			p += snprintf(p, l - (p - sip), "%s ", inet_ntoa(addr));
650			dl -= sizeof(addr.s_addr);
651		}
652		*--p = '\0';
653		break;
654	default:
655		errno = EINVAL;
656		return 0;
657	}
658
659	return sip;
660}
661
662/* Decode an RFC5969 6rd order option into a space
663 * separated string. Returns length of string (including
664 * terminating zero) or zero on error. */
665static ssize_t
666decode_rfc5969(char *out, ssize_t len, int pl, const uint8_t *p)
667{
668	uint8_t ipv4masklen, ipv6prefixlen;
669	uint8_t ipv6prefix[16];
670	uint8_t br[4];
671	int i;
672	ssize_t b, bytes = 0;
673
674	if (pl < 22) {
675		errno = EINVAL;
676		return 0;
677	}
678
679	ipv4masklen = *p++;
680	pl--;
681	ipv6prefixlen = *p++;
682	pl--;
683
684	for (i = 0; i < 16; i++) {
685		ipv6prefix[i] = *p++;
686		pl--;
687	}
688	if (out) {
689		b= snprintf(out, len,
690		    "%d %d "
691		    "%02x%02x:%02x%02x:"
692		    "%02x%02x:%02x%02x:"
693		    "%02x%02x:%02x%02x:"
694		    "%02x%02x:%02x%02x",
695		    ipv4masklen, ipv6prefixlen,
696		    ipv6prefix[0], ipv6prefix[1], ipv6prefix[2], ipv6prefix[3],
697		    ipv6prefix[4], ipv6prefix[5], ipv6prefix[6], ipv6prefix[7],
698		    ipv6prefix[8], ipv6prefix[9], ipv6prefix[10],ipv6prefix[11],
699		    ipv6prefix[12],ipv6prefix[13],ipv6prefix[14], ipv6prefix[15]
700		);
701
702		len -= b;
703		out += b;
704		bytes += b;
705	} else {
706		bytes += 16 * 2 + 8 + 2 + 1 + 2;
707	}
708
709	while (pl >= 4) {
710		br[0] = *p++;
711		br[1] = *p++;
712		br[2] = *p++;
713		br[3] = *p++;
714		pl -= 4;
715
716		if (out) {
717			b= snprintf(out, len, " %d.%d.%d.%d",
718			    br[0], br[1], br[2], br[3]);
719			len -= b;
720			out += b;
721			bytes += b;
722		} else {
723			bytes += (4 * 4);
724		}
725	}
726
727	return bytes;
728}
729
730char *
731get_option_string(const struct dhcp_message *dhcp, uint8_t option)
732{
733	int type = 0;
734	int len;
735	const uint8_t *p;
736	char *s;
737
738	p = get_option(dhcp, option, &len, &type);
739	if (!p || *p == '\0')
740		return NULL;
741
742	if (type & RFC3397) {
743		type = decode_rfc3397(NULL, 0, len, p);
744		if (!type) {
745			errno = EINVAL;
746			return NULL;
747		}
748		s = xmalloc(sizeof(char) * type);
749		decode_rfc3397(s, type, len, p);
750		return s;
751	}
752
753	if (type & RFC3361)
754		return decode_rfc3361(len, p);
755
756	s = xmalloc(sizeof(char) * (len + 1));
757	memcpy(s, p, len);
758	s[len] = '\0';
759	return s;
760}
761
762/* This calculates the netmask that we should use for static routes.
763 * This IS different from the calculation used to calculate the netmask
764 * for an interface address. */
765static uint32_t
766route_netmask(uint32_t ip_in)
767{
768	/* used to be unsigned long - check if error */
769	uint32_t p = ntohl(ip_in);
770	uint32_t t;
771
772	if (IN_CLASSA(p))
773		t = ~IN_CLASSA_NET;
774	else {
775		if (IN_CLASSB(p))
776			t = ~IN_CLASSB_NET;
777		else {
778			if (IN_CLASSC(p))
779				t = ~IN_CLASSC_NET;
780			else
781				t = 0;
782		}
783	}
784
785	while (t & p)
786		t >>= 1;
787
788	return (htonl(~t));
789}
790
791/* We need to obey routing options.
792 * If we have a CSR then we only use that.
793 * Otherwise we add static routes and then routers. */
794struct rt *
795get_option_routes(const struct dhcp_message *dhcp,
796    const char *ifname, unsigned long long *opts)
797{
798	const uint8_t *p;
799	const uint8_t *e;
800	struct rt *routes = NULL;
801	struct rt *route = NULL;
802	int len;
803
804	/* If we have CSR's then we MUST use these only */
805	p = get_option(dhcp, DHO_CSR, &len, NULL);
806	/* Check for crappy MS option */
807	if (!p)
808		p = get_option(dhcp, DHO_MSCSR, &len, NULL);
809	if (p) {
810		routes = decode_rfc3442_rt(len, p);
811		if (routes) {
812			if (!(*opts & DHCPCD_CSR_WARNED)) {
813				syslog(LOG_DEBUG,
814				    "%s: using Classless Static Routes",
815				    ifname);
816				*opts |= DHCPCD_CSR_WARNED;
817			}
818			return routes;
819		}
820	}
821
822	/* OK, get our static routes first. */
823	p = get_option(dhcp, DHO_STATICROUTE, &len, NULL);
824	if (p) {
825		e = p + len;
826		while (p < e) {
827			if (route) {
828				route->next = xmalloc(sizeof(*route));
829				route = route->next;
830			} else
831				routes = route = xmalloc(sizeof(*routes));
832			route->next = NULL;
833			memcpy(&route->dest.s_addr, p, 4);
834			p += 4;
835			memcpy(&route->gate.s_addr, p, 4);
836			p += 4;
837			route->net.s_addr = route_netmask(route->dest.s_addr);
838		}
839	}
840
841	/* Now grab our routers */
842	p = get_option(dhcp, DHO_ROUTER, &len, NULL);
843	if (p) {
844		e = p + len;
845		while (p < e) {
846			if (route) {
847				route->next = xzalloc(sizeof(*route));
848				route = route->next;
849			} else
850				routes = route = xzalloc(sizeof(*route));
851			memcpy(&route->gate.s_addr, p, 4);
852			p += 4;
853		}
854	}
855
856	return routes;
857}
858
859static size_t
860encode_rfc1035(const char *src, uint8_t *dst)
861{
862	uint8_t *p = dst;
863	uint8_t *lp = p++;
864
865	if (*src == '\0')
866		return 0;
867	for (; *src; src++) {
868		if (*src == '\0')
869			break;
870		if (*src == '.') {
871			/* Skip the trailing . */
872			if (src[1] == '\0')
873				break;
874			*lp = p - lp - 1;
875			if (*lp == '\0')
876				return p - dst;
877			lp = p++;
878		} else
879			*p++ = (uint8_t)*src;
880	}
881	*lp = p - lp - 1;
882	*p++ = '\0';
883	return p - dst;
884}
885
886#define PUTADDR(_type, _val)						      \
887	{								      \
888		*p++ = _type;						      \
889		*p++ = 4;						      \
890		memcpy(p, &_val.s_addr, 4);				      \
891		p += 4;							      \
892	}
893
894int
895dhcp_message_add_addr(struct dhcp_message *dhcp,
896    uint8_t type, struct in_addr addr)
897{
898	uint8_t *p;
899	size_t len;
900
901	p = dhcp->options;
902	while (*p != DHO_END) {
903		p++;
904		p += *p + 1;
905	}
906
907	len = p - (uint8_t *)dhcp;
908	if (len + 6 > sizeof(*dhcp)) {
909		errno = ENOMEM;
910		return -1;
911	}
912
913	PUTADDR(type, addr);
914	*p = DHO_END;
915	return 0;
916}
917
918ssize_t
919make_message(struct dhcp_message **message,
920    const struct interface *iface,
921    uint8_t type)
922{
923	struct dhcp_message *dhcp;
924	uint8_t *m, *lp, *p;
925	uint8_t *n_params = NULL;
926	time_t up = uptime() - iface->start_uptime;
927	uint32_t ul;
928	uint16_t sz;
929	size_t len;
930	const char *hp;
931	const struct dhcp_opt *opt;
932	const struct if_options *ifo = iface->state->options;
933	const struct dhcp_lease *lease = &iface->state->lease;
934
935	dhcp = xzalloc(sizeof (*dhcp));
936	m = (uint8_t *)dhcp;
937	p = dhcp->options;
938
939	if ((type == DHCP_INFORM || type == DHCP_RELEASE ||
940		(type == DHCP_REQUEST &&
941		    iface->net.s_addr == lease->net.s_addr &&
942		    (iface->state->new == NULL ||
943			iface->state->new->cookie == htonl(MAGIC_COOKIE)))))
944	{
945		dhcp->ciaddr = iface->addr.s_addr;
946		/* In-case we haven't actually configured the address yet */
947		if (type == DHCP_INFORM && iface->addr.s_addr == 0)
948			dhcp->ciaddr = lease->addr.s_addr;
949	}
950
951	dhcp->op = DHCP_BOOTREQUEST;
952	dhcp->hwtype = iface->family;
953	switch (iface->family) {
954	case ARPHRD_ETHER:
955	case ARPHRD_IEEE802:
956		dhcp->hwlen = iface->hwlen;
957		memcpy(&dhcp->chaddr, &iface->hwaddr, iface->hwlen);
958		break;
959	}
960
961	if (ifo->options & DHCPCD_BROADCAST &&
962	    dhcp->ciaddr == 0 &&
963	    type != DHCP_DECLINE &&
964	    type != DHCP_RELEASE)
965		dhcp->flags = htons(BROADCAST_FLAG);
966
967	if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
968		if (up < 0 || up > (time_t)UINT16_MAX)
969			dhcp->secs = htons((uint16_t)UINT16_MAX);
970		else
971			dhcp->secs = htons(up);
972	}
973	dhcp->xid = iface->state->xid;
974	dhcp->cookie = htonl(MAGIC_COOKIE);
975
976	*p++ = DHO_MESSAGETYPE;
977	*p++ = 1;
978	*p++ = type;
979
980	if (iface->clientid) {
981		*p++ = DHO_CLIENTID;
982		memcpy(p, iface->clientid, iface->clientid[0] + 1);
983		p += iface->clientid[0] + 1;
984	}
985
986	if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
987		if (type == DHCP_DECLINE ||
988		    (type == DHCP_REQUEST &&
989			lease->addr.s_addr != iface->addr.s_addr))
990		{
991			PUTADDR(DHO_IPADDRESS, lease->addr);
992			if (lease->server.s_addr)
993				PUTADDR(DHO_SERVERID, lease->server);
994		}
995
996		if (type == DHCP_RELEASE) {
997			if (lease->server.s_addr)
998				PUTADDR(DHO_SERVERID, lease->server);
999		}
1000	}
1001
1002	if (type == DHCP_DECLINE) {
1003		*p++ = DHO_MESSAGE;
1004		len = strlen(DAD);
1005		*p++ = len;
1006		memcpy(p, DAD, len);
1007		p += len;
1008	}
1009
1010	if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
1011		PUTADDR(DHO_IPADDRESS, ifo->req_addr);
1012
1013	if (type == DHCP_DISCOVER ||
1014	    type == DHCP_INFORM ||
1015	    type == DHCP_REQUEST)
1016	{
1017		*p++ = DHO_MAXMESSAGESIZE;
1018		*p++ = 2;
1019		sz = get_mtu(iface->name);
1020		if (sz < MTU_MIN) {
1021			if (set_mtu(iface->name, MTU_MIN) == 0)
1022				sz = MTU_MIN;
1023		} else if (sz > MTU_MAX) {
1024			/* Even though our MTU could be greater than
1025			 * MTU_MAX (1500) dhcpcd does not presently
1026			 * handle DHCP packets any bigger. */
1027			sz = MTU_MAX;
1028		}
1029		sz = htons(sz);
1030		memcpy(p, &sz, 2);
1031		p += 2;
1032
1033		if (ifo->userclass[0]) {
1034			*p++ = DHO_USERCLASS;
1035			memcpy(p, ifo->userclass, ifo->userclass[0] + 1);
1036			p += ifo->userclass[0] + 1;
1037		}
1038
1039		if (ifo->vendorclassid[0]) {
1040			*p++ = DHO_VENDORCLASSID;
1041			memcpy(p, ifo->vendorclassid,
1042			    ifo->vendorclassid[0] + 1);
1043			p += ifo->vendorclassid[0] + 1;
1044		}
1045
1046
1047		if (type != DHCP_INFORM) {
1048			if (ifo->leasetime != 0) {
1049				*p++ = DHO_LEASETIME;
1050				*p++ = 4;
1051				ul = htonl(ifo->leasetime);
1052				memcpy(p, &ul, 4);
1053				p += 4;
1054			}
1055		}
1056
1057		/* Regardless of RFC2132, we should always send a hostname
1058		 * upto the first dot (the short hostname) as otherwise
1059		 * confuses some DHCP servers when updating DNS.
1060		 * The FQDN option should be used if a FQDN is required. */
1061		if (ifo->options & DHCPCD_HOSTNAME && ifo->hostname[0]) {
1062			*p++ = DHO_HOSTNAME;
1063			hp = strchr(ifo->hostname, '.');
1064			if (hp)
1065				len = hp - ifo->hostname;
1066			else
1067				len = strlen(ifo->hostname);
1068			*p++ = len;
1069			memcpy(p, ifo->hostname, len);
1070			p += len;
1071		}
1072		if (ifo->fqdn != FQDN_DISABLE && ifo->hostname[0]) {
1073			/* IETF DHC-FQDN option (81), RFC4702 */
1074			*p++ = DHO_FQDN;
1075			lp = p;
1076			*p++ = 3;
1077			/*
1078			 * Flags: 0000NEOS
1079			 * S: 1 => Client requests Server to update
1080			 *         a RR in DNS as well as PTR
1081			 * O: 1 => Server indicates to client that
1082			 *         DNS has been updated
1083			 * E: 1 => Name data is DNS format
1084			 * N: 1 => Client requests Server to not
1085			 *         update DNS
1086			 */
1087			*p++ = (ifo->fqdn & 0x09) | 0x04;
1088			*p++ = 0; /* from server for PTR RR */
1089			*p++ = 0; /* from server for A RR if S=1 */
1090			ul = encode_rfc1035(ifo->hostname, p);
1091			*lp += ul;
1092			p += ul;
1093		}
1094
1095		/* vendor is already encoded correctly, so just add it */
1096		if (ifo->vendor[0]) {
1097			*p++ = DHO_VENDOR;
1098			memcpy(p, ifo->vendor, ifo->vendor[0] + 1);
1099			p += ifo->vendor[0] + 1;
1100		}
1101
1102		*p++ = DHO_PARAMETERREQUESTLIST;
1103		n_params = p;
1104		*p++ = 0;
1105		for (opt = dhcp_opts; opt->option; opt++) {
1106			if (!(opt->type & REQUEST ||
1107				has_option_mask(ifo->requestmask, opt->option)))
1108				continue;
1109			if (type == DHCP_INFORM &&
1110			    (opt->option == DHO_RENEWALTIME ||
1111				opt->option == DHO_REBINDTIME))
1112				continue;
1113			*p++ = opt->option;
1114		}
1115		*n_params = p - n_params - 1;
1116	}
1117	*p++ = DHO_END;
1118
1119#ifdef BOOTP_MESSAGE_LENTH_MIN
1120	/* Some crappy DHCP servers think they have to obey the BOOTP minimum
1121	 * message length.
1122	 * They are wrong, but we should still cater for them. */
1123	while (p - m < BOOTP_MESSAGE_LENTH_MIN)
1124		*p++ = DHO_PAD;
1125#endif
1126
1127	*message = dhcp;
1128	return p - m;
1129}
1130
1131ssize_t
1132write_lease(const struct interface *iface, const struct dhcp_message *dhcp)
1133{
1134	int fd;
1135	ssize_t bytes = sizeof(*dhcp);
1136	const uint8_t *p = dhcp->options;
1137	const uint8_t *e = p + sizeof(dhcp->options);
1138	uint8_t l;
1139	uint8_t o = 0;
1140
1141	/* We don't write BOOTP leases */
1142	if (is_bootp(dhcp)) {
1143		unlink(iface->leasefile);
1144		return 0;
1145	}
1146
1147	syslog(LOG_DEBUG, "%s: writing lease `%s'",
1148	    iface->name, iface->leasefile);
1149
1150	fd = open(iface->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0444);
1151#ifdef ANDROID
1152	if (fd == -1 && errno == EACCES) {
1153		/* the lease file might have been created when dhcpcd was running as root */
1154		unlink(iface->leasefile);
1155		fd = open(iface->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0444);
1156	}
1157#endif
1158	if (fd == -1) {
1159		syslog(LOG_ERR, "%s: open: %m", iface->name);
1160		return -1;
1161	}
1162
1163	/* Only write as much as we need */
1164	while (p < e) {
1165		o = *p;
1166		if (o == DHO_END) {
1167			bytes = p - (const uint8_t *)dhcp;
1168			break;
1169		}
1170		p++;
1171		if (o != DHO_PAD) {
1172			l = *p++;
1173			p += l;
1174		}
1175	}
1176	bytes = write(fd, dhcp, bytes);
1177	close(fd);
1178	return bytes;
1179}
1180
1181struct dhcp_message *
1182read_lease(const struct interface *iface)
1183{
1184	int fd;
1185	struct dhcp_message *dhcp;
1186	ssize_t bytes;
1187
1188	fd = open(iface->leasefile, O_RDONLY);
1189	if (fd == -1) {
1190		if (errno != ENOENT)
1191			syslog(LOG_ERR, "%s: open `%s': %m",
1192			    iface->name, iface->leasefile);
1193		return NULL;
1194	}
1195	syslog(LOG_DEBUG, "%s: reading lease `%s'",
1196	    iface->name, iface->leasefile);
1197	dhcp = xmalloc(sizeof(*dhcp));
1198	memset(dhcp, 0, sizeof(*dhcp));
1199	bytes = read(fd, dhcp, sizeof(*dhcp));
1200	close(fd);
1201	if (bytes < 0) {
1202		free(dhcp);
1203		dhcp = NULL;
1204	}
1205	return dhcp;
1206}
1207
1208static ssize_t
1209print_string(char *s, ssize_t len, int dl, const uint8_t *data)
1210{
1211	uint8_t c;
1212	const uint8_t *e, *p;
1213	ssize_t bytes = 0;
1214	ssize_t r;
1215
1216	e = data + dl;
1217	while (data < e) {
1218		c = *data++;
1219		if (c == '\0') {
1220			/* If rest is all NULL, skip it. */
1221			for (p = data; p < e; p++)
1222				if (*p != '\0')
1223					break;
1224			if (p == e)
1225				break;
1226		}
1227		if (!isascii(c) || !isprint(c)) {
1228			if (s) {
1229				if (len < 5) {
1230					errno = ENOBUFS;
1231					return -1;
1232				}
1233				r = snprintf(s, len, "\\%03o", c);
1234				len -= r;
1235				bytes += r;
1236				s += r;
1237			} else
1238				bytes += 4;
1239			continue;
1240		}
1241		switch (c) {
1242		case '"':  /* FALLTHROUGH */
1243		case '\'': /* FALLTHROUGH */
1244		case '$':  /* FALLTHROUGH */
1245		case '`':  /* FALLTHROUGH */
1246 		case '\\': /* FALLTHROUGH */
1247		case '|':  /* FALLTHROUGH */
1248		case '&':
1249			if (s) {
1250				if (len < 3) {
1251					errno = ENOBUFS;
1252					return -1;
1253				}
1254				*s++ = '\\';
1255				len--;
1256			}
1257			bytes++;
1258			break;
1259		}
1260		if (s) {
1261			*s++ = c;
1262			len--;
1263		}
1264		bytes++;
1265	}
1266
1267	/* NULL */
1268	if (s)
1269		*s = '\0';
1270	bytes++;
1271	return bytes;
1272}
1273
1274static ssize_t
1275print_option(char *s, ssize_t len, int type, int dl, const uint8_t *data)
1276{
1277	const uint8_t *e, *t;
1278	uint16_t u16;
1279	int16_t s16;
1280	uint32_t u32;
1281	int32_t s32;
1282	struct in_addr addr;
1283	ssize_t bytes = 0;
1284	ssize_t l;
1285	char *tmp;
1286
1287	if (type & RFC3397) {
1288		l = decode_rfc3397(NULL, 0, dl, data);
1289		if (l < 1)
1290			return l;
1291		tmp = xmalloc(l);
1292		decode_rfc3397(tmp, l, dl, data);
1293		l = print_string(s, len, l - 1, (uint8_t *)tmp);
1294		free(tmp);
1295		return l;
1296	}
1297
1298	if (type & RFC3361) {
1299		if ((tmp = decode_rfc3361(dl, data)) == NULL)
1300			return -1;
1301		l = strlen(tmp);
1302		l = print_string(s, len, l - 1, (uint8_t *)tmp);
1303		free(tmp);
1304		return l;
1305	}
1306
1307	if (type & RFC3442)
1308		return decode_rfc3442(s, len, dl, data);
1309
1310	if (type & RFC5969)
1311		return decode_rfc5969(s, len, dl, data);
1312
1313	if (type & STRING) {
1314		/* Some DHCP servers return NULL strings */
1315		if (*data == '\0')
1316			return 0;
1317		return print_string(s, len, dl, data);
1318	}
1319
1320	if (!s) {
1321		if (type & UINT8)
1322			l = 3;
1323		else if (type & UINT16) {
1324			l = 5;
1325			dl /= 2;
1326		} else if (type & SINT16) {
1327			l = 6;
1328			dl /= 2;
1329		} else if (type & UINT32) {
1330			l = 10;
1331			dl /= 4;
1332		} else if (type & SINT32) {
1333			l = 11;
1334			dl /= 4;
1335		} else if (type & IPV4) {
1336			l = 16;
1337			dl /= 4;
1338		} else {
1339			errno = EINVAL;
1340			return -1;
1341		}
1342		return (l + 1) * dl;
1343	}
1344
1345	t = data;
1346	e = data + dl;
1347	while (data < e) {
1348		if (data != t) {
1349			*s++ = ' ';
1350			bytes++;
1351			len--;
1352		}
1353		if (type & UINT8) {
1354			l = snprintf(s, len, "%d", *data);
1355			data++;
1356		} else if (type & UINT16) {
1357			memcpy(&u16, data, sizeof(u16));
1358			u16 = ntohs(u16);
1359			l = snprintf(s, len, "%d", u16);
1360			data += sizeof(u16);
1361		} else if (type & SINT16) {
1362			memcpy(&s16, data, sizeof(s16));
1363			s16 = ntohs(s16);
1364			l = snprintf(s, len, "%d", s16);
1365			data += sizeof(s16);
1366		} else if (type & UINT32) {
1367			memcpy(&u32, data, sizeof(u32));
1368			u32 = ntohl(u32);
1369			l = snprintf(s, len, "%d", u32);
1370			data += sizeof(u32);
1371		} else if (type & SINT32) {
1372			memcpy(&s32, data, sizeof(s32));
1373			s32 = ntohl(s32);
1374			l = snprintf(s, len, "%d", s32);
1375			data += sizeof(s32);
1376		} else if (type & IPV4) {
1377			memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
1378			l = snprintf(s, len, "%s", inet_ntoa(addr));
1379			data += sizeof(addr.s_addr);
1380		} else
1381			l = 0;
1382		if (len <= l) {
1383			bytes += len;
1384			break;
1385		}
1386		len -= l;
1387		bytes += l;
1388		s += l;
1389	}
1390
1391	return bytes;
1392}
1393
1394ssize_t
1395configure_env(char **env, const char *prefix, const struct dhcp_message *dhcp,
1396    const struct if_options *ifo)
1397{
1398	const uint8_t *p;
1399	int pl;
1400	struct in_addr addr;
1401	struct in_addr net;
1402	struct in_addr brd;
1403	char *val, *v;
1404	const struct dhcp_opt *opt;
1405	ssize_t len, e = 0;
1406	char **ep;
1407	char cidr[4];
1408	uint8_t overl = 0;
1409
1410	get_option_uint8(&overl, dhcp, DHO_OPTIONSOVERLOADED);
1411
1412	if (!env) {
1413		for (opt = dhcp_opts; opt->option; opt++) {
1414			if (!opt->var)
1415				continue;
1416			if (has_option_mask(ifo->nomask, opt->option))
1417				continue;
1418			if (get_option_raw(dhcp, opt->option))
1419				e++;
1420		}
1421		if (dhcp->yiaddr || dhcp->ciaddr)
1422			e += 5;
1423		if (*dhcp->bootfile && !(overl & 1))
1424			e++;
1425		if (*dhcp->servername && !(overl & 2))
1426			e++;
1427		return e;
1428	}
1429
1430	ep = env;
1431	if (dhcp->yiaddr || dhcp->ciaddr) {
1432		/* Set some useful variables that we derive from the DHCP
1433		 * message but are not necessarily in the options */
1434		addr.s_addr = dhcp->yiaddr ? dhcp->yiaddr : dhcp->ciaddr;
1435		setvar(&ep, prefix, "ip_address", inet_ntoa(addr));
1436		if (get_option_addr(&net, dhcp, DHO_SUBNETMASK) == -1) {
1437			net.s_addr = get_netmask(addr.s_addr);
1438			setvar(&ep, prefix, "subnet_mask", inet_ntoa(net));
1439		}
1440		snprintf(cidr, sizeof(cidr), "%d", inet_ntocidr(net));
1441		setvar(&ep, prefix, "subnet_cidr", cidr);
1442		if (get_option_addr(&brd, dhcp, DHO_BROADCAST) == -1) {
1443			brd.s_addr = addr.s_addr | ~net.s_addr;
1444			setvar(&ep, prefix, "broadcast_address", inet_ntoa(brd));
1445		}
1446		addr.s_addr = dhcp->yiaddr & net.s_addr;
1447		setvar(&ep, prefix, "network_number", inet_ntoa(addr));
1448	}
1449
1450	if (*dhcp->bootfile && !(overl & 1))
1451		setvar(&ep, prefix, "filename", (const char *)dhcp->bootfile);
1452	if (*dhcp->servername && !(overl & 2))
1453		setvar(&ep, prefix, "server_name", (const char *)dhcp->servername);
1454
1455	for (opt = dhcp_opts; opt->option; opt++) {
1456		if (!opt->var)
1457			continue;
1458		if (has_option_mask(ifo->nomask, opt->option))
1459			continue;
1460		val = NULL;
1461		p = get_option(dhcp, opt->option, &pl, NULL);
1462		if (!p)
1463			continue;
1464		/* We only want the FQDN name */
1465		if (opt->option == DHO_FQDN) {
1466			p += 3;
1467			pl -= 3;
1468		}
1469		len = print_option(NULL, 0, opt->type, pl, p);
1470		if (len < 0)
1471			return -1;
1472		e = strlen(prefix) + strlen(opt->var) + len + 4;
1473		v = val = *ep++ = xmalloc(e);
1474		v += snprintf(val, e, "%s_%s=", prefix, opt->var);
1475		if (len != 0)
1476			print_option(v, len, opt->type, pl, p);
1477	}
1478
1479	return ep - env;
1480}
1481
1482void
1483get_lease(struct dhcp_lease *lease, const struct dhcp_message *dhcp)
1484{
1485	struct timeval now;
1486
1487	lease->cookie = dhcp->cookie;
1488	/* BOOTP does not set yiaddr for replies when ciaddr is set. */
1489	if (dhcp->yiaddr)
1490		lease->addr.s_addr = dhcp->yiaddr;
1491	else
1492		lease->addr.s_addr = dhcp->ciaddr;
1493	if (get_option_addr(&lease->net, dhcp, DHO_SUBNETMASK) == -1)
1494		lease->net.s_addr = get_netmask(lease->addr.s_addr);
1495	if (get_option_addr(&lease->brd, dhcp, DHO_BROADCAST) == -1)
1496		lease->brd.s_addr = lease->addr.s_addr | ~lease->net.s_addr;
1497	if (get_option_uint32(&lease->leasetime, dhcp, DHO_LEASETIME) == 0) {
1498		/* Ensure that we can use the lease */
1499		get_monotonic(&now);
1500		if (now.tv_sec + (time_t)lease->leasetime < now.tv_sec)
1501			lease->leasetime = ~0U; /* Infinite lease */
1502	} else
1503		lease->leasetime = ~0U; /* Default to infinite lease */
1504	if (get_option_uint32(&lease->renewaltime, dhcp, DHO_RENEWALTIME) != 0)
1505		lease->renewaltime = 0;
1506	if (get_option_uint32(&lease->rebindtime, dhcp, DHO_REBINDTIME) != 0)
1507		lease->rebindtime = 0;
1508	if (get_option_addr(&lease->server, dhcp, DHO_SERVERID) != 0)
1509		lease->server.s_addr = INADDR_ANY;
1510}
1511