/
dhclient.c
2099 lines (1819 loc) · 54.6 KB
/
dhclient.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.146 2012/07/09 16:21:21 krw Exp $ */
/*
* Copyright 2004 Henning Brauer <henning@openbsd.org>
* Copyright (c) 1995, 1996, 1997, 1998, 1999
* The Internet Software Consortium. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of The Internet Software Consortium nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software has been written for the Internet Software Consortium
* by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
* Enterprises. To learn more about the Internet Software Consortium,
* see ``http://www.vix.com/isc''. To learn more about Vixie
* Enterprises, see ``http://www.vix.com''.
*
* This client was substantially modified and enhanced by Elliot Poger
* for use on Linux while he was working on the MosquitoNet project at
* Stanford.
*
* The current version owes much to Elliot's Linux enhancements, but
* was substantially reorganized and partially rewritten by Ted Lemon
* so as to use the same networking framework that the Internet Software
* Consortium DHCP server uses. Much system-specific configuration code
* was moved into a shell script so that as support for more operating
* systems is added, it will not be necessary to port and maintain
* system-specific configuration code to these operating systems - instead,
* the shell script can invoke the native tools to accomplish the same
* purpose.
*/
#include <sys/ioctl.h>
#include <ctype.h>
#include <poll.h>
#include <pwd.h>
#include <unistd.h>
#include "dhcpd.h"
#include "privsep.h"
#define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
#define DEFAULT_LEASE_TIME 43200 /* 12 hours... */
#define TIME_MAX 2147483647
#define POLL_FAILURES 10
#define POLL_FAILURE_WAIT 1 /* Back off multiplier (seconds) */
time_t cur_time;
char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
char *path_dhclient_db = NULL;
int log_perror = 1;
int privfd;
int nullfd = -1;
int no_daemon;
int unknown_ok = 1;
int routefd = -1;
struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
struct in_addr inaddr_any;
struct sockaddr_in sockaddr_broadcast;
struct interface_info *ifi;
struct client_state *client;
struct client_config *config;
int findproto(char *, int);
struct sockaddr *get_ifa(char *, int);
void usage(void);
int check_option(struct client_lease *l, int option);
int ipv4addrs(char * buf);
int res_hnok(const char *dn);
char *option_as_string(unsigned int code, unsigned char *data, int len);
int fork_privchld(int, int);
void get_ifname(char *, char *);
#define ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
time_t scripttime;
static FILE *leaseFile;
int
findproto(char *cp, int n)
{
struct sockaddr *sa;
int i;
if (n == 0)
return -1;
for (i = 1; i; i <<= 1) {
if (i & n) {
sa = (struct sockaddr *)cp;
switch (i) {
case RTA_IFA:
case RTA_DST:
case RTA_GATEWAY:
case RTA_NETMASK:
if (sa->sa_family == AF_INET)
return AF_INET;
if (sa->sa_family == AF_INET6)
return AF_INET6;
break;
case RTA_IFP:
break;
}
ADVANCE(cp, sa);
}
}
return (-1);
}
struct sockaddr *
get_ifa(char *cp, int n)
{
struct sockaddr *sa;
int i;
if (n == 0)
return (NULL);
for (i = 1; i; i <<= 1)
if (i & n) {
sa = (struct sockaddr *)cp;
if (i == RTA_IFA)
return (sa);
ADVANCE(cp, sa);
}
return (NULL);
}
struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
void
routehandler(void)
{
int linkstat;
char msg[2048];
struct rt_msghdr *rtm;
struct if_msghdr *ifm;
struct ifa_msghdr *ifam;
struct if_announcemsghdr *ifan;
struct client_lease *l;
time_t t = time(NULL);
struct sockaddr *sa;
struct iaddr a;
ssize_t n;
char *errmsg, buf[64];
do {
n = read(routefd, &msg, sizeof(msg));
} while (n == -1 && errno == EINTR);
rtm = (struct rt_msghdr *)msg;
if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
rtm->rtm_version != RTM_VERSION)
return;
switch (rtm->rtm_type) {
case RTM_NEWADDR:
ifam = (struct ifa_msghdr *)rtm;
if (ifam->ifam_index != ifi->index)
break;
if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
break;
sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
if (sa == NULL) {
errmsg = "sa == NULL";
goto die;
}
if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
error("king bula sez: len mismatch");
memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
if (addr_eq(a, defaddr))
break;
/* state_panic() can try unexpired existing leases */
if (client->active && addr_eq(a, client->active->address))
break;
for (l = client->leases; l != NULL; l = l->next)
if (addr_eq(a, l->address))
break;
if (l != NULL)
/* new addr is the one we set */
break;
snprintf(buf, sizeof(buf), "%s: %s",
"new address not one we set", piaddr(a));
errmsg = buf;
goto die;
case RTM_DELADDR:
ifam = (struct ifa_msghdr *)rtm;
if (ifam->ifam_index != ifi->index)
break;
if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
break;
/* XXX check addrs like RTM_NEWADDR instead of this? */
if (scripttime == 0 || t < scripttime + 10)
break;
errmsg = "interface address deleted";
goto die;
case RTM_IFINFO:
ifm = (struct if_msghdr *)rtm;
if (ifm->ifm_index != ifi->index)
break;
if ((rtm->rtm_flags & RTF_UP) == 0) {
errmsg = "interface down";
goto die;
}
linkstat =
LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
if (linkstat != ifi->linkstat) {
#ifdef DEBUG
debug("link state %s -> %s",
ifi->linkstat ? "up" : "down",
linkstat ? "up" : "down");
#endif
ifi->linkstat = interface_status(ifi->name);
if (ifi->linkstat) {
client->state = S_REBOOTING;
state_reboot();
}
}
break;
case RTM_IFANNOUNCE:
ifan = (struct if_announcemsghdr *)rtm;
if (ifan->ifan_what == IFAN_DEPARTURE &&
ifan->ifan_index == ifi->index) {
errmsg = "interface departure";
goto die;
}
break;
default:
break;
}
return;
die:
script_init("FAIL");
script_go();
error("routehandler: %s", errmsg);
}
int
main(int argc, char *argv[])
{
int ch, fd, quiet = 0, i = 0, pipe_fd[2];
struct passwd *pw;
/* Initially, log errors to stderr as well as to syslogd. */
openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
setlogmask(LOG_UPTO(LOG_INFO));
while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
switch (ch) {
case 'c':
path_dhclient_conf = optarg;
break;
case 'd':
no_daemon = 1;
break;
case 'l':
path_dhclient_db = optarg;
break;
case 'q':
quiet = 1;
break;
case 'u':
unknown_ok = 0;
break;
default:
usage();
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
ifi = calloc(1, sizeof(*ifi));
if (ifi == NULL)
error("ifi calloc");
client = calloc(1, sizeof(*client));
if (client == NULL)
error("client calloc");
config = calloc(1, sizeof(*config));
if (config == NULL)
error("config calloc");
get_ifname(ifi->name, argv[0]);
if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
_PATH_DHCLIENT_DB, ifi->name) == -1)
error("asprintf");
if (quiet)
log_perror = 0;
tzset();
time(&cur_time);
memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
sockaddr_broadcast.sin_family = AF_INET;
sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
inaddr_any.s_addr = INADDR_ANY;
read_client_conf();
if (interface_status(ifi->name) == 0) {
interface_link_forceup(ifi->name);
/* Give it up to 4 seconds of silent grace to find link */
i = -4;
} else
i = 0;
while (!(ifi->linkstat = interface_status(ifi->name))) {
if (i == 0)
fprintf(stderr, "%s: no link ...", ifi->name);
else if (i > 0)
fprintf(stderr, ".");
fflush(stderr);
if (++i > config->link_timeout) {
fprintf(stderr, " sleeping\n");
goto dispatch;
}
sleep(1);
}
if (i > 0)
fprintf(stderr, " got link\n");
dispatch:
if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
error("cannot open %s: %m", _PATH_DEVNULL);
if ((pw = getpwnam("_dhcp")) == NULL)
error("no such user: _dhcp");
if (pipe(pipe_fd) == -1)
error("pipe");
fork_privchld(pipe_fd[0], pipe_fd[1]);
close(pipe_fd[0]);
privfd = pipe_fd[1];
if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
error("can't open and lock %s: %m", path_dhclient_db);
read_client_leases();
if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
error("can't open %s: %m", path_dhclient_db);
rewrite_client_leases();
close(fd);
if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
error("socket(PF_ROUTE, SOCK_RAW): %m");
/* set up the interface */
discover_interface();
if (chroot(_PATH_VAREMPTY) == -1)
error("chroot");
if (chdir("/") == -1)
error("chdir(\"/\")");
if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
error("setresgid");
if (setgroups(1, &pw->pw_gid) == -1)
error("setgroups");
if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
error("setresuid");
endpwent();
setproctitle("%s", ifi->name);
if (ifi->linkstat) {
client->state = S_REBOOTING;
state_reboot();
} else
go_daemon();
dispatch();
/* not reached */
return (0);
}
void
usage(void)
{
fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
getprogname());
exit(1);
}
/*
* Individual States:
*
* Each routine is called from the dhclient_state_machine() in one of
* these conditions:
* -> entering INIT state
* -> recvpacket_flag == 0: timeout in this state
* -> otherwise: received a packet in this state
*
* Return conditions as handled by dhclient_state_machine():
* Returns 1, sendpacket_flag = 1: send packet, reset timer.
* Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
* Returns 0: finish the nap which was interrupted for no good reason.
*
* Several per-interface variables are used to keep track of the process:
* active_lease: the lease that is being used on the interface
* (null pointer if not configured yet).
* offered_leases: leases corresponding to DHCPOFFER messages that have
* been sent to us by DHCP servers.
* acked_leases: leases corresponding to DHCPACK messages that have been
* sent to us by DHCP servers.
* sendpacket: DHCP packet we're trying to send.
* destination: IP address to send sendpacket to
* In addition, there are several relevant per-lease variables.
* T1_expiry, T2_expiry, lease_expiry: lease milestones
* In the active lease, these control the process of renewing the lease;
* In leases on the acked_leases list, this simply determines when we
* can no longer legitimately use the lease.
*/
void
state_reboot(void)
{
/* Cancel all timeouts, since a link state change gets us here
and can happen anytime. */
cancel_timeout();
/* If we don't remember an active lease, go straight to INIT. */
if (!client->active || client->active->is_bootp) {
client->state = S_INIT;
state_init();
return;
}
/* make_request doesn't initialize xid because it normally comes
from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
so pick an xid now. */
client->xid = arc4random();
/* Make a DHCPREQUEST packet, and set appropriate per-interface
flags. */
make_request(client->active);
client->destination = iaddr_broadcast;
client->first_sending = cur_time;
client->interval = 0;
/* Send out the first DHCPREQUEST packet. */
send_request();
}
/*
* Called when a lease has completely expired and we've
* been unable to renew it.
*/
void
state_init(void)
{
/* Make a DHCPDISCOVER packet, and set appropriate per-interface
flags. */
make_discover(client->active);
client->xid = client->packet.xid;
client->destination = iaddr_broadcast;
client->state = S_SELECTING;
client->first_sending = cur_time;
client->interval = 0;
/* Add an immediate timeout to cause the first DHCPDISCOVER packet
to go out. */
send_discover();
}
/*
* state_selecting is called when one or more DHCPOFFER packets
* have been received and a configurable period of time has passed.
*/
void
state_selecting(void)
{
struct client_lease *lp, *next, *picked;
/* Cancel state_selecting and send_discover timeouts, since either
one could have got us here. */
cancel_timeout();
/* We have received one or more DHCPOFFER packets. Currently,
the only criterion by which we judge leases is whether or
not we get a response when we arp for them. */
picked = NULL;
for (lp = client->offered_leases; lp; lp = next) {
next = lp->next;
if (!picked) {
picked = lp;
} else {
make_decline(lp);
send_decline();
free_client_lease(lp);
}
}
client->offered_leases = NULL;
/* If we just tossed all the leases we were offered, go back
to square one. */
if (!picked) {
client->state = S_INIT;
state_init();
return;
}
picked->next = NULL;
/* If it was a BOOTREPLY, we can just take the address right now. */
if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
client->new = picked;
/* Make up some lease expiry times
XXX these should be configurable. */
client->new->expiry = cur_time + 12000;
client->new->renewal += cur_time + 8000;
client->new->rebind += cur_time + 10000;
client->state = S_REQUESTING;
/* Bind to the address we received. */
bind_lease();
return;
}
/* Go to the REQUESTING state. */
client->destination = iaddr_broadcast;
client->state = S_REQUESTING;
client->first_sending = cur_time;
client->interval = 0;
/* Make a DHCPREQUEST packet from the lease we picked. */
make_request(picked);
client->xid = client->packet.xid;
/* Toss the lease we picked - we'll get it back in a DHCPACK. */
free_client_lease(picked);
/* Add an immediate timeout to send the first DHCPREQUEST packet. */
send_request();
}
void
dhcpack(struct iaddr client_addr, struct option_data *options)
{
struct client_lease *lease;
if (client->state != S_REBOOTING &&
client->state != S_REQUESTING &&
client->state != S_RENEWING &&
client->state != S_REBINDING)
return;
lease = packet_to_lease(options);
if (!lease) {
note("packet_to_lease failed.");
return;
}
client->new = lease;
/* Stop resending DHCPREQUEST. */
cancel_timeout();
/* Figure out the lease time. */
if (client->new->options[DHO_DHCP_LEASE_TIME].data)
client->new->expiry =
getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
else
client->new->expiry = DEFAULT_LEASE_TIME;
/* A number that looks negative here is really just very large,
because the lease expiry offset is unsigned. */
if (client->new->expiry < 0)
client->new->expiry = TIME_MAX;
/* XXX should be fixed by resetting the client state */
if (client->new->expiry < 60)
client->new->expiry = 60;
/* Take the server-provided renewal time if there is one;
otherwise figure it out according to the spec. */
if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
client->new->renewal =
getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
else
client->new->renewal = client->new->expiry / 2;
/* Same deal with the rebind time. */
if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
client->new->rebind =
getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
else
client->new->rebind = client->new->renewal +
client->new->renewal / 2 + client->new->renewal / 4;
client->new->expiry += cur_time;
/* Lease lengths can never be negative. */
if (client->new->expiry < cur_time)
client->new->expiry = TIME_MAX;
client->new->renewal += cur_time;
if (client->new->renewal < cur_time)
client->new->renewal = TIME_MAX;
client->new->rebind += cur_time;
if (client->new->rebind < cur_time)
client->new->rebind = TIME_MAX;
bind_lease();
}
void
bind_lease(void)
{
/* Run the client script with the new parameters. */
script_init((client->state == S_REQUESTING ? "BOUND" :
(client->state == S_RENEWING ? "RENEW" :
(client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
if (client->active && client->state != S_REBOOTING)
script_write_params("old_", client->active);
script_write_params("new_", client->new);
script_go();
/* Replace the old active lease with the new one. */
if (client->active)
free_client_lease(client->active);
client->active = client->new;
client->new = NULL;
/* Write out new leases file. */
rewrite_client_leases();
/* Set timeout to start the renewal process. */
set_timeout(client->active->renewal, state_bound);
note("bound to %s -- renewal in %ld seconds.",
piaddr(client->active->address),
client->active->renewal - cur_time);
client->state = S_BOUND;
reinitialize_interface();
go_daemon();
}
/*
* state_bound is called when we've successfully bound to a particular
* lease, but the renewal time on that lease has expired. We are
* expected to unicast a DHCPREQUEST to the server that gave us our
* original lease.
*/
void
state_bound(void)
{
/* T1 has expired. */
make_request(client->active);
client->xid = client->packet.xid;
if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
memcpy(client->destination.iabuf,
client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
4);
client->destination.len = 4;
} else
client->destination = iaddr_broadcast;
client->first_sending = cur_time;
client->interval = 0;
client->state = S_RENEWING;
/* Send the first packet immediately. */
send_request();
}
void
dhcpoffer(struct iaddr client_addr, struct option_data *options)
{
struct client_lease *lease, *lp;
int i;
int stop_selecting;
char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
"BOOTREPLY";
if (client->state != S_SELECTING)
return;
/* If this lease doesn't supply the minimum required parameters,
blow it off. */
for (i = 0; config->required_options[i]; i++) {
if (!options[config->required_options[i]].len) {
note("%s isn't satisfactory.", name);
return;
}
}
/* If we've already seen this lease, don't record it again. */
for (lease = client->offered_leases;
lease; lease = lease->next) {
if (lease->address.len == sizeof(client->packet.yiaddr) &&
!memcmp(lease->address.iabuf,
&client->packet.yiaddr, lease->address.len)) {
#ifdef DEBUG
debug("%s already seen.", name);
#endif
return;
}
}
lease = packet_to_lease(options);
if (!lease) {
note("packet_to_lease failed.");
return;
}
/* If this lease was acquired through a BOOTREPLY, record that
fact. */
if (!options[DHO_DHCP_MESSAGE_TYPE].len)
lease->is_bootp = 1;
/* Figure out when we're supposed to stop selecting. */
stop_selecting = client->first_sending + config->select_interval;
/* If this is the lease we asked for, put it at the head of the
list, and don't mess with the arp request timeout. */
if (addr_eq(lease->address, client->requested_address)) {
lease->next = client->offered_leases;
client->offered_leases = lease;
} else {
/* Put the lease at the end of the list. */
lease->next = NULL;
if (!client->offered_leases)
client->offered_leases = lease;
else {
for (lp = client->offered_leases; lp->next;
lp = lp->next)
; /* nothing */
lp->next = lease;
}
}
/* If the selecting interval has expired, go immediately to
state_selecting(). Otherwise, time out into
state_selecting at the select interval. */
if (stop_selecting <= cur_time)
state_selecting();
else {
set_timeout(stop_selecting, state_selecting);
}
}
/*
* Allocate a client_lease structure and initialize it from the
* parameters in the specified packet.
*/
struct client_lease *
packet_to_lease(struct option_data *options)
{
struct client_lease *lease;
int i;
lease = malloc(sizeof(struct client_lease));
if (!lease) {
warning("dhcpoffer: no memory to record lease.");
return (NULL);
}
memset(lease, 0, sizeof(*lease));
/* Copy the lease options. */
for (i = 0; i < 256; i++) {
if (options[i].len) {
lease->options[i] = options[i];
options[i].data = NULL;
options[i].len = 0;
if (!check_option(lease, i)) {
warning("Invalid lease option - ignoring offer");
free_client_lease(lease);
return (NULL);
}
}
}
lease->address.len = sizeof(client->packet.yiaddr);
memcpy(lease->address.iabuf, &client->packet.yiaddr,
lease->address.len);
/* If the server name was filled out, copy it. */
if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
!(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
client->packet.sname[0]) {
lease->server_name = malloc(DHCP_SNAME_LEN + 1);
if (!lease->server_name) {
warning("dhcpoffer: no memory for server name.");
free_client_lease(lease);
return (NULL);
}
memcpy(lease->server_name, client->packet.sname,
DHCP_SNAME_LEN);
lease->server_name[DHCP_SNAME_LEN] = '\0';
if (!res_hnok(lease->server_name)) {
warning("Bogus server name %s", lease->server_name);
free(lease->server_name);
lease->server_name = NULL;
}
}
/* Ditto for the filename. */
if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
!(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
client->packet.file[0]) {
/* Don't count on the NUL terminator. */
lease->filename = malloc(DHCP_FILE_LEN + 1);
if (!lease->filename) {
warning("dhcpoffer: no memory for filename.");
free_client_lease(lease);
return (NULL);
}
memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
lease->filename[DHCP_FILE_LEN] = '\0';
}
return lease;
}
void
dhcpnak(struct iaddr client_addr, struct option_data *options)
{
if (client->state != S_REBOOTING &&
client->state != S_REQUESTING &&
client->state != S_RENEWING &&
client->state != S_REBINDING)
return;
if (!client->active) {
note("DHCPNAK with no active lease.");
return;
}
free_client_lease(client->active);
client->active = NULL;
/* Stop sending DHCPREQUEST packets... */
cancel_timeout();
client->state = S_INIT;
state_init();
}
/*
* Send out a DHCPDISCOVER packet, and set a timeout to send out another
* one after the right interval has expired. If we don't get an offer by
* the time we reach the panic interval, call the panic function.
*/
void
send_discover(void)
{
int interval, increase = 1;
/* Figure out how long it's been since we started transmitting. */
interval = cur_time - client->first_sending;
/* If we're past the panic timeout, call the script and tell it
we haven't found anything for this interface yet. */
if (interval > config->timeout) {
state_panic();
return;
}
/*
* If we're supposed to increase the interval, do so. If it's
* currently zero (i.e., we haven't sent any packets yet), set
* it to initial_interval; otherwise, add to it a random
* number between zero and two times itself. On average, this
* means that it will double with every transmission.
*/
if (increase) {
if (!client->interval)
client->interval = config->initial_interval;
else {
client->interval += (arc4random() >> 2) %
(2 * client->interval);
}
/* Don't backoff past cutoff. */
if (client->interval > config->backoff_cutoff)
client->interval = ((config->backoff_cutoff / 2)
+ ((arc4random() >> 2) %
config->backoff_cutoff));
} else if (!client->interval)
client->interval = config->initial_interval;
/* If the backoff would take us to the panic timeout, just use that
as the interval. */
if (cur_time + client->interval >
client->first_sending + config->timeout)
client->interval = (client->first_sending +
config->timeout) - cur_time + 1;
/* Record the number of seconds since we started sending. */
if (interval < 65536)
client->packet.secs = htons(interval);
else
client->packet.secs = htons(65535);
client->secs = client->packet.secs;
note("DHCPDISCOVER on %s to %s port %d interval %ld",
ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
ntohs(sockaddr_broadcast.sin_port), client->interval);
/* Send out a packet. */
send_packet(inaddr_any, &sockaddr_broadcast, NULL);
set_timeout(cur_time + client->interval, send_discover);
}
/*
* state_panic gets called if we haven't received any offers in a preset
* amount of time. When this happens, we try to use existing leases
* that haven't yet expired, and failing that, we call the client script
* and hope it can do something.
*/
void
state_panic(void)
{
struct client_lease *loop = client->active;
struct client_lease *lp;
note("No DHCPOFFERS received.");
/* We may not have an active lease, but we may have some
predefined leases that we can try. */
if (!client->active && client->leases)
goto activate_next;
/* Run through the list of leases and see if one can be used. */
while (client->active) {
if (client->active->expiry > cur_time) {
note("Trying recorded lease %s",
piaddr(client->active->address));
/* Run the client script with the existing
parameters. */
script_init("TIMEOUT");
script_write_params("new_", client->active);
/* If the old lease is still good and doesn't
yet need renewal, go into BOUND state and
timeout at the renewal time. */
if (!script_go()) {
if (cur_time <
client->active->renewal) {
client->state = S_BOUND;
note("bound: renewal in %ld seconds.",
client->active->renewal -
cur_time);
set_timeout(client->active->renewal,
state_bound);
} else {
client->state = S_BOUND;
note("bound: immediate renewal.");
state_bound();
}
reinitialize_interface();
go_daemon();
return;
}
}