dhclient - Cancel all timeouts in state_reboot().
[dragonfly.git] / sbin / dhclient / dhclient.c
CommitLineData
86cc4af6 1/* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.143 2012/06/20 21:53:51 kettenis Exp $ */
846204b6
HT
2
3/*
4 * Copyright 2004 Henning Brauer <henning@openbsd.org>
5 * Copyright (c) 1995, 1996, 1997, 1998, 1999
6 * The Internet Software Consortium. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of The Internet Software Consortium nor the names
18 * of its contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 * This software has been written for the Internet Software Consortium
36 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37 * Enterprises. To learn more about the Internet Software Consortium,
38 * see ``http://www.vix.com/isc''. To learn more about Vixie
39 * Enterprises, see ``http://www.vix.com''.
40 *
41 * This client was substantially modified and enhanced by Elliot Poger
42 * for use on Linux while he was working on the MosquitoNet project at
43 * Stanford.
44 *
45 * The current version owes much to Elliot's Linux enhancements, but
46 * was substantially reorganized and partially rewritten by Ted Lemon
47 * so as to use the same networking framework that the Internet Software
48 * Consortium DHCP server uses. Much system-specific configuration code
49 * was moved into a shell script so that as support for more operating
50 * systems is added, it will not be necessary to port and maintain
51 * system-specific configuration code to these operating systems - instead,
52 * the shell script can invoke the native tools to accomplish the same
53 * purpose.
54 */
d63fb838 55#include <sys/ioctl.h>
846204b6
HT
56
57#include <ctype.h>
58#include <poll.h>
59#include <pwd.h>
a05d48e6 60#include <unistd.h>
846204b6
HT
61
62#include "dhcpd.h"
63#include "privsep.h"
64
65#define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
66#define DEFAULT_LEASE_TIME 43200 /* 12 hours... */
67#define TIME_MAX 2147483647
a05d48e6
SG
68#define POLL_FAILURES 10
69#define POLL_FAILURE_WAIT 1 /* Back off multiplier (seconds) */
846204b6
HT
70
71time_t cur_time;
72
73char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
74char *path_dhclient_db = NULL;
75
76int log_perror = 1;
77int privfd;
78int nullfd = -1;
79int no_daemon;
80int unknown_ok = 1;
81int routefd = -1;
82
83struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
84struct in_addr inaddr_any;
85struct sockaddr_in sockaddr_broadcast;
86
87struct interface_info *ifi;
88struct client_state *client;
89struct client_config *config;
90
91int findproto(char *, int);
92struct sockaddr *get_ifa(char *, int);
93void usage(void);
94int check_option(struct client_lease *l, int option);
95int ipv4addrs(char * buf);
96int res_hnok(const char *dn);
97char *option_as_string(unsigned int code, unsigned char *data, int len);
98int fork_privchld(int, int);
d63fb838 99void get_ifname(char *, char *);
846204b6
HT
100#define ROUNDUP(a) \
101 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
102#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
103
104time_t scripttime;
105static FILE *leaseFile;
106
107int
108findproto(char *cp, int n)
109{
110 struct sockaddr *sa;
111 int i;
112
113 if (n == 0)
114 return -1;
115 for (i = 1; i; i <<= 1) {
116 if (i & n) {
117 sa = (struct sockaddr *)cp;
118 switch (i) {
119 case RTA_IFA:
120 case RTA_DST:
121 case RTA_GATEWAY:
122 case RTA_NETMASK:
123 if (sa->sa_family == AF_INET)
124 return AF_INET;
125 if (sa->sa_family == AF_INET6)
126 return AF_INET6;
127 break;
128 case RTA_IFP:
129 break;
130 }
131 ADVANCE(cp, sa);
132 }
133 }
134 return (-1);
135}
136
137struct sockaddr *
138get_ifa(char *cp, int n)
139{
140 struct sockaddr *sa;
141 int i;
142
143 if (n == 0)
144 return (NULL);
145 for (i = 1; i; i <<= 1)
146 if (i & n) {
147 sa = (struct sockaddr *)cp;
148 if (i == RTA_IFA)
149 return (sa);
150 ADVANCE(cp, sa);
151 }
152
153 return (NULL);
154}
be18cf74 155struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
846204b6 156
846204b6
HT
157void
158routehandler(void)
159{
160 int linkstat;
161 char msg[2048];
162 struct rt_msghdr *rtm;
163 struct if_msghdr *ifm;
164 struct ifa_msghdr *ifam;
165 struct if_announcemsghdr *ifan;
166 struct client_lease *l;
167 time_t t = time(NULL);
168 struct sockaddr *sa;
169 struct iaddr a;
170 ssize_t n;
44967127 171 char *errmsg, buf[64];
846204b6
HT
172
173 do {
174 n = read(routefd, &msg, sizeof(msg));
175 } while (n == -1 && errno == EINTR);
176
177 rtm = (struct rt_msghdr *)msg;
178 if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
179 rtm->rtm_version != RTM_VERSION)
180 return;
181
182 switch (rtm->rtm_type) {
183 case RTM_NEWADDR:
184 ifam = (struct ifa_msghdr *)rtm;
185 if (ifam->ifam_index != ifi->index)
186 break;
187 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
188 break;
189 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
44967127
AHJ
190 if (sa == NULL) {
191 errmsg = "sa == NULL";
846204b6 192 goto die;
44967127 193 }
846204b6
HT
194
195 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
196 error("king bula sez: len mismatch");
197 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
198 if (addr_eq(a, defaddr))
199 break;
200
6954ee78
AHJ
201 /* state_panic() can try unexpired existing leases */
202 if (client->active && addr_eq(a, client->active->address))
203 break;
204 for (l = client->leases; l != NULL; l = l->next)
846204b6
HT
205 if (addr_eq(a, l->address))
206 break;
207
7cbe3601 208 if (l != NULL)
846204b6
HT
209 /* new addr is the one we set */
210 break;
44967127
AHJ
211 snprintf(buf, sizeof(buf), "%s: %s",
212 "new address not one we set", piaddr(a));
213 errmsg = buf;
846204b6
HT
214 goto die;
215 case RTM_DELADDR:
216 ifam = (struct ifa_msghdr *)rtm;
217 if (ifam->ifam_index != ifi->index)
218 break;
219 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
220 break;
6954ee78 221 /* XXX check addrs like RTM_NEWADDR instead of this? */
846204b6
HT
222 if (scripttime == 0 || t < scripttime + 10)
223 break;
44967127 224 errmsg = "interface address deleted";
846204b6
HT
225 goto die;
226 case RTM_IFINFO:
227 ifm = (struct if_msghdr *)rtm;
228 if (ifm->ifm_index != ifi->index)
229 break;
44967127
AHJ
230 if ((rtm->rtm_flags & RTF_UP) == 0) {
231 errmsg = "interface down";
846204b6 232 goto die;
44967127 233 }
846204b6
HT
234
235 linkstat =
236 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
237 if (linkstat != ifi->linkstat) {
4cada237 238#ifdef DEBUG
846204b6
HT
239 debug("link state %s -> %s",
240 ifi->linkstat ? "up" : "down",
241 linkstat ? "up" : "down");
4cada237 242#endif
846204b6
HT
243 ifi->linkstat = interface_link_status(ifi->name);
244 if (ifi->linkstat) {
245 client->state = S_INIT;
246 state_reboot();
247 }
248 }
249 break;
250 case RTM_IFANNOUNCE:
251 ifan = (struct if_announcemsghdr *)rtm;
252 if (ifan->ifan_what == IFAN_DEPARTURE &&
44967127
AHJ
253 ifan->ifan_index == ifi->index) {
254 errmsg = "interface departure";
846204b6 255 goto die;
44967127 256 }
846204b6
HT
257 break;
258 default:
259 break;
260 }
261 return;
262
263die:
7cbe3601 264 script_init("FAIL");
846204b6 265 script_go();
44967127 266 error("routehandler: %s", errmsg);
846204b6
HT
267}
268
269int
270main(int argc, char *argv[])
271{
272 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
273 struct passwd *pw;
274
275 /* Initially, log errors to stderr as well as to syslogd. */
276 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
277 setlogmask(LOG_UPTO(LOG_INFO));
278
279 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
280 switch (ch) {
281 case 'c':
282 path_dhclient_conf = optarg;
283 break;
284 case 'd':
285 no_daemon = 1;
286 break;
287 case 'l':
288 path_dhclient_db = optarg;
289 break;
290 case 'q':
291 quiet = 1;
292 break;
293 case 'u':
294 unknown_ok = 0;
295 break;
296 default:
297 usage();
298 }
299
300 argc -= optind;
301 argv += optind;
302
303 if (argc != 1)
304 usage();
305
306 ifi = calloc(1, sizeof(*ifi));
307 if (ifi == NULL)
308 error("ifi calloc");
309 client = calloc(1, sizeof(*client));
310 if (client == NULL)
311 error("client calloc");
312 config = calloc(1, sizeof(*config));
313 if (config == NULL)
314 error("config calloc");
315
d63fb838 316 get_ifname(ifi->name, argv[0]);
846204b6
HT
317 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
318 _PATH_DHCLIENT_DB, ifi->name) == -1)
319 error("asprintf");
320
321 if (quiet)
322 log_perror = 0;
323
324 tzset();
325 time(&cur_time);
326
327 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
328 sockaddr_broadcast.sin_family = AF_INET;
329 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
330 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
331 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
332 inaddr_any.s_addr = INADDR_ANY;
333
334 read_client_conf();
335
336 if (interface_status(ifi->name) == 0) {
337 interface_link_forceup(ifi->name);
338 /* Give it up to 4 seconds of silent grace to find link */
339 i = -4;
340 } else
341 i = 0;
342
343 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
344 if (i == 0)
345 fprintf(stderr, "%s: no link ...", ifi->name);
346 else if (i > 0)
347 fprintf(stderr, ".");
348 fflush(stderr);
349 if (++i > config->link_timeout) {
350 fprintf(stderr, " sleeping\n");
351 goto dispatch;
352 }
353 sleep(1);
846204b6 354 }
ade429c6 355 if (i > 0)
77a69a5f 356 fprintf(stderr, " got link\n");
846204b6
HT
357
358 dispatch:
359 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
360 error("cannot open %s: %m", _PATH_DEVNULL);
361
38623c79
AHJ
362 if ((pw = getpwnam("_dhcp")) == NULL)
363 error("no such user: _dhcp");
846204b6
HT
364
365 if (pipe(pipe_fd) == -1)
366 error("pipe");
367
368 fork_privchld(pipe_fd[0], pipe_fd[1]);
369
370 close(pipe_fd[0]);
371 privfd = pipe_fd[1];
372
373 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
374 error("can't open and lock %s: %m", path_dhclient_db);
375 read_client_leases();
376 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
377 error("can't open %s: %m", path_dhclient_db);
378 rewrite_client_leases();
379 close(fd);
380
846204b6
HT
381 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
382 error("socket(PF_ROUTE, SOCK_RAW): %m");
383
384 /* set up the interface */
385 discover_interface();
386
387 if (chroot(_PATH_VAREMPTY) == -1)
388 error("chroot");
389 if (chdir("/") == -1)
390 error("chdir(\"/\")");
391
392 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
393 error("setresgid");
394 if (setgroups(1, &pw->pw_gid) == -1)
395 error("setgroups");
396 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
397 error("setresuid");
398
399 endpwent();
400
401 setproctitle("%s", ifi->name);
402
403 if (ifi->linkstat) {
404 client->state = S_INIT;
405 state_reboot();
406 } else
407 go_daemon();
408
409 dispatch();
410
411 /* not reached */
412 return (0);
413}
414
415void
416usage(void)
417{
418 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
419 getprogname());
420 exit(1);
421}
422
423/*
424 * Individual States:
425 *
426 * Each routine is called from the dhclient_state_machine() in one of
427 * these conditions:
428 * -> entering INIT state
429 * -> recvpacket_flag == 0: timeout in this state
430 * -> otherwise: received a packet in this state
431 *
432 * Return conditions as handled by dhclient_state_machine():
433 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
434 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
435 * Returns 0: finish the nap which was interrupted for no good reason.
436 *
437 * Several per-interface variables are used to keep track of the process:
438 * active_lease: the lease that is being used on the interface
439 * (null pointer if not configured yet).
440 * offered_leases: leases corresponding to DHCPOFFER messages that have
441 * been sent to us by DHCP servers.
442 * acked_leases: leases corresponding to DHCPACK messages that have been
443 * sent to us by DHCP servers.
444 * sendpacket: DHCP packet we're trying to send.
445 * destination: IP address to send sendpacket to
446 * In addition, there are several relevant per-lease variables.
447 * T1_expiry, T2_expiry, lease_expiry: lease milestones
448 * In the active lease, these control the process of renewing the lease;
449 * In leases on the acked_leases list, this simply determines when we
450 * can no longer legitimately use the lease.
451 */
452void
453state_reboot(void)
454{
86cc4af6
AHJ
455 /* Cancel all timeouts, since a link state change gets us here
456 and can happen anytime. */
457 cancel_timeout(state_init);
458 cancel_timeout(state_selecting);
459 cancel_timeout(state_bound);
460 cancel_timeout(send_discover);
461 cancel_timeout(send_request);
462
846204b6
HT
463 /* If we don't remember an active lease, go straight to INIT. */
464 if (!client->active || client->active->is_bootp) {
465 state_init();
466 return;
467 }
468
469 /* We are in the rebooting state. */
470 client->state = S_REBOOTING;
471
472 /* make_request doesn't initialize xid because it normally comes
473 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
474 so pick an xid now. */
475 client->xid = arc4random();
476
477 /* Make a DHCPREQUEST packet, and set appropriate per-interface
478 flags. */
479 make_request(client->active);
480 client->destination = iaddr_broadcast;
481 client->first_sending = cur_time;
601f8f90 482 client->interval = 0;
846204b6 483
846204b6
HT
484 /* Send out the first DHCPREQUEST packet. */
485 send_request();
486}
487
488/*
489 * Called when a lease has completely expired and we've
490 * been unable to renew it.
491 */
492void
493state_init(void)
494{
495 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
496 flags. */
497 make_discover(client->active);
498 client->xid = client->packet.xid;
499 client->destination = iaddr_broadcast;
500 client->state = S_SELECTING;
501 client->first_sending = cur_time;
601f8f90 502 client->interval = 0;
846204b6
HT
503
504 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
505 to go out. */
506 send_discover();
507}
508
509/*
510 * state_selecting is called when one or more DHCPOFFER packets
511 * have been received and a configurable period of time has passed.
512 */
513void
514state_selecting(void)
515{
516 struct client_lease *lp, *next, *picked;
517
518 /* Cancel state_selecting and send_discover timeouts, since either
519 one could have got us here. */
520 cancel_timeout(state_selecting);
521 cancel_timeout(send_discover);
522
523 /* We have received one or more DHCPOFFER packets. Currently,
524 the only criterion by which we judge leases is whether or
525 not we get a response when we arp for them. */
526 picked = NULL;
527 for (lp = client->offered_leases; lp; lp = next) {
528 next = lp->next;
529
846204b6 530 if (!picked) {
846204b6 531 picked = lp;
846204b6 532 } else {
7cbe3601
AHJ
533 make_decline(lp);
534 send_decline();
846204b6
HT
535 free_client_lease(lp);
536 }
537 }
538 client->offered_leases = NULL;
539
540 /* If we just tossed all the leases we were offered, go back
541 to square one. */
542 if (!picked) {
543 client->state = S_INIT;
544 state_init();
545 return;
546 }
7cbe3601 547 picked->next = NULL;
846204b6
HT
548
549 /* If it was a BOOTREPLY, we can just take the address right now. */
550 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
551 client->new = picked;
552
553 /* Make up some lease expiry times
554 XXX these should be configurable. */
555 client->new->expiry = cur_time + 12000;
556 client->new->renewal += cur_time + 8000;
557 client->new->rebind += cur_time + 10000;
558
559 client->state = S_REQUESTING;
560
561 /* Bind to the address we received. */
562 bind_lease();
563 return;
564 }
565
566 /* Go to the REQUESTING state. */
567 client->destination = iaddr_broadcast;
568 client->state = S_REQUESTING;
569 client->first_sending = cur_time;
601f8f90 570 client->interval = 0;
846204b6
HT
571
572 /* Make a DHCPREQUEST packet from the lease we picked. */
573 make_request(picked);
574 client->xid = client->packet.xid;
575
576 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
577 free_client_lease(picked);
578
579 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
580 send_request();
581}
582
583void
584dhcpack(struct iaddr client_addr, struct option_data *options)
585{
586 struct client_lease *lease;
587
846204b6
HT
588
589 if (client->state != S_REBOOTING &&
590 client->state != S_REQUESTING &&
591 client->state != S_RENEWING &&
592 client->state != S_REBINDING)
593 return;
594
846204b6
HT
595
596 lease = packet_to_lease(options);
597 if (!lease) {
598 note("packet_to_lease failed.");
599 return;
600 }
601
602 client->new = lease;
603
604 /* Stop resending DHCPREQUEST. */
605 cancel_timeout(send_request);
606
607 /* Figure out the lease time. */
608 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
609 client->new->expiry =
610 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
611 else
612 client->new->expiry = DEFAULT_LEASE_TIME;
613 /* A number that looks negative here is really just very large,
614 because the lease expiry offset is unsigned. */
615 if (client->new->expiry < 0)
616 client->new->expiry = TIME_MAX;
617 /* XXX should be fixed by resetting the client state */
618 if (client->new->expiry < 60)
619 client->new->expiry = 60;
620
621 /* Take the server-provided renewal time if there is one;
622 otherwise figure it out according to the spec. */
623 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
624 client->new->renewal =
625 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
626 else
627 client->new->renewal = client->new->expiry / 2;
628
629 /* Same deal with the rebind time. */
630 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
631 client->new->rebind =
632 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
633 else
634 client->new->rebind = client->new->renewal +
635 client->new->renewal / 2 + client->new->renewal / 4;
636
637 client->new->expiry += cur_time;
638 /* Lease lengths can never be negative. */
639 if (client->new->expiry < cur_time)
640 client->new->expiry = TIME_MAX;
641 client->new->renewal += cur_time;
642 if (client->new->renewal < cur_time)
643 client->new->renewal = TIME_MAX;
644 client->new->rebind += cur_time;
645 if (client->new->rebind < cur_time)
646 client->new->rebind = TIME_MAX;
647
648 bind_lease();
649}
650
651void
652bind_lease(void)
653{
846204b6
HT
654 /* Run the client script with the new parameters. */
655 script_init((client->state == S_REQUESTING ? "BOUND" :
656 (client->state == S_RENEWING ? "RENEW" :
7cbe3601 657 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
846204b6
HT
658 if (client->active && client->state != S_REBOOTING)
659 script_write_params("old_", client->active);
660 script_write_params("new_", client->new);
846204b6
HT
661 script_go();
662
663 /* Replace the old active lease with the new one. */
664 if (client->active)
665 free_client_lease(client->active);
666 client->active = client->new;
667 client->new = NULL;
668
cc08537d
AHJ
669 /* Write out new leases file. */
670 rewrite_client_leases();
671
846204b6
HT
672 /* Set up a timeout to start the renewal process. */
673 add_timeout(client->active->renewal, state_bound);
674
675 note("bound to %s -- renewal in %ld seconds.",
676 piaddr(client->active->address),
677 client->active->renewal - cur_time);
678 client->state = S_BOUND;
679 reinitialize_interface();
680 go_daemon();
681}
682
683/*
684 * state_bound is called when we've successfully bound to a particular
685 * lease, but the renewal time on that lease has expired. We are
686 * expected to unicast a DHCPREQUEST to the server that gave us our
687 * original lease.
688 */
689void
690state_bound(void)
691{
692 /* T1 has expired. */
693 make_request(client->active);
694 client->xid = client->packet.xid;
695
696 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
697 memcpy(client->destination.iabuf,
698 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
699 4);
700 client->destination.len = 4;
701 } else
702 client->destination = iaddr_broadcast;
703
704 client->first_sending = cur_time;
601f8f90 705 client->interval = 0;
846204b6
HT
706 client->state = S_RENEWING;
707
708 /* Send the first packet immediately. */
709 send_request();
710}
711
712void
713dhcpoffer(struct iaddr client_addr, struct option_data *options)
714{
715 struct client_lease *lease, *lp;
716 int i;
7cbe3601 717 int stop_selecting;
846204b6
HT
718 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
719 "BOOTREPLY";
720
846204b6
HT
721
722 if (client->state != S_SELECTING)
723 return;
724
846204b6
HT
725
726 /* If this lease doesn't supply the minimum required parameters,
727 blow it off. */
728 for (i = 0; config->required_options[i]; i++) {
729 if (!options[config->required_options[i]].len) {
730 note("%s isn't satisfactory.", name);
731 return;
732 }
733 }
734
735 /* If we've already seen this lease, don't record it again. */
736 for (lease = client->offered_leases;
737 lease; lease = lease->next) {
738 if (lease->address.len == sizeof(client->packet.yiaddr) &&
739 !memcmp(lease->address.iabuf,
740 &client->packet.yiaddr, lease->address.len)) {
4cada237 741#ifdef DEBUG
846204b6 742 debug("%s already seen.", name);
4cada237 743#endif
846204b6
HT
744 return;
745 }
746 }
747
748 lease = packet_to_lease(options);
749 if (!lease) {
750 note("packet_to_lease failed.");
751 return;
752 }
753
754 /* If this lease was acquired through a BOOTREPLY, record that
755 fact. */
756 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
757 lease->is_bootp = 1;
758
846204b6
HT
759 /* Figure out when we're supposed to stop selecting. */
760 stop_selecting = client->first_sending + config->select_interval;
761
762 /* If this is the lease we asked for, put it at the head of the
763 list, and don't mess with the arp request timeout. */
c3b31e60 764 if (addr_eq(lease->address, client->requested_address)) {
846204b6
HT
765 lease->next = client->offered_leases;
766 client->offered_leases = lease;
767 } else {
846204b6
HT
768 /* Put the lease at the end of the list. */
769 lease->next = NULL;
770 if (!client->offered_leases)
771 client->offered_leases = lease;
772 else {
773 for (lp = client->offered_leases; lp->next;
774 lp = lp->next)
775 ; /* nothing */
776 lp->next = lease;
777 }
778 }
779
846204b6
HT
780 /* If the selecting interval has expired, go immediately to
781 state_selecting(). Otherwise, time out into
782 state_selecting at the select interval. */
601f8f90 783 if (stop_selecting <= cur_time)
846204b6
HT
784 state_selecting();
785 else {
786 add_timeout(stop_selecting, state_selecting);
787 cancel_timeout(send_discover);
788 }
789}
790
791/*
792 * Allocate a client_lease structure and initialize it from the
793 * parameters in the specified packet.
794 */
795struct client_lease *
796packet_to_lease(struct option_data *options)
797{
798 struct client_lease *lease;
799 int i;
800
801 lease = malloc(sizeof(struct client_lease));
802
803 if (!lease) {
804 warning("dhcpoffer: no memory to record lease.");
805 return (NULL);
806 }
807
808 memset(lease, 0, sizeof(*lease));
809
810 /* Copy the lease options. */
811 for (i = 0; i < 256; i++) {
812 if (options[i].len) {
813 lease->options[i] = options[i];
814 options[i].data = NULL;
815 options[i].len = 0;
816 if (!check_option(lease, i)) {
817 warning("Invalid lease option - ignoring offer");
818 free_client_lease(lease);
819 return (NULL);
820 }
821 }
822 }
823
824 lease->address.len = sizeof(client->packet.yiaddr);
825 memcpy(lease->address.iabuf, &client->packet.yiaddr,
826 lease->address.len);
827
828 /* If the server name was filled out, copy it. */
829 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
830 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
831 client->packet.sname[0]) {
832 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
833 if (!lease->server_name) {
834 warning("dhcpoffer: no memory for server name.");
835 free_client_lease(lease);
836 return (NULL);
837 }
838 memcpy(lease->server_name, client->packet.sname,
839 DHCP_SNAME_LEN);
840 lease->server_name[DHCP_SNAME_LEN] = '\0';
841 if (!res_hnok(lease->server_name)) {
842 warning("Bogus server name %s", lease->server_name);
843 free(lease->server_name);
844 lease->server_name = NULL;
845 }
846 }
847
848 /* Ditto for the filename. */
849 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
850 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
851 client->packet.file[0]) {
852 /* Don't count on the NUL terminator. */
853 lease->filename = malloc(DHCP_FILE_LEN + 1);
854 if (!lease->filename) {
855 warning("dhcpoffer: no memory for filename.");
856 free_client_lease(lease);
857 return (NULL);
858 }
859 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
860 lease->filename[DHCP_FILE_LEN] = '\0';
861 }
862 return lease;
863}
864
865void
866dhcpnak(struct iaddr client_addr, struct option_data *options)
867{
846204b6
HT
868
869 if (client->state != S_REBOOTING &&
870 client->state != S_REQUESTING &&
871 client->state != S_RENEWING &&
872 client->state != S_REBINDING)
873 return;
874
846204b6
HT
875
876 if (!client->active) {
877 note("DHCPNAK with no active lease.");
878 return;
879 }
880
881 free_client_lease(client->active);
882 client->active = NULL;
883
884 /* Stop sending DHCPREQUEST packets... */
885 cancel_timeout(send_request);
886
887 client->state = S_INIT;
888 state_init();
889}
890
891/*
892 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
893 * one after the right interval has expired. If we don't get an offer by
894 * the time we reach the panic interval, call the panic function.
895 */
896void
897send_discover(void)
898{
899 int interval, increase = 1;
900
901 /* Figure out how long it's been since we started transmitting. */
902 interval = cur_time - client->first_sending;
903
904 /* If we're past the panic timeout, call the script and tell it
905 we haven't found anything for this interface yet. */
906 if (interval > config->timeout) {
907 state_panic();
908 return;
909 }
910
846204b6
HT
911 /*
912 * If we're supposed to increase the interval, do so. If it's
913 * currently zero (i.e., we haven't sent any packets yet), set
914 * it to initial_interval; otherwise, add to it a random
915 * number between zero and two times itself. On average, this
916 * means that it will double with every transmission.
917 */
918 if (increase) {
919 if (!client->interval)
920 client->interval = config->initial_interval;
921 else {
922 client->interval += (arc4random() >> 2) %
923 (2 * client->interval);
924 }
925
926 /* Don't backoff past cutoff. */
927 if (client->interval > config->backoff_cutoff)
928 client->interval = ((config->backoff_cutoff / 2)
929 + ((arc4random() >> 2) %
930 config->backoff_cutoff));
931 } else if (!client->interval)
932 client->interval = config->initial_interval;
933
934 /* If the backoff would take us to the panic timeout, just use that
935 as the interval. */
936 if (cur_time + client->interval >
937 client->first_sending + config->timeout)
938 client->interval = (client->first_sending +
939 config->timeout) - cur_time + 1;
940
941 /* Record the number of seconds since we started sending. */
942 if (interval < 65536)
943 client->packet.secs = htons(interval);
944 else
945 client->packet.secs = htons(65535);
946 client->secs = client->packet.secs;
947
948 note("DHCPDISCOVER on %s to %s port %d interval %ld",
949 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
950 ntohs(sockaddr_broadcast.sin_port), client->interval);
951
952 /* Send out a packet. */
953 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
954
955 add_timeout(cur_time + client->interval, send_discover);
956}
957
958/*
959 * state_panic gets called if we haven't received any offers in a preset
960 * amount of time. When this happens, we try to use existing leases
961 * that haven't yet expired, and failing that, we call the client script
962 * and hope it can do something.
963 */
964void
965state_panic(void)
966{
967 struct client_lease *loop = client->active;
968 struct client_lease *lp;
969
970 note("No DHCPOFFERS received.");
971
972 /* We may not have an active lease, but we may have some
973 predefined leases that we can try. */
974 if (!client->active && client->leases)
975 goto activate_next;
976
977 /* Run through the list of leases and see if one can be used. */
978 while (client->active) {
979 if (client->active->expiry > cur_time) {
980 note("Trying recorded lease %s",
981 piaddr(client->active->address));
982 /* Run the client script with the existing
983 parameters. */
7cbe3601 984 script_init("TIMEOUT");
846204b6 985 script_write_params("new_", client->active);
846204b6
HT
986
987 /* If the old lease is still good and doesn't
988 yet need renewal, go into BOUND state and
989 timeout at the renewal time. */
990 if (!script_go()) {
991 if (cur_time <
992 client->active->renewal) {
993 client->state = S_BOUND;
994 note("bound: renewal in %ld seconds.",
995 client->active->renewal -
996 cur_time);
997 add_timeout(client->active->renewal,
998 state_bound);
999 } else {
1000 client->state = S_BOUND;
1001 note("bound: immediate renewal.");
1002 state_bound();
1003 }
1004 reinitialize_interface();
1005 go_daemon();
1006 return;
1007 }
1008 }
1009
1010 /* If there are no other leases, give up. */
1011 if (!client->leases) {
1012 client->leases = client->active;
1013 client->active = NULL;
1014 break;
1015 }
1016
1017activate_next:
1018 /* Otherwise, put the active lease at the end of the
1019 lease list, and try another lease.. */
1020 for (lp = client->leases; lp->next; lp = lp->next)
1021 ;
1022 lp->next = client->active;
1023 if (lp->next)
1024 lp->next->next = NULL;
1025 client->active = client->leases;
1026 client->leases = client->leases->next;
1027
1028 /* If we already tried this lease, we've exhausted the
1029 set of leases, so we might as well give up for
1030 now. */
1031 if (client->active == loop)
1032 break;
1033 else if (!loop)
1034 loop = client->active;
1035 }
1036
1037 /* No leases were available, or what was available didn't work, so
1038 tell the shell script that we failed to allocate an address,
1039 and try again later. */
1040 note("No working leases in persistent database - sleeping.");
7cbe3601 1041 script_init("FAIL");
846204b6
HT
1042 script_go();
1043 client->state = S_INIT;
1044 add_timeout(cur_time + config->retry_interval, state_init);
1045 go_daemon();
1046}
1047
1048void
1049send_request(void)
1050{
1051 struct sockaddr_in destination;
1052 struct in_addr from;
1053 int interval;
1054
1055 /* Figure out how long it's been since we started transmitting. */
1056 interval = cur_time - client->first_sending;
1057
1058 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1059 past the reboot timeout, go to INIT and see if we can
1060 DISCOVER an address... */
1061 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1062 means either that we're on a network with no DHCP server,
1063 or that our server is down. In the latter case, assuming
1064 that there is a backup DHCP server, DHCPDISCOVER will get
1065 us a new address, but we could also have successfully
1066 reused our old address. In the former case, we're hosed
1067 anyway. This is not a win-prone situation. */
1068 if ((client->state == S_REBOOTING ||
1069 client->state == S_REQUESTING) &&
1070 interval > config->reboot_timeout) {
846204b6
HT
1071 client->state = S_INIT;
1072 cancel_timeout(send_request);
1073 state_init();
1074 return;
1075 }
1076
846204b6
HT
1077 /* If the lease has expired, relinquish the address and go back
1078 to the INIT state. */
1079 if (client->state != S_REQUESTING &&
1080 cur_time > client->active->expiry) {
1081 /* Run the client script with the new parameters. */
7cbe3601 1082 script_init("EXPIRE");
846204b6 1083 script_write_params("old_", client->active);
846204b6
HT
1084 script_go();
1085
1086 client->state = S_INIT;
1087 state_init();
1088 return;
1089 }
1090
1091 /* Do the exponential backoff... */
1092 if (!client->interval)
1093 client->interval = config->initial_interval;
1094 else
1095 client->interval += ((arc4random() >> 2) %
1096 (2 * client->interval));
1097
1098 /* Don't backoff past cutoff. */
1099 if (client->interval > config->backoff_cutoff)
1100 client->interval = ((config->backoff_cutoff / 2) +
1101 ((arc4random() >> 2) % client->interval));
1102
1103 /* If the backoff would take us to the expiry time, just set the
1104 timeout to the expiry time. */
1105 if (client->state != S_REQUESTING && cur_time + client->interval >
1106 client->active->expiry)
1107 client->interval = client->active->expiry - cur_time + 1;
1108
1109 /* If the lease T2 time has elapsed, or if we're not yet bound,
1110 broadcast the DHCPREQUEST rather than unicasting. */
1111 memset(&destination, 0, sizeof(destination));
1112 if (client->state == S_REQUESTING ||
1113 client->state == S_REBOOTING ||
1114 cur_time > client->active->rebind)
1115 destination.sin_addr.s_addr = INADDR_BROADCAST;
1116 else
1117 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1118 sizeof(destination.sin_addr.s_addr));
1119 destination.sin_port = htons(REMOTE_PORT);
1120 destination.sin_family = AF_INET;
1121 destination.sin_len = sizeof(destination);
1122
1123 if (client->state != S_REQUESTING)
1124 memcpy(&from, client->active->address.iabuf, sizeof(from));
1125 else
1126 from.s_addr = INADDR_ANY;
1127
1128 /* Record the number of seconds since we started sending. */
1129 if (client->state == S_REQUESTING)
1130 client->packet.secs = client->secs;
1131 else {
1132 if (interval < 65536)
1133 client->packet.secs = htons(interval);
1134 else
1135 client->packet.secs = htons(65535);
1136 }
1137
1138 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1139 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1140
1141 /* Send out a packet. */
1142 send_packet(from, &destination, NULL);
1143
1144 add_timeout(cur_time + client->interval, send_request);
1145}
1146
1147void
1148send_decline(void)
1149{
1150 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1151 inet_ntoa(sockaddr_broadcast.sin_addr),
1152 ntohs(sockaddr_broadcast.sin_port));
1153
1154 /* Send out a packet. */
1155 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1156}
1157
1158void
1159make_discover(struct client_lease *lease)
1160{
1161 unsigned char discover = DHCPDISCOVER;
1162 struct option_data options[256];
1163 int i;
1164
1165 memset(options, 0, sizeof(options));
1166 memset(&client->packet, 0, sizeof(client->packet));
1167
1168 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1169 i = DHO_DHCP_MESSAGE_TYPE;
1170 options[i].data = &discover;
1171 options[i].len = sizeof(discover);
1172
1173 /* Request the options we want */
1174 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1175 options[i].data = config->requested_options;
1176 options[i].len = config->requested_option_count;
1177
1178 /* If we had an address, try to get it again. */
1179 if (lease) {
1180 client->requested_address = lease->address;
1181 i = DHO_DHCP_REQUESTED_ADDRESS;
1182 options[i].data = lease->address.iabuf;
1183 options[i].len = lease->address.len;
1184 } else
1185 client->requested_address.len = 0;
1186
1187 /* Send any options requested in the config file. */
1188 for (i = 0; i < 256; i++)
1189 if (!options[i].data &&
1190 config->send_options[i].data) {
1191 options[i].data = config->send_options[i].data;
1192 options[i].len = config->send_options[i].len;
1193 }
1194
1195 /* Set up the option buffer to fit in a minimal UDP packet. */
741bbb9f 1196 i = cons_options(options);
846204b6
HT
1197 if (i == -1 || client->packet.options[i] != DHO_END)
1198 error("options do not fit in DHCPDISCOVER packet.");
1199 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1200 if (client->packet_length < BOOTP_MIN_LEN)
1201 client->packet_length = BOOTP_MIN_LEN;
1202
1203 client->packet.op = BOOTREQUEST;
1204 client->packet.htype = ifi->hw_address.htype;
1205 client->packet.hlen = ifi->hw_address.hlen;
1206 client->packet.hops = 0;
1207 client->packet.xid = arc4random();
1208 client->packet.secs = 0; /* filled in by send_discover. */
1209 client->packet.flags = 0;
1210
1211 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1212 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1213 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1214 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1215 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1216 ifi->hw_address.hlen);
1217}
1218
1219void
1220make_request(struct client_lease * lease)
1221{
1222 unsigned char request = DHCPREQUEST;
1223 struct option_data options[256];
1224 int i;
1225
1226 memset(options, 0, sizeof(options));
1227 memset(&client->packet, 0, sizeof(client->packet));
1228
1229 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1230 i = DHO_DHCP_MESSAGE_TYPE;
1231 options[i].data = &request;
1232 options[i].len = sizeof(request);
1233
1234 /* Request the options we want */
1235 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1236 options[i].data = config->requested_options;
1237 options[i].len = config->requested_option_count;
1238
1239 /* If we are requesting an address that hasn't yet been assigned
1240 to us, use the DHCP Requested Address option. */
1241 if (client->state == S_REQUESTING) {
1242 /* Send back the server identifier... */
1243 i = DHO_DHCP_SERVER_IDENTIFIER;
1244 options[i].data = lease->options[i].data;
1245 options[i].len = lease->options[i].len;
1246 }
1247 if (client->state == S_REQUESTING ||
1248 client->state == S_REBOOTING) {
1249 client->requested_address = lease->address;
1250 i = DHO_DHCP_REQUESTED_ADDRESS;
1251 options[i].data = lease->address.iabuf;
1252 options[i].len = lease->address.len;
1253 } else
1254 client->requested_address.len = 0;
1255
1256 /* Send any options requested in the config file. */
1257 for (i = 0; i < 256; i++)
1258 if (!options[i].data && config->send_options[i].data) {
1259 options[i].data = config->send_options[i].data;
1260 options[i].len = config->send_options[i].len;
1261 }
1262
1263 /* Set up the option buffer to fit in a minimal UDP packet. */
741bbb9f 1264 i = cons_options(options);
846204b6
HT
1265 if (i == -1 || client->packet.options[i] != DHO_END)
1266 error("options do not fit in DHCPREQUEST packet.");
1267 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1268 if (client->packet_length < BOOTP_MIN_LEN)
1269 client->packet_length = BOOTP_MIN_LEN;
1270
1271 client->packet.op = BOOTREQUEST;
1272 client->packet.htype = ifi->hw_address.htype;
1273 client->packet.hlen = ifi->hw_address.hlen;
1274 client->packet.hops = 0;
1275 client->packet.xid = client->xid;
1276 client->packet.secs = 0; /* Filled in by send_request. */
1277 client->packet.flags = 0;
1278
1279 /* If we own the address we're requesting, put it in ciaddr;
1280 otherwise set ciaddr to zero. */
1281 if (client->state == S_BOUND ||
1282 client->state == S_RENEWING ||
1283 client->state == S_REBINDING) {
1284 memcpy(&client->packet.ciaddr,
1285 lease->address.iabuf, lease->address.len);
1286 } else {
1287 memset(&client->packet.ciaddr, 0,
1288 sizeof(client->packet.ciaddr));
1289 }
1290
1291 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1292 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1293 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1294 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1295 ifi->hw_address.hlen);
1296}
1297
1298void
1299make_decline(struct client_lease *lease)
1300{
1301 struct option_data options[256];
1302 unsigned char decline = DHCPDECLINE;
1303 int i;
1304
1305 memset(options, 0, sizeof(options));
1306 memset(&client->packet, 0, sizeof(client->packet));
1307
1308 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1309 i = DHO_DHCP_MESSAGE_TYPE;
1310 options[i].data = &decline;
1311 options[i].len = sizeof(decline);
1312
1313 /* Send back the server identifier... */
1314 i = DHO_DHCP_SERVER_IDENTIFIER;
1315 options[i].data = lease->options[i].data;
1316 options[i].len = lease->options[i].len;
1317
1318 /* Send back the address we're declining. */
1319 i = DHO_DHCP_REQUESTED_ADDRESS;
1320 options[i].data = lease->address.iabuf;
1321 options[i].len = lease->address.len;
1322
1323 /* Send the uid if the user supplied one. */
1324 i = DHO_DHCP_CLIENT_IDENTIFIER;
1325 if (config->send_options[i].len) {
1326 options[i].data = config->send_options[i].data;
1327 options[i].len = config->send_options[i].len;
1328 }
1329
1330 /* Set up the option buffer to fit in a minimal UDP packet. */
741bbb9f 1331 i = cons_options(options);
846204b6
HT
1332 if (i == -1 || client->packet.options[i] != DHO_END)
1333 error("options do not fit in DHCPDECLINE packet.");
1334 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1335 if (client->packet_length < BOOTP_MIN_LEN)
1336 client->packet_length = BOOTP_MIN_LEN;
1337
1338 client->packet.op = BOOTREQUEST;
1339 client->packet.htype = ifi->hw_address.htype;
1340 client->packet.hlen = ifi->hw_address.hlen;
1341 client->packet.hops = 0;
1342 client->packet.xid = client->xid;
1343 client->packet.secs = 0; /* Filled in by send_request. */
1344 client->packet.flags = 0;
1345
1346 /* ciaddr must always be zero. */
1347 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1348 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1349 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1350 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1351 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1352 ifi->hw_address.hlen);
1353}
1354
1355void
1356free_client_lease(struct client_lease *lease)
1357{
1358 int i;
1359
1360 if (lease->server_name)
1361 free(lease->server_name);
1362 if (lease->filename)
1363 free(lease->filename);
1364 for (i = 0; i < 256; i++) {
1365 if (lease->options[i].len)
1366 free(lease->options[i].data);
1367 }
1368 free(lease);
1369}
1370
1371void
1372rewrite_client_leases(void)
1373{
1374 struct client_lease *lp;
1375
1376 if (!leaseFile) /* XXX */
1377 error("lease file not open");
1378
1379 fflush(leaseFile);
1380 rewind(leaseFile);
1381
cc08537d
AHJ
1382 for (lp = client->leases; lp; lp = lp->next) {
1383 if (client->active && addr_eq(lp->address,
1384 client->active->address))
1385 continue;
1386 write_client_lease(lp);
1387 }
1388
846204b6 1389 if (client->active)
cc08537d 1390 write_client_lease(client->active);
846204b6
HT
1391
1392 fflush(leaseFile);
1393 ftruncate(fileno(leaseFile), ftello(leaseFile));
1394 fsync(fileno(leaseFile));
1395}
1396
1397void
cc08537d 1398write_client_lease(struct client_lease *lease)
846204b6 1399{
846204b6
HT
1400 struct tm *t;
1401 int i;
1402
846204b6
HT
1403 /* If the lease came from the config file, we don't need to stash
1404 a copy in the lease database. */
1405 if (lease->is_static)
1406 return;
1407
1408 if (!leaseFile) /* XXX */
1409 error("lease file not open");
1410
1411 fprintf(leaseFile, "lease {\n");
1412 if (lease->is_bootp)
1413 fprintf(leaseFile, " bootp;\n");
1414 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1415 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1416 if (lease->filename)
1417 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1418 if (lease->server_name)
1419 fprintf(leaseFile, " server-name \"%s\";\n",
1420 lease->server_name);
846204b6
HT
1421 for (i = 0; i < 256; i++)
1422 if (lease->options[i].len)
1423 fprintf(leaseFile, " option %s %s;\n",
1424 dhcp_options[i].name,
1425 pretty_print_option(i, lease->options[i].data,
1426 lease->options[i].len, 1, 1));
1427
1428 t = gmtime(&lease->renewal);
1429 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1430 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1431 t->tm_hour, t->tm_min, t->tm_sec);
1432 t = gmtime(&lease->rebind);
1433 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1434 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1435 t->tm_hour, t->tm_min, t->tm_sec);
1436 t = gmtime(&lease->expiry);
1437 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1438 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1439 t->tm_hour, t->tm_min, t->tm_sec);
1440 fprintf(leaseFile, "}\n");
1441 fflush(leaseFile);
1442}
1443
1444void
7cbe3601 1445script_init(char *reason)
846204b6 1446{
7cbe3601 1447 size_t len;
846204b6
HT
1448 struct imsg_hdr hdr;
1449 struct buf *buf;
1450
846204b6 1451 hdr.code = IMSG_SCRIPT_INIT;
7cbe3601 1452 hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
846204b6
HT
1453 buf = buf_open(hdr.len);
1454
1455 buf_add(buf, &hdr, sizeof(hdr));
846204b6
HT
1456 len = strlen(reason);
1457 buf_add(buf, &len, sizeof(len));
1458 buf_add(buf, reason, len);
1459
1460 buf_close(privfd, buf);
1461}
1462
1463void
7cbe3601 1464priv_script_init(char *reason)
846204b6
HT
1465{
1466 client->scriptEnvsize = 100;
1467 if (client->scriptEnv == NULL)
1468 client->scriptEnv =
1469 calloc(client->scriptEnvsize, sizeof(char *));
1470 if (client->scriptEnv == NULL)
1471 error("script_init: no memory for environment");
1472
1473 client->scriptEnv[0] = strdup(CLIENT_PATH);
1474 if (client->scriptEnv[0] == NULL)
1475 error("script_init: no memory for environment");
1476
1477 client->scriptEnv[1] = NULL;
1478
1479 script_set_env("", "interface", ifi->name);
1480
846204b6
HT
1481 script_set_env("", "reason", reason);
1482}
1483
1484void
1485priv_script_write_params(char *prefix, struct client_lease *lease)
1486{
1487 u_int8_t dbuf[1500];
1488 int i, len = 0;
1489 char tbuf[128];
1490
1491 script_set_env(prefix, "ip_address", piaddr(lease->address));
1492
1493 if (lease->options[DHO_SUBNET_MASK].len &&
1494 (lease->options[DHO_SUBNET_MASK].len <
1495 sizeof(lease->address.iabuf))) {
1496 struct iaddr netmask, subnet, broadcast;
1497
1498 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1499 lease->options[DHO_SUBNET_MASK].len);
1500 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1501
1502 subnet = subnet_number(lease->address, netmask);
1503 if (subnet.len) {
1504 script_set_env(prefix, "network_number",
1505 piaddr(subnet));
1506 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1507 broadcast = broadcast_addr(subnet, netmask);
1508 if (broadcast.len)
1509 script_set_env(prefix,
1510 "broadcast_address",
1511 piaddr(broadcast));
1512 }
1513 }
1514 }
1515
1516 if (lease->filename)
1517 script_set_env(prefix, "filename", lease->filename);
1518 if (lease->server_name)
1519 script_set_env(prefix, "server_name",
1520 lease->server_name);
1521 for (i = 0; i < 256; i++) {
1522 u_int8_t *dp = NULL;
1523
1524 if (config->defaults[i].len) {
1525 if (lease->options[i].len) {
1526 switch (config->default_actions[i]) {
1527 case ACTION_DEFAULT:
1528 dp = lease->options[i].data;
1529 len = lease->options[i].len;
1530 break;
1531 case ACTION_SUPERSEDE:
1532supersede:
1533 dp = config->defaults[i].data;
1534 len = config->defaults[i].len;
1535 break;
1536 case ACTION_PREPEND:
1537 len = config->defaults[i].len +
1538 lease->options[i].len;
c1b95e62 1539 if (len >= sizeof(dbuf)) {
846204b6
HT
1540 warning("no space to %s %s",
1541 "prepend option",
1542 dhcp_options[i].name);
1543 goto supersede;
1544 }
1545 dp = dbuf;
1546 memcpy(dp,
1547 config->defaults[i].data,
1548 config->defaults[i].len);
1549 memcpy(dp +
1550 config->defaults[i].len,
1551 lease->options[i].data,
1552 lease->options[i].len);
1553 dp[len] = '\0';
1554 break;
1555 case ACTION_APPEND:
1556 len = config->defaults[i].len +
1557 lease->options[i].len;
c1b95e62 1558 if (len >= sizeof(dbuf)) {
846204b6
HT
1559 warning("no space to %s %s",
1560 "append option",
1561 dhcp_options[i].name);
1562 goto supersede;
1563 }
1564 dp = dbuf;
1565 memcpy(dp, lease->options[i].data,
1566 lease->options[i].len);
1567 memcpy(dp + lease->options[i].len,
1568 config->defaults[i].data,
1569 config->defaults[i].len);
1570 dp[len] = '\0';
1571 }
1572 } else {
1573 dp = config->defaults[i].data;
1574 len = config->defaults[i].len;
1575 }
1576 } else if (lease->options[i].len) {
1577 len = lease->options[i].len;
1578 dp = lease->options[i].data;
1579 } else {
1580 len = 0;
1581 }
1582 if (len) {
1583 char name[256];
1584
1585 if (dhcp_option_ev_name(name, sizeof(name),
1586 &dhcp_options[i]))
1587 script_set_env(prefix, name,
1588 pretty_print_option(i, dp, len, 0, 0));
1589 }
1590 }
1591 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1592 script_set_env(prefix, "expiry", tbuf);
1593}
1594
1595void
1596script_write_params(char *prefix, struct client_lease *lease)
1597{
1598 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1599 struct imsg_hdr hdr;
1600 struct buf *buf;
1601 int i;
1602
1603 if (lease->filename != NULL)
1604 fn_len = strlen(lease->filename);
1605 if (lease->server_name != NULL)
1606 sn_len = strlen(lease->server_name);
1607 if (prefix != NULL)
1608 pr_len = strlen(prefix);
1609
1610 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1611 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1612 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1613 sizeof(size_t) + pr_len;
1614
1615 for (i = 0; i < 256; i++)
1616 hdr.len += sizeof(int) + lease->options[i].len;
1617
1618 scripttime = time(NULL);
1619
1620 buf = buf_open(hdr.len);
1621
1622 buf_add(buf, &hdr, sizeof(hdr));
1623 buf_add(buf, lease, sizeof(struct client_lease));
1624 buf_add(buf, &fn_len, sizeof(fn_len));
1625 buf_add(buf, lease->filename, fn_len);
1626 buf_add(buf, &sn_len, sizeof(sn_len));
1627 buf_add(buf, lease->server_name, sn_len);
1628 buf_add(buf, &pr_len, sizeof(pr_len));
1629 buf_add(buf, prefix, pr_len);
1630
1631 for (i = 0; i < 256; i++) {
1632 buf_add(buf, &lease->options[i].len,
1633 sizeof(lease->options[i].len));
1634 buf_add(buf, lease->options[i].data,
1635 lease->options[i].len);
1636 }
1637
1638 buf_close(privfd, buf);
1639}
1640
1641int
1642script_go(void)
1643{
1644 struct imsg_hdr hdr;
1645 struct buf *buf;
1646 int ret;
1647
1648 scripttime = time(NULL);
1649
1650 hdr.code = IMSG_SCRIPT_GO;
1651 hdr.len = sizeof(struct imsg_hdr);
1652
1653 buf = buf_open(hdr.len);
1654
1655 buf_add(buf, &hdr, sizeof(hdr));
1656 buf_close(privfd, buf);
1657
1658 bzero(&hdr, sizeof(hdr));
1659 buf_read(privfd, &hdr, sizeof(hdr));
1660 if (hdr.code != IMSG_SCRIPT_GO_RET)
1661 error("unexpected msg type %u", hdr.code);
1662 if (hdr.len != sizeof(hdr) + sizeof(int))
1663 error("received corrupted message");
1664 buf_read(privfd, &ret, sizeof(ret));
1665
1666 return (ret);
1667}
1668
1669int
1670priv_script_go(void)
1671{
1672 char *scriptName, *argv[2], **envp;
1673 int pid, wpid, wstatus;
1674
1675 scripttime = time(NULL);
1676
1677 scriptName = config->script_name;
1678 envp = client->scriptEnv;
1679
1680 argv[0] = scriptName;
1681 argv[1] = NULL;
1682
1683 pid = fork();
1684 if (pid < 0) {
1685 error("fork: %m");
1686 wstatus = 0;
1687 } else if (pid) {
1688 do {
1689 wpid = wait(&wstatus);
1690 } while (wpid != pid && wpid > 0);
1691 if (wpid < 0) {
1692 error("wait: %m");
1693 wstatus = 0;
1694 }
1695 } else {
1696 execve(scriptName, argv, envp);
1697 error("execve (%s, ...): %m", scriptName);
1698 }
1699
1700 script_flush_env();
1701
1702 return (WEXITSTATUS(wstatus));
1703}
1704
1705void
1706script_set_env(const char *prefix, const char *name, const char *value)
1707{
1708 int i, j, namelen;
1709
1710 namelen = strlen(name);
1711
1712 for (i = 0; client->scriptEnv[i]; i++)
1713 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1714 client->scriptEnv[i][namelen] == '=')
1715 break;
1716
1717 if (client->scriptEnv[i])
1718 /* Reuse the slot. */
1719 free(client->scriptEnv[i]);
1720 else {
1721 /* New variable. Expand if necessary. */
1722 if (i >= client->scriptEnvsize - 1) {
1723 char **newscriptEnv;
1724 int newscriptEnvsize = client->scriptEnvsize + 50;
1725
1726 newscriptEnv = realloc(client->scriptEnv,
1727 newscriptEnvsize);
1728 if (newscriptEnv == NULL) {
1729 free(client->scriptEnv);
1730 client->scriptEnv = NULL;
1731 client->scriptEnvsize = 0;
1732 error("script_set_env: no memory for variable");
1733 }
1734 client->scriptEnv = newscriptEnv;
1735 client->scriptEnvsize = newscriptEnvsize;
1736 }
1737 /* need to set the NULL pointer at end of array beyond
1738 the new slot. */
1739 client->scriptEnv[i + 1] = NULL;
1740 }
1741 /* Allocate space and format the variable in the appropriate slot. */
1742 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1743 strlen(value) + 1);
1744 if (client->scriptEnv[i] == NULL)
1745 error("script_set_env: no memory for variable assignment");
1746
1747 /* No `` or $() command substitution allowed in environment values! */
1748 for (j = 0; j < strlen(value); j++)
1749 switch (value[j]) {
1750 case '`':
1751 case '$':
1752 error("illegal character (%c) in value '%s'", value[j],
1753 value);
1754 /* not reached */
1755 }
1756 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1757 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1758}
1759
1760void
1761script_flush_env(void)
1762{
1763 int i;
1764
1765 for (i = 0; client->scriptEnv[i]; i++) {
1766 free(client->scriptEnv[i]);
1767 client->scriptEnv[i] = NULL;
1768 }
1769 client->scriptEnvsize = 0;
1770}
1771
1772int
1773dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1774{
1775 size_t i;
1776
1777 for (i = 0; option->name[i]; i++) {
1778 if (i + 1 == buflen)
1779 return 0;
1780 if (option->name[i] == '-')
1781 buf[i] = '_';
1782 else
1783 buf[i] = option->name[i];
1784 }
1785
1786 buf[i] = 0;
1787 return 1;
1788}
1789
1790void
1791go_daemon(void)
1792{
1793 static int state = 0;
1794
1795 if (no_daemon || state)
1796 return;
1797
1798 state = 1;
1799
1800 /* Stop logging to stderr... */
1801 log_perror = 0;
1802
1803 if (daemon(1, 0) == -1)
1804 error("daemon");
1805
1806 /* we are chrooted, daemon(3) fails to open /dev/null */
1807 if (nullfd != -1) {
1808 dup2(nullfd, STDIN_FILENO);
1809 dup2(nullfd, STDOUT_FILENO);
1810 dup2(nullfd, STDERR_FILENO);
1811 close(nullfd);
1812 nullfd = -1;
1813 }
1814}
1815
1816int
1817check_option(struct client_lease *l, int option)
1818{
1819 char *opbuf;
1820 char *sbuf;
1821
1822 /* we use this, since this is what gets passed to dhclient-script */
1823
1824 opbuf = pretty_print_option(option, l->options[option].data,
1825 l->options[option].len, 0, 0);
1826
1827 sbuf = option_as_string(option, l->options[option].data,
1828 l->options[option].len);
1829
1830 switch (option) {
1831 case DHO_SUBNET_MASK:
313ef36c
AHJ
1832 case DHO_SWAP_SERVER:
1833 case DHO_BROADCAST_ADDRESS:
1834 case DHO_DHCP_SERVER_IDENTIFIER:
1835 case DHO_ROUTER_SOLICITATION_ADDRESS:
1836 case DHO_DHCP_REQUESTED_ADDRESS:
1837 if (ipv4addrs(opbuf) == 0) {
1838 warning("Invalid IP address in option %s: %s",
1839 dhcp_options[option].name, opbuf);
1840 return (0);
1841 }
1842 if (l->options[option].len != 4) { /* RFC 2132 */
1843 warning("warning: Only 1 IP address allowed in "
1844 "%s option; length %d, must be 4",
1845 dhcp_options[option].name,
1846 l->options[option].len);
1847 l->options[option].len = 4;
1848 }
1849 return (1);
846204b6
HT
1850 case DHO_TIME_SERVERS:
1851 case DHO_NAME_SERVERS:
1852 case DHO_ROUTERS:
1853 case DHO_DOMAIN_NAME_SERVERS:
1854 case DHO_LOG_SERVERS:
1855 case DHO_COOKIE_SERVERS:
1856 case DHO_LPR_SERVERS:
1857 case DHO_IMPRESS_SERVERS:
1858 case DHO_RESOURCE_LOCATION_SERVERS:
846204b6
HT
1859 case DHO_NIS_SERVERS:
1860 case DHO_NTP_SERVERS:
1861 case DHO_NETBIOS_NAME_SERVERS:
1862 case DHO_NETBIOS_DD_SERVER:
1863 case DHO_FONT_SERVERS:
313ef36c
AHJ
1864 if (ipv4addrs(opbuf) == 0) {
1865 warning("Invalid IP address in option %s: %s",
1866 dhcp_options[option].name, opbuf);
846204b6
HT
1867 return (0);
1868 }
1869 return (1);
1870 case DHO_HOST_NAME:
1871 case DHO_DOMAIN_NAME:
1872 case DHO_NIS_DOMAIN:
1873 if (!res_hnok(sbuf)) {
1874 warning("Bogus Host Name option %d: %s (%s)", option,
1875 sbuf, opbuf);
1876 l->options[option].len = 0;
1877 free(l->options[option].data);
1878 }
1879 return (1);
1880 case DHO_PAD:
1881 case DHO_TIME_OFFSET:
1882 case DHO_BOOT_SIZE:
1883 case DHO_MERIT_DUMP:
1884 case DHO_ROOT_PATH:
1885 case DHO_EXTENSIONS_PATH:
1886 case DHO_IP_FORWARDING:
1887 case DHO_NON_LOCAL_SOURCE_ROUTING:
1888 case DHO_POLICY_FILTER:
1889 case DHO_MAX_DGRAM_REASSEMBLY:
1890 case DHO_DEFAULT_IP_TTL:
1891 case DHO_PATH_MTU_AGING_TIMEOUT:
1892 case DHO_PATH_MTU_PLATEAU_TABLE:
1893 case DHO_INTERFACE_MTU:
1894 case DHO_ALL_SUBNETS_LOCAL:
1895 case DHO_PERFORM_MASK_DISCOVERY:
1896 case DHO_MASK_SUPPLIER:
1897 case DHO_ROUTER_DISCOVERY:
846204b6
HT
1898 case DHO_STATIC_ROUTES:
1899 case DHO_TRAILER_ENCAPSULATION:
1900 case DHO_ARP_CACHE_TIMEOUT:
1901 case DHO_IEEE802_3_ENCAPSULATION:
1902 case DHO_DEFAULT_TCP_TTL:
1903 case DHO_TCP_KEEPALIVE_INTERVAL:
1904 case DHO_TCP_KEEPALIVE_GARBAGE:
1905 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1906 case DHO_NETBIOS_NODE_TYPE:
1907 case DHO_NETBIOS_SCOPE:
1908 case DHO_X_DISPLAY_MANAGER:
846204b6
HT
1909 case DHO_DHCP_LEASE_TIME:
1910 case DHO_DHCP_OPTION_OVERLOAD:
1911 case DHO_DHCP_MESSAGE_TYPE:
1912 case DHO_DHCP_PARAMETER_REQUEST_LIST:
1913 case DHO_DHCP_MESSAGE:
1914 case DHO_DHCP_MAX_MESSAGE_SIZE:
1915 case DHO_DHCP_RENEWAL_TIME:
1916 case DHO_DHCP_REBINDING_TIME:
1917 case DHO_DHCP_CLASS_IDENTIFIER:
1918 case DHO_DHCP_CLIENT_IDENTIFIER:
1919 case DHO_DHCP_USER_CLASS_ID:
7a6ba664 1920 case DHO_TFTP_SERVER:
846204b6
HT
1921 case DHO_END:
1922 return (1);
1923 default:
b796b237
AHJ
1924 if (!unknown_ok)
1925 warning("unknown dhcp option value 0x%x", option);
846204b6
HT
1926 return (unknown_ok);
1927 }
1928}
1929
1930int
1931res_hnok(const char *name)
1932{
1933 const char *dn = name;
1934 int pch = '.', ch = *dn++;
1935 int warn = 0;
1936
1937 while (ch != '\0') {
1938 int nch = *dn++;
1939
1940 if (ch == '.') {
1941 ;
1942 } else if (pch == '.' || nch == '.' || nch == '\0') {
1943 if (!isalnum(ch))
1944 return (0);
1945 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1946 return (0);
1947 else if (ch == '_' && warn == 0) {
1948 warning("warning: hostname %s contains an "
1949 "underscore which violates RFC 952", name);
1950 warn++;
1951 }
1952 pch = ch, ch = nch;
1953 }
1954 return (1);
1955}
1956
1957/* Does buf consist only of dotted decimal ipv4 addrs?
1958 * return how many if so,
1959 * otherwise, return 0
1960 */
1961int
1962ipv4addrs(char * buf)
1963{
1964 struct in_addr jnk;
1965 int count = 0;
1966
1967 while (inet_aton(buf, &jnk) == 1){
1968 count++;
1969 while (*buf == '.' || isdigit(*buf))
1970 buf++;
1971 if (*buf == '\0')
1972 return (count);
1973 while (*buf == ' ')
1974 buf++;
1975 }
1976 return (0);
1977}
1978
1979char *
1980option_as_string(unsigned int code, unsigned char *data, int len)
1981{
1982 static char optbuf[32768]; /* XXX */
1983 char *op = optbuf;
1984 int opleft = sizeof(optbuf);
1985 unsigned char *dp = data;
1986
1987 if (code > 255)
1988 error("option_as_string: bad code %d", code);
1989
1990 for (; dp < data + len; dp++) {
1991 if (!isascii(*dp) || !isprint(*dp)) {
1992 if (dp + 1 != data + len || *dp != 0) {
1993 size_t oplen;
1994 snprintf(op, opleft, "\\%03o", *dp);
1995 oplen = strlen(op);
1996 op += oplen;
1997 opleft -= oplen;
1998 }
1999 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2000 *dp == '`' || *dp == '\\') {
2001 *op++ = '\\';
2002 *op++ = *dp;
2003 opleft -= 2;
2004 } else {
2005 *op++ = *dp;
2006 opleft--;
2007 }
2008 }
2009 if (opleft < 1)
2010 goto toobig;
2011 *op = 0;
2012 return optbuf;
2013toobig:
2014 warning("dhcp option too large");
2015 return "<error>";
2016}
2017
2018int
2019fork_privchld(int fd, int fd2)
2020{
2021 struct pollfd pfd[1];
a05d48e6 2022 int nfds, pfail = 0;
846204b6
HT
2023
2024 switch (fork()) {
2025 case -1:
2026 error("cannot fork");
2027 break;
2028 case 0:
2029 break;
2030 default:
2031 return (0);
2032 }
2033
2034 if (chdir("/") == -1)
2035 error("chdir(\"/\")");
2036
2037 setproctitle("%s [priv]", ifi->name);
2038
2039 dup2(nullfd, STDIN_FILENO);
2040 dup2(nullfd, STDOUT_FILENO);
2041 dup2(nullfd, STDERR_FILENO);
2042 close(nullfd);
2043 close(fd2);
2044
2045 for (;;) {
2046 pfd[0].fd = fd;
2047 pfd[0].events = POLLIN;
2048 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2049 if (errno != EINTR)
2050 error("poll error");
2051
a05d48e6
SG
2052 /*
2053 * Handle temporary errors, but bail if they persist.
2054 */
2055 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2056 if (pfail > POLL_FAILURES)
2057 error("poll failed > %d times", POLL_FAILURES);
2058 sleep(pfail * POLL_FAILURE_WAIT);
2059 pfail++;
846204b6 2060 continue;
a05d48e6 2061 }
846204b6
HT
2062
2063 dispatch_imsg(fd);
2064 }
2065}
d63fb838
AHJ
2066
2067void
2068get_ifname(char *ifname, char *arg)
2069{
2070 struct ifgroupreq ifgr;
2071 struct ifg_req *ifg;
2072 int s, len;
2073
2074 if (!strcmp(arg, "egress")) {
2075 s = socket(AF_INET, SOCK_DGRAM, 0);
2076 if (s == -1)
2077 error("socket error");
2078 bzero(&ifgr, sizeof(ifgr));
2079 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2080 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2081 if (errno == ENOENT)
2082 error("no interface in group egress found");
2083 error("ioctl SIOCGIFGMEMB: %m");
2084 }
2085 len = ifgr.ifgr_len;
2086 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2087 error("get_ifname");
2088 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2089 error("ioctl SIOCGIFGMEMB: %m");
2090
2091 arg = NULL;
2092 for (ifg = ifgr.ifgr_groups;
2093 ifg && len >= sizeof(struct ifg_req); ifg++) {
2094 len -= sizeof(struct ifg_req);
2095 if (arg)
2096 error("too many interfaces in group egress");
2097 arg = ifg->ifgrq_member;
2098 }
2099
2100 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2101 error("Interface name too long: %m");
2102
2103 free(ifgr.ifgr_groups);
2104 close(s);
2105 } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2106 error("Interface name too long");
2107}