Implement optional syslog logging using ordinary
[oweals/busybox.git] / networking / udhcp / dhcpc.c
1 /* vi: set sw=4 ts=4: */
2 /* dhcpc.c
3  *
4  * udhcp DHCP client
5  *
6  * Russ Dill <Russ.Dill@asu.edu> July 2001
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  */
10
11 #include <sys/file.h>
12 #include <unistd.h>
13 #include <getopt.h>
14 #include <stdlib.h>
15 #include <sys/socket.h>
16 #include <netinet/in.h>
17 #include <arpa/inet.h>
18 #include <signal.h>
19 #include <time.h>
20 #include <string.h>
21 #include <sys/ioctl.h>
22 #include <net/if.h>
23 #include <errno.h>
24
25 #include "common.h"
26 #include "dhcpd.h"
27 #include "dhcpc.h"
28 #include "options.h"
29 #include "clientpacket.h"
30 #include "clientsocket.h"
31 #include "socket.h"
32 #include "signalpipe.h"
33
34 static int state;
35 static unsigned long requested_ip; /* = 0 */
36 static unsigned long server_addr;
37 static unsigned long timeout;
38 static int packet_num; /* = 0 */
39 static int fd = -1;
40
41 #define LISTEN_NONE 0
42 #define LISTEN_KERNEL 1
43 #define LISTEN_RAW 2
44 static int listen_mode;
45
46 struct client_config_t client_config = {
47         /* Default options. */
48         .abort_if_no_lease = 0,
49         .foreground = 0,
50         .quit_after_lease = 0,
51         .background_if_no_lease = 0,
52         .interface = "eth0",
53         .pidfile = NULL,
54         .script = DEFAULT_SCRIPT,
55         .clientid = NULL,
56         .vendorclass = NULL,
57         .hostname = NULL,
58         .fqdn = NULL,
59         .ifindex = 0,
60         .retries = 3,
61         .timeout = 3,
62         .arp = "\0\0\0\0\0\0",          /* appease gcc-3.0 */
63 };
64
65 /* just a little helper */
66 static void change_mode(int new_mode)
67 {
68         DEBUG("entering %s listen mode",
69                 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
70         if (fd >= 0) close(fd);
71         fd = -1;
72         listen_mode = new_mode;
73 }
74
75
76 /* perform a renew */
77 static void perform_renew(void)
78 {
79         bb_info_msg("Performing a DHCP renew");
80         switch (state) {
81         case BOUND:
82                 change_mode(LISTEN_KERNEL);
83         case RENEWING:
84         case REBINDING:
85                 state = RENEW_REQUESTED;
86                 break;
87         case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
88                 udhcp_run_script(NULL, "deconfig");
89         case REQUESTING:
90         case RELEASED:
91                 change_mode(LISTEN_RAW);
92                 state = INIT_SELECTING;
93                 break;
94         case INIT_SELECTING:
95                 break;
96         }
97
98         /* start things over */
99         packet_num = 0;
100
101         /* Kill any timeouts because the user wants this to hurry along */
102         timeout = 0;
103 }
104
105
106 /* perform a release */
107 static void perform_release(void)
108 {
109         char buffer[16];
110         struct in_addr temp_addr;
111
112         /* send release packet */
113         if (state == BOUND || state == RENEWING || state == REBINDING) {
114                 temp_addr.s_addr = server_addr;
115                 sprintf(buffer, "%s", inet_ntoa(temp_addr));
116                 temp_addr.s_addr = requested_ip;
117                 bb_info_msg("Unicasting a release of %s to %s",
118                                 inet_ntoa(temp_addr), buffer);
119                 send_release(server_addr, requested_ip); /* unicast */
120                 udhcp_run_script(NULL, "deconfig");
121         }
122         bb_info_msg("Entering released state");
123
124         change_mode(LISTEN_NONE);
125         state = RELEASED;
126         timeout = 0x7fffffff;
127 }
128
129
130 static void client_background(void)
131 {
132         udhcp_background(client_config.pidfile);
133         client_config.foreground = 1; /* Do not fork again. */
134         client_config.background_if_no_lease = 0;
135 }
136
137
138 int udhcpc_main(int argc, char *argv[])
139 {
140         uint8_t *temp, *message;
141         unsigned long t1 = 0, t2 = 0, xid = 0;
142         unsigned long start = 0, lease;
143         fd_set rfds;
144         int retval;
145         struct timeval tv;
146         int c, len;
147         struct dhcpMessage packet;
148         struct in_addr temp_addr;
149         long now;
150         int max_fd;
151         int sig;
152         int no_clientid = 0;
153
154         static const struct option arg_options[] = {
155                 {"clientid",    required_argument,      0, 'c'},
156                 {"clientid-none", no_argument,          0, 'C'},
157                 {"vendorclass", required_argument,      0, 'V'},
158                 {"foreground",  no_argument,            0, 'f'},
159                 {"background",  no_argument,            0, 'b'},
160                 {"hostname",    required_argument,      0, 'H'},
161                 {"hostname",    required_argument,      0, 'h'},
162                 {"fqdn",        required_argument,      0, 'F'},
163                 {"interface",   required_argument,      0, 'i'},
164                 {"now",         no_argument,            0, 'n'},
165                 {"pidfile",     required_argument,      0, 'p'},
166                 {"quit",        no_argument,            0, 'q'},
167                 {"request",     required_argument,      0, 'r'},
168                 {"script",      required_argument,      0, 's'},
169                 {"timeout",     required_argument,      0, 'T'},
170                 {"version",     no_argument,            0, 'v'},
171                 {"retries",     required_argument,      0, 't'},
172                 {0, 0, 0, 0}
173         };
174
175         /* get options */
176         while (1) {
177                 int option_index = 0;
178                 c = getopt_long(argc, argv, "c:CV:fbH:h:F:i:np:qr:s:T:t:v", arg_options, &option_index);
179                 if (c == -1) break;
180
181                 switch (c) {
182                 case 'c':
183                         if (no_clientid) bb_show_usage();
184                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
185                         free(client_config.clientid);
186                         client_config.clientid = xmalloc(len + 2);
187                         client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
188                         client_config.clientid[OPT_LEN] = len;
189                         client_config.clientid[OPT_DATA] = '\0';
190                         strncpy((char*)client_config.clientid + OPT_DATA, optarg, len);
191                         break;
192                 case 'C':
193                         if (client_config.clientid) bb_show_usage();
194                         no_clientid = 1;
195                         break;
196                 case 'V':
197                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
198                         free(client_config.vendorclass);
199                         client_config.vendorclass = xmalloc(len + 2);
200                         client_config.vendorclass[OPT_CODE] = DHCP_VENDOR;
201                         client_config.vendorclass[OPT_LEN] = len;
202                         strncpy((char*)client_config.vendorclass + OPT_DATA, optarg, len);
203                         break;
204                 case 'f':
205                         client_config.foreground = 1;
206                         break;
207                 case 'b':
208                         client_config.background_if_no_lease = 1;
209                         break;
210                 case 'h':
211                 case 'H':
212                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
213                         free(client_config.hostname);
214                         client_config.hostname = xmalloc(len + 2);
215                         client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
216                         client_config.hostname[OPT_LEN] = len;
217                         strncpy((char*)client_config.hostname + 2, optarg, len);
218                         break;
219                 case 'F':
220                         len = strlen(optarg) > 255 ? 255 : strlen(optarg);
221                         free(client_config.fqdn);
222                         client_config.fqdn = xmalloc(len + 5);
223                         client_config.fqdn[OPT_CODE] = DHCP_FQDN;
224                         client_config.fqdn[OPT_LEN] = len + 3;
225                         /* Flags: 0000NEOS
226                         S: 1 => Client requests Server to update A RR in DNS as well as PTR
227                         O: 1 => Server indicates to client that DNS has been updated regardless
228                         E: 1 => Name data is DNS format, i.e. <4>host<6>domain<4>com<0> not "host.domain.com"
229                         N: 1 => Client requests Server to not update DNS
230                         */
231                         client_config.fqdn[OPT_LEN + 1] = 0x1;
232                         client_config.fqdn[OPT_LEN + 2] = 0;
233                         client_config.fqdn[OPT_LEN + 3] = 0;
234                         strncpy((char*)client_config.fqdn + 5, optarg, len);
235                         break;
236                 case 'i':
237                         client_config.interface =  optarg;
238                         break;
239                 case 'n':
240                         client_config.abort_if_no_lease = 1;
241                         break;
242                 case 'p':
243                         client_config.pidfile = optarg;
244                         break;
245                 case 'q':
246                         client_config.quit_after_lease = 1;
247                         break;
248                 case 'r':
249                         requested_ip = inet_addr(optarg);
250                         break;
251                 case 's':
252                         client_config.script = optarg;
253                         break;
254                 case 'T':
255                         client_config.timeout = atoi(optarg);
256                         break;
257                 case 't':
258                         client_config.retries = atoi(optarg);
259                         break;
260                 case 'v':
261                         printf("version %s\n\n", BB_VER);
262                         return 0;
263                         break;
264                 default:
265                         bb_show_usage();
266                 }
267         }
268
269         /* Start the log, sanitize fd's, and write a pid file */
270         udhcp_start_log_and_pid("udhcpc", client_config.pidfile);
271
272         if (read_interface(client_config.interface, &client_config.ifindex,
273                            NULL, client_config.arp) < 0)
274                 return 1;
275
276         /* if not set, and not suppressed, setup the default client ID */
277         if (!client_config.clientid && !no_clientid) {
278                 client_config.clientid = xmalloc(6 + 3);
279                 client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
280                 client_config.clientid[OPT_LEN] = 7;
281                 client_config.clientid[OPT_DATA] = 1;
282                 memcpy(client_config.clientid + 3, client_config.arp, 6);
283         }
284
285         if (!client_config.vendorclass) {
286                 client_config.vendorclass = xmalloc(sizeof("udhcp "BB_VER) + 2);
287                 client_config.vendorclass[OPT_CODE] = DHCP_VENDOR;
288                 client_config.vendorclass[OPT_LEN] = sizeof("udhcp "BB_VER) - 1;
289                 client_config.vendorclass[OPT_DATA] = 1;
290                 memcpy(&client_config.vendorclass[OPT_DATA],
291                         "udhcp "BB_VER, sizeof("udhcp "BB_VER) - 1);
292         }
293
294
295         /* setup the signal pipe */
296         udhcp_sp_setup();
297
298         state = INIT_SELECTING;
299         udhcp_run_script(NULL, "deconfig");
300         change_mode(LISTEN_RAW);
301
302         for (;;) {
303
304                 tv.tv_sec = timeout - uptime();
305                 tv.tv_usec = 0;
306
307                 if (listen_mode != LISTEN_NONE && fd < 0) {
308                         if (listen_mode == LISTEN_KERNEL)
309                                 fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
310                         else
311                                 fd = raw_socket(client_config.ifindex);
312                         if (fd < 0) {
313                                 bb_perror_msg("FATAL: couldn't listen on socket");
314                                 return 0;
315                         }
316                 }
317                 max_fd = udhcp_sp_fd_set(&rfds, fd);
318
319                 if (tv.tv_sec > 0) {
320                         DEBUG("Waiting on select...");
321                         retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
322                 } else retval = 0; /* If we already timed out, fall through */
323
324                 now = uptime();
325                 if (retval == 0) {
326                         /* timeout dropped to zero */
327                         switch (state) {
328                         case INIT_SELECTING:
329                                 if (packet_num < client_config.retries) {
330                                         if (packet_num == 0)
331                                                 xid = random_xid();
332
333                                         /* send discover packet */
334                                         send_discover(xid, requested_ip); /* broadcast */
335
336                                         timeout = now + client_config.timeout;
337                                         packet_num++;
338                                 } else {
339                                         udhcp_run_script(NULL, "leasefail");
340                                         if (client_config.background_if_no_lease) {
341                                                 bb_info_msg("No lease, forking to background");
342                                                 client_background();
343                                         } else if (client_config.abort_if_no_lease) {
344                                                 bb_info_msg("No lease, failing");
345                                                 return 1;
346                                         }
347                                         /* wait to try again */
348                                         packet_num = 0;
349                                         timeout = now + 60;
350                                 }
351                                 break;
352                         case RENEW_REQUESTED:
353                         case REQUESTING:
354                                 if (packet_num < client_config.retries) {
355                                         /* send request packet */
356                                         if (state == RENEW_REQUESTED)
357                                                 send_renew(xid, server_addr, requested_ip); /* unicast */
358                                         else send_selecting(xid, server_addr, requested_ip); /* broadcast */
359
360                                         timeout = now + ((packet_num == 2) ? 10 : 2);
361                                         packet_num++;
362                                 } else {
363                                         /* timed out, go back to init state */
364                                         if (state == RENEW_REQUESTED) udhcp_run_script(NULL, "deconfig");
365                                         state = INIT_SELECTING;
366                                         timeout = now;
367                                         packet_num = 0;
368                                         change_mode(LISTEN_RAW);
369                                 }
370                                 break;
371                         case BOUND:
372                                 /* Lease is starting to run out, time to enter renewing state */
373                                 state = RENEWING;
374                                 change_mode(LISTEN_KERNEL);
375                                 DEBUG("Entering renew state");
376                                 /* fall right through */
377                         case RENEWING:
378                                 /* Either set a new T1, or enter REBINDING state */
379                                 if ((t2 - t1) <= (lease / 14400 + 1)) {
380                                         /* timed out, enter rebinding state */
381                                         state = REBINDING;
382                                         timeout = now + (t2 - t1);
383                                         DEBUG("Entering rebinding state");
384                                 } else {
385                                         /* send a request packet */
386                                         send_renew(xid, server_addr, requested_ip); /* unicast */
387
388                                         t1 = (t2 - t1) / 2 + t1;
389                                         timeout = t1 + start;
390                                 }
391                                 break;
392                         case REBINDING:
393                                 /* Either set a new T2, or enter INIT state */
394                                 if ((lease - t2) <= (lease / 14400 + 1)) {
395                                         /* timed out, enter init state */
396                                         state = INIT_SELECTING;
397                                         bb_info_msg("Lease lost, entering init state");
398                                         udhcp_run_script(NULL, "deconfig");
399                                         timeout = now;
400                                         packet_num = 0;
401                                         change_mode(LISTEN_RAW);
402                                 } else {
403                                         /* send a request packet */
404                                         send_renew(xid, 0, requested_ip); /* broadcast */
405
406                                         t2 = (lease - t2) / 2 + t2;
407                                         timeout = t2 + start;
408                                 }
409                                 break;
410                         case RELEASED:
411                                 /* yah, I know, *you* say it would never happen */
412                                 timeout = 0x7fffffff;
413                                 break;
414                         }
415                 } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
416                         /* a packet is ready, read it */
417
418                         if (listen_mode == LISTEN_KERNEL)
419                                 len = udhcp_get_packet(&packet, fd);
420                         else len = get_raw_packet(&packet, fd);
421
422                         if (len == -1 && errno != EINTR) {
423                                 DEBUG("error on read, %s, reopening socket", strerror(errno));
424                                 change_mode(listen_mode); /* just close and reopen */
425                         }
426                         if (len < 0) continue;
427
428                         if (packet.xid != xid) {
429                                 DEBUG("Ignoring XID %lx (our xid is %lx)",
430                                         (unsigned long) packet.xid, xid);
431                                 continue;
432                         }
433
434                         /* Ignore packets that aren't for us */
435                         if (memcmp(packet.chaddr, client_config.arp, 6)) {
436                                 DEBUG("Packet does not have our chaddr - ignoring");
437                                 continue;
438                         }
439
440                         if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
441                                 bb_error_msg("Couldnt get option from packet - ignoring");
442                                 continue;
443                         }
444
445                         switch (state) {
446                         case INIT_SELECTING:
447                                 /* Must be a DHCPOFFER to one of our xid's */
448                                 if (*message == DHCPOFFER) {
449                                         if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
450                                                 memcpy(&server_addr, temp, 4);
451                                                 xid = packet.xid;
452                                                 requested_ip = packet.yiaddr;
453
454                                                 /* enter requesting state */
455                                                 state = REQUESTING;
456                                                 timeout = now;
457                                                 packet_num = 0;
458                                         } else {
459                                                 bb_error_msg("No server ID in message");
460                                         }
461                                 }
462                                 break;
463                         case RENEW_REQUESTED:
464                         case REQUESTING:
465                         case RENEWING:
466                         case REBINDING:
467                                 if (*message == DHCPACK) {
468                                         if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
469                                                 bb_error_msg("No lease time with ACK, using 1 hour lease");
470                                                 lease = 60 * 60;
471                                         } else {
472                                                 memcpy(&lease, temp, 4);
473                                                 lease = ntohl(lease);
474                                         }
475
476                                         /* enter bound state */
477                                         t1 = lease / 2;
478
479                                         /* little fixed point for n * .875 */
480                                         t2 = (lease * 0x7) >> 3;
481                                         temp_addr.s_addr = packet.yiaddr;
482                                         bb_info_msg("Lease of %s obtained, lease time %ld",
483                                                 inet_ntoa(temp_addr), lease);
484                                         start = now;
485                                         timeout = t1 + start;
486                                         requested_ip = packet.yiaddr;
487                                         udhcp_run_script(&packet,
488                                                    ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
489
490                                         state = BOUND;
491                                         change_mode(LISTEN_NONE);
492                                         if (client_config.quit_after_lease)
493                                                 return 0;
494                                         if (!client_config.foreground)
495                                                 client_background();
496
497                                 } else if (*message == DHCPNAK) {
498                                         /* return to init state */
499                                         bb_info_msg("Received DHCP NAK");
500                                         udhcp_run_script(&packet, "nak");
501                                         if (state != REQUESTING)
502                                                 udhcp_run_script(NULL, "deconfig");
503                                         state = INIT_SELECTING;
504                                         timeout = now;
505                                         requested_ip = 0;
506                                         packet_num = 0;
507                                         change_mode(LISTEN_RAW);
508                                         sleep(3); /* avoid excessive network traffic */
509                                 }
510                                 break;
511                         /* case BOUND, RELEASED: - ignore all packets */
512                         }
513                 } else if (retval > 0 && (sig = udhcp_sp_read(&rfds))) {
514                         switch (sig) {
515                         case SIGUSR1:
516                                 perform_renew();
517                                 break;
518                         case SIGUSR2:
519                                 perform_release();
520                                 break;
521                         case SIGTERM:
522                                 bb_info_msg("Received SIGTERM");
523                                 return 0;
524                         }
525                 } else if (retval == -1 && errno == EINTR) {
526                         /* a signal was caught */
527                 } else {
528                         /* An error occured */
529                         bb_perror_msg("select");
530                 }
531
532         }
533         return 0;
534 }