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