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