• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * dhcpcd - DHCP client daemon
3  * Copyright 2006-2008 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 <sys/stat.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <arpa/inet.h>
32 
33 #ifdef __linux__
34 # include <netinet/ether.h>
35 #endif
36 
37 #include <errno.h>
38 #include <poll.h>
39 #include <signal.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <time.h>
44 #include <unistd.h>
45 
46 #include "config.h"
47 #include "common.h"
48 #include "client.h"
49 #include "configure.h"
50 #include "dhcp.h"
51 #include "dhcpcd.h"
52 #include "net.h"
53 #include "logger.h"
54 #include "signals.h"
55 
56 #define IPV4LL_LEASETIME 	2
57 
58 /* Some platforms don't define INFTIM */
59 #ifndef INFTIM
60 # define INFTIM                 -1
61 #endif
62 
63 #define STATE_INIT              0
64 #define STATE_DISCOVERING	1
65 #define STATE_REQUESTING        2
66 #define STATE_BOUND             3
67 #define STATE_RENEWING          4
68 #define STATE_REBINDING         5
69 #define STATE_REBOOT            6
70 #define STATE_RENEW_REQUESTED   7
71 #define STATE_INIT_IPV4LL	8
72 #define STATE_PROBING		9
73 #define STATE_ANNOUNCING	10
74 
75 /* Constants taken from RFC 2131. */
76 #define T1			0.5
77 #define T2			0.875
78 #define DHCP_BASE		4
79 #define DHCP_MAX		64
80 #define DHCP_RAND_MIN		-1
81 #define DHCP_RAND_MAX		1
82 #define DHCP_ARP_FAIL		10
83 
84 /* We should define a maximum for the NAK exponential backoff */
85 #define NAKOFF_MAX              60
86 
87 #define SOCKET_CLOSED           0
88 #define SOCKET_OPEN             1
89 
90 /* These are for IPV4LL, RFC 3927. */
91 #define PROBE_WAIT		 1
92 #define PROBE_NUM		 3
93 #define PROBE_MIN		 1
94 #define PROBE_MAX		 2
95 #define ANNOUNCE_WAIT		 2
96 /* BSD systems always do a grauitous ARP when assigning an address,
97  * so we can do one less announce. */
98 #ifdef BSD
99 # define ANNOUNCE_NUM		 1
100 #else
101 # define ANNOUNCE_NUM		 2
102 #endif
103 #define ANNOUNCE_INTERVAL	 2
104 #define MAX_CONFLICTS		10
105 #define RATE_LIMIT_INTERVAL	60
106 #define DEFEND_INTERVAL		10
107 
108 
109 /* number of usecs in a second. */
110 #define USECS_SECOND		1000000
111 /* As we use timevals, we should use the usec part for
112  * greater randomisation. */
113 #define DHCP_RAND_MIN_U		DHCP_RAND_MIN * USECS_SECOND
114 #define DHCP_RAND_MAX_U		DHCP_RAND_MAX * USECS_SECOND
115 #define PROBE_MIN_U		PROBE_MIN * USECS_SECOND
116 #define PROBE_MAX_U		PROBE_MAX * USECS_SECOND
117 
118 #define timernorm(tvp)						\
119 	do {							\
120 		while ((tvp)->tv_usec >= 1000000) {		\
121 			(tvp)->tv_sec++;			\
122 			(tvp)->tv_usec -= 1000000;		\
123 		}						\
124 	} while (0 /* CONSTCOND */);
125 
126 #define timerneg(tvp)	((tvp)->tv_sec < 0 || (tvp)->tv_usec < 0)
127 
128 struct if_state {
129 	int options;
130 	struct interface *interface;
131 	struct dhcp_message *offer;
132 	struct dhcp_message *new;
133 	struct dhcp_message *old;
134 	struct dhcp_lease lease;
135 	struct timeval timeout;
136 	struct timeval stop;
137 	struct timeval exit;
138 	int state;
139 	int messages;
140 	time_t nakoff;
141 	uint32_t xid;
142 	int socket;
143 	int *pid_fd;
144 	int signal_fd;
145 	int carrier;
146 	int probes;
147 	int claims;
148 	int conflicts;
149 	time_t defend;
150 	struct in_addr fail;
151 };
152 
153 #define LINK_UP 	1
154 #define LINK_UNKNOWN	0
155 #define LINK_DOWN 	-1
156 
157 struct dhcp_op {
158         uint8_t value;
159         const char *name;
160 };
161 
162 static const struct dhcp_op const dhcp_ops[] = {
163 	{ DHCP_DISCOVER, "DHCP_DISCOVER" },
164 	{ DHCP_OFFER,    "DHCP_OFFER" },
165 	{ DHCP_REQUEST,  "DHCP_REQUEST" },
166 	{ DHCP_DECLINE,  "DHCP_DECLINE" },
167 	{ DHCP_ACK,      "DHCP_ACK" },
168 	{ DHCP_NAK,      "DHCP_NAK" },
169 	{ DHCP_RELEASE,  "DHCP_RELEASE" },
170 	{ DHCP_INFORM,   "DHCP_INFORM" },
171 	{ 0, NULL }
172 };
173 
174 static const char *
get_dhcp_op(uint8_t type)175 get_dhcp_op(uint8_t type)
176 {
177 	const struct dhcp_op *d;
178 
179 	for (d = dhcp_ops; d->name; d++)
180 		if (d->value == type)
181 			return d->name;
182 	return NULL;
183 }
184 
185 #ifdef THERE_IS_NO_FORK
186 #define daemonise(a,b) 0
187 #else
188 static int
daemonise(struct if_state * state,const struct options * options)189 daemonise(struct if_state *state, const struct options *options)
190 {
191 	pid_t pid;
192 	sigset_t full;
193 	sigset_t old;
194 	char buf = '\0';
195 	int sidpipe[2];
196 
197 	if (state->options & DHCPCD_DAEMONISED ||
198 	    !(options->options & DHCPCD_DAEMONISE))
199 		return 0;
200 
201 	sigfillset(&full);
202 	sigprocmask(SIG_SETMASK, &full, &old);
203 
204 	/* Setup a signal pipe so parent knows when to exit. */
205 	if (pipe(sidpipe) == -1) {
206 		logger(LOG_ERR,"pipe: %s", strerror(errno));
207 		return -1;
208 	}
209 
210 	logger(LOG_DEBUG, "forking to background");
211 	switch (pid = fork()) {
212 		case -1:
213 			logger(LOG_ERR, "fork: %s", strerror(errno));
214 			exit(EXIT_FAILURE);
215 			/* NOTREACHED */
216 		case 0:
217 			setsid();
218 			/* Notify parent it's safe to exit as we've detached. */
219 			close(sidpipe[0]);
220 			write(sidpipe[1], &buf, 1);
221 			close(sidpipe[1]);
222 			close_fds();
223 			break;
224 		default:
225 			/* Reset signals as we're the parent about to exit. */
226 			signal_reset();
227 			/* Wait for child to detach */
228 			close(sidpipe[1]);
229 			read(sidpipe[0], &buf, 1);
230 			close(sidpipe[0]);
231 			break;
232 	}
233 
234 	/* Done with the fd now */
235 	if (pid != 0) {
236 		writepid(*state->pid_fd, pid);
237 		close(*state->pid_fd);
238 		*state->pid_fd = -1;
239 	}
240 
241 	sigprocmask(SIG_SETMASK, &old, NULL);
242 	if (pid == 0) {
243 		state->options |= DHCPCD_DAEMONISED;
244 		timerclear(&state->exit);
245 		return 0;
246 	}
247 	state->options |= DHCPCD_PERSISTENT | DHCPCD_FORKED;
248 	return -1;
249 }
250 #endif
251 
252 #define THIRTY_YEARS_IN_SECONDS    946707779
253 static size_t
get_duid(unsigned char * duid,const struct interface * iface)254 get_duid(unsigned char *duid, const struct interface *iface)
255 {
256 	FILE *f;
257 	uint16_t type = 0;
258 	uint16_t hw = 0;
259 	uint32_t ul;
260 	time_t t;
261 	int x = 0;
262 	unsigned char *p = duid;
263 	size_t len = 0, l = 0;
264 	char *buffer = NULL, *line, *option;
265 
266 	/* If we already have a DUID then use it as it's never supposed
267 	 * to change once we have one even if the interfaces do */
268 	if ((f = fopen(DUID, "r"))) {
269 		while ((get_line(&buffer, &len, f))) {
270 			line = buffer;
271 			while ((option = strsep(&line, " \t")))
272 				if (*option != '\0')
273 					break;
274 			if (!option || *option == '\0' || *option == '#')
275 				continue;
276 			l = hwaddr_aton(NULL, option);
277 			if (l && l <= DUID_LEN) {
278 				hwaddr_aton(duid, option);
279 				break;
280 			}
281 			l = 0;
282 		}
283 		fclose(f);
284 		free(buffer);
285 		if (l)
286 			return l;
287 	} else {
288 		if (errno != ENOENT)
289 			return 0;
290 	}
291 
292 	/* No file? OK, lets make one based on our interface */
293 	if (!(f = fopen(DUID, "w")))
294 		return 0;
295 	type = htons(1); /* DUI-D-LLT */
296 	memcpy(p, &type, 2);
297 	p += 2;
298 	hw = htons(iface->family);
299 	memcpy(p, &hw, 2);
300 	p += 2;
301 	/* time returns seconds from jan 1 1970, but DUID-LLT is
302 	 * seconds from jan 1 2000 modulo 2^32 */
303 	t = time(NULL) - THIRTY_YEARS_IN_SECONDS;
304 	ul = htonl(t & 0xffffffff);
305 	memcpy(p, &ul, 4);
306 	p += 4;
307 	/* Finally, add the MAC address of the interface */
308 	memcpy(p, iface->hwaddr, iface->hwlen);
309 	p += iface->hwlen;
310 	len = p - duid;
311 	x = fprintf(f, "%s\n", hwaddr_ntoa(duid, len));
312 	fclose(f);
313 	/* Failed to write the duid? scrub it, we cannot use it */
314 	if (x < 1) {
315 		len = 0;
316 		unlink(DUID);
317 	}
318 	return len;
319 }
320 
321 static struct dhcp_message*
ipv4ll_get_dhcp(uint32_t old_addr)322 ipv4ll_get_dhcp(uint32_t old_addr)
323 {
324 	uint32_t u32;
325 	struct dhcp_message *dhcp;
326 	uint8_t *p;
327 
328 	dhcp = xzalloc(sizeof(*dhcp));
329 	/* Put some LL options in */
330 	p = dhcp->options;
331 	*p++ = DHO_SUBNETMASK;
332 	*p++ = sizeof(u32);
333 	u32 = htonl(LINKLOCAL_MASK);
334 	memcpy(p, &u32, sizeof(u32));
335 	p += sizeof(u32);
336 	*p++ = DHO_BROADCAST;
337 	*p++ = sizeof(u32);
338 	u32 = htonl(LINKLOCAL_BRDC);
339 	memcpy(p, &u32, sizeof(u32));
340 	p += sizeof(u32);
341 	*p++ = DHO_END;
342 
343 	for (;;) {
344 		dhcp->yiaddr = htonl(LINKLOCAL_ADDR |
345 				     (((uint32_t)abs((int)arc4random())
346 				       % 0xFD00) + 0x0100));
347 		if (dhcp->yiaddr != old_addr &&
348 		    IN_LINKLOCAL(ntohl(dhcp->yiaddr)))
349 			break;
350 	}
351 	return dhcp;
352 }
353 
354 static double
timeval_to_double(struct timeval * tv)355 timeval_to_double(struct timeval *tv)
356 {
357 	return tv->tv_sec * 1.0 + tv->tv_usec * 1.0e-6;
358 }
359 
360 static void
get_lease(struct dhcp_lease * lease,const struct dhcp_message * dhcp)361 get_lease(struct dhcp_lease *lease, const struct dhcp_message *dhcp)
362 {
363 	time_t t;
364 
365 	lease->frominfo = 0;
366 	lease->addr.s_addr = dhcp->yiaddr;
367 
368 	if (get_option_addr(&lease->net.s_addr, dhcp, DHO_SUBNETMASK) == -1)
369 		lease->net.s_addr = get_netmask(dhcp->yiaddr);
370 	if (get_option_uint32(&lease->leasetime, dhcp, DHO_LEASETIME) == 0) {
371 		/* Ensure that we can use the lease */
372 		t = 0;
373 		if (t + (time_t)lease->leasetime < t) {
374 			logger(LOG_WARNING, "lease of %u would overflow, "
375 			       "treating as infinite", lease->leasetime);
376 			lease->leasetime = ~0U; /* Infinite lease */
377 		}
378 	} else
379 		lease->leasetime = DEFAULT_LEASETIME;
380 	if (get_option_uint32(&lease->renewaltime, dhcp, DHO_RENEWALTIME) != 0)
381 		lease->renewaltime = 0;
382 	if (get_option_uint32(&lease->rebindtime, dhcp, DHO_REBINDTIME) != 0)
383 		lease->rebindtime = 0;
384 }
385 
386 static int
get_old_lease(struct if_state * state)387 get_old_lease(struct if_state *state)
388 {
389 	struct interface *iface = state->interface;
390 	struct dhcp_lease *lease = &state->lease;
391 	struct dhcp_message *dhcp = NULL;
392 	struct timeval tv;
393 	unsigned int offset = 0;
394 	struct stat sb;
395 
396 	if (stat(iface->leasefile, &sb) == -1) {
397 		if (errno != ENOENT)
398 			logger(LOG_ERR, "stat: %s", strerror(errno));
399 		goto eexit;
400 	}
401 	if (!IN_LINKLOCAL(ntohl(iface->addr.s_addr)))
402 		logger(LOG_INFO, "trying to use old lease in `%s'",
403 		       iface->leasefile);
404 	if ((dhcp = read_lease(iface)) == NULL) {
405 		logger(LOG_INFO, "read_lease: %s", strerror(errno));
406 		goto eexit;
407 	}
408 	get_lease(&state->lease, dhcp);
409 	lease->frominfo = 1;
410 	lease->leasedfrom = sb.st_mtime;
411 
412 	/* Vitaly important we remove the server information here */
413 	state->lease.server.s_addr = 0;
414 	dhcp->servername[0] = '\0';
415 
416 	if (!IN_LINKLOCAL(ntohl(dhcp->yiaddr))) {
417 		if (!(state->options & DHCPCD_LASTLEASE))
418 			goto eexit;
419 
420 		/* Ensure that we can still use the lease */
421 		if (gettimeofday(&tv, NULL) == -1) {
422 			logger(LOG_ERR, "gettimeofday: %s", strerror(errno));
423 			goto eexit;
424 		}
425 
426 		offset = tv.tv_sec - lease->leasedfrom;
427 		if (lease->leasedfrom &&
428 		    tv.tv_sec - lease->leasedfrom > (time_t)lease->leasetime)
429 		{
430 			logger(LOG_ERR, "lease expired %u seconds ago",
431 			       offset + lease->leasetime);
432 			/* Persistent interfaces should still try and use the
433 			 * lease if we can't contact a DHCP server.
434 			 * We just set the timeout to 1 second. */
435 			if (state->options & DHCPCD_PERSISTENT)
436 				offset = lease->renewaltime - 1;
437 			else
438 				goto eexit;
439 		}
440 	}
441 
442 	if (lease->leasedfrom == 0)
443 		offset = 0;
444 	iface->start_uptime = uptime();
445 	state->timeout.tv_sec = lease->renewaltime - offset;
446 	free(state->old);
447 	state->old = state->new;
448 	state->new = NULL;
449 	state->offer = dhcp;
450 	return 0;
451 
452 eexit:
453 	lease->addr.s_addr = 0;
454 	free(dhcp);
455 	return -1;
456 }
457 
458 static int
client_setup(struct if_state * state,const struct options * options)459 client_setup(struct if_state *state, const struct options *options)
460 {
461 	struct interface *iface = state->interface;
462 	struct dhcp_lease *lease = &state->lease;
463 	struct in_addr addr;
464 	struct timeval tv;
465 	size_t len = 0;
466 	unsigned char *duid = NULL;
467 	uint32_t ul;
468 
469 	state->state = STATE_INIT;
470 	state->nakoff = 1;
471 	state->options = options->options;
472 	timerclear(&tv);
473 
474 	if (options->request_address.s_addr == 0 &&
475 	    (options->options & DHCPCD_INFORM ||
476 	     options->options & DHCPCD_REQUEST ||
477 	     (options->options & DHCPCD_DAEMONISED &&
478 	      !(options->options & DHCPCD_BACKGROUND))))
479 	{
480 		if (get_old_lease(state) != 0)
481 			return -1;
482 		timerclear(&state->timeout);
483 
484 		if (!(options->options & DHCPCD_DAEMONISED) &&
485 		    IN_LINKLOCAL(ntohl(lease->addr.s_addr)))
486 		{
487 			logger(LOG_ERR, "cannot request a link local address");
488 			return -1;
489 		}
490 	} else {
491 		lease->addr.s_addr = options->request_address.s_addr;
492 		lease->net.s_addr = options->request_netmask.s_addr;
493 	}
494 
495 	if (options->options & DHCPCD_REQUEST &&
496 	    state->options & DHCPCD_ARP &&
497 	    !state->offer)
498 	{
499 		state->offer = xzalloc(sizeof(*state->offer));
500 		state->offer->yiaddr = options->request_address.s_addr;
501 		state->state = STATE_PROBING;
502 		state->xid = arc4random();
503 	}
504 
505 	/* If INFORMing, ensure the interface has the address */
506 	if (state->options & DHCPCD_INFORM &&
507 	    has_address(iface->name, &lease->addr, &lease->net) < 1)
508 	{
509 		addr.s_addr = lease->addr.s_addr | ~lease->net.s_addr;
510 		logger(LOG_DEBUG, "adding IP address %s/%d",
511 		       inet_ntoa(lease->addr), inet_ntocidr(lease->net));
512 		if (add_address(iface->name, &lease->addr,
513 				&lease->net, &addr) == -1)
514 		{
515 			logger(LOG_ERR, "add_address: %s", strerror(errno));
516 			return -1;
517 		}
518 		iface->addr.s_addr = lease->addr.s_addr;
519 		iface->net.s_addr = lease->net.s_addr;
520 	}
521 
522 	if (*options->clientid) {
523 		iface->clientid = xmalloc(options->clientid[0] + 1);
524 		memcpy(iface->clientid,
525 		       options->clientid, options->clientid[0] + 1);
526 	} else if (options->options & DHCPCD_CLIENTID) {
527 		if (options->options & DHCPCD_DUID) {
528 			duid = xmalloc(DUID_LEN);
529 			if ((len = get_duid(duid, iface)) == 0)
530 				logger(LOG_ERR, "get_duid: %s",
531 				       strerror(errno));
532 		}
533 
534 		if (len > 0) {
535 			logger(LOG_DEBUG, "DUID = %s",
536 			       hwaddr_ntoa(duid, len));
537 
538 			iface->clientid = xmalloc(len + 6);
539 			iface->clientid[0] = len + 5;
540 			iface->clientid[1] = 255; /* RFC 4361 */
541 
542 			/* IAID is 4 bytes, so if the iface name is 4 bytes
543 			 * or less, use it */
544 			ul = strlen(iface->name);
545 			if (ul < 5) {
546 				memcpy(iface->clientid + 2, iface->name, ul);
547 				if (ul < 4)
548 					memset(iface->clientid + 2 + ul,
549 					       0, 4 - ul);
550 			} else {
551 				/* Name isn't 4 bytes, so use the index */
552 				ul = htonl(if_nametoindex(iface->name));
553 				memcpy(iface->clientid + 2, &ul, 4);
554 			}
555 
556 			memcpy(iface->clientid + 6, duid, len);
557 			free(duid);
558 		}
559 		if (len == 0) {
560 			len = iface->hwlen + 1;
561 			iface->clientid = xmalloc(len + 1);
562 			iface->clientid[0] = len;
563 			iface->clientid[1] = iface->family;
564 			memcpy(iface->clientid + 2, iface->hwaddr, iface->hwlen);
565 		}
566 	}
567 
568 	if (state->options & DHCPCD_LINK) {
569 		open_link_socket(iface);
570 		switch (carrier_status(iface->name)) {
571 		case 0:
572 			state->carrier = LINK_DOWN;
573 			break;
574 		case 1:
575 			state->carrier = LINK_UP;
576 			break;
577 		default:
578 			state->carrier = LINK_UNKNOWN;
579 		}
580 	}
581 
582 	if (options->timeout > 0 &&
583 	    !(state->options & DHCPCD_DAEMONISED))
584 	{
585 		if (state->options & DHCPCD_IPV4LL) {
586 			state->stop.tv_sec = options->timeout;
587 			if (!(state->options & DHCPCD_BACKGROUND))
588 				state->exit.tv_sec = state->stop.tv_sec + 10;
589 		} else if (!(state->options & DHCPCD_BACKGROUND))
590 			state->exit.tv_sec = options->timeout;
591 	}
592 	return 0;
593 }
594 
595 static int
do_socket(struct if_state * state,int mode)596 do_socket(struct if_state *state, int mode)
597 {
598 	if (state->interface->raw_fd != -1) {
599 		close(state->interface->raw_fd);
600 		state->interface->raw_fd = -1;
601 	}
602 	if (mode == SOCKET_CLOSED) {
603 		if (state->interface->udp_fd != -1) {
604 			close(state->interface->udp_fd);
605 			state->interface->udp_fd = -1;
606 		}
607 		if (state->interface->arp_fd != -1) {
608 			close(state->interface->arp_fd);
609 			state->interface->arp_fd = -1;
610 		}
611 	}
612 
613 	/* Always have the UDP socket open to avoid the kernel sending
614 	 * ICMP unreachable messages. */
615 	/* For systems without SO_BINDTODEVICE, (ie BSD ones) we may get an
616 	 * error or EADDRINUSE when binding to INADDR_ANY as another dhcpcd
617 	 * instance could be running.
618 	 * Oddly enough, we don't care about this as the socket is there
619 	 * just to please the kernel - we don't care for reading from it. */
620 	if (mode == SOCKET_OPEN &&
621 	    state->interface->udp_fd == -1 &&
622 	    open_udp_socket(state->interface) == -1 &&
623 	    (errno != EADDRINUSE || state->interface->addr.s_addr != 0))
624 		logger(LOG_ERR, "open_udp_socket: %s", strerror(errno));
625 
626 	if (mode == SOCKET_OPEN)
627 		if (open_socket(state->interface, ETHERTYPE_IP) == -1) {
628 			logger(LOG_ERR, "open_socket: %s", strerror(errno));
629 			return -1;
630 		}
631 	state->socket = mode;
632 	return 0;
633 }
634 
635 static ssize_t
send_message(struct if_state * state,int type,const struct options * options)636 send_message(struct if_state *state, int type, const struct options *options)
637 {
638 	struct dhcp_message *dhcp;
639 	uint8_t *udp;
640 	ssize_t len, r;
641 	struct in_addr from, to;
642 	in_addr_t a = 0;
643 
644 	if (state->carrier == LINK_DOWN)
645 		return 0;
646 	if (type == DHCP_RELEASE)
647 		logger(LOG_DEBUG, "sending %s with xid 0x%x",
648 		       get_dhcp_op(type), state->xid);
649 	else
650 		logger(LOG_DEBUG,
651 		       "sending %s with xid 0x%x, next in %0.2f seconds",
652 		       get_dhcp_op(type), state->xid,
653 		       timeval_to_double(&state->timeout));
654 	state->messages++;
655 	if (state->messages < 0)
656 		state->messages = INT_MAX;
657 	/* If we couldn't open a UDP port for our IP address
658 	 * then we cannot renew.
659 	 * This could happen if our IP was pulled out from underneath us. */
660 	if (state->interface->udp_fd == -1) {
661 		a = state->interface->addr.s_addr;
662 		state->interface->addr.s_addr = 0;
663 	}
664 	len = make_message(&dhcp, state->interface, &state->lease, state->xid,
665 			   type, options);
666 	if (state->interface->udp_fd == -1)
667 		state->interface->addr.s_addr = a;
668 	from.s_addr = dhcp->ciaddr;
669 	if (from.s_addr)
670 		to.s_addr = state->lease.server.s_addr;
671 	else
672 		to.s_addr = 0;
673 	if (to.s_addr && to.s_addr != INADDR_BROADCAST) {
674 		r = send_packet(state->interface, to, (uint8_t *)dhcp, len);
675 		if (r == -1)
676 			logger(LOG_ERR, "send_packet: %s", strerror(errno));
677 	} else {
678 		len = make_udp_packet(&udp, (uint8_t *)dhcp, len, from, to);
679 		r = send_raw_packet(state->interface, ETHERTYPE_IP, udp, len);
680 		free(udp);
681 		if (r == -1)
682 			logger(LOG_ERR, "send_raw_packet: %s", strerror(errno));
683 	}
684 	free(dhcp);
685 	/* Failed to send the packet? Return to the init state */
686 	if (r == -1) {
687 		state->state = STATE_INIT;
688 		timerclear(&state->timeout);
689 		timerclear(&state->stop);
690 		do_socket(state, SOCKET_CLOSED);
691 	}
692 	return r;
693 }
694 
695 static void
drop_config(struct if_state * state,const char * reason,const struct options * options)696 drop_config(struct if_state *state, const char *reason,
697 	    const struct options *options)
698 {
699 	if (state->new || strcmp(reason, "FAIL") == 0) {
700 		configure(state->interface, reason, NULL, state->new,
701 			  &state->lease, options, 0);
702 		free(state->old);
703 		state->old = NULL;
704 		free(state->new);
705 		state->new = NULL;
706 	}
707 	state->lease.addr.s_addr = 0;
708 }
709 
710 static void
reduce_timers(struct if_state * state,const struct timeval * tv)711 reduce_timers(struct if_state *state, const struct timeval *tv)
712 {
713 	if (timerisset(&state->exit)) {
714 		timersub(&state->exit, tv, &state->exit);
715 		if (!timerisset(&state->exit))
716 			state->exit.tv_sec = -1;
717 	}
718 	if (timerisset(&state->stop)) {
719 		timersub(&state->stop, tv, &state->stop);
720 		if (!timerisset(&state->stop))
721 			state->stop.tv_sec = -1;
722 	}
723 	if (timerisset(&state->timeout)) {
724 		timersub(&state->timeout, tv, &state->timeout);
725 		if (!timerisset(&state->timeout))
726 			state->timeout.tv_sec = -1;
727 	}
728 }
729 
730 static struct timeval *
get_lowest_timer(struct if_state * state)731 get_lowest_timer(struct if_state *state)
732 {
733 	struct timeval *ref = NULL;
734 
735 	if (timerisset(&state->exit))
736 		ref = &state->exit;
737 	if (timerisset(&state->stop)) {
738 		if (!ref || timercmp(&state->stop, ref, <))
739 			ref = &state->stop;
740 	}
741 	if (timerisset(&state->timeout)) {
742 		if (!ref || timercmp(&state->timeout, ref, <))
743 			ref = &state->timeout;
744 	}
745 	return ref;
746 }
747 
748 static int
wait_for_fd(struct if_state * state,int * fd)749 wait_for_fd(struct if_state *state, int *fd)
750 {
751 	struct pollfd fds[4]; /* signal, link, raw, arp */
752 	struct interface *iface = state->interface;
753 	int i, r, nfds = 0, msecs = -1;
754 	struct timeval start, stop, diff, *ref;
755 	static int lastinf = 0;
756 
757 	/* Ensure that we haven't already timed out */
758 	ref = get_lowest_timer(state);
759 	if (ref && timerneg(ref))
760 		return 0;
761 
762 	/* We always listen to signals */
763 	fds[nfds].fd = state->signal_fd;
764 	fds[nfds].events = POLLIN;
765 	nfds++;
766 	/* And links */
767 	if (iface->link_fd != -1) {
768 		fds[nfds].fd = iface->link_fd;
769 		fds[nfds].events = POLLIN;
770 		nfds++;
771 	}
772 
773 	if (state->lease.leasetime == ~0U &&
774 	    state->state == STATE_BOUND)
775 	{
776 		if (!lastinf) {
777 			logger(LOG_DEBUG, "waiting for infinity");
778 			lastinf = 1;
779 		}
780 		ref = NULL;
781 	} else if (state->carrier == LINK_DOWN && !ref) {
782 		if (!lastinf) {
783 			logger(LOG_DEBUG, "waiting for carrier");
784 			lastinf = 1;
785 		}
786 		if (timerisset(&state->exit))
787 			ref = &state->exit;
788 		else
789 			ref = NULL;
790 	} else {
791 		if (iface->raw_fd != -1) {
792 			fds[nfds].fd = iface->raw_fd;
793 			fds[nfds].events = POLLIN;
794 			nfds++;
795 		}
796 		if (iface->arp_fd != -1) {
797 			fds[nfds].fd = iface->arp_fd;
798 			fds[nfds].events = POLLIN;
799 			nfds++;
800 		}
801 	}
802 
803 	/* Wait and then reduce the timers.
804 	 * If we reduce a timer to zero, set it negative to indicate timeout.
805 	 * We cannot reliably use select as there is no guarantee we will
806 	 * actually wait the whole time if greater than 31 days according
807 	 * to POSIX. So we loop on poll if needed as it's limitation of
808 	 * INT_MAX milliseconds is known. */
809 	for (;;) {
810 		get_monotonic(&start);
811 		if (ref) {
812 			lastinf = 0;
813 			if (ref->tv_sec > INT_MAX / 1000 ||
814 			    (ref->tv_sec == INT_MAX / 1000 &&
815 			     (ref->tv_usec + 999) / 1000 > INT_MAX % 1000))
816 				msecs = INT_MAX;
817 			else
818 				msecs = ref->tv_sec * 1000 +
819 					(ref->tv_usec + 999) / 1000;
820 		} else
821 			msecs = -1;
822 		r = poll(fds, nfds, msecs);
823 		get_monotonic(&stop);
824 		timersub(&stop, &start, &diff);
825 		reduce_timers(state, &diff);
826 		if (r == -1) {
827 			if (errno != EINTR)
828 				logger(LOG_ERR, "poll: %s", strerror(errno));
829 			return -1;
830 		}
831 		if (r)
832 			break;
833 		/* We should not have an infinite timeout if we get here */
834 		if (timerneg(ref))
835 			return 0;
836 	}
837 
838 	/* We configured our array in the order we should deal with them */
839 	for (i = 0; i < nfds; i++)
840 		if (fds[i].revents & POLLIN) {
841 			*fd = fds[i].fd;
842 			return r;
843 		}
844 	return r;
845 }
846 
847 static int
handle_signal(int sig,struct if_state * state,const struct options * options)848 handle_signal(int sig, struct if_state *state,  const struct options *options)
849 {
850 	struct dhcp_lease *lease = &state->lease;
851 
852 	switch (sig) {
853 	case SIGINT:
854 		logger(LOG_INFO, "received SIGINT, stopping");
855 		if (!(state->options & DHCPCD_PERSISTENT))
856 			drop_config(state, "STOP", options);
857 		return -1;
858 	case SIGTERM:
859 		logger(LOG_INFO, "received SIGTERM, stopping");
860 		if (!(state->options & DHCPCD_PERSISTENT))
861 			drop_config(state, "STOP", options);
862 		return -1;
863 	case SIGALRM:
864 		logger(LOG_INFO, "received SIGALRM, renewing lease");
865 		do_socket(state, SOCKET_CLOSED);
866 		state->state = STATE_RENEW_REQUESTED;
867 		timerclear(&state->timeout);
868 		timerclear(&state->stop);
869 		return 1;
870 	case SIGHUP:
871 		logger(LOG_INFO, "received SIGHUP, releasing lease");
872 		if (lease->addr.s_addr &&
873 		    !IN_LINKLOCAL(ntohl(lease->addr.s_addr)))
874 		{
875 			do_socket(state, SOCKET_OPEN);
876 			state->xid = arc4random();
877 			send_message(state, DHCP_RELEASE, options);
878 			do_socket(state, SOCKET_CLOSED);
879 		}
880 		drop_config(state, "RELEASE", options);
881 		return -1;
882 	default:
883 		logger (LOG_ERR,
884 			"received signal %d, but don't know what to do with it",
885 			sig);
886 	}
887 
888 	return 0;
889 }
890 
bind_dhcp(struct if_state * state,const struct options * options)891 static int bind_dhcp(struct if_state *state, const struct options *options)
892 {
893 	struct interface *iface = state->interface;
894 	struct dhcp_lease *lease = &state->lease;
895 	const char *reason = NULL;
896 	struct timeval start, stop, diff;
897 	int retval;
898 
899 	free(state->old);
900 	state->old = state->new;
901 	state->new = state->offer;
902 	state->offer = NULL;
903 	state->messages = 0;
904 	state->conflicts = 0;
905 	state->defend = 0;
906 	timerclear(&state->exit);
907 	if (clock_monotonic)
908 		get_monotonic(&lease->boundtime);
909 
910 	if (options->options & DHCPCD_INFORM) {
911 		if (options->request_address.s_addr != 0)
912 			lease->addr.s_addr = options->request_address.s_addr;
913 		else
914 			lease->addr.s_addr = iface->addr.s_addr;
915 		logger(LOG_INFO, "received approval for %s",
916 		       inet_ntoa(lease->addr));
917 		state->state = STATE_BOUND;
918 		state->lease.leasetime = ~0U;
919 		timerclear(&state->stop);
920 		reason = "INFORM";
921 	} else if (IN_LINKLOCAL(htonl(state->new->yiaddr))) {
922 		get_lease(lease, state->new);
923 		logger(LOG_INFO, "using IPv4LL address %s",
924 		       inet_ntoa(lease->addr));
925 		state->state = STATE_INIT;
926 		timerclear(&state->timeout);
927 		reason = "IPV4LL";
928 	} else {
929 		if (gettimeofday(&start, NULL) == 0)
930 			lease->leasedfrom = start.tv_sec;
931 
932 		get_lease(lease, state->new);
933 		if (lease->frominfo)
934 			reason = "TIMEOUT";
935 
936 		if (lease->leasetime == ~0U) {
937 			lease->renewaltime = lease->rebindtime = lease->leasetime;
938 			logger(LOG_INFO, "leased %s for infinity",
939 			       inet_ntoa(lease->addr));
940 			state->state = STATE_BOUND;
941 			timerclear(&state->stop);
942 		} else {
943 			if (lease->rebindtime >= lease->leasetime) {
944 				lease->rebindtime = lease->leasetime * T2;
945 				logger(LOG_ERR,
946 				       "rebind time greater than lease "
947 				       "time, forcing to %u seconds",
948 				       lease->rebindtime);
949 			}
950 			if (lease->renewaltime > lease->rebindtime) {
951 				lease->renewaltime = lease->leasetime * T1;
952 				logger(LOG_ERR,
953 				       "renewal time greater than rebind time, "
954 				       "forcing to %u seconds",
955 				       lease->renewaltime);
956 			}
957 			if (!lease->renewaltime)
958 				lease->renewaltime = lease->leasetime * T1;
959 			if (!lease->rebindtime)
960 				lease->rebindtime = lease->leasetime * T2;
961 			logger(LOG_INFO,
962 			       "leased %s for %u seconds",
963 			       inet_ntoa(lease->addr), lease->leasetime);
964 			state->stop.tv_sec = lease->renewaltime;
965 			state->stop.tv_usec = 0;
966 		}
967 		state->state = STATE_BOUND;
968 	}
969 
970 	state->xid = 0;
971 	timerclear(&state->timeout);
972 	if (!reason) {
973 		if (state->old) {
974 			if (state->old->yiaddr == state->new->yiaddr &&
975 			    lease->server.s_addr)
976 				reason = "RENEW";
977 			else
978 				reason = "REBIND";
979 		} else
980 			reason = "BOUND";
981 	}
982 	/* If we have a monotonic clock we can safely substract the
983 	 * script execution time from our timers.
984 	 * Otherwise we can't as the script may update the real time. */
985 	if (clock_monotonic)
986 		get_monotonic(&start);
987 	retval = configure(iface, reason, state->new, state->old,
988 			   &state->lease, options, 1);
989 	if (clock_monotonic) {
990 		get_monotonic(&stop);
991 		timersub(&stop, &start, &diff);
992 		reduce_timers(state, &diff);
993 	}
994 	if (retval != 0)
995 		return -1;
996 	return daemonise(state, options);
997 }
998 
999 static int
handle_timeout_fail(struct if_state * state,const struct options * options)1000 handle_timeout_fail(struct if_state *state, const struct options *options)
1001 {
1002 	struct dhcp_lease *lease = &state->lease;
1003 	struct interface *iface = state->interface;
1004 	int gotlease = -1;
1005 	const char *reason = NULL;
1006 
1007 	timerclear(&state->stop);
1008 	timerclear(&state->exit);
1009 	if (state->state != STATE_DISCOVERING)
1010 		state->messages = 0;
1011 
1012 	switch (state->state) {
1013 	case STATE_INIT:	/* FALLTHROUGH */
1014 	case STATE_DISCOVERING: /* FALLTHROUGH */
1015 	case STATE_REQUESTING:
1016 		if (IN_LINKLOCAL(ntohl(iface->addr.s_addr))) {
1017 			if (!(state->options & DHCPCD_DAEMONISED))
1018 				logger(LOG_ERR, "timed out");
1019 		} else {
1020 			if (iface->addr.s_addr != 0 &&
1021 			    !(state->options & DHCPCD_INFORM))
1022 				logger(LOG_ERR, "lost lease");
1023 			else if (state->carrier != LINK_DOWN ||
1024 				!(state->options & DHCPCD_DAEMONISED))
1025 				logger(LOG_ERR, "timed out");
1026 		}
1027 		do_socket(state, SOCKET_CLOSED);
1028 		if (state->options & DHCPCD_INFORM ||
1029 		    state->options & DHCPCD_TEST)
1030 			return -1;
1031 
1032 		if (state->carrier != LINK_DOWN &&
1033 		    (state->options & DHCPCD_IPV4LL ||
1034 		     state->options & DHCPCD_LASTLEASE))
1035 			gotlease = get_old_lease(state);
1036 
1037 		if (state->carrier != LINK_DOWN &&
1038 		    state->options & DHCPCD_IPV4LL &&
1039 		    gotlease != 0)
1040 		{
1041 			logger(LOG_INFO, "probing for an IPV4LL address");
1042 			free(state->offer);
1043 			state->offer = ipv4ll_get_dhcp(0);
1044 			gotlease = 0;
1045 		}
1046 
1047 		if (gotlease == 0 &&
1048 		    state->offer->yiaddr != iface->addr.s_addr)
1049 		{
1050 			state->state = STATE_PROBING;
1051 			state->claims = 0;
1052 			state->probes = 0;
1053 			if (iface->addr.s_addr)
1054 				state->conflicts = 0;
1055 			return 1;
1056 		}
1057 
1058 		if (gotlease == 0)
1059 			return bind_dhcp(state, options);
1060 
1061 		if (iface->addr.s_addr)
1062 			reason = "EXPIRE";
1063 		else
1064 			reason = "FAIL";
1065 		drop_config(state, reason, options);
1066 		if (!(state->options & DHCPCD_DAEMONISED) &&
1067 		    (state->options & DHCPCD_DAEMONISE))
1068 			return -1;
1069 		state->state = STATE_RENEW_REQUESTED;
1070 		return 1;
1071 	case STATE_BOUND:
1072 		logger(LOG_INFO, "renewing lease of %s",inet_ntoa(lease->addr));
1073 		if (state->carrier != LINK_DOWN)
1074 			do_socket(state, SOCKET_OPEN);
1075 		state->xid = arc4random();
1076 		state->state = STATE_RENEWING;
1077 		state->stop.tv_sec = lease->rebindtime - lease->renewaltime;
1078 		break;
1079 	case STATE_RENEWING:
1080 		logger(LOG_ERR, "failed to renew, attempting to rebind");
1081 		state->state = STATE_REBINDING;
1082 		if (lease->server.s_addr == 0)
1083 			state->stop.tv_sec = options->timeout;
1084 		else
1085 			state->stop.tv_sec = lease->rebindtime - \
1086 					     lease->renewaltime;
1087 		lease->server.s_addr = 0;
1088 		break;
1089 	case STATE_REBINDING:
1090 		logger(LOG_ERR, "failed to rebind");
1091 		reason = "EXPIRE";
1092 		drop_config(state, reason, options);
1093 		state->state = STATE_INIT;
1094 		break;
1095 	case STATE_PROBING:    /* FALLTHROUGH */
1096 	case STATE_ANNOUNCING:
1097 		/* We should have lost carrier here and exit timer went */
1098 		logger(LOG_ERR, "timed out");
1099 		return -1;
1100 	default:
1101 		logger(LOG_DEBUG, "handle_timeout_failed: invalid state %d",
1102 		       state->state);
1103 	}
1104 
1105 	/* This effectively falls through into the handle_timeout funtion */
1106 	return 1;
1107 }
1108 
1109 static int
handle_timeout(struct if_state * state,const struct options * options)1110 handle_timeout(struct if_state *state, const struct options *options)
1111 {
1112 	struct dhcp_lease *lease = &state->lease;
1113 	struct interface *iface = state->interface;
1114 	int i = 0;
1115 	struct in_addr addr;
1116 	struct timeval tv;
1117 
1118 	timerclear(&state->timeout);
1119 	if (timerneg(&state->exit))
1120 		return handle_timeout_fail(state, options);
1121 
1122 	if (state->state == STATE_RENEW_REQUESTED &&
1123 	    IN_LINKLOCAL(ntohl(lease->addr.s_addr)))
1124 	{
1125 		state->state = STATE_PROBING;
1126 		free(state->offer);
1127 		state->offer = read_lease(state->interface);
1128 		state->probes = 0;
1129 		state->claims = 0;
1130 	}
1131 	switch (state->state) {
1132 	case STATE_INIT_IPV4LL:
1133 		state->state = STATE_PROBING;
1134 		free(state->offer);
1135 		state->offer = ipv4ll_get_dhcp(0);
1136 		state->probes = 0;
1137 		state->claims = 0;
1138 		/* FALLTHROUGH */
1139 	case STATE_PROBING:
1140 		if (iface->arp_fd == -1)
1141 			open_socket(iface, ETHERTYPE_ARP);
1142 		if (state->probes < PROBE_NUM) {
1143 			if (state->probes == 0) {
1144 				addr.s_addr = state->offer->yiaddr;
1145 				logger(LOG_INFO, "checking %s is available"
1146 				       " on attached networks",
1147 				       inet_ntoa(addr));
1148 			}
1149 			state->probes++;
1150 			if (state->probes < PROBE_NUM) {
1151 				state->timeout.tv_sec = PROBE_MIN;
1152 				state->timeout.tv_usec = arc4random() %
1153 					(PROBE_MAX_U - PROBE_MIN_U);
1154 				timernorm(&state->timeout);
1155 			} else {
1156 				state->timeout.tv_sec = ANNOUNCE_WAIT;
1157 				state->timeout.tv_usec = 0;
1158 			}
1159 			logger(LOG_DEBUG,
1160 			       "sending ARP probe (%d of %d), next in %0.2f seconds",
1161 			       state->probes, PROBE_NUM,
1162 			       timeval_to_double(&state->timeout));
1163 			if (send_arp(iface, ARPOP_REQUEST, 0,
1164 				     state->offer->yiaddr) == -1)
1165 			{
1166 				logger(LOG_ERR, "send_arp: %s", strerror(errno));
1167 				return -1;
1168 			}
1169 			return 0;
1170 		} else {
1171 			/* We've waited for ANNOUNCE_WAIT after the final probe
1172 			 * so the address is now ours */
1173 			if (IN_LINKLOCAL(htonl(state->offer->yiaddr))) {
1174 				i = bind_dhcp(state, options);
1175 				state->state = STATE_ANNOUNCING;
1176 				state->timeout.tv_sec = ANNOUNCE_INTERVAL;
1177 				state->timeout.tv_usec = 0;
1178 				return i;
1179 			}
1180 			state->state = STATE_REQUESTING;
1181 		}
1182 		break;
1183 	case STATE_ANNOUNCING:
1184 		if (iface->arp_fd == -1)
1185 			open_socket(iface, ETHERTYPE_ARP);
1186 		if (state->claims < ANNOUNCE_NUM) {
1187 			state->claims++;
1188 			if (state->claims < ANNOUNCE_NUM) {
1189 				state->timeout.tv_sec = ANNOUNCE_INTERVAL;
1190 				state->timeout.tv_usec = 0;
1191 				logger(LOG_DEBUG,
1192 				       "sending ARP announce (%d of %d),"
1193 				       " next in %0.2f seconds",
1194 				       state->claims, ANNOUNCE_NUM,
1195 				       timeval_to_double(&state->timeout));
1196 			} else
1197 				logger(LOG_DEBUG,
1198 				       "sending ARP announce (%d of %d)",
1199 				       state->claims, ANNOUNCE_NUM);
1200 			i = send_arp(iface, ARPOP_REQUEST,
1201 				     state->new->yiaddr, state->new->yiaddr);
1202 			if (i == -1) {
1203 				logger(LOG_ERR, "send_arp: %s", strerror(errno));
1204 				return -1;
1205 			}
1206 		}
1207 		if (state->claims < ANNOUNCE_NUM)
1208 			return 0;
1209 		if (IN_LINKLOCAL(htonl(state->new->yiaddr))) {
1210 			/* We should pretend to be at the end
1211 			 * of the DHCP negotation cycle */
1212 			state->state = STATE_INIT;
1213 			state->messages = DHCP_MAX / DHCP_BASE;
1214 			state->probes = 0;
1215 			state->claims = 0;
1216 			timerclear(&state->stop);
1217 			goto dhcp_timeout;
1218 		} else {
1219 			state->state = STATE_BOUND;
1220 			close(iface->arp_fd);
1221 			iface->arp_fd = -1;
1222 			if (lease->leasetime != ~0U) {
1223 				state->stop.tv_sec = lease->renewaltime;
1224 				state->stop.tv_usec = 0;
1225 				if (clock_monotonic) {
1226 					get_monotonic(&tv);
1227 					timersub(&tv, &lease->boundtime, &tv);
1228 					timersub(&state->stop, &tv, &state->stop);
1229 				} else {
1230 					state->stop.tv_sec -=
1231 						(ANNOUNCE_INTERVAL * ANNOUNCE_NUM);
1232 				}
1233 				logger(LOG_DEBUG, "renew in %ld seconds",
1234 				       (long int)state->stop.tv_sec);
1235 			}
1236 		}
1237 		return 0;
1238 	}
1239 
1240 	if (timerneg(&state->stop))
1241 		return handle_timeout_fail(state, options);
1242 
1243 	switch (state->state) {
1244 	case STATE_BOUND: /* FALLTHROUGH */
1245 	case STATE_RENEW_REQUESTED:
1246 		timerclear(&state->stop);
1247 		/* FALLTHROUGH */
1248 	case STATE_INIT:
1249 		do_socket(state, SOCKET_OPEN);
1250 		state->xid = arc4random();
1251 		iface->start_uptime = uptime();
1252 		break;
1253 	}
1254 
1255 	switch(state->state) {
1256 	case STATE_RENEW_REQUESTED:
1257 		/* If a renew was requested (ie, didn't timeout) we actually
1258 		 * enter the REBIND state so that we broadcast to all servers.
1259 		 * We need to do this for when we change networks. */
1260 		lease->server.s_addr = 0;
1261 		state->messages = 0;
1262 		if (lease->addr.s_addr && !(state->options & DHCPCD_INFORM)) {
1263 			logger(LOG_INFO, "rebinding lease of %s",
1264 			       inet_ntoa(lease->addr));
1265 			state->state = STATE_REBINDING;
1266 			state->stop.tv_sec = options->timeout;
1267 			state->stop.tv_usec = 0;
1268 			break;
1269 		}
1270 		/* FALLTHROUGH */
1271 	case STATE_INIT:
1272 		if (state->carrier == LINK_DOWN)
1273 			return 0;
1274 		if (lease->addr.s_addr == 0 ||
1275 		    IN_LINKLOCAL(ntohl(iface->addr.s_addr)))
1276 		{
1277 			logger(LOG_INFO, "broadcasting for a lease");
1278 			state->state = STATE_DISCOVERING;
1279 		} else if (state->options & DHCPCD_INFORM) {
1280 			logger(LOG_INFO, "broadcasting inform for %s",
1281 			       inet_ntoa(lease->addr));
1282 			state->state = STATE_REQUESTING;
1283 		} else {
1284 			logger(LOG_INFO, "broadcasting for a lease of %s",
1285 			       inet_ntoa(lease->addr));
1286 			state->state = STATE_REQUESTING;
1287 		}
1288 		if (!lease->addr.s_addr && !timerisset(&state->stop)) {
1289 			state->stop.tv_sec = DHCP_MAX + DHCP_RAND_MIN;
1290 			state->stop.tv_usec = arc4random() % (DHCP_RAND_MAX_U - DHCP_RAND_MIN_U);
1291 			timernorm(&state->stop);
1292 		}
1293 		break;
1294 	}
1295 
1296 dhcp_timeout:
1297 	if (state->carrier == LINK_DOWN) {
1298 		timerclear(&state->timeout);
1299 		return 0;
1300 	}
1301 	state->timeout.tv_sec = DHCP_BASE;
1302 	for (i = 0; i < state->messages; i++) {
1303 		state->timeout.tv_sec *= 2;
1304 		if (state->timeout.tv_sec > DHCP_MAX) {
1305 			state->timeout.tv_sec = DHCP_MAX;
1306 			break;
1307 		}
1308 	}
1309 	state->timeout.tv_sec += DHCP_RAND_MIN;
1310 	state->timeout.tv_usec = arc4random() %
1311 		(DHCP_RAND_MAX_U - DHCP_RAND_MIN_U);
1312 	timernorm(&state->timeout);
1313 
1314 	/* We send the message here so that the timeout is reported */
1315 	switch (state->state) {
1316 	case STATE_DISCOVERING:
1317 		send_message(state, DHCP_DISCOVER, options);
1318 		break;
1319 	case STATE_REQUESTING:
1320 		if (state->options & DHCPCD_INFORM) {
1321 			send_message(state, DHCP_INFORM, options);
1322 			break;
1323 		}
1324 		/* FALLTHROUGH */
1325 	case STATE_RENEWING:   /* FALLTHROUGH */
1326 	case STATE_REBINDING:
1327 		if (iface->raw_fd == -1)
1328 			do_socket(state, SOCKET_OPEN);
1329 		send_message(state, DHCP_REQUEST, options);
1330 		break;
1331 	}
1332 
1333 	return 0;
1334 }
1335 
1336 static void
log_dhcp(int lvl,const char * msg,const struct dhcp_message * dhcp)1337 log_dhcp(int lvl, const char *msg, const struct dhcp_message *dhcp)
1338 {
1339 	char *a;
1340 	struct in_addr addr;
1341 	int r;
1342 
1343 	if (strcmp(msg, "NAK:") == 0)
1344 		a = get_option_string(dhcp, DHO_MESSAGE);
1345 	else {
1346 		addr.s_addr = dhcp->yiaddr;
1347 		a = xstrdup(inet_ntoa(addr));
1348 	}
1349 	r = get_option_addr(&addr.s_addr, dhcp, DHO_SERVERID);
1350 	if (dhcp->servername[0] && r == 0)
1351 		logger(lvl, "%s %s from %s `%s'", msg, a,
1352 		       inet_ntoa(addr), dhcp->servername);
1353 	else if (r == 0)
1354 		logger(lvl, "%s %s from %s", msg, a, inet_ntoa(addr));
1355 	else
1356 		logger(lvl, "%s %s", msg, a);
1357 	free(a);
1358 }
1359 
1360 static int
handle_dhcp(struct if_state * state,struct dhcp_message ** dhcpp,const struct options * options)1361 handle_dhcp(struct if_state *state, struct dhcp_message **dhcpp,
1362 	    const struct options *options)
1363 {
1364 	struct dhcp_message *dhcp = *dhcpp;
1365 	struct interface *iface = state->interface;
1366 	struct dhcp_lease *lease = &state->lease;
1367 	uint8_t type, tmp;
1368 	struct in_addr addr;
1369 	size_t i;
1370 	int r;
1371 
1372 	/* reset the message counter */
1373 	state->messages = 0;
1374 
1375 	/* We have to have DHCP type to work */
1376 	if (get_option_uint8(&type, dhcp, DHO_MESSAGETYPE) == -1) {
1377 		log_dhcp(LOG_ERR, "no DHCP type in", dhcp);
1378 		return 0;
1379 	}
1380 
1381 	/* Ensure that it's not from a blacklisted server.
1382 	 * We should expand this to check IP and/or hardware address
1383 	 * at the packet level. */
1384 	if (options->blacklist_len != 0 &&
1385 	    get_option_addr(&addr.s_addr, dhcp, DHO_SERVERID) == 0)
1386 	{
1387 		for (i = 0; i < options->blacklist_len; i++) {
1388 			if (options->blacklist[i] != addr.s_addr)
1389 				continue;
1390 			if (dhcp->servername[0])
1391 				logger(LOG_WARNING,
1392 				       "ignoring blacklisted server %s `%s'",
1393 					inet_ntoa(addr), dhcp->servername);
1394 			else
1395 				logger(LOG_WARNING,
1396 				       "ignoring blacklisted server %s",
1397 				       inet_ntoa(addr));
1398 			return 0;
1399 		}
1400 	}
1401 
1402 	/* We should restart on a NAK */
1403 	if (type == DHCP_NAK) {
1404 		log_dhcp(LOG_WARNING, "NAK:", dhcp);
1405 		drop_config(state, "EXPIRE", options);
1406 		do_socket(state, SOCKET_CLOSED);
1407 		state->state = STATE_INIT;
1408 		/* If we constantly get NAKS then we should slowly back off */
1409 		if (state->nakoff == 0) {
1410 			state->nakoff = 1;
1411 			timerclear(&state->timeout);
1412 		} else {
1413 			state->timeout.tv_sec = state->nakoff;
1414 			state->timeout.tv_usec = 0;
1415 			state->nakoff *= 2;
1416 			if (state->nakoff > NAKOFF_MAX)
1417 				state->nakoff = NAKOFF_MAX;
1418 		}
1419 		return 0;
1420 	}
1421 
1422 	/* No NAK, so reset the backoff */
1423 	state->nakoff = 1;
1424 
1425 	/* Ensure that all required options are present */
1426 	for (i = 1; i < 255; i++) {
1427 		if (has_option_mask(options->requiremask, i) &&
1428 		    get_option_uint8(&tmp, dhcp, i) != 0)
1429 		{
1430 			log_dhcp(LOG_WARNING, "reject", dhcp);
1431 			return 0;
1432 		}
1433 	}
1434 
1435 	if (type == DHCP_OFFER && state->state == STATE_DISCOVERING) {
1436 		lease->addr.s_addr = dhcp->yiaddr;
1437 		get_option_addr(&lease->server.s_addr, dhcp, DHO_SERVERID);
1438 		log_dhcp(LOG_INFO, "offered", dhcp);
1439 		if (state->options & DHCPCD_TEST) {
1440 			run_script(options, iface->name, "TEST", dhcp, NULL);
1441 			/* Fake the fact we forked so we return 0 to userland */
1442 			state->options |= DHCPCD_FORKED;
1443 			return -1;
1444 		}
1445 		free(state->offer);
1446 		state->offer = dhcp;
1447 		*dhcpp = NULL;
1448 		timerclear(&state->timeout);
1449 		if (state->options & DHCPCD_ARP &&
1450 		    iface->addr.s_addr != state->offer->yiaddr)
1451 		{
1452 			/* If the interface already has the address configured
1453 			 * then we can't ARP for duplicate detection. */
1454 			addr.s_addr = state->offer->yiaddr;
1455 			if (!has_address(iface->name, &addr, NULL)) {
1456 				state->state = STATE_PROBING;
1457 				state->claims = 0;
1458 				state->probes = 0;
1459 				state->conflicts = 0;
1460 				timerclear(&state->stop);
1461 				return 1;
1462 			}
1463 		}
1464 		state->state = STATE_REQUESTING;
1465 		return 1;
1466 	}
1467 
1468 	if (type == DHCP_OFFER) {
1469 		log_dhcp(LOG_INFO, "ignoring offer of", dhcp);
1470 		return 0;
1471 	}
1472 
1473 	/* We should only be dealing with acks */
1474 	if (type != DHCP_ACK) {
1475 		log_dhcp(LOG_ERR, "not ACK or OFFER", dhcp);
1476 		return 0;
1477 	}
1478 
1479 	switch (state->state) {
1480 	case STATE_RENEW_REQUESTED:
1481 	case STATE_REQUESTING:
1482 	case STATE_RENEWING:
1483 	case STATE_REBINDING:
1484 		if (!(state->options & DHCPCD_INFORM)) {
1485 			get_option_addr(&lease->server.s_addr,
1486 					dhcp, DHO_SERVERID);
1487 			log_dhcp(LOG_INFO, "acknowledged", dhcp);
1488 		}
1489 		free(state->offer);
1490 		state->offer = dhcp;
1491 		*dhcpp = NULL;
1492 		break;
1493 	default:
1494 		logger(LOG_ERR, "wrong state %d", state->state);
1495 	}
1496 
1497 	do_socket(state, SOCKET_CLOSED);
1498 	r = bind_dhcp(state, options);
1499 	if (!(state->options & DHCPCD_ARP)) {
1500 		if (!(state->options & DHCPCD_INFORM))
1501 			logger(LOG_DEBUG, "renew in %ld seconds",
1502 			       (long int)state->stop.tv_sec);
1503 		return r;
1504 	}
1505 	state->state = STATE_ANNOUNCING;
1506 	if (state->options & DHCPCD_FORKED)
1507 		return r;
1508 	return 1;
1509 }
1510 
1511 static int
handle_dhcp_packet(struct if_state * state,const struct options * options)1512 handle_dhcp_packet(struct if_state *state, const struct options *options)
1513 {
1514 	uint8_t *packet;
1515 	struct interface *iface = state->interface;
1516 	struct dhcp_message *dhcp = NULL;
1517 	const uint8_t *pp;
1518 	uint8_t *p;
1519 	ssize_t bytes;
1520 	int retval = -1;
1521 
1522 	/* We loop through until our buffer is empty.
1523 	 * The benefit is that if we get >1 DHCP packet in our buffer and
1524 	 * the first one fails for any reason, we can use the next. */
1525 	packet = xmalloc(udp_dhcp_len);
1526 	for(;;) {
1527 		bytes = get_raw_packet(iface, ETHERTYPE_IP,
1528 				       packet, udp_dhcp_len);
1529 		if (bytes == 0) {
1530 			retval = 0;
1531 			break;
1532 		}
1533 		if (bytes == -1)
1534 			break;
1535 		if (valid_udp_packet(packet) == -1)
1536 			continue;
1537 		bytes = get_udp_data(&pp, packet);
1538 		if ((size_t)bytes > sizeof(*dhcp)) {
1539 			logger(LOG_ERR, "packet greater than DHCP size");
1540 			continue;
1541 		}
1542 		if (!dhcp)
1543 			dhcp = xmalloc(sizeof(*dhcp));
1544 		memcpy(dhcp, pp, bytes);
1545 		if (dhcp->cookie != htonl(MAGIC_COOKIE)) {
1546 			logger(LOG_DEBUG, "bogus cookie, ignoring");
1547 			continue;
1548 		}
1549 		/* Ensure it's the right transaction */
1550 		if (state->xid != dhcp->xid) {
1551 			logger(LOG_DEBUG,
1552 			       "ignoring packet with xid 0x%x as"
1553 			       " it's not ours (0x%x)",
1554 			       dhcp->xid, state->xid);
1555 			continue;
1556 		}
1557 		/* Ensure packet is for us */
1558 		if (iface->hwlen <= sizeof(dhcp->chaddr) &&
1559 		    memcmp(dhcp->chaddr, iface->hwaddr, iface->hwlen))
1560 		{
1561 			logger(LOG_DEBUG, "xid 0x%x is not for our hwaddr %s",
1562 			       dhcp->xid,
1563 			       hwaddr_ntoa(dhcp->chaddr, sizeof(dhcp->chaddr)));
1564 			continue;
1565 		}
1566 		/* We should ensure that the packet is terminated correctly
1567 		 * if we have space for the terminator */
1568 		if ((size_t)bytes < sizeof(struct dhcp_message)) {
1569 			p = (uint8_t *)dhcp + bytes - 1;
1570 			while (p > dhcp->options && *p == DHO_PAD)
1571 				p--;
1572 			if (*p != DHO_END)
1573 				*++p = DHO_END;
1574 		}
1575 		retval = handle_dhcp(state, &dhcp, options);
1576 		if (retval == 0 && state->options & DHCPCD_TEST)
1577 			state->options |= DHCPCD_FORKED;
1578 		break;
1579 	}
1580 
1581 	free(packet);
1582 	free(dhcp);
1583 	return retval;
1584 }
1585 
1586 static int
handle_arp_packet(struct if_state * state)1587 handle_arp_packet(struct if_state *state)
1588 {
1589 	struct arphdr reply;
1590 	uint32_t reply_s;
1591 	uint32_t reply_t;
1592 	uint8_t arp_reply[sizeof(reply) + 2 * sizeof(reply_s) + 2 * HWADDR_LEN];
1593 	uint8_t *hw_s, *hw_t;
1594 	ssize_t bytes;
1595 	struct interface *iface = state->interface;
1596 
1597 	state->fail.s_addr = 0;
1598 	for(;;) {
1599 		bytes = get_raw_packet(iface, ETHERTYPE_ARP,
1600 				       arp_reply, sizeof(arp_reply));
1601 		if (bytes == 0 || bytes == -1)
1602 			return (int)bytes;
1603 		/* We must have a full ARP header */
1604 		if ((size_t)bytes < sizeof(reply))
1605 			continue;
1606 		memcpy(&reply, arp_reply, sizeof(reply));
1607 		/* Protocol must be IP. */
1608 		if (reply.ar_pro != htons(ETHERTYPE_IP))
1609 			continue;
1610 		if (reply.ar_pln != sizeof(reply_s))
1611 			continue;
1612 		/* Only these types are recognised */
1613 		if (reply.ar_op != htons(ARPOP_REPLY) &&
1614 		    reply.ar_op != htons(ARPOP_REQUEST))
1615 			continue;
1616 
1617 		/* Get pointers to the hardware addreses */
1618 		hw_s = arp_reply + sizeof(reply);
1619 		hw_t = hw_s + reply.ar_hln + reply.ar_pln;
1620 		/* Ensure we got all the data */
1621 		if ((hw_t + reply.ar_hln + reply.ar_pln) - arp_reply > bytes)
1622 			continue;
1623 		/* Ignore messages from ourself */
1624 		if (reply.ar_hln == iface->hwlen &&
1625 		    memcmp(hw_s, iface->hwaddr, iface->hwlen) == 0)
1626 			continue;
1627 		/* Copy out the IP addresses */
1628 		memcpy(&reply_s, hw_s + reply.ar_hln, reply.ar_pln);
1629 		memcpy(&reply_t, hw_t + reply.ar_hln, reply.ar_pln);
1630 
1631 		/* Check for conflict */
1632 		if (state->offer &&
1633 		    (reply_s == state->offer->yiaddr ||
1634 		     (reply_s == 0 && reply_t == state->offer->yiaddr)))
1635 			state->fail.s_addr = state->offer->yiaddr;
1636 
1637 		/* Handle IPv4LL conflicts */
1638 		if (IN_LINKLOCAL(htonl(iface->addr.s_addr)) &&
1639 		    (reply_s == iface->addr.s_addr ||
1640 		     (reply_s == 0 && reply_t == iface->addr.s_addr)))
1641 			state->fail.s_addr = iface->addr.s_addr;
1642 
1643 		if (state->fail.s_addr) {
1644 			logger(LOG_ERR, "hardware address %s claims %s",
1645 			       hwaddr_ntoa((unsigned char *)hw_s,
1646 					   (size_t)reply.ar_hln),
1647 			       inet_ntoa(state->fail));
1648 			errno = EEXIST;
1649 			return -1;
1650 		}
1651 	}
1652 }
1653 
1654 static int
handle_arp_fail(struct if_state * state,const struct options * options)1655 handle_arp_fail(struct if_state *state, const struct options *options)
1656 {
1657 	time_t up;
1658 	int cookie = state->offer->cookie;
1659 
1660 	if (!IN_LINKLOCAL(htonl(state->fail.s_addr))) {
1661 		state->state = STATE_INIT;
1662 		free(state->offer);
1663 		state->offer = NULL;
1664 		state->lease.addr.s_addr = 0;
1665 		if (!cookie)
1666 			return 1;
1667 		state->timeout.tv_sec = DHCP_ARP_FAIL;
1668 		state->timeout.tv_usec = 0;
1669 		do_socket(state, SOCKET_OPEN);
1670 		send_message(state, DHCP_DECLINE, options);
1671 		do_socket(state, SOCKET_CLOSED);
1672 		return 0;
1673 	}
1674 
1675 	if (state->fail.s_addr == state->interface->addr.s_addr) {
1676 		if (state->state == STATE_PROBING)
1677 			/* This should only happen when SIGALRM or
1678 			 * link when down/up and we have a conflict. */
1679 			drop_config(state, "EXPIRE", options);
1680 		else {
1681 			up = uptime();
1682 			if (state->defend + DEFEND_INTERVAL > up) {
1683 				drop_config(state, "EXPIRE", options);
1684 				state->conflicts = -1;
1685 				/* drop through to set conflicts to 0 */
1686 			} else {
1687 				state->defend = up;
1688 				return 0;
1689 			}
1690 		}
1691 	}
1692 	do_socket(state, SOCKET_CLOSED);
1693 	state->conflicts++;
1694 	timerclear(&state->stop);
1695 	if (state->conflicts > MAX_CONFLICTS) {
1696 		logger(LOG_ERR, "failed to obtain an IPv4LL address");
1697 		state->state = STATE_INIT;
1698 		timerclear(&state->timeout);
1699 		if (!(state->options & DHCPCD_DAEMONISED) &&
1700 		    (state->options & DHCPCD_DAEMONISE))
1701 			return -1;
1702 		return 1;
1703 	}
1704 	state->state = STATE_INIT_IPV4LL;
1705 	state->timeout.tv_sec = PROBE_WAIT;
1706 	state->timeout.tv_usec = 0;
1707 	return 0;
1708 }
1709 
1710 static int
handle_link(struct if_state * state)1711 handle_link(struct if_state *state)
1712 {
1713 	int retval;
1714 
1715 	retval = link_changed(state->interface);
1716 	if (retval == -1) {
1717 		logger(LOG_ERR, "link_changed: %s", strerror(errno));
1718 		return -1;
1719 	}
1720 	if (retval == 0)
1721 		return 0;
1722 
1723 	timerclear(&state->timeout);
1724 	switch (carrier_status(state->interface->name)) {
1725 	case -1:
1726 		logger(LOG_ERR, "carrier_status: %s", strerror(errno));
1727 		return -1;
1728 	case 0:
1729 		if (state->carrier != LINK_DOWN) {
1730 			logger(LOG_INFO, "carrier lost");
1731 			state->carrier = LINK_DOWN;
1732 			do_socket(state, SOCKET_CLOSED);
1733 			if (state->state != STATE_BOUND)
1734 				timerclear(&state->stop);
1735 		}
1736 		break;
1737 	default:
1738 		if (state->carrier != LINK_UP) {
1739 			logger(LOG_INFO, "carrier acquired");
1740 			state->state = STATE_RENEW_REQUESTED;
1741 			state->carrier = LINK_UP;
1742 			timerclear(&state->stop);
1743 			return 1;
1744 		}
1745 		break;
1746 	}
1747 	return 0;
1748 }
1749 
1750 int
dhcp_run(const struct options * options,int * pid_fd)1751 dhcp_run(const struct options *options, int *pid_fd)
1752 {
1753 	struct interface *iface;
1754 	struct if_state *state = NULL;
1755 	int fd = -1, r = 0, sig;
1756 
1757 	iface = read_interface(options->interface, options->metric);
1758 	if (!iface) {
1759 		logger(LOG_ERR, "read_interface: %s", strerror(errno));
1760 		goto eexit;
1761 	}
1762 	logger(LOG_DEBUG, "hardware address = %s",
1763 	       hwaddr_ntoa(iface->hwaddr, iface->hwlen));
1764 	state = xzalloc(sizeof(*state));
1765 	state->pid_fd = pid_fd;
1766 	state->interface = iface;
1767 	if (!(options->options & DHCPCD_TEST))
1768 		run_script(options, iface->name, "PREINIT", NULL, NULL);
1769 
1770 	if (client_setup(state, options) == -1)
1771 		goto eexit;
1772 	if (signal_init() == -1)
1773 		goto eexit;
1774 	if (signal_setup() == -1)
1775 		goto eexit;
1776 	state->signal_fd = signal_fd();
1777 
1778 	if (state->options & DHCPCD_BACKGROUND &&
1779 	    !(state->options & DHCPCD_DAEMONISED))
1780 		if (daemonise(state, options) == -1)
1781 			goto eexit;
1782 
1783 	if (state->carrier == LINK_DOWN)
1784 		logger(LOG_INFO, "waiting for carrier");
1785 
1786 	for (;;) {
1787 		if (r == 0)
1788 			r = handle_timeout(state, options);
1789 		else if (r > 0) {
1790 			if (fd == state->signal_fd) {
1791 			    	if ((sig = signal_read()) != -1)
1792 					r = handle_signal(sig, state, options);
1793 			} else if (fd == iface->link_fd)
1794 				r = handle_link(state);
1795 			else if (fd == iface->raw_fd)
1796 				r = handle_dhcp_packet(state, options);
1797 			else if (fd == iface->arp_fd) {
1798 				if ((r = handle_arp_packet(state)) == -1)
1799 					r = handle_arp_fail(state, options);
1800 			} else
1801 				r = 0;
1802 		}
1803 		if (r == -1)
1804 			break;
1805 		if (r == 0) {
1806 			fd = -1;
1807 			r = wait_for_fd(state, &fd);
1808 			if (r == -1 && errno == EINTR) {
1809 				r = 1;
1810 				fd = state->signal_fd;
1811 			}
1812 		} else
1813 			r = 0;
1814 	}
1815 
1816 eexit:
1817 	if (iface) {
1818 		do_socket(state, SOCKET_CLOSED);
1819 		if (iface->link_fd != -1)
1820 		    close(iface->link_fd);
1821 		free_routes(iface->routes);
1822 		free(iface->clientid);
1823 		free(iface->buffer);
1824 		free(iface);
1825 	}
1826 
1827 	if (state) {
1828 		if (state->options & DHCPCD_FORKED)
1829 			r = 0;
1830 		if (state->options & DHCPCD_DAEMONISED)
1831 			unlink(options->pidfile);
1832 		free(state->offer);
1833 		free(state->new);
1834 		free(state->old);
1835 		free(state);
1836 	}
1837 
1838 	return r;
1839 }
1840