File: client.c

package info (click to toggle)
dhcpcd 0.70-3
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 276 kB
  • ctags: 270
  • sloc: ansic: 2,300; sh: 391; makefile: 93
file content (855 lines) | stat: -rw-r--r-- 23,658 bytes parent folder | download | duplicates (3)
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
/* $Id: client.c,v 0.12 1997/08/28 14:35:52 yoichi v0_70 $
 *
 * dhcpcd - DHCP client daemon -
 * Copyright (C) 1996 - 1997 Yoichi Hariguchi <yoichi@fore.com>
 *
 * dhcpcd is an RFC2131 and RFC1541 compliant DHCP client daemon.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <net/if.h>
#include <arpa/inet.h>
/*#include <linux/netdevice.h>*/
#include <net/if_arp.h>
#include <netinet/if_ether.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "if.h"
#include "dhcp.h"
#include "dhcp-options.h"
#include "socket-if.h"
#include "arp.h"
#include "error-handler.h"
#include "hostinfo.h"
#include "client.h"

extern int BeRFC1541;			/* if 1, Be RFC154 compliant */
extern char *Hostname;			/* if !NULL, put hostname into DHCP msg */


int (*Fsm[MAX_STATES])();		/* finite state machine */
int CurrState;					/* current state */
int PrevState;					/* previous state */

dhcpMessage DhcpMsgSend;		/* DHCP message to send */
dhcpMessage DhcpMsgRecv;		/* DHCP message received */

int Ssend;						/* socket fd for send */
int Srecv;						/* socket fd for receive */

time_t ReqSentTime;				/* time when DHCPREQUEST message is sent */
u_long SuggestLeaseTime = 0;	/* lease time suggested by the user */

/* DHCP information
*/
u_long ServerInaddr;			/* Server's IP address (network byte order) */
u_long LeaseTime;				/* lease time (network byte order) */
u_long RenewTime;				/* T1 time (network byte order) */
u_long RebindTime;				/* T2 time (network byte order) */

static u_char *OptPtr[MAXNOPT];	/* array of ptrs to DHCP option element */
static u_char *OptOffer[MAXNOPT];	/* same as above in DHCPOFFER msg */
static u_char ClassId[MAXIDCHARS];	/* class identifier */
static u_char ClientId[MAXIDCHARS];	/* client identifier */


void
classIDsetup(char *id)
{
	struct utsname		sname;

	if ( id != NULL ) {
		strncpy(ClassId, id, sizeof(ClassId));
		return;
	}
	/* setup default class identifier if id is NULL
	 */
	if ( uname(&sname) < 0 ) {
		logSysExit("uname (dhcpMsgInit)");
	}
	sprintf(ClassId, "%s %s %s", sname.sysname, sname.release, sname.machine);
}

void
clientIDsetup(char *id, char *ifname)
{
	struct  ifinfo ifinfo;
	u_char *s;
	int		len;

	s = ClientId;
	*s++ = 61;					/* type value of client identifier */

	if ( id != NULL ) {
		len = strlen(id);
		if ( len > sizeof(ClientId) - 4 ) {
			/* 4: code, len, type, EOS */
			logQuit("clientIDsetup: too long client ID string");
		}
		*s++ = len + 1;			/* 1 for the # field */
		*s++ = 0;				/* type: string */
		strcpy(s, id);
		return;
	}
	/* setup default client identifier if id is NULL
	 */
	strcpy(ifinfo.ifname, ifname);
	getIfInfo(&ifinfo);
	*s++ = 7;					/* length: 6 (MAC Addr) + 1 (# field) */
	*s++ = ARPHRD_ETHER;		/* type: Ethernet address */
	bcopy(ifinfo.haddr, s, sizeof(ifinfo.haddr));
}

void
dhcpMsgInit(u_char *ifname)
{
	struct sockaddr_in	addr;

#if 0
	/* open and bind socket for receiving
	 */
	setSockAddrIn(htons(0), htonl(INADDR_ANY), &addr);
	openRecvSocket(&addr, &Srecv);
#endif

	/* open and bind socket for sending
	 */
	setSockAddrIn(htons(DHCP_CLIENT_PORT), htonl(INADDR_ANY), &addr);
	openSendSocket(&addr, &Ssend);
	Srecv = Ssend;
}

void
dhcpClient()
{
	int next_state;

	Fsm[INIT_REBOOT] = initReboot;
	Fsm[INIT]		 = init;
	Fsm[REBOOTING]	 = rebooting;
	Fsm[SELECTING]	 = selecting;
	Fsm[REQUESTING]	 = requesting;
	Fsm[BOUND]		 = bound;
	Fsm[RENEWING]	 = renewing;
	Fsm[REBINDING]	 = rebinding;

	CurrState = PrevState = INIT_REBOOT;

	for(;;) {
		next_state = (*Fsm[CurrState])();
		if ( next_state == EXCEPTION ) {
			errQuit("Exception occured in the fsm (dhcpClient)");
		}
		PrevState = CurrState;
		CurrState  = next_state;
	}
}

int
initReboot()
{
	int					fd;
	int					nextState = REBOOTING;
	char				filename[IFNAMSIZ + 128];
	struct sockaddr_in	addr;

	bzero((char *)&addr, sizeof(addr));
	strcpy(filename, DHCP_CACHE_FILE);
	strcat(filename, Ifbuf.ifname);
	if ( (fd = open(filename, O_RDONLY)) < 0 ) {
		return INIT;
	}
	/* try to open cache file
	 */
	if ( read(fd, (char *)&addr.sin_addr.s_addr,
			  sizeof(addr.sin_addr.s_addr)) < 0 ) {
		nextState = INIT;
	}
	close(fd);
	unlink(filename);
	if ( nextState != REBOOTING ) {
		return nextState;
	}
	/* found cache file
	 */
	mkDhcpDiscoverMsg(Ifbuf.haddr, &DhcpMsgSend); /* set up MAC adddr, etc. */
	/* TODO: cache file should have the lease time previously used
	 */
	mkDhcpRequestMsg(REBOOTING, 0, 0, rand(),
					 addr.sin_addr.s_addr, &DhcpMsgSend);
	setSockAddrIn(htons(DHCP_SERVER_PORT), htonl(INADDR_BROADCAST), &addr);
	time(&ReqSentTime);
#ifdef NEED_BCAST_RESPONSE
	DhcpMsgSend.flags = htons(F_BROADCAST);
#endif
	if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
				(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
		logSysExit("sendto (initReboot)");
	}
	return REBOOTING;
}

int
init()
{
	char ifname[IFNAMSIZ];
	int waitTime = 0;
	struct sockaddr_in	addr;

	freeOptInfo(OptOffer);		/* clear up 'OptOffer' */
	if ( PrevState == RENEWING || PrevState == REBINDING ) {
		strcpy(ifname, Ifbuf.ifname);
		ifReset(ifname);
		dhcpMsgInit(Ifbuf.ifname);
	}
	mkDhcpDiscoverMsg(Ifbuf.haddr, &DhcpMsgSend);
	setSockAddrIn(htons(DHCP_SERVER_PORT), htonl(INADDR_BROADCAST), &addr);

	do {
		waitTime = random() % 10;
	} while ( waitTime == 0 );
	sleep(waitTime);
	time(&ReqSentTime);			/* record local time
								   not @ REQUEST but @ DISCOVER (RFC1541) */
	if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
				(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
		logSysExit("sendto (init)");
	}
	return SELECTING;
}

int
rebooting()
{
	int					 nextState;
	struct sockaddr_in	 addr;
	u_int				 waitMsgType;

	setSockAddrIn(htons(DHCP_SERVER_PORT), htonl(INADDR_BROADCAST), &addr);
	waitMsgType			 = 0;
	setWaitMsgType(DHCP_ACK, &waitMsgType);
	setWaitMsgType(DHCP_NAK, &waitMsgType);

	/* DhcpMsgSend should contain DHCPREQUEST message (created in initReboot).
	 */
	if ( !waitChkReXmitMsg(Srecv, &DhcpMsgRecv, Ssend, &DhcpMsgSend,
					   &addr, waitMsgType, OptPtr, N_REXMIT_REQ_REBOOT) ) {
		logRet("REBOOTING: timeout. Fall back to INIT");
		return INIT;
	}
	nextState = setDhcpInfo(OptPtr, &DhcpMsgRecv);
	if ( nextState == BOUND ) {
		/* check if yiaddr is already used
		 */
		if ( !arpCheck(DhcpMsgRecv.yiaddr, &Ifbuf, ARP_REPLY_TIMEOUT) ) {
			sendDhcpDecline(DHCP_DECLINE,
							*((u_int *)(OptPtr[OserverInaddr]+1)),
							DhcpMsgRecv.yiaddr);
			sleep(10);
			logRet("REBOOTING: %s is already used. Fall back to INIT",
				   inet_ntoa(*((struct in_addr *)&DhcpMsgRecv.yiaddr)));
			return INIT;
		}
		/* now the client is initialized
		 */

		/* initHost uses the values of Ifbuf.bcast and Ifbuf.mask as is
		 * under the following condition:
		 *   1. the DHCP ACK msg does not includes bcast or subnetmask option
		 *   2. Ifbuf.bcast or Ifbuf.mask is not 0.
		 * So we have to set these values to 0 not to confuse initHost.
		 */
		Ifbuf.bcast = Ifbuf.mask = 0;
		initHost(&Ifbuf, DhcpMsgRecv.yiaddr);
		execCommandFile();
		if ( LeaseTime == INFINITE_LEASE_TIME ) {
                      char pidfile[BUFSIZ];
                      sprintf(pidfile, PIDFILE, Ifbuf.ifname);
                      unlink(pidfile);
			logRet("got the INFINITE lease time. exit(0).");
			exit(0);
		}
	} else if ( nextState == INIT ) {
		logRet("REBOOTING: got DHCPNAK. Fall back to INIT");
	}
	return nextState;
}

int
selecting()
{
	time_t				 prevTime;
	struct sockaddr_in	 addr;
	u_int				 waitMsgType;

	time(&prevTime);

	setSockAddrIn(htons(DHCP_SERVER_PORT), htonl(INADDR_BROADCAST), &addr);

	/* DhcpMsgSend shoud contain DHCPDISCOVER message (created in 'init')
	 */
	waitMsgType			 = 0;
	setWaitMsgType(DHCP_OFFER, &waitMsgType);
	if ( waitChkReXmitMsg(Srecv, &DhcpMsgRecv, Ssend, &DhcpMsgSend,
						  &addr, waitMsgType, OptPtr, N_REXMIT_DISCOVER) ) {
		/* send DHCPREQUEST msessage
		 */
		ServerInaddr = *((u_int *)(OptPtr[OserverInaddr]+1));
		LeaseTime	 = *((u_int *)(OptPtr[OleaseTime]+1));
		mkDhcpRequestMsg(SELECTING, ServerInaddr, LeaseTime,
							 DhcpMsgRecv.xid, DhcpMsgRecv.yiaddr,
							 &DhcpMsgSend);
#ifdef NEED_BCAST_RESPONSE
		DhcpMsgSend.flags = htons(F_BROADCAST);
#endif
		if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
					(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
			logSysExit("sendto (selecting)");
		}
		/* record option values in the DHCPOFFER message because NT server
		   does not include those values in the DHCPACK message
		 */
		setupIfInfo(&Ifbuf, DhcpMsgRecv.yiaddr, OptPtr);
		setupOptInfo(OptOffer, (const u_char **)OptPtr);
		return REQUESTING;
	}
	ifDown(&Ifbuf);
	logQuit("no DHCPOFFER messages");
	return EXCEPTION;			/* should not happen */
}

int
requesting()
{
	struct sockaddr_in	 addr;
	int					 nextState;
	u_int				 waitMsgType;

	/* wait DHCPACK/DHCPNAK, rexmit RHCPREQUEST if necessary
	 */
	setSockAddrIn(htons(DHCP_SERVER_PORT), htonl(INADDR_BROADCAST), &addr);
	waitMsgType = 0;
	setWaitMsgType(DHCP_ACK, &waitMsgType);
	setWaitMsgType(DHCP_NAK, &waitMsgType);
	if ( waitChkReXmitMsg(Srecv, &DhcpMsgRecv, Ssend, &DhcpMsgSend,
						  &addr, waitMsgType, OptPtr, N_REXMIT_REQUEST) ) {
		if ( (nextState = setDhcpInfo(OptPtr, &DhcpMsgRecv)) != EXCEPTION ) {
			if ( nextState == BOUND ) {
				/* check if yiaddr is already used
				 */
				Ifbuf.addr = htonl(0);	/* sender's IP address must be 0 */
				if ( !arpCheck(DhcpMsgRecv.yiaddr, &Ifbuf,
							   ARP_REPLY_TIMEOUT) ) {
					sendDhcpDecline(DHCP_DECLINE,
									*((u_int *)(OptPtr[OserverInaddr]+1)),
									DhcpMsgRecv.yiaddr);
					logRet("REQUESTING: %s is already used. Fall back to INIT",
						   inet_ntoa(*((struct in_addr *)
									   &DhcpMsgRecv.yiaddr)));
					sleep(10);
					return INIT;
				}
				/* now the client is initialized
				 */
				setupOptInfo(OptOffer, (const u_char **)OptPtr);
				initHost(&Ifbuf, DhcpMsgRecv.yiaddr);
				sendArpReply(MAC_BCAST_ADDR, Ifbuf.bcast, &Ifbuf);
				execCommandFile();
				if ( LeaseTime == INFINITE_LEASE_TIME ) {
                                      char pidfile[BUFSIZ];
                                      sprintf(pidfile, PIDFILE, Ifbuf.ifname);
                                      unlink(pidfile);
					logRet("got the INFINITE lease time. exit(0).");
					exit(0);
				}
			}
			return nextState;
		}
	}
	logRet("no response to DHCPREEQUEST message. move to INIT state");
	return INIT;
}

int
bound()
{
	logRet("got in BOUND state");
	sleep(ntohl(RenewTime));
	return RENEWING;
}

int
renewing()
{
	struct sockaddr_in	 addr;
	int					 nextState;
	time_t				 sendTime;
	time_t				 prevTime;
	long				 timeout;
	long				 tm;
	u_int				 waitMsgType;

	logRet("got in RENEWING state");

	/* setup for sending unicast DHCPREQUEST message
	 */
	setSockAddrIn(htons(DHCP_SERVER_PORT), ServerInaddr, &addr);
	mkDhcpRequestMsg(RENEWING, ServerInaddr, LeaseTime,
					 rand(), Ifbuf.addr, &DhcpMsgSend);
	/* send DHCPREQUESTvia unicast, and
	 * wait server's response (DHCPACK/DHCPNAK)
	 */
	timeout = ReqSentTime + ntohl(RebindTime) - time(NULL);
	/* timeout     = ntohl(RebindTime) - ntohl(RenewTime); */
	nextState   = REBINDING;
	waitMsgType = 0;
	setWaitMsgType(DHCP_ACK, &waitMsgType);	/* wait DHCPACK, DHCPNAK */
	setWaitMsgType(DHCP_NAK, &waitMsgType);
	tm = getNextTimeout(INIT_TIMEOUT);
	time(&prevTime);
	while ( timeout > 0 ) {
		/* send DHCPREQUEST via unicast
		 */
		time(&sendTime);
		if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
					(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
			logSysRet("sendto (renewing)");
			sleep(tm/1000000);
		} else {
			/* wait server's response
			 */
			if ( rcvAndCheckDhcpMsg(Srecv, &DhcpMsgRecv,
									waitMsgType, OptPtr, tm) ) {
				nextState = setDhcpInfo(OptPtr, &DhcpMsgRecv);
				if ( nextState == EXCEPTION ) {
					return nextState;
				}
				break;
			}
		}
		tm = getNextTimeout(NEXT_TIMEOUT);	/* renew response timeout value */
		timeout -= time(NULL) - prevTime;
		time(&prevTime);
	}
	if ( nextState == BOUND ) {
		ReqSentTime = sendTime;			/* renew time when DHCPREQ is sent */
	} else if ( nextState == INIT ) {	/* got DHCPNAK */
		logRet("RENEWING: got DHCPNAK. Fall back to INIT");
		close(Ssend);
		close(Srecv);
		ifDown(&Ifbuf);
	}
	return nextState;
}

int
rebinding()
{
	struct sockaddr_in	 addr;
	int					 nextState;
	time_t				 sendTime;
	time_t				 prevTime;
	long				 timeout;
	long				 tm;
	u_int				 waitMsgType;

	logRet("got in REBINDING state");

	nextState = INIT;			/* init nextState */

	/* setup for sending broadcast DHCPREQUEST message
	 */
	setSockAddrIn(htons(DHCP_SERVER_PORT), Ifbuf.bcast, &addr);
	mkDhcpRequestMsg(REBINDING, ServerInaddr, LeaseTime,
					 rand(), Ifbuf.addr, &DhcpMsgSend);

	/* send DHCPREQUEST via broadcast, and
	 * wait server's response (DHCPACK/DHCPNAK)
	 */
	timeout = ReqSentTime + ntohl(LeaseTime) - time(NULL);
	/* timeout     = ntohl(LeaseTime) - ntohl(RebindTime); */
	waitMsgType = 0;
	setWaitMsgType(DHCP_ACK, &waitMsgType);	/* wait DHCPACK, DHCPNAK */
	setWaitMsgType(DHCP_NAK, &waitMsgType);
	tm = getNextTimeout(INIT_TIMEOUT);
	time(&prevTime);
	while ( timeout > 0 ) {
		time(&sendTime);
		if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
					(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
			logSysRet("sendto (rebinding)");
			sleep(tm/1000000);
		} else {
			if ( rcvAndCheckDhcpMsg(Srecv, &DhcpMsgRecv,
									waitMsgType, OptPtr, tm) ) {
				nextState = setDhcpInfo(OptPtr, &DhcpMsgRecv);
				if ( nextState == EXCEPTION ) {
					return nextState;
				}
				break;
			}
		}
		tm = getNextTimeout(NEXT_TIMEOUT);
		timeout -= time(NULL) - prevTime;
		time(&prevTime);
	}
	if ( nextState == BOUND ) {
		ReqSentTime = sendTime;	/* renew time when DHCPREQ is sent */
		return nextState;
	}
	/* Lease expired. halt network
	 */
	logRet("REBINDING: Lease time expired. Fall back to INIT");
	close(Ssend);
	close(Srecv);
	ifDown(&Ifbuf);
	return INIT;
}

void
mkDhcpDiscoverMsg(u_char *haddr, dhcpMessage *msg)
{
	u_char *p =	msg->options + 4; /* just after the magic cookie */

	bzero((char *)msg, sizeof(*msg));
	msg->htype = HTYPE_ETHER;	/* supports Etherenet only */
	msg->hlen  = 6;
	bcopy(haddr, msg->chaddr, 6);
	msg->op	   = BOOTREQUEST;
#ifdef NEED_BCAST_RESPONSE
	msg->flags = htons(F_BROADCAST);
#endif
	msg->xid   = htonl(random());

	/* make DHCP message option field
	 */
	*((u_long *)msg->options) = htonl(MAGIC_COOKIE);
	*p++ = dhcpMessageType;		/* DHCP message type */
	*p++ = 1;
	*p++ = DHCP_DISCOVER;
	*p++ = dhcpMaxMsgSize;		/* Maximum DHCP message size */
	*p++ = 2;
	*((u_short *)p) = htons(sizeof(*msg));
	p += sizeof(u_short);
	if ( SuggestLeaseTime ) {
		*p++ = dhcpIPaddrLeaseTime;	/* IP address lease time */
		*p++ = 4;
		*((u_int *)p) = htonl(SuggestLeaseTime);
		p += sizeof(long);
	}
	*p++ = dhcpParamRequest;	/* Parameter Request List */
	*p++ = 8;					/* number of requests */
	*p++ = subnetMask;
	*p++ = routersOnSubnet;
	*p++ = dns;
	*p++ = hostName;
	*p++ = domainName;
	*p++ = broadcastAddr;
	*p++ = ntpServers;
	*p++ = nisDomainName;

	if ( Hostname != NULL ) {
		int len;

		len = strlen(Hostname);
		*p++ = hostName;
		*p++ = len;
		strncpy(p, Hostname, len);
		p += len;
	}
	*p++ = dhcpClassIdentifier;	/* class identifier */
	*p++ = strlen(ClassId);
	strcpy(p, ClassId);
	p += strlen(ClassId);
	bcopy(ClientId, p, ClientId[1]+2); /* client identifier */
	p += ClientId[1] + 2;
	*p = endOption;				/* end */
}

void
mkDhcpRequestMsg(int flag, u_long serverInaddr, u_long leaseTime,
				 u_long xid, u_long ciaddr, dhcpMessage *msg)
{
	u_char *p =	msg->options + 4; /* just after the magic cookie */

	msg->xid	= xid;
	msg->ciaddr = ciaddr;
	msg->flags = htons(0);		/* do not set the broadcast flag here */
	bzero((char *)p, sizeof(msg->options) - 4);	/* clear DHCP option field */

	/* 1. Requested IP address must not be in the DHCPREQUEST message
	 *    under the RFC1541 mode.
	 * 2. Requested IP address must be in the DHCPREQUEST message
	 *    sent in the SELECTING or INIT-REBOOT state under the Internet
	 *    Draft mode
	 */
	if ( !BeRFC1541 ) {
		if ( flag == REBOOTING || flag == SELECTING ) {
			/* ciaddr must be 0 in REBOOTING & SELECTING */
			msg->ciaddr = htonl(0);
			*p++ = dhcpRequestedIPaddr;
			*p++ = 4;
			*((u_int *)p) = ciaddr;
			p += sizeof(u_int);
		}
	}
	*p++ = dhcpMessageType;				/* DHCP message type */
	*p++ = 1;
	*p++ = DHCP_REQUEST;
	*p++ = dhcpMaxMsgSize;				/* Maximum DHCP message size */
	*p++ = 2;
	*((u_short *)p) = htons(sizeof(*msg));
	p += sizeof(u_short);
	if ( flag == REBOOTING && SuggestLeaseTime ) {
		*p++ = dhcpIPaddrLeaseTime;	/* IP address lease time */
		*p++ = 4;
		*((u_int *)p) = htonl(SuggestLeaseTime);
		p += sizeof(long);
	}
	if ( flag == SELECTING || flag == REQUESTING ) {
		*p++ = dhcpServerIdentifier;	/* server identifier */
		*p++ = 4;
		*((u_int *)p) = serverInaddr;
		p += sizeof(u_int);
	}
	if ( leaseTime != 0 ) {
		*p++ = dhcpIPaddrLeaseTime;		/* IP address lease time */
		*p++ = 4;
		*((u_int *)p) = leaseTime;
		p += sizeof(u_int);
	}
	*p++ = dhcpParamRequest;	/* Parameter Request List */
	*p++ = 8;					/* number of requests */
	*p++ = subnetMask;
	*p++ = routersOnSubnet;
	*p++ = dns;
	*p++ = hostName;
	*p++ = domainName;
	*p++ = broadcastAddr;
	*p++ = ntpServers;
	*p++ = nisDomainName;

	if ( Hostname != NULL ) {
		int len;

		len = strlen(Hostname);
		*p++ = hostName;
		*p++ = len;
		strncpy(p, Hostname, len);
		p += len;
	}
	*p++ = dhcpClassIdentifier;			/* class identifier */
	*p++ = strlen(ClassId);
	strcpy(p, ClassId);
	p += strlen(ClassId);
	bcopy(ClientId, p, ClientId[1]+2);	/* client identifier */
	p += ClientId[1] + 2;
	*p = endOption;						/* end */
}

void
mkDhcpDeclineMsg(int flag, u_long serverInaddr, u_long ciaddr,
				 dhcpMessage *msg)
{
	u_char *p =	msg->options + 4; /* just after the magic cookie */

	msg->xid	= rand();
	if ( flag == DHCP_RELEASE ) {	/* make a DHCPRELEASE msg */
		msg->ciaddr = ciaddr;
	} else {						/* make a DHCPDECLINE msg */
		if ( BeRFC1541 ) {			/* use ciaddr in RFC1541 compliant mode */
			msg->ciaddr = ciaddr;
		} else {
			msg->ciaddr = 0;
		}
	}

	bzero((char *)p, sizeof(msg->options) - 4);
	*p++ = dhcpMessageType;		/* DHCP message type */
	*p++ = 1;
	*p++ = (u_char)flag;
	*p++ = dhcpServerIdentifier; /* server identifier */
	*p++ = 4;
	*((u_int *)p) = serverInaddr;
	p += sizeof(long);
	if ( flag == DHCP_DECLINE && !BeRFC1541 ) {
		/* use the requested IP address option
		 * in the Internet Draft compliant mode
		 */
		*p++ = dhcpRequestedIPaddr;
		*p++ = 4;
		*((u_int *)p) = ciaddr;
		p += sizeof(u_int);
	}
	if ( Hostname != NULL ) {
		int len;

		len = strlen(Hostname);
		*p++ = hostName;
		*p++ = len;
		strncpy(p, Hostname, len);
		p += len;
	}
	bcopy(ClientId, p, ClientId[1]+2); /* client identifier */
	p += ClientId[1] + 2;
	*p = endOption;				/* end */
}

void
sendDhcpDecline(int flag, u_long serverInaddr, u_long ciaddr)
{
	struct sockaddr_in	 addr;

	bzero((char *)&addr, sizeof(addr));
	addr.sin_family 	 = AF_INET;
	addr.sin_port		 = htons(DHCP_SERVER_PORT);
	switch ( flag ) {
	  case DHCP_DECLINE:
		addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
		break;
	  case DHCP_RELEASE:
		addr.sin_addr.s_addr = serverInaddr;
		break;
	  default:
		logQuit("illegal flag value (sendDhcpDecline)");
		break;
	}
	mkDhcpDeclineMsg(flag, serverInaddr, ciaddr, &DhcpMsgSend);
	if ( sendto(Ssend, (char *)&DhcpMsgSend, sizeof(DhcpMsgSend), 0,
				(struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
		logSysExit("sendto (sendDhcpDecline)");
	}
}

int
setDhcpInfo(u_char *optp[], dhcpMessage *msg)
{
	switch ( *(optp[OmsgType]+1) ) {
	  case DHCP_NAK:
		return INIT;
	  case DHCP_ACK:
		ServerInaddr = *((u_long *)(optp[OserverInaddr]+1));
		LeaseTime	 = *((u_long *)(optp[OleaseTime]+1));
		if ( optp[OrenewalTime] == NULL ) {
			RenewTime = htonl(ntohl(LeaseTime) / 2);		/* default T1 time */
		} else {
			RenewTime = *((u_long *)(optp[OrenewalTime]+1));
		}
		if ( optp[OrebindTime] == NULL ) {
			RebindTime = htonl(ntohl(LeaseTime) / 8 * 7);	/* default T2 time */
		} else {
			RebindTime = *((u_long *)(optp[OrebindTime]+1));
		}
		return BOUND;
	  default:
		return EXCEPTION;		/* should not happen */
	}
}

/* NOTE: this function is called from 'selecting()', and sets up the network
 *       interface information. It sets subnetmask and broadcast to 0 unless
 *       it receives these values. These values are set correctly in
 *       'initHost()'. This is for the following case: these values were in
 *       the DHCPOFFER message, and were not in the DHCPACK message. In this
 *       case, dhcpcd must not override these values with the 'natural'
 *       subenetmask and broadcast.
 */
void
setupIfInfo(struct ifinfo *ifbuf, u_long yiaddr, u_char *optp[])
{
	ifbuf->addr = yiaddr;
	if ( optp[Onetmask] != NULL ) {
		ifbuf->mask = *((u_int *)(optp[Onetmask]+1));
	} else {
		ifbuf->mask = 0;
	}
	if ( optp[ObcastInaddr] != NULL ) {
		ifbuf->bcast = *((u_int *)(optp[ObcastInaddr]+1));
	} else {
		ifbuf->bcast = 0;
	}
}

void
initHost(struct ifinfo *ifbuf, u_long yiaddr)
{
	/* configure interface
	 */
	ifbuf->addr  = yiaddr;
	logRet("assigned IP address:        %s",
		   inet_ntoa(*((struct in_addr *)&ifbuf->addr)));
	if ( OptPtr[Onetmask] == NULL ) {
		if ( ifbuf->mask == 0 ) {
			/* if ifbuf->mask != 0, subnetmask info. was included in the
			 *  DHCPOFFER message and not included in the DHCPACK message.
			 *  In this case, subnetmask value must not been overwritten.
			 */
			ifbuf->mask = getNaturalMask(ifbuf->addr);
		}
	} else {
		ifbuf->mask  = *((u_int *)(OptPtr[Onetmask]+1));
		logRet("assigned subnetmask:        %s",
			   inet_ntoa(*((struct in_addr *)&ifbuf->mask)));
	}
	if ( OptPtr[ObcastInaddr] == NULL ) {
		/* if the server responds only subnetmask, I should presume
		 * the broadcast address from the subnetmask instead of
		 * using the 'natural' broadcast address.
		 */
		if ( ifbuf->bcast == 0 ) {
			/* if ifbuf->bcast != 0, broadcast info. was included in the
			 *  DHCPOFFER message and not included in the DHCPACK message.
			 *  In this case, broadcast addr. must not been overwritten.
			 */
			ifbuf->bcast = (ifbuf->addr & ifbuf->mask) | ~ifbuf->mask;
		}
	} else {
		ifbuf->bcast = *((u_int *)(OptPtr[ObcastInaddr]+1));
		logRet("assigned broadcast address: %s",
			   inet_ntoa(*((struct in_addr *)&ifbuf->bcast)));
	}
	ifbuf->flags =
		IFF_UP | IFF_BROADCAST | IFF_NOTRAILERS | IFF_RUNNING | IFF_MULTICAST;
      ifConfig(ifbuf,2);

	saveIfInfo(ifbuf);			/* save interface information onto file */
	saveHostInfo((const u_char **)OptPtr);
}

long
getNextTimeout(int flag)
{
	static long  prevTimeout;
	long		 rv;			/* return value */

	if ( flag == INIT_TIMEOUT ) {
		prevTimeout = 4;		/* 4 seconds */
	} else if ( prevTimeout > 64 ) {
		prevTimeout = 4;
	}
      rv = 1000000 * (prevTimeout - 1) + rand()/(RAND_MAX/1000000);
	prevTimeout *= 2;
	return rv;
}