blob: d766ea53bdd09d263b1bd8b098dfc7f220824364 [file] [log] [blame]
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001/* dhcpd.c
2 *
3 * udhcp DHCP client
4 *
5 * Russ Dill <Russ.Dill@asu.edu> July 2001
6 *
7 * Converted to busybox by Glenn McGrath August 2002
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24#include <stdio.h>
25#include <sys/time.h>
26#include <sys/types.h>
27#include <sys/file.h>
28#include <unistd.h>
29#include <getopt.h>
30#include <stdlib.h>
31#include <sys/socket.h>
32#include <netinet/in.h>
33#include <arpa/inet.h>
34#include <signal.h>
35#include <time.h>
36#include <string.h>
37#include <sys/ioctl.h>
38#include <net/if.h>
39#include <errno.h>
40#include <netinet/ip.h>
41#include <netinet/udp.h>
42#include <sys/types.h>
43#include <sys/wait.h>
44
45#if __GLIBC__ >=2 && __GLIBC_MINOR >= 1
46#include <netpacket/packet.h>
47#include <net/ethernet.h>
48#else
49#include <asm/types.h>
50#include <linux/if_packet.h>
51#include <linux/if_ether.h>
52#endif
53#include "libbb.h"
54
55static int state;
56static unsigned long requested_ip; /* = 0 */
57static unsigned long server_addr;
58static unsigned long timeout;
59static int packet_num; /* = 0 */
60static int fd_main;
61#define DEBUG
62
63#define VERSION "0.9.7"
64
65#define LISTEN_NONE 0
66#define LISTEN_KERNEL 1
67#define LISTEN_RAW 2
68static int listen_mode;
69
70#define DEFAULT_SCRIPT "/usr/share/udhcpc/default.script"
71
72#define DHCP_END 0xFF
73#define TYPE_MASK 0x0F
74#define BROADCAST_FLAG 0x8000
75
76#define SERVER_PORT 67
77
78#define DHCP_MAGIC 0x63825363
79
80#define BOOTREQUEST 1
81#define BOOTREPLY 2
82
83#define ETH_10MB 1
84#define ETH_10MB_LEN 6
85
86#define OPTION_FIELD 0
87#define FILE_FIELD 1
88#define SNAME_FIELD 2
89
90#define INIT_SELECTING 0
91#define REQUESTING 1
92#define BOUND 2
93#define RENEWING 3
94#define REBINDING 4
95#define INIT_REBOOT 5
96#define RENEW_REQUESTED 6
97#define RELEASED 7
98
99#define CLIENT_PORT 68
100
101#define DHCPDISCOVER 1
102#define DHCPOFFER 2
103#define DHCPREQUEST 3
104#define DHCPDECLINE 4
105#define DHCPACK 5
106#define DHCPNAK 6
107#define DHCPRELEASE 7
108#define DHCPINFORM 8
109
110/* DHCP option codes (partial list) */
111#define DHCP_PADDING 0x00
112#define DHCP_SUBNET 0x01
113#define DHCP_TIME_OFFSET 0x02
114#define DHCP_ROUTER 0x03
115#define DHCP_TIME_SERVER 0x04
116#define DHCP_NAME_SERVER 0x05
117#define DHCP_DNS_SERVER 0x06
118#define DHCP_LOG_SERVER 0x07
119#define DHCP_COOKIE_SERVER 0x08
120#define DHCP_LPR_SERVER 0x09
121#define DHCP_HOST_NAME 0x0c
122#define DHCP_BOOT_SIZE 0x0d
123#define DHCP_DOMAIN_NAME 0x0f
124#define DHCP_SWAP_SERVER 0x10
125#define DHCP_ROOT_PATH 0x11
126#define DHCP_IP_TTL 0x17
127#define DHCP_MTU 0x1a
128#define DHCP_BROADCAST 0x1c
129#define DHCP_NTP_SERVER 0x2a
130#define DHCP_WINS_SERVER 0x2c
131#define DHCP_REQUESTED_IP 0x32
132#define DHCP_LEASE_TIME 0x33
133#define DHCP_OPTION_OVER 0x34
134#define DHCP_MESSAGE_TYPE 0x35
135#define DHCP_SERVER_ID 0x36
136#define DHCP_PARAM_REQ 0x37
137#define DHCP_MESSAGE 0x38
138#define DHCP_MAX_SIZE 0x39
139#define DHCP_T1 0x3a
140#define DHCP_T2 0x3b
141#define DHCP_VENDOR 0x3c
142#define DHCP_CLIENT_ID 0x3d
143
144/* miscellaneous defines */
145#define MAC_BCAST_ADDR (unsigned char *) "\xff\xff\xff\xff\xff\xff"
146#define OPT_CODE 0
147#define OPT_LEN 1
148#define OPT_DATA 2
149
150enum {
151 OPTION_IP=1,
152 OPTION_IP_PAIR,
153 OPTION_STRING,
154 OPTION_BOOLEAN,
155 OPTION_U8,
156 OPTION_U16,
157 OPTION_S16,
158 OPTION_U32,
159 OPTION_S32
160};
161
162#define OPTION_REQ 0x10 /* have the client request this option */
163#define OPTION_LIST 0x20 /* There can be a list of 1 or more of these */
164
165#ifdef SYSLOG
166# define LOG(level, str, args...) do { printf(str, ## args); \
167 printf("\n"); \
168 syslog(level, str, ## args); } while(0)
169# define OPEN_LOG(name) openlog(name, 0, 0)
170#define CLOSE_LOG() closelog()
171#else
172# define LOG_EMERG "EMERGENCY!"
173# define LOG_ALERT "ALERT!"
174# define LOG_CRIT "critical!"
175# define LOG_WARNING "warning"
176# define LOG_ERR "error"
177# define LOG_INFO "info"
178# define LOG_DEBUG "debug"
179# define LOG(level, str, args...) do { printf("%s, ", level); printf(str, ## args); printf("\n"); } while(0)
180# define OPEN_LOG(name) do {;} while(0)
181#define CLOSE_LOG() do {;} while(0)
182#endif
183
184#ifdef DEBUG
185# undef DEBUG
186# define DEBUG(level, str, args...) LOG(level, str, ## args)
187# define DEBUGGING
188#else
189# define DEBUG(level, str, args...) do {;} while(0)
190#endif
191
192struct client_config_t {
193 char foreground; /* Do not fork */
194 char quit_after_lease; /* Quit after obtaining lease */
195 char abort_if_no_lease; /* Abort if no lease */
196 char *interface; /* The name of the interface to use */
197 char *pidfile; /* Optionally store the process ID */
198 char *script; /* User script to run at dhcp events */
199 unsigned char *clientid; /* Optional client id to use */
200 unsigned char *hostname; /* Optional hostname to use */
201 int ifindex; /* Index number of the interface to use */
202 unsigned char arp[6]; /* Our arp address */
203};
204extern struct client_config_t client_config;
205
206struct dhcpMessage {
207 u_int8_t op;
208 u_int8_t htype;
209 u_int8_t hlen;
210 u_int8_t hops;
211 u_int32_t xid;
212 u_int16_t secs;
213 u_int16_t flags;
214 u_int32_t ciaddr;
215 u_int32_t yiaddr;
216 u_int32_t siaddr;
217 u_int32_t giaddr;
218 u_int8_t chaddr[16];
219 u_int8_t sname[64];
220 u_int8_t file[128];
221 u_int32_t cookie;
222 u_int8_t options[308]; /* 312 - cookie */
223};
224
225struct client_config_t client_config = {
226 /* Default options. */
227 abort_if_no_lease: 0,
228 foreground: 0,
229 quit_after_lease: 0,
230 interface: "eth0",
231 pidfile: NULL,
232 script: DEFAULT_SCRIPT,
233 clientid: NULL,
234 hostname: NULL,
235 ifindex: 0,
236 arp: "\0\0\0\0\0\0", /* appease gcc-3.0 */
237};
238
239struct dhcp_option {
240 char name[10];
241 char flags;
242 unsigned char code;
243};
244
245struct udp_dhcp_packet {
246 struct iphdr ip;
247 struct udphdr udp;
248 struct dhcpMessage data;
249};
250
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000251static const struct dhcp_option options[] = {
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000252 /* name[10] flags code */
253 {"subnet", OPTION_IP | OPTION_REQ, 0x01},
254 {"timezone", OPTION_S32, 0x02},
255 {"router", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x03},
256 {"timesvr", OPTION_IP | OPTION_LIST, 0x04},
257 {"namesvr", OPTION_IP | OPTION_LIST, 0x05},
258 {"dns", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x06},
259 {"logsvr", OPTION_IP | OPTION_LIST, 0x07},
260 {"cookiesvr", OPTION_IP | OPTION_LIST, 0x08},
261 {"lprsvr", OPTION_IP | OPTION_LIST, 0x09},
262 {"hostname", OPTION_STRING | OPTION_REQ, 0x0c},
263 {"bootsize", OPTION_U16, 0x0d},
264 {"domain", OPTION_STRING | OPTION_REQ, 0x0f},
265 {"swapsvr", OPTION_IP, 0x10},
266 {"rootpath", OPTION_STRING, 0x11},
267 {"ipttl", OPTION_U8, 0x17},
268 {"mtu", OPTION_U16, 0x1a},
269 {"broadcast", OPTION_IP | OPTION_REQ, 0x1c},
270 {"ntpsrv", OPTION_IP | OPTION_LIST, 0x2a},
271 {"wins", OPTION_IP | OPTION_LIST, 0x2c},
272 {"requestip", OPTION_IP, 0x32},
273 {"lease", OPTION_U32, 0x33},
274 {"dhcptype", OPTION_U8, 0x35},
275 {"serverid", OPTION_IP, 0x36},
276 {"message", OPTION_STRING, 0x38},
277 {"tftp", OPTION_STRING, 0x42},
278 {"bootfile", OPTION_STRING, 0x43},
279 {"", 0x00, 0x00}
280};
281
282/* Lengths of the different option types */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000283static const int option_lengths[] = {
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000284 [OPTION_IP] = 4,
285 [OPTION_IP_PAIR] = 8,
286 [OPTION_BOOLEAN] = 1,
287 [OPTION_STRING] = 1,
288 [OPTION_U8] = 1,
289 [OPTION_U16] = 2,
290 [OPTION_S16] = 2,
291 [OPTION_U32] = 4,
292 [OPTION_S32] = 4
293};
294
295/* get a rough idea of how long an option will be (rounding up...) */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000296static const unsigned char max_option_length[] = {
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000297 [OPTION_IP] = sizeof("255.255.255.255 "),
298 [OPTION_IP_PAIR] = sizeof("255.255.255.255 ") * 2,
299 [OPTION_STRING] = 1,
300 [OPTION_BOOLEAN] = sizeof("yes "),
301 [OPTION_U8] = sizeof("255 "),
302 [OPTION_U16] = sizeof("65535 "),
303 [OPTION_S16] = sizeof("-32768 "),
304 [OPTION_U32] = sizeof("4294967295 "),
305 [OPTION_S32] = sizeof("-2147483684 "),
306};
307
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000308/* return the position of the 'end' option (no bounds checking) */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000309static int end_option(unsigned char *optionptr)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000310{
311 int i = 0;
312
313 while (optionptr[i] != DHCP_END) {
314 if (optionptr[i] == DHCP_PADDING) i++;
315 else i += optionptr[i + OPT_LEN] + 2;
316 }
317 return i;
318}
319
320/* add an option string to the options (an option string contains an option code,
321 * length, then data) */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000322static int add_option_string(unsigned char *optionptr, unsigned char *string)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000323{
324 int end = end_option(optionptr);
325
326 /* end position + string length + option code/length + end option */
327 if (end + string[OPT_LEN] + 2 + 1 >= 308) {
328 LOG(LOG_ERR, "Option 0x%02x did not fit into the packet!", string[OPT_CODE]);
329 return 0;
330 }
331 DEBUG(LOG_INFO, "adding option 0x%02x", string[OPT_CODE]);
332 memcpy(optionptr + end, string, string[OPT_LEN] + 2);
333 optionptr[end + string[OPT_LEN] + 2] = DHCP_END;
334 return string[OPT_LEN] + 2;
335}
336
337/* add a one to four byte option to a packet */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000338static int add_simple_option(unsigned char *optionptr, unsigned char code, u_int32_t data)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000339{
340 char length = 0;
341 int i;
342 unsigned char option[2 + 4];
343 unsigned char *u8;
344 u_int16_t *u16;
345 u_int32_t *u32;
346 u_int32_t aligned;
347 u8 = (unsigned char *) &aligned;
348 u16 = (u_int16_t *) &aligned;
349 u32 = &aligned;
350
351 for (i = 0; options[i].code; i++)
352 if (options[i].code == code) {
353 length = option_lengths[options[i].flags & TYPE_MASK];
354 }
355
356 if (!length) {
357 DEBUG(LOG_ERR, "Could not add option 0x%02x", code);
358 return 0;
359 }
360
361 option[OPT_CODE] = code;
362 option[OPT_LEN] = length;
363
364 switch (length) {
365 case 1: *u8 = data; break;
366 case 2: *u16 = data; break;
367 case 4: *u32 = data; break;
368 }
369
370 memcpy(option + 2, &aligned, length);
371 return add_option_string(optionptr, option);
372}
373#if 0
374void init_header(struct dhcpMessage *packet, char type)
375{
376 memset(packet, 0, sizeof(struct dhcpMessage));
377 switch (type) {
378 case DHCPDISCOVER:
379 case DHCPREQUEST:
380 case DHCPRELEASE:
381 case DHCPINFORM:
382 packet->op = BOOTREQUEST;
383 break;
384 case DHCPOFFER:
385 case DHCPACK:
386 case DHCPNAK:
387 packet->op = BOOTREPLY;
388 }
389 packet->htype = ETH_10MB;
390 packet->hlen = ETH_10MB_LEN;
391 packet->cookie = htonl(DHCP_MAGIC);
392 packet->options[0] = DHCP_END;
393 add_simple_option(packet->options, DHCP_MESSAGE_TYPE, type);
394}
395#endif
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000396static u_int16_t checksum(void *addr, int count)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000397{
398 /* Compute Internet Checksum for "count" bytes
399 * beginning at location "addr".
400 */
401 register int32_t sum = 0;
402 u_int16_t *source = (u_int16_t *) addr;
403
404 while( count > 1 ) {
405 /* This is the inner loop */
406 sum += *source++;
407 count -= 2;
408 }
409
410 /* Add left-over byte, if any */
411 if( count > 0 )
412 sum += * (unsigned char *) source;
413
414 /* Fold 32-bit sum to 16 bits */
415 while (sum>>16)
416 sum = (sum & 0xffff) + (sum >> 16);
417
418 return ~sum;
419}
420
421/* Constuct a ip/udp header for a packet, and specify the source and dest hardware address */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000422static int raw_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port,
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000423 u_int32_t dest_ip, int dest_port, unsigned char *dest_arp, int ifindex)
424{
425 int l_fd;
426 int result;
427 struct sockaddr_ll dest;
428 struct udp_dhcp_packet packet;
429
430 if ((l_fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
431 DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]);
432 return -1;
433 }
434
435 memset(&dest, 0, sizeof(dest));
436 memset(&packet, 0, sizeof(packet));
437
438 dest.sll_family = AF_PACKET;
439 dest.sll_protocol = htons(ETH_P_IP);
440 dest.sll_ifindex = ifindex;
441 dest.sll_halen = 6;
442 memcpy(dest.sll_addr, dest_arp, 6);
443 if (bind(l_fd, (struct sockaddr *)&dest, sizeof(struct sockaddr_ll)) < 0) {
444 DEBUG(LOG_ERR, "bind call failed: %s", sys_errlist[errno]);
445 close(l_fd);
446 return -1;
447 }
448
449 packet.ip.protocol = IPPROTO_UDP;
450 packet.ip.saddr = source_ip;
451 packet.ip.daddr = dest_ip;
452 packet.udp.source = htons(source_port);
453 packet.udp.dest = htons(dest_port);
454 packet.udp.len = htons(sizeof(packet.udp) + sizeof(struct dhcpMessage)); /* cheat on the psuedo-header */
455 packet.ip.tot_len = packet.udp.len;
456 memcpy(&(packet.data), payload, sizeof(struct dhcpMessage));
457 packet.udp.check = checksum(&packet, sizeof(struct udp_dhcp_packet));
458
459 packet.ip.tot_len = htons(sizeof(struct udp_dhcp_packet));
460 packet.ip.ihl = sizeof(packet.ip) >> 2;
461 packet.ip.version = IPVERSION;
462 packet.ip.ttl = IPDEFTTL;
463 packet.ip.check = checksum(&(packet.ip), sizeof(packet.ip));
464
465 result = sendto(l_fd, &packet, sizeof(struct udp_dhcp_packet), 0, (struct sockaddr *) &dest, sizeof(dest));
466 if (result <= 0) {
467 DEBUG(LOG_ERR, "write on socket failed: %s", sys_errlist[errno]);
468 }
469 close(l_fd);
470 return result;
471}
472
473/* Let the kernel do all the work for packet generation */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000474static int kernel_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port,
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000475 u_int32_t dest_ip, int dest_port)
476{
477 int n = 1;
478 int l_fd, result;
479 struct sockaddr_in client;
480
481 if ((l_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
482 return -1;
483
484 if (setsockopt(l_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1)
485 return -1;
486
487 memset(&client, 0, sizeof(client));
488 client.sin_family = AF_INET;
489 client.sin_port = htons(source_port);
490 client.sin_addr.s_addr = source_ip;
491
492 if (bind(l_fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1)
493 return -1;
494
495 memset(&client, 0, sizeof(client));
496 client.sin_family = AF_INET;
497 client.sin_port = htons(dest_port);
498 client.sin_addr.s_addr = dest_ip;
499
500 if (connect(l_fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1)
501 return -1;
502
503 result = write(l_fd, payload, sizeof(struct dhcpMessage));
504 close(l_fd);
505 return result;
506}
507
508/* initialize a packet with the proper defaults */
509static void init_packet(struct dhcpMessage *packet, char type)
510{
511 struct vendor {
512 char vendor, length;
513 char str[sizeof("udhcp "VERSION)];
514 } vendor_id = { DHCP_VENDOR, sizeof("udhcp "VERSION) - 1, "udhcp "VERSION};
515
516// init_header(packet, type);
517 memset(packet, 0, sizeof(struct dhcpMessage));
518 switch (type) {
519 case DHCPDISCOVER:
520 case DHCPREQUEST:
521 case DHCPRELEASE:
522 case DHCPINFORM:
523 packet->op = BOOTREQUEST;
524 break;
525 case DHCPOFFER:
526 case DHCPACK:
527 case DHCPNAK:
528 packet->op = BOOTREPLY;
529 }
530 packet->htype = ETH_10MB;
531 packet->hlen = ETH_10MB_LEN;
532 packet->cookie = htonl(DHCP_MAGIC);
533 packet->options[0] = DHCP_END;
534 add_simple_option(packet->options, DHCP_MESSAGE_TYPE, type);
535
536 memcpy(packet->chaddr, client_config.arp, 6);
537 add_option_string(packet->options, client_config.clientid);
538 if (client_config.hostname) add_option_string(packet->options, client_config.hostname);
539 add_option_string(packet->options, (unsigned char *) &vendor_id);
540}
541
542
543/* Add a paramater request list for stubborn DHCP servers. Pull the data
544 * from the struct in options.c. Don't do bounds checking here because it
545 * goes towards the head of the packet. */
546static void add_requests(struct dhcpMessage *packet)
547{
548 int end = end_option(packet->options);
549 int i, len = 0;
550
551 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
552 for (i = 0; options[i].code; i++)
553 if (options[i].flags & OPTION_REQ)
554 packet->options[end + OPT_DATA + len++] = options[i].code;
555 packet->options[end + OPT_LEN] = len;
556 packet->options[end + OPT_DATA + len] = DHCP_END;
557
558}
559
560/* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000561static int send_discover(unsigned long xid, unsigned long requested)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000562{
563 struct dhcpMessage packet;
564
565 init_packet(&packet, DHCPDISCOVER);
566 packet.xid = xid;
567 if (requested)
568 add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);
569
570 add_requests(&packet);
571 LOG(LOG_DEBUG, "Sending discover...");
572 return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
573 SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
574}
575
576/* Broadcasts a DHCP request message */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000577static int send_selecting(unsigned long xid, unsigned long server, unsigned long requested)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000578{
579 struct dhcpMessage packet;
580 struct in_addr addr;
581
582 init_packet(&packet, DHCPREQUEST);
583 packet.xid = xid;
584
585 add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);
586 add_simple_option(packet.options, DHCP_SERVER_ID, server);
587
588 add_requests(&packet);
589 addr.s_addr = requested;
590 LOG(LOG_DEBUG, "Sending select for %s...", inet_ntoa(addr));
591 return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
592 SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
593}
594
595
596/* Unicasts or broadcasts a DHCP renew message */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000597static int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000598{
599 struct dhcpMessage packet;
600 int ret = 0;
601
602 init_packet(&packet, DHCPREQUEST);
603 packet.xid = xid;
604 packet.ciaddr = ciaddr;
605
606 add_requests(&packet);
607 LOG(LOG_DEBUG, "Sending renew...");
608 if (server)
609 ret = kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
610 else ret = raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
611 SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
612 return ret;
613}
614
615/* Create a random xid */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000616static unsigned long random_xid(void)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000617{
618 static int initialized;
619 if (!initialized) {
620 srand(time(0));
621 initialized++;
622 }
623 return rand();
624}
625#if 0
626/* Unicasts a DHCP release message */
627int send_release(unsigned long server, unsigned long ciaddr)
628{
629 struct dhcpMessage packet;
630
631 init_packet(&packet, DHCPRELEASE);
632 packet.xid = random_xid();
633 packet.ciaddr = ciaddr;
634
635 add_simple_option(packet.options, DHCP_REQUESTED_IP, ciaddr);
636 add_simple_option(packet.options, DHCP_SERVER_ID, server);
637
638 LOG(LOG_DEBUG, "Sending release...");
639 return kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
640}
641#endif
642
643/* just a little helper */
644static void change_mode(int new_mode)
645{
646 DEBUG(LOG_INFO, "entering %s listen mode",
647 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
648 close(fd_main);
649 fd_main = -1;
650 listen_mode = new_mode;
651}
652
653
654/* SIGUSR1 handler (renew) */
655static void renew_requested(int sig)
656{
657 sig = 0;
658 LOG(LOG_INFO, "Received SIGUSR1");
659 if (state == BOUND || state == RENEWING || state == REBINDING ||
660 state == RELEASED) {
661 change_mode(LISTEN_KERNEL);
662 packet_num = 0;
663 state = RENEW_REQUESTED;
664 }
665
666 if (state == RELEASED) {
667 change_mode(LISTEN_RAW);
668 state = INIT_SELECTING;
669 }
670
671 /* Kill any timeouts because the user wants this to hurry along */
672 timeout = 0;
673}
674
675/* get an option with bounds checking (warning, not aligned). */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000676static unsigned char *get_option(struct dhcpMessage *packet, int code)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000677{
678 int i, length;
679 unsigned char *optionptr;
680 int over = 0, done = 0, curr = OPTION_FIELD;
681
682 optionptr = packet->options;
683 i = 0;
684 length = 308;
685 while (!done) {
686 if (i >= length) {
687 LOG(LOG_WARNING, "bogus packet, option fields too long.");
688 return NULL;
689 }
690 if (optionptr[i + OPT_CODE] == code) {
691 if (i + 1 + optionptr[i + OPT_LEN] >= length) {
692 LOG(LOG_WARNING, "bogus packet, option fields too long.");
693 return NULL;
694 }
695 return optionptr + i + 2;
696 }
697 switch (optionptr[i + OPT_CODE]) {
698 case DHCP_PADDING:
699 i++;
700 break;
701 case DHCP_OPTION_OVER:
702 if (i + 1 + optionptr[i + OPT_LEN] >= length) {
703 LOG(LOG_WARNING, "bogus packet, option fields too long.");
704 return NULL;
705 }
706 over = optionptr[i + 3];
707 i += optionptr[OPT_LEN] + 2;
708 break;
709 case DHCP_END:
710 if (curr == OPTION_FIELD && over & FILE_FIELD) {
711 optionptr = packet->file;
712 i = 0;
713 length = 128;
714 curr = FILE_FIELD;
715 } else if (curr == FILE_FIELD && over & SNAME_FIELD) {
716 optionptr = packet->sname;
717 i = 0;
718 length = 64;
719 curr = SNAME_FIELD;
720 } else done = 1;
721 break;
722 default:
723 i += optionptr[OPT_LEN + i] + 2;
724 }
725 }
726 return NULL;
727}
728#if 0
729static int upper_length(int length, struct dhcp_option *option)
730{
731 return max_option_length[option->flags & TYPE_MASK] *
732 (length / option_lengths[option->flags & TYPE_MASK]);
733}
734#endif
735
736static int sprintip(char *dest, char *pre, unsigned char *ip) {
737 return sprintf(dest, "%s%d.%d.%d.%d ", pre, ip[0], ip[1], ip[2], ip[3]);
738}
739
740
741/* Fill dest with the text of option 'option'. */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000742static void fill_options(char *dest, unsigned char *option, const struct dhcp_option *type_p)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000743{
744 int type, optlen;
745 u_int16_t val_u16;
746 int16_t val_s16;
747 u_int32_t val_u32;
748 int32_t val_s32;
749 int len = option[OPT_LEN - 2];
750
751 dest += sprintf(dest, "%s=", type_p->name);
752
753 type = type_p->flags & TYPE_MASK;
754 optlen = option_lengths[type];
755 for(;;) {
756 switch (type) {
757 case OPTION_IP_PAIR:
758 dest += sprintip(dest, "", option);
759 *(dest++) = '/';
760 option += 4;
761 optlen = 4;
762 case OPTION_IP: /* Works regardless of host byte order. */
763 dest += sprintip(dest, "", option);
764 break;
765 case OPTION_BOOLEAN:
766 dest += sprintf(dest, *option ? "yes " : "no ");
767 break;
768 case OPTION_U8:
769 dest += sprintf(dest, "%u ", *option);
770 break;
771 case OPTION_U16:
772 memcpy(&val_u16, option, 2);
773 dest += sprintf(dest, "%u ", ntohs(val_u16));
774 break;
775 case OPTION_S16:
776 memcpy(&val_s16, option, 2);
777 dest += sprintf(dest, "%d ", ntohs(val_s16));
778 break;
779 case OPTION_U32:
780 memcpy(&val_u32, option, 4);
781 dest += sprintf(dest, "%lu ", (unsigned long) ntohl(val_u32));
782 break;
783 case OPTION_S32:
784 memcpy(&val_s32, option, 4);
785 dest += sprintf(dest, "%ld ", (long) ntohl(val_s32));
786 break;
787 case OPTION_STRING:
788 memcpy(dest, option, len);
789 dest[len] = '\0';
790 return; /* Short circuit this case */
791 }
792 option += optlen;
793 len -= optlen;
794 if (len <= 0) break;
795 }
796}
797
798static char *find_env(const char *prefix, char *defaultstr)
799{
800 extern char **environ;
801 char **ptr;
802 const int len = strlen(prefix);
803
804 for (ptr = environ; *ptr != NULL; ptr++) {
805 if (strncmp(prefix, *ptr, len) == 0)
806 return *ptr;
807 }
808 return defaultstr;
809}
810
811/* put all the paramaters into an environment */
812static char **fill_envp(struct dhcpMessage *packet)
813{
814 /* supported options are easily added here */
815 int num_options = 0;
816 int i, j;
817 char **envp;
818 unsigned char *temp;
819 char over = 0;
820
821 if (packet == NULL)
822 num_options = 0;
823 else {
824 for (i = 0; options[i].code; i++)
825 if (get_option(packet, options[i].code))
826 num_options++;
827 if (packet->siaddr) num_options++;
828 if ((temp = get_option(packet, DHCP_OPTION_OVER)))
829 over = *temp;
830 if (!(over & FILE_FIELD) && packet->file[0]) num_options++;
831 if (!(over & SNAME_FIELD) && packet->sname[0]) num_options++;
832 }
833
834 envp = xmalloc((num_options + 5) * sizeof(char *));
835 envp[0] = xmalloc(sizeof("interface=") + strlen(client_config.interface));
836 sprintf(envp[0], "interface=%s", client_config.interface);
837 envp[1] = find_env("PATH", "PATH=/bin:/usr/bin:/sbin:/usr/sbin");
838 envp[2] = find_env("HOME", "HOME=/");
839
840 if (packet == NULL) {
841 envp[3] = NULL;
842 return envp;
843 }
844
845 envp[3] = xmalloc(sizeof("ip=255.255.255.255"));
846 sprintip(envp[3], "ip=", (unsigned char *) &packet->yiaddr);
847 for (i = 0, j = 4; options[i].code; i++) {
848 if ((temp = get_option(packet, options[i].code))) {
849 envp[j] = xmalloc(max_option_length[(&options[i])->flags & TYPE_MASK] * (temp[OPT_LEN - 2] / option_lengths[(&options[i])->flags & TYPE_MASK]) + strlen((&options[i])->name) + 2);
850// envp[j] = xmalloc(upper_length(temp[OPT_LEN - 2], &options[i]) + strlen(options[i].name) + 2);
851 fill_options(envp[j], temp, &options[i]);
852 j++;
853 }
854 }
855 if (packet->siaddr) {
856 envp[j] = xmalloc(sizeof("siaddr=255.255.255.255"));
857 sprintip(envp[j++], "siaddr=", (unsigned char *) &packet->yiaddr);
858 }
859 if (!(over & FILE_FIELD) && packet->file[0]) {
860 /* watch out for invalid packets */
861 packet->file[sizeof(packet->file) - 1] = '\0';
862 envp[j] = xmalloc(sizeof("boot_file=") + strlen(packet->file));
863 sprintf(envp[j++], "boot_file=%s", packet->file);
864 }
865 if (!(over & SNAME_FIELD) && packet->sname[0]) {
866 /* watch out for invalid packets */
867 packet->sname[sizeof(packet->sname) - 1] = '\0';
868 envp[j] = xmalloc(sizeof("sname=") + strlen(packet->sname));
869 sprintf(envp[j++], "sname=%s", packet->sname);
870 }
871 envp[j] = NULL;
872 return envp;
873}
874
875/* Call a script with a par file and env vars */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000876static void run_script(struct dhcpMessage *packet, const char *name)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000877{
878 int pid;
879 char **envp;
880
881 if (client_config.script == NULL)
882 return;
883
884 /* call script */
885 pid = fork();
886 if (pid) {
887 waitpid(pid, NULL, 0);
888 return;
889 } else if (pid == 0) {
890 envp = fill_envp(packet);
891
892 /* close fd's? */
893
894 /* exec script */
895 DEBUG(LOG_INFO, "execle'ing %s", client_config.script);
896 execle(client_config.script, client_config.script,
897 name, NULL, envp);
898 LOG(LOG_ERR, "script %s failed: %s",
899 client_config.script, sys_errlist[errno]);
900 exit(1);
901 }
902}
903
904/* SIGUSR2 handler (release) */
905static void release_requested(int sig)
906{
907 sig = 0;
908 LOG(LOG_INFO, "Received SIGUSR2");
909 /* send release packet */
910 if (state == BOUND || state == RENEWING || state == REBINDING) {
911 struct dhcpMessage packet;
912
913 init_packet(&packet, DHCPRELEASE);
914 packet.xid = random_xid();
915 packet.ciaddr = requested_ip;
916
917 add_simple_option(packet.options, DHCP_REQUESTED_IP, requested_ip);
918 add_simple_option(packet.options, DHCP_SERVER_ID, server_addr);
919
920 LOG(LOG_DEBUG, "Sending release...");
921 kernel_packet(&packet, requested_ip, CLIENT_PORT, server_addr, SERVER_PORT);
922 run_script(NULL, "deconfig");
923 }
924
925 change_mode(LISTEN_NONE);
926 state = RELEASED;
927 timeout = 0x7fffffff;
928}
929
930
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000931static int pidfile_acquire(char *pidfile)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000932{
933 int pid_fd;
934 if (pidfile == NULL) return -1;
935
936 pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644);
937 if (pid_fd < 0) {
938 LOG(LOG_ERR, "Unable to open pidfile %s: %s\n",
939 pidfile, strerror(errno));
940 } else {
941 lockf(pid_fd, F_LOCK, 0);
942 }
943
944 return pid_fd;
945}
946
947
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000948static void pidfile_write_release(int pid_fd)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000949{
950 FILE *out;
951
952 if (pid_fd < 0) return;
953
954 if ((out = fdopen(pid_fd, "w")) != NULL) {
955 fprintf(out, "%d\n", getpid());
956 fclose(out);
957 }
958 lockf(pid_fd, F_UNLCK, 0);
959 close(pid_fd);
960}
961
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000962/* Exit and cleanup */
963static void exit_client(int retval)
964{
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000965 unlink(client_config.pidfile);
966 if (client_config.pidfile) unlink(client_config.pidfile);
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000967 CLOSE_LOG();
968 exit(retval);
969}
970
971
972/* SIGTERM handler */
973static void terminate(int sig)
974{
975 sig = 0;
976 LOG(LOG_INFO, "Received SIGTERM");
977 exit_client(0);
978}
979
980
Aaron Lehmann1ff58b62002-08-21 11:21:19 +0000981static int read_interface(char *interface, int *ifindex, u_int32_t *addr, unsigned char *arp)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +0000982{
983 int l_fd;
984 struct ifreq ifr;
985 struct sockaddr_in *s_in;
986
987 memset(&ifr, 0, sizeof(struct ifreq));
988 if((l_fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) >= 0) {
989 ifr.ifr_addr.sa_family = AF_INET;
990 strcpy(ifr.ifr_name, interface);
991
992 if (addr) {
993 if (ioctl(l_fd, SIOCGIFADDR, &ifr) == 0) {
994 s_in = (struct sockaddr_in *) &ifr.ifr_addr;
995 *addr = s_in->sin_addr.s_addr;
996 DEBUG(LOG_INFO, "%s (our ip) = %s", ifr.ifr_name, inet_ntoa(s_in->sin_addr));
997 } else {
998 LOG(LOG_ERR, "SIOCGIFADDR failed!: %s", sys_errlist[errno]);
999 return -1;
1000 }
1001 }
1002
1003 if (ioctl(l_fd, SIOCGIFINDEX, &ifr) == 0) {
1004 DEBUG(LOG_INFO, "adapter index %d", ifr.ifr_ifindex);
1005 *ifindex = ifr.ifr_ifindex;
1006 } else {
1007 LOG(LOG_ERR, "SIOCGIFINDEX failed!: %s", sys_errlist[errno]);
1008 return -1;
1009 }
1010 if (ioctl(l_fd, SIOCGIFHWADDR, &ifr) == 0) {
1011 memcpy(arp, ifr.ifr_hwaddr.sa_data, 6);
1012 DEBUG(LOG_INFO, "adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x",
1013 arp[0], arp[1], arp[2], arp[3], arp[4], arp[5]);
1014 } else {
1015 LOG(LOG_ERR, "SIOCGIFHWADDR failed!: %s", sys_errlist[errno]);
1016 return -1;
1017 }
1018 } else {
1019 LOG(LOG_ERR, "socket failed!: %s", sys_errlist[errno]);
1020 return -1;
1021 }
1022 close(l_fd);
1023 return 0;
1024}
1025
1026
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001027static int listen_socket(unsigned int ip, int port, char *inf)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001028{
1029 struct ifreq interface;
1030 int l_fd;
1031 struct sockaddr_in addr;
1032 int n = 1;
1033
1034 DEBUG(LOG_INFO, "Opening listen socket on 0x%08x:%d %s\n", ip, port, inf);
1035 if ((l_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
1036 DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]);
1037 return -1;
1038 }
1039
1040 memset(&addr, 0, sizeof(addr));
1041 addr.sin_family = AF_INET;
1042 addr.sin_port = htons(port);
1043 addr.sin_addr.s_addr = ip;
1044
1045 if (setsockopt(l_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1) {
1046 close(l_fd);
1047 return -1;
1048 }
1049 if (setsockopt(l_fd, SOL_SOCKET, SO_BROADCAST, (char *) &n, sizeof(n)) == -1) {
1050 close(l_fd);
1051 return -1;
1052 }
1053
1054 strncpy(interface.ifr_ifrn.ifrn_name, inf, IFNAMSIZ);
1055 if (setsockopt(l_fd, SOL_SOCKET, SO_BINDTODEVICE,(char *)&interface, sizeof(interface)) < 0) {
1056 close(l_fd);
1057 return -1;
1058 }
1059
1060 if (bind(l_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
1061 close(l_fd);
1062 return -1;
1063 }
1064
1065 return l_fd;
1066}
1067
1068
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001069static int raw_socket(int ifindex)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001070{
1071 int l_fd;
1072 struct sockaddr_ll sock;
1073
1074 DEBUG(LOG_INFO, "Opening raw socket on ifindex %d\n", ifindex);
1075 if ((l_fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
1076 DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]);
1077 return -1;
1078 }
1079
1080 sock.sll_family = AF_PACKET;
1081 sock.sll_protocol = htons(ETH_P_IP);
1082 sock.sll_ifindex = ifindex;
1083 if (bind(l_fd, (struct sockaddr *) &sock, sizeof(sock)) < 0) {
1084 DEBUG(LOG_ERR, "bind call failed: %s", sys_errlist[errno]);
1085 close(l_fd);
1086 return -1;
1087 }
1088
1089 return l_fd;
1090
1091}
1092
1093/* read a packet from socket fd, return -1 on read error, -2 on packet error */
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001094static int get_packet(struct dhcpMessage *packet, int l_fd)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001095{
1096 int bytes;
1097 int i;
1098 const char broken_vendors[][8] = {
1099 "MSFT 98",
1100 ""
1101 };
1102 char unsigned *vendor;
1103
1104 memset(packet, 0, sizeof(struct dhcpMessage));
1105 bytes = read(l_fd, packet, sizeof(struct dhcpMessage));
1106 if (bytes < 0) {
1107 DEBUG(LOG_INFO, "couldn't read on listening socket, ignoring");
1108 return -1;
1109 }
1110
1111 if (ntohl(packet->cookie) != DHCP_MAGIC) {
1112 LOG(LOG_ERR, "received bogus message, ignoring");
1113 return -2;
1114 }
1115 DEBUG(LOG_INFO, "Received a packet");
1116
1117 if (packet->op == BOOTREQUEST && (vendor = get_option(packet, DHCP_VENDOR))) {
1118 for (i = 0; broken_vendors[i][0]; i++) {
1119 if (vendor[OPT_LEN - 2] == (unsigned char) strlen(broken_vendors[i]) &&
1120 !strncmp(vendor, broken_vendors[i], vendor[OPT_LEN - 2])) {
1121 DEBUG(LOG_INFO, "broken client (%s), forcing broadcast",
1122 broken_vendors[i]);
1123 packet->flags |= htons(BROADCAST_FLAG);
1124 }
1125 }
1126 }
1127
1128
1129 return bytes;
1130}
1131
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001132static int get_raw_packet(struct dhcpMessage *payload, int l_fd)
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001133{
1134 int bytes;
1135 struct udp_dhcp_packet packet;
1136 u_int32_t source, dest;
1137 u_int16_t check;
1138
1139 memset(&packet, 0, sizeof(struct udp_dhcp_packet));
1140 bytes = read(l_fd, &packet, sizeof(struct udp_dhcp_packet));
1141 if (bytes < 0) {
1142 DEBUG(LOG_INFO, "couldn't read on raw listening socket -- ignoring");
1143 usleep(500000); /* possible down interface, looping condition */
1144 return -1;
1145 }
1146
1147 if (bytes < (int) (sizeof(struct iphdr) + sizeof(struct udphdr))) {
1148 DEBUG(LOG_INFO, "message too short, ignoring");
1149 return -1;
1150 }
1151
1152 if (bytes < ntohs(packet.ip.tot_len)) {
1153 DEBUG(LOG_INFO, "Truncated packet");
1154 return -1;
1155 }
1156
1157 /* ignore any extra garbage bytes */
1158 bytes = ntohs(packet.ip.tot_len);
1159
1160 /* Make sure its the right packet for us, and that it passes sanity checks */
1161 if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION ||
1162 packet.ip.ihl != sizeof(packet.ip) >> 2 || packet.udp.dest != htons(CLIENT_PORT) ||
1163 bytes > (int) sizeof(struct udp_dhcp_packet) ||
1164 ntohs(packet.udp.len) != (short) (bytes - sizeof(packet.ip))) {
1165 DEBUG(LOG_INFO, "unrelated/bogus packet");
1166 return -1;
1167 }
1168
1169 /* check IP checksum */
1170 check = packet.ip.check;
1171 packet.ip.check = 0;
1172 if (check != checksum(&(packet.ip), sizeof(packet.ip))) {
1173 DEBUG(LOG_INFO, "bad IP header checksum, ignoring");
1174 return -1;
1175 }
1176
1177 /* verify the UDP checksum by replacing the header with a psuedo header */
1178 source = packet.ip.saddr;
1179 dest = packet.ip.daddr;
1180 check = packet.udp.check;
1181 packet.udp.check = 0;
1182 memset(&packet.ip, 0, sizeof(packet.ip));
1183
1184 packet.ip.protocol = IPPROTO_UDP;
1185 packet.ip.saddr = source;
1186 packet.ip.daddr = dest;
1187 packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */
1188 if (check && check != checksum(&packet, bytes)) {
1189 DEBUG(LOG_ERR, "packet with bad UDP checksum received, ignoring");
1190 return -1;
1191 }
1192
1193 memcpy(payload, &(packet.data), bytes - (sizeof(packet.ip) + sizeof(packet.udp)));
1194
1195 if (ntohl(payload->cookie) != DHCP_MAGIC) {
1196 LOG(LOG_ERR, "received bogus message (bad magic) -- ignoring");
1197 return -1;
1198 }
1199 DEBUG(LOG_INFO, "oooooh!!! got some!");
1200 return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
1201
1202}
1203
1204
1205int udhcpc_main(int argc, char *argv[])
1206{
1207 unsigned char *temp, *message;
1208 unsigned long t1 = 0, t2 = 0, xid = 0;
1209 unsigned long start = 0, lease;
1210 fd_set rfds;
1211 int retval;
1212 struct timeval tv;
1213 int c, len;
1214 struct dhcpMessage packet;
1215 struct in_addr temp_addr;
1216 int pid_fd;
1217 time_t now;
1218
1219 static struct option l_options[] = {
1220 {"clientid", required_argument, 0, 'c'},
1221 {"foreground", no_argument, 0, 'f'},
1222 {"hostname", required_argument, 0, 'H'},
1223 {"help", no_argument, 0, 'h'},
1224 {"interface", required_argument, 0, 'i'},
1225 {"now", no_argument, 0, 'n'},
1226 {"pidfile", required_argument, 0, 'p'},
1227 {"quit", no_argument, 0, 'q'},
1228 {"request", required_argument, 0, 'r'},
1229 {"script", required_argument, 0, 's'},
1230 {"version", no_argument, 0, 'v'},
1231 {0, 0, 0, 0}
1232 };
1233
1234 /* get options */
1235 while (1) {
1236 int option_index = 0;
1237 c = getopt_long(argc, argv, "c:fH:hi:np:qr:s:v", l_options, &option_index);
1238 if (c == -1) break;
1239
1240 switch (c) {
1241 case 'c':
1242 len = strlen(optarg) > 255 ? 255 : strlen(optarg);
1243 if (client_config.clientid) free(client_config.clientid);
1244 client_config.clientid = xmalloc(len + 2);
1245 client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
1246 client_config.clientid[OPT_LEN] = len;
1247 client_config.clientid[OPT_DATA] = '\0';
1248 strncpy(client_config.clientid + 3, optarg, len - 1);
1249 break;
1250 case 'f':
1251 client_config.foreground = 1;
1252 break;
1253 case 'H':
1254 len = strlen(optarg) > 255 ? 255 : strlen(optarg);
1255 if (client_config.hostname) free(client_config.hostname);
1256 client_config.hostname = xmalloc(len + 2);
1257 client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
1258 client_config.hostname[OPT_LEN] = len;
1259 strncpy(client_config.hostname + 2, optarg, len);
1260 break;
1261 case 'h':
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001262 puts(
1263"Usage: udhcpcd [OPTIONS]\n\n"
1264" -c, --clientid=CLIENTID Client identifier\n"
1265" -H, --hostname=HOSTNAME Client hostname\n"
1266" -f, --foreground Do not fork after getting lease\n"
1267" -i, --interface=INTERFACE Interface to use (default: eth0)\n"
1268" -n, --now Exit with failure if lease cannot be\n"
1269" immediately negotiated.\n"
1270" -p, --pidfile=file Store process ID of daemon in file\n"
1271" -q, --quit Quit after obtaining lease\n"
1272" -r, --request=IP IP address to request (default: none)\n"
1273" -s, --script=file Run file at dhcp events (default:\n"
1274" " DEFAULT_SCRIPT ")\n"
1275" -v, --version Display version"
1276 );
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001277 return 0;
1278 case 'i':
1279 client_config.interface = optarg;
1280 break;
1281 case 'n':
1282 client_config.abort_if_no_lease = 1;
1283 break;
1284 case 'p':
1285 client_config.pidfile = optarg;
1286 break;
1287 case 'q':
1288 client_config.quit_after_lease = 1;
1289 break;
1290 case 'r':
1291 requested_ip = inet_addr(optarg);
1292 break;
1293 case 's':
1294 client_config.script = optarg;
1295 break;
1296 case 'v':
1297 printf("udhcpcd, version %s\n\n", VERSION);
1298 exit_client(0);
1299 break;
1300 }
1301 }
1302
1303 OPEN_LOG("udhcpc");
1304 LOG(LOG_INFO, "udhcp client (v%s) started", VERSION);
1305
1306 pid_fd = pidfile_acquire(client_config.pidfile);
1307 pidfile_write_release(pid_fd);
1308
1309 if (read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.arp) < 0) {
1310 exit_client(1);
1311 }
1312
1313 if (!client_config.clientid) {
1314 client_config.clientid = xmalloc(6 + 3);
1315 client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
1316 client_config.clientid[OPT_LEN] = 7;
1317 client_config.clientid[OPT_DATA] = 1;
1318 memcpy(client_config.clientid + 3, client_config.arp, 6);
1319 }
1320
1321 /* setup signal handlers */
1322 signal(SIGUSR1, renew_requested);
1323 signal(SIGUSR2, release_requested);
1324 signal(SIGTERM, terminate);
1325
1326 state = INIT_SELECTING;
1327 run_script(NULL, "deconfig");
1328 change_mode(LISTEN_RAW);
1329
1330 for (;;) {
1331 tv.tv_sec = timeout - time(0);
1332 tv.tv_usec = 0;
1333 FD_ZERO(&rfds);
1334
1335 if (listen_mode != LISTEN_NONE && fd_main < 0) {
1336 if (listen_mode == LISTEN_KERNEL) {
1337 fd_main = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
1338 } else {
1339 fd_main = raw_socket(client_config.ifindex);
1340 }
1341 if (fd_main < 0) {
1342 LOG(LOG_ERR, "FATAL: couldn't listen on socket, %s", sys_errlist[errno]);
1343 exit_client(0);
1344 }
1345 }
1346 if (fd_main >= 0) {
1347 FD_SET(fd_main, &rfds);
1348 }
1349
1350 if (tv.tv_sec > 0) {
1351 DEBUG(LOG_INFO, "Waiting on select...\n");
1352 retval = select(fd_main + 1, &rfds, NULL, NULL, &tv);
1353 } else {
1354 retval = 0; /* If we already timed out, fall through */
1355 }
1356
1357 now = time(0);
1358 if (retval == 0) {
1359 /* timeout dropped to zero */
1360 switch (state) {
1361 case INIT_SELECTING:
1362 if (packet_num < 3) {
1363 if (packet_num == 0) {
1364 xid = random_xid();
1365 }
1366 /* send discover packet */
1367 send_discover(xid, requested_ip); /* broadcast */
1368
1369 timeout = now + ((packet_num == 2) ? 10 : 2);
1370 packet_num++;
1371 } else {
1372 if (client_config.abort_if_no_lease) {
1373 LOG(LOG_INFO, "No lease, failing.");
1374 exit_client(1);
1375 }
1376 /* wait to try again */
1377 packet_num = 0;
1378 timeout = now + 60;
1379 }
1380 break;
1381 case RENEW_REQUESTED:
1382 case REQUESTING:
1383 if (packet_num < 3) {
1384 /* send request packet */
1385 if (state == RENEW_REQUESTED) {
1386 send_renew(xid, server_addr, requested_ip); /* unicast */
1387 } else {
1388 send_selecting(xid, server_addr, requested_ip); /* broadcast */
1389 }
1390 timeout = now + ((packet_num == 2) ? 10 : 2);
1391 packet_num++;
1392 } else {
1393 /* timed out, go back to init state */
1394 state = INIT_SELECTING;
1395 timeout = now;
1396 packet_num = 0;
1397 change_mode(LISTEN_RAW);
1398 }
1399 break;
1400 case BOUND:
1401 /* Lease is starting to run out, time to enter renewing state */
1402 state = RENEWING;
1403 change_mode(LISTEN_KERNEL);
1404 DEBUG(LOG_INFO, "Entering renew state");
1405 /* fall right through */
1406 case RENEWING:
1407 /* Either set a new T1, or enter REBINDING state */
1408 if ((t2 - t1) <= (lease / 14400 + 1)) {
1409 /* timed out, enter rebinding state */
1410 state = REBINDING;
1411 timeout = now + (t2 - t1);
1412 DEBUG(LOG_INFO, "Entering rebinding state");
1413 } else {
1414 /* send a request packet */
1415 send_renew(xid, server_addr, requested_ip); /* unicast */
1416
1417 t1 = (t2 - t1) / 2 + t1;
1418 timeout = t1 + start;
1419 }
1420 break;
1421 case REBINDING:
1422 /* Either set a new T2, or enter INIT state */
1423 if ((lease - t2) <= (lease / 14400 + 1)) {
1424 /* timed out, enter init state */
1425 state = INIT_SELECTING;
1426 LOG(LOG_INFO, "Lease lost, entering init state");
1427 run_script(NULL, "deconfig");
1428 timeout = now;
1429 packet_num = 0;
1430 change_mode(LISTEN_RAW);
1431 } else {
1432 /* send a request packet */
1433 send_renew(xid, 0, requested_ip); /* broadcast */
1434
1435 t2 = (lease - t2) / 2 + t2;
1436 timeout = t2 + start;
1437 }
1438 break;
1439 case RELEASED:
1440 /* yah, I know, *you* say it would never happen */
1441 timeout = 0x7fffffff;
1442 break;
1443 }
1444 } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd_main, &rfds)) {
1445 /* a packet is ready, read it */
1446
1447 if (listen_mode == LISTEN_KERNEL) {
1448 len = get_packet(&packet, fd_main);
1449 } else {
1450 len = get_raw_packet(&packet, fd_main);
1451 }
1452 if (len == -1 && errno != EINTR) {
1453 DEBUG(LOG_INFO, "error on read, %s, reopening socket", sys_errlist[errno]);
1454 change_mode(listen_mode); /* just close and reopen */
1455 }
1456 if (len < 0) {
1457 continue;
1458 }
1459
1460 if (packet.xid != xid) {
1461 DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
1462 (unsigned long) packet.xid, xid);
1463 continue;
1464 }
1465
1466 if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
1467 DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
1468 continue;
1469 }
1470
1471 switch (state) {
1472 case INIT_SELECTING:
1473 /* Must be a DHCPOFFER to one of our xid's */
1474 if (*message == DHCPOFFER) {
1475 if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
1476 memcpy(&server_addr, temp, 4);
1477 xid = packet.xid;
1478 requested_ip = packet.yiaddr;
1479
1480 /* enter requesting state */
1481 state = REQUESTING;
1482 timeout = now;
1483 packet_num = 0;
1484 } else {
1485 DEBUG(LOG_ERR, "No server ID in message");
1486 }
1487 }
1488 break;
1489 case RENEW_REQUESTED:
1490 case REQUESTING:
1491 case RENEWING:
1492 case REBINDING:
1493 if (*message == DHCPACK) {
1494 if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
1495 LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
1496 lease = 60 * 60;
1497 } else {
1498 memcpy(&lease, temp, 4);
1499 lease = ntohl(lease);
1500 }
1501
1502 /* enter bound state */
1503 t1 = lease / 2;
1504
1505 /* little fixed point for n * .875 */
1506 t2 = (lease * 0x7) >> 3;
1507 temp_addr.s_addr = packet.yiaddr;
1508 LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", inet_ntoa(temp_addr), lease);
1509 start = now;
1510 timeout = t1 + start;
1511 requested_ip = packet.yiaddr;
1512 run_script(&packet, ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
1513
1514 state = BOUND;
1515 change_mode(LISTEN_NONE);
Aaron Lehmann1ff58b62002-08-21 11:21:19 +00001516 {
1517 int pid_fd2;
1518 if (client_config.quit_after_lease) {
1519 exit_client(0);
1520 } else if (!client_config.foreground) {
1521 pid_fd2 = pidfile_acquire(client_config.pidfile); /* hold lock during fork. */
1522 if (daemon(0, 0) == -1) {
1523 perror("fork");
1524 exit_client(1);
1525 }
1526 client_config.foreground = 1; /* Do not fork again. */
1527 pidfile_write_release(pid_fd2);
1528 }
1529 }
Glenn L McGrath8eb0dc12002-08-21 10:27:58 +00001530 }
1531 else if (*message == DHCPNAK) {
1532 /* return to init state */
1533 LOG(LOG_INFO, "Received DHCP NAK");
1534 run_script(&packet, "nak");
1535 if (state != REQUESTING) {
1536 run_script(NULL, "deconfig");
1537 }
1538 state = INIT_SELECTING;
1539 timeout = now;
1540 requested_ip = 0;
1541 packet_num = 0;
1542 change_mode(LISTEN_RAW);
1543 sleep(3); /* avoid excessive network traffic */
1544 }
1545 break;
1546 /* case BOUND, RELEASED: - ignore all packets */
1547 }
1548 }
1549 else if (retval == -1 && errno == EINTR) {
1550 /* a signal was caught */
1551
1552 } else {
1553 /* An error occured */
1554 DEBUG(LOG_ERR, "Error on select");
1555 }
1556
1557 }
1558 return 0;
1559}