sdhcp.c (13763B)
1 /* sdhcp: simple DHCP client, ported from git.2f30.org/sdhcp */ 2 /* see LICENSE file for copyright and license details */ 3 #if FEATURE_NET_IOCTL 4 #ifndef _DEFAULT_SOURCE 5 #define _DEFAULT_SOURCE 6 #endif 7 #endif 8 9 #include "arg.h" 10 #include "net.h" 11 #include "timer.h" 12 #include "util.h" 13 #include "wexec.h" 14 15 #include <errno.h> 16 #include <fcntl.h> 17 #include <limits.h> 18 #include <netinet/in.h> 19 #include <signal.h> 20 #include <stdint.h> 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <string.h> 24 #include <sys/socket.h> 25 #include <time.h> 26 #include <unistd.h> 27 28 /* bootp packet layout: fields are byte arrays to avoid alignment/endian issues 29 */ 30 struct Bootp { 31 unsigned char op[1]; 32 unsigned char htype[1]; 33 unsigned char hlen[1]; 34 unsigned char hops[1]; 35 unsigned char xid[4]; 36 unsigned char secs[2]; 37 unsigned char flags[2]; 38 unsigned char ciaddr[4]; 39 unsigned char yiaddr[4]; 40 unsigned char siaddr[4]; 41 unsigned char giaddr[4]; 42 unsigned char chaddr[16]; 43 unsigned char sname[64]; 44 unsigned char file[128]; 45 unsigned char magic[4]; 46 unsigned char optdata[312 - 4]; 47 }; 48 49 enum { 50 DHCP_DISCOVER = 1, 51 DHCP_OFFER, 52 DHCP_REQUEST, 53 DHCP_DECLINE, 54 DHCP_ACK, 55 DHCP_NAK, 56 DHCP_RELEASE, 57 DHCP_INFORM, 58 /* internal sentinel values returned by dhcprecv */ 59 TIMEOUT0 = 200, 60 TIMEOUT1, 61 TIMEOUT2, 62 63 BOOT_REQUEST = 1, 64 BOOT_REPLY = 2, 65 /* bootp flags */ 66 F_BROADCAST = 1 << 15, 67 68 /* bootp options */ 69 OB_PAD = 0, 70 OB_MASK = 1, 71 OB_ROUTER = 3, 72 OB_NAMESERVER = 5, 73 OB_DNSSERVER = 6, 74 OB_HOSTNAME = 12, 75 OB_BADDR = 28, 76 /* dhcp-specific options */ 77 OD_IPADDR = 50, /* 0x32 */ 78 OD_LEASE = 51, 79 OD_OVERLOAD = 52, 80 OD_TYPE = 53, /* 0x35 */ 81 OD_SERVERID = 54, /* 0x36 */ 82 OD_PARAMS = 55, /* 0x37 */ 83 OD_MESSAGE = 56, 84 OD_MAXMSG = 57, 85 OD_RENEWALTIME = 58, 86 OD_REBINDINGTIME = 59, 87 OD_VENDORCLASS = 60, 88 OD_CLIENTID = 61, /* 0x3d */ 89 OD_TFTPSERVER = 66, 90 OD_BOOTFILE = 67, 91 OB_END = 255, 92 }; 93 94 enum { BROADCAST, UNICAST }; 95 96 static struct Bootp bp; 97 static unsigned char magic[] = {99, 130, 83, 99}; 98 99 /* conf */ 100 static unsigned char xid[sizeof(bp.xid)]; 101 static unsigned char hwaddr[16]; 102 static char hostname[HOST_NAME_MAX + 1]; 103 static time_t starttime; 104 static char *ifname = "eth0"; 105 static unsigned char cid[16]; 106 static char *program = ""; 107 static int sock; 108 /* negotiated lease values */ 109 static unsigned char server[4]; 110 static unsigned char client[4]; 111 static unsigned char mask[4]; 112 static unsigned char router[4]; 113 static unsigned char dns[4]; 114 115 /* flags: default on=1, foreground=0 */ 116 static int dflag = 1; 117 static int iflag = 1; 118 static int fflag = 0; 119 120 #define IP(a, b, c, d) \ 121 (unsigned char[4]) \ 122 { \ 123 a, b, c, d \ 124 } 125 126 /* write src as n-byte big-endian into dst */ 127 static void 128 hnput(unsigned char *dst, uint32_t src, size_t n) 129 { 130 unsigned int i; 131 132 for (i = 0; n--; i++) 133 dst[i] = (src >> (n * 8)) & 0xff; 134 } 135 136 static struct sockaddr * 137 iptoaddr(struct sockaddr *ifaddr, unsigned char ip[4], int port) 138 { 139 struct sockaddr_in *in = (struct sockaddr_in *)ifaddr; 140 141 in->sin_family = AF_INET; 142 in->sin_port = htons(port); 143 memcpy(&(in->sin_addr), ip, sizeof(in->sin_addr)); 144 145 return ifaddr; 146 } 147 148 /* sendto UDP wrapper: sends n bytes of data to bootp server port on ip */ 149 static ssize_t 150 udpsend(unsigned char ip[4], int fd, void *data, size_t n) 151 { 152 struct sockaddr addr; 153 socklen_t addrlen = sizeof(addr); 154 ssize_t sent; 155 156 iptoaddr(&addr, ip, 67); /* bootp server */ 157 if ((sent = sendto(fd, data, n, 0, &addr, addrlen)) == -1) 158 eprintf("sendto:"); 159 160 return sent; 161 } 162 163 /* recvfrom UDP wrapper: receives into data from bootp client port */ 164 static ssize_t 165 udprecv(unsigned char ip[4], int fd, void *data, size_t n) 166 { 167 struct sockaddr addr; 168 socklen_t addrlen = sizeof(addr); 169 ssize_t r; 170 171 iptoaddr(&addr, ip, 68); /* bootp client */ 172 if ((r = recvfrom(fd, data, n, 0, &addr, &addrlen)) == -1) 173 eprintf("recvfrom:"); 174 175 return r; 176 } 177 178 /* copy contents of src path into dfd; silently skips missing files */ 179 static void 180 appendfile(int dfd, char *src) 181 { 182 char buf[BUFSIZ]; 183 int fd, n; 184 185 if ((fd = open(src, O_RDONLY)) == -1) 186 return; 187 while ((n = read(fd, buf, sizeof(buf))) > 0) 188 writeall(dfd, buf, n); 189 close(fd); 190 } 191 192 static void 193 setdns(unsigned char ip[4]) 194 { 195 char buf[128]; 196 int fd, n; 197 198 if ((fd = creat("/etc/resolv.conf", 0644)) == -1) { 199 weprintf("can't change /etc/resolv.conf:"); 200 return; 201 } 202 appendfile(fd, "/etc/resolv.conf.head"); 203 n = snprintf(buf, sizeof(buf), "\nnameserver %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); 204 if (n > 0) 205 writeall(fd, buf, n); 206 appendfile(fd, "/etc/resolv.conf.tail"); 207 close(fd); 208 } 209 210 /* scan b's option data for opt; copy up to n bytes into data */ 211 static void 212 optget(struct Bootp *b, void *data, int opt, int n) 213 { 214 unsigned char *p = b->optdata; 215 unsigned char *top = ((unsigned char *)b) + sizeof(*b); 216 int code, len; 217 218 while (p < top) { 219 code = *p++; 220 if (code == OB_PAD) 221 continue; 222 if (code == OB_END || p == top) 223 break; 224 len = *p++; 225 if (len > top - p) 226 break; 227 if (code == opt) { 228 memcpy(data, p, MIN(len, n)); 229 break; 230 } 231 p += len; 232 } 233 } 234 235 /* append a raw-bytes option to p; return new write cursor */ 236 static unsigned char * 237 optput(unsigned char *p, int opt, unsigned char *data, size_t len) 238 { 239 *p++ = opt; 240 *p++ = (unsigned char)len; 241 memcpy(p, data, len); 242 243 return p + len; 244 } 245 246 /* append a big-endian numeric option to p; return new write cursor */ 247 static unsigned char * 248 hnoptput(unsigned char *p, int opt, uint32_t data, size_t len) 249 { 250 *p++ = opt; 251 *p++ = (unsigned char)len; 252 hnput(p, data, len); 253 254 return p + len; 255 } 256 257 static void 258 dhcpsend(int type, int how) 259 { 260 unsigned char *ip, *p; 261 262 memset(&bp, 0, sizeof(bp)); 263 hnput(bp.op, BOOT_REQUEST, 1); 264 hnput(bp.htype, 1, 1); 265 hnput(bp.hlen, 6, 1); 266 memcpy(bp.xid, xid, sizeof(xid)); 267 hnput(bp.flags, F_BROADCAST, sizeof(bp.flags)); 268 hnput(bp.secs, time(NULL) - starttime, sizeof(bp.secs)); 269 memcpy(bp.magic, magic, sizeof(bp.magic)); 270 memcpy(bp.chaddr, hwaddr, sizeof(bp.chaddr)); 271 p = bp.optdata; 272 p = hnoptput(p, OD_TYPE, type, 1); 273 p = optput(p, OD_CLIENTID, cid, sizeof(cid)); 274 p = optput(p, OB_HOSTNAME, (unsigned char *)hostname, strlen(hostname)); 275 276 switch (type) { 277 case DHCP_DISCOVER: 278 break; 279 case DHCP_REQUEST: 280 p = optput(p, OD_IPADDR, client, sizeof(client)); 281 p = optput(p, OD_SERVERID, server, sizeof(server)); 282 break; 283 case DHCP_RELEASE: 284 memcpy(bp.ciaddr, client, sizeof(client)); 285 p = optput(p, OD_IPADDR, client, sizeof(client)); 286 p = optput(p, OD_SERVERID, server, sizeof(server)); 287 break; 288 } 289 *p++ = OB_END; 290 291 ip = (how == BROADCAST) ? IP(255, 255, 255, 255) : server; 292 udpsend(ip, sock, &bp, p - (unsigned char *)&bp); 293 } 294 295 /* block until a message or a timer; return DHCP message type or a 296 * TIMEOUT* sentinel */ 297 static int 298 dhcprecv(void) 299 { 300 unsigned char type = 0; 301 int fired; 302 303 if ((fired = timer_wait(sock)) == -1) 304 eprintf("poll:"); 305 if (!fired) { 306 memset(&bp, 0, sizeof(bp)); 307 udprecv(IP(255, 255, 255, 255), sock, &bp, sizeof(bp)); 308 optget(&bp, &type, OD_TYPE, sizeof(type)); 309 return type; 310 } 311 if (fired & 1) 312 type = TIMEOUT0; 313 if (fired & 2) 314 type = TIMEOUT1; 315 if (fired & 4) 316 type = TIMEOUT2; 317 return type; 318 } 319 320 static void 321 acceptlease(void) 322 { 323 char buf[128]; 324 325 if (iflag) 326 if (net_set_lease(ifname, client, mask, router) < 0) 327 eprintf("can't set ip, socket:"); 328 if (dflag) 329 setdns(dns); 330 if (*program) { 331 snprintf(buf, sizeof(buf), "%d.%d.%d.%d", server[0], server[1], server[2], server[3]); 332 setenv("SERVER", buf, 1); 333 snprintf(buf, sizeof(buf), "%d.%d.%d.%d", client[0], client[1], client[2], client[3]); 334 setenv("CLIENT", buf, 1); 335 snprintf(buf, sizeof(buf), "%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3]); 336 setenv("MASK", buf, 1); 337 snprintf(buf, sizeof(buf), "%d.%d.%d.%d", router[0], router[1], router[2], router[3]); 338 setenv("ROUTER", buf, 1); 339 snprintf(buf, sizeof(buf), "%d.%d.%d.%d", dns[0], dns[1], dns[2], dns[3]); 340 setenv("DNS", buf, 1); 341 wsystem(program); 342 } 343 } 344 345 static void 346 settimeout(int n, const struct timespec *ts) 347 { 348 if (timer_set(n, ts) < 0) 349 eprintf("timer_set:"); 350 } 351 352 /* set ts to expire halfway to the remaining time on timer n, minimum 60s */ 353 static void 354 calctimeout(int n, struct timespec *ts) 355 { 356 if (timer_left(n, ts) < 0) 357 eprintf("timer_left:"); 358 ts->tv_nsec /= 2; 359 if (ts->tv_sec % 2) 360 ts->tv_nsec += 500000000; 361 ts->tv_sec /= 2; 362 if (ts->tv_sec < 60) { 363 ts->tv_sec = 60; 364 ts->tv_nsec = 0; 365 } 366 } 367 368 /* RFC 2131 DHCP state machine */ 369 static void 370 run(void) 371 { 372 int forked = 0, t; 373 pid_t pid; 374 struct timespec timeout = {0}; 375 uint32_t renewaltime, rebindingtime, lease; 376 377 Init: 378 dhcpsend(DHCP_DISCOVER, BROADCAST); 379 timeout.tv_sec = 1; 380 timeout.tv_nsec = 0; 381 settimeout(0, &timeout); 382 goto Selecting; 383 Selecting: 384 for (;;) { 385 switch (dhcprecv()) { 386 case DHCP_OFFER: 387 memcpy(client, bp.yiaddr, sizeof(client)); 388 optget(&bp, server, OD_SERVERID, sizeof(server)); 389 goto Requesting; 390 case TIMEOUT0: 391 goto Init; 392 } 393 } 394 Requesting: 395 for (t = 4; t <= 64; t *= 2) { 396 dhcpsend(DHCP_REQUEST, BROADCAST); 397 timeout.tv_sec = t; 398 settimeout(0, &timeout); 399 for (;;) { 400 switch (dhcprecv()) { 401 case DHCP_ACK: 402 goto Bound; 403 case DHCP_NAK: 404 goto Init; 405 case TIMEOUT0: 406 break; 407 default: 408 continue; 409 } 410 break; 411 } 412 } 413 /* no ACK after several DHCPREQUEST attempts */ 414 goto Init; 415 Bound: 416 optget(&bp, mask, OB_MASK, sizeof(mask)); 417 optget(&bp, router, OB_ROUTER, sizeof(router)); 418 optget(&bp, dns, OB_DNSSERVER, sizeof(dns)); 419 optget(&bp, &renewaltime, OD_RENEWALTIME, sizeof(renewaltime)); 420 optget(&bp, &rebindingtime, OD_REBINDINGTIME, sizeof(rebindingtime)); 421 optget(&bp, &lease, OD_LEASE, sizeof(lease)); 422 renewaltime = ntohl(renewaltime); 423 rebindingtime = ntohl(rebindingtime); 424 lease = ntohl(lease); 425 acceptlease(); 426 puts("Bound. Network configured."); 427 if (!fflag && !forked) { 428 pid = fork(); 429 if (pid < 0) 430 eprintf("fork:"); 431 if (pid > 0) 432 exit(0); 433 forked = 1; 434 } 435 timeout.tv_sec = renewaltime; 436 settimeout(0, &timeout); 437 timeout.tv_sec = rebindingtime; 438 settimeout(1, &timeout); 439 timeout.tv_sec = lease; 440 settimeout(2, &timeout); 441 for (;;) { 442 switch (dhcprecv()) { 443 case TIMEOUT0: /* t1: enter renewing */ 444 goto Renewing; 445 case TIMEOUT1: /* t2: enter rebinding */ 446 goto Rebinding; 447 case TIMEOUT2: /* lease expired */ 448 goto Init; 449 } 450 } 451 Renewing: 452 dhcpsend(DHCP_REQUEST, UNICAST); 453 calctimeout(1, &timeout); 454 settimeout(0, &timeout); 455 for (;;) { 456 switch (dhcprecv()) { 457 case DHCP_ACK: 458 goto Bound; 459 case TIMEOUT0: /* resend unicast */ 460 goto Renewing; 461 case TIMEOUT1: /* t2 elapsed */ 462 goto Rebinding; 463 case TIMEOUT2: 464 case DHCP_NAK: 465 goto Init; 466 } 467 } 468 Rebinding: 469 calctimeout(2, &timeout); 470 settimeout(0, &timeout); 471 dhcpsend(DHCP_REQUEST, BROADCAST); 472 for (;;) { 473 switch (dhcprecv()) { 474 case DHCP_ACK: 475 goto Bound; 476 case TIMEOUT0: /* resend broadcast */ 477 goto Rebinding; 478 case TIMEOUT2: /* lease expired */ 479 case DHCP_NAK: 480 goto Init; 481 } 482 } 483 } 484 485 static void 486 cleanexit(int unused) 487 { 488 (void)unused; 489 dhcpsend(DHCP_RELEASE, UNICAST); 490 _exit(0); 491 } 492 493 static void 494 usage(void) 495 { 496 eprintf("usage: %s [-d] [-e program] [-f] [-i] [ifname] [clientid]\n", argv0); 497 } 498 499 // ?man sdhcp: minimal DHCP client 500 // ?man arguments: [ifname] [clientid] 501 // ?man obtain an IPv4 lease via DHCP on the given interface 502 int 503 main(int argc, char *argv[]) 504 { 505 struct sockaddr addr; 506 int bcast = 1; 507 int rnd; 508 509 ARGBEGIN 510 { 511 case 'd': /* dont update /etc/resolv.conf */ 512 dflag = 0; 513 break; 514 case 'e': /* exec program on each lease */ 515 program = EARGF(usage()); 516 break; 517 case 'f': /* stay in foreground */ 518 fflag = 1; 519 break; 520 case 'i': /* dont configure IP address */ 521 iflag = 0; 522 break; 523 default: 524 usage(); 525 break; 526 } 527 ARGEND 528 529 if (argc) 530 ifname = argv[0]; 531 if (argc >= 2) 532 strlcpy((char *)cid, argv[1], sizeof(cid)); 533 534 signal(SIGTERM, cleanexit); 535 536 if (gethostname(hostname, sizeof(hostname)) == -1) 537 eprintf("gethostname:"); 538 539 if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 540 eprintf("socket:"); 541 if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(bcast)) == -1) 542 eprintf("setsockopt SO_BROADCAST:"); 543 544 if (net_bind_device(sock, ifname) == -1) 545 eprintf("setsockopt SO_BINDTODEVICE:"); 546 iptoaddr(&addr, IP(255, 255, 255, 255), 68); 547 if (bind(sock, &addr, sizeof(addr)) != 0) 548 eprintf("bind:"); 549 net_get_hwaddr(sock, ifname, hwaddr, sizeof(hwaddr)); 550 if (!cid[0]) 551 memcpy(cid, hwaddr, sizeof(cid)); 552 553 if ((rnd = open("/dev/urandom", O_RDONLY)) == -1) 554 eprintf("open /dev/urandom:"); 555 if (read(rnd, xid, sizeof(xid)) != (ssize_t)sizeof(xid)) 556 eprintf("read /dev/urandom:"); 557 close(rnd); 558 559 if (timer_init(3) == -1) 560 eprintf("timer_init:"); 561 562 starttime = time(NULL); 563 run(); 564 565 return 0; 566 }