1 /* dhcp.c - DHCP client for dynamic network configuration.
2  *
3  * Copyright 2012 Madhur Verma <mad.flexi@gmail.com>
4  * Copyright 2013 Kyungwan Han <asura321@gmail.com>
5  *
6  * Not in SUSv4.
7 USE_DHCP(NEWTOY(dhcp, "V:H:F:x*r:O*A#<0=20T#<0=3t#<0=3s:p:i:SBRCaovqnbf", TOYFLAG_SBIN|TOYFLAG_ROOTONLY))
8 
9 config DHCP
10   bool "dhcp"
11   default n
12   help
13    usage: dhcp [-fbnqvoCRB] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]
14                [-H HOSTNAME] [-V VENDOR] [-x OPT:VAL] [-O OPT]
15 
16         Configure network dynamicaly using DHCP.
17 
18       -i Interface to use (default eth0)
19       -p Create pidfile
20       -s Run PROG at DHCP events (default /usr/share/dhcp/default.script)
21       -B Request broadcast replies
22       -t Send up to N discover packets
23       -T Pause between packets (default 3 seconds)
24       -A Wait N seconds after failure (default 20)
25       -f Run in foreground
26       -b Background if lease is not obtained
27       -n Exit if lease is not obtained
28       -q Exit after obtaining lease
29       -R Release IP on exit
30       -S Log to syslog too
31       -a Use arping to validate offered address
32       -O Request option OPT from server (cumulative)
33       -o Don't request any options (unless -O is given)
34       -r Request this IP address
35       -x OPT:VAL  Include option OPT in sent packets (cumulative)
36       -F Ask server to update DNS mapping for NAME
37       -H Send NAME as client hostname (default none)
38       -V VENDOR Vendor identifier (default 'toybox VERSION')
39       -C Don't send MAC as client identifier
40       -v Verbose
41 
42       Signals:
43       USR1  Renew current lease
44       USR2  Release current lease
45 
46 */
47 
48 #define FOR_dhcp
49 #include "toys.h"
50 
51 // TODO: headers not in posix:
52 #include <netinet/ip.h>
53 #include <netinet/udp.h>
54 #include <netpacket/packet.h>
55 
56 #include <linux/filter.h> //FIXME: linux specific. fix for other OS ports
57 #include <linux/if_ether.h>
58 
59 GLOBALS(
60     char *iface;
61     char *pidfile;
62     char *script;
63     long retries;
64     long timeout;
65     long tryagain;
66     struct arg_list *req_opt;
67     char *req_ip;
68     struct arg_list *pkt_opt;
69     char *fdn_name;
70     char *hostname;
71     char *vendor_cls;
72 )
73 
74 #define STATE_INIT            0
75 #define STATE_REQUESTING      1
76 #define STATE_BOUND           2
77 #define STATE_RENEWING        3
78 #define STATE_REBINDING       4
79 #define STATE_RENEW_REQUESTED 5
80 #define STATE_RELEASED        6
81 
82 #define BOOTP_BROADCAST   0x8000
83 #define DHCP_MAGIC        0x63825363
84 
85 #define DHCP_REQUEST          1
86 #define DHCP_REPLY            2
87 #define DHCP_HTYPE_ETHERNET   1
88 
89 #define DHCPC_SERVER_PORT     67
90 #define DHCPC_CLIENT_PORT     68
91 
92 #define DHCPDISCOVER      1
93 #define DHCPOFFER         2
94 #define DHCPREQUEST       3
95 #define DHCPACK           5
96 #define DHCPNAK           6
97 #define DHCPRELEASE       7
98 
99 #define DHCP_OPTION_PADDING     0x00
100 #define DHCP_OPTION_SUBNET_MASK 0x01
101 #define DHCP_OPTION_ROUTER      0x03
102 #define DHCP_OPTION_DNS_SERVER  0x06
103 #define DHCP_OPTION_HOST_NAME   0x0c
104 #define DHCP_OPTION_BROADCAST   0x1c
105 #define DHCP_OPTION_REQ_IPADDR  0x32
106 #define DHCP_OPTION_LEASE_TIME  0x33
107 #define DHCP_OPTION_OVERLOAD    0x34
108 #define DHCP_OPTION_MSG_TYPE    0x35
109 #define DHCP_OPTION_SERVER_ID   0x36
110 #define DHCP_OPTION_REQ_LIST    0x37
111 #define DHCP_OPTION_MAX_SIZE    0x39
112 #define DHCP_OPTION_CLIENTID    0x3D
113 #define DHCP_OPTION_VENDOR      0x3C
114 #define DHCP_OPTION_FQDN        0x51
115 #define DHCP_OPTION_END         0xFF
116 
117 #define DHCP_NUM8           (1<<8)
118 #define DHCP_NUM16          (1<<9)
119 #define DHCP_NUM32          DHCP_NUM16 | DHCP_NUM8
120 #define DHCP_STRING         (1<<10)
121 #define DHCP_STRLST         (1<<11)
122 #define DHCP_IP             (1<<12)
123 #define DHCP_IPLIST         (1<<13)
124 #define DHCP_IPPLST         (1<<14)
125 #define DHCP_STCRTS         (1<<15)
126 
127 #define LOG_SILENT          0x0
128 #define LOG_CONSOLE         0x1
129 #define LOG_SYSTEM          0x2
130 
131 #define MODE_OFF        0
132 #define MODE_RAW        1
133 #define MODE_APP        2
134 
135 static void (*dbg)(char *format, ...);
dummy(char * format,...)136 static void dummy(char *format, ...){
137 	return;
138 }
139 
140 typedef struct dhcpc_result_s {
141   struct in_addr serverid;
142   struct in_addr ipaddr;
143   struct in_addr netmask;
144   struct in_addr dnsaddr;
145   struct in_addr default_router;
146   uint32_t lease_time;
147 } dhcpc_result_t;
148 
149 typedef struct __attribute__((packed)) dhcp_msg_s {
150   uint8_t op;
151   uint8_t htype;
152   uint8_t hlen;
153   uint8_t hops;
154   uint32_t xid;
155   uint16_t secs;
156   uint16_t flags;
157   uint32_t ciaddr;
158   uint32_t yiaddr;
159   uint32_t nsiaddr;
160   uint32_t ngiaddr;
161   uint8_t chaddr[16];
162   uint8_t sname[64];
163   uint8_t file[128];
164   uint32_t cookie;
165   uint8_t options[308];
166 } dhcp_msg_t;
167 
168 typedef struct __attribute__((packed)) dhcp_raw_s {
169   struct iphdr iph;
170   struct udphdr udph;
171   dhcp_msg_t dhcp;
172 } dhcp_raw_t;
173 
174 typedef struct dhcpc_state_s {
175   uint8_t macaddr[6];
176    char *iface;
177   int ifindex;
178   int sockfd;
179   int status;
180   int mode;
181   uint32_t mask;
182   struct in_addr ipaddr;
183   struct in_addr serverid;
184   dhcp_msg_t pdhcp;
185 } dhcpc_state_t;
186 
187 typedef struct option_val_s {
188   char *key;
189   uint16_t code;
190   void *val;
191   size_t len;
192 } option_val_t;
193 
194 struct fd_pair { int rd; int wr; };
195 static uint32_t xid;
196 static dhcpc_state_t *state;
197 static struct fd_pair sigfd;
198 uint8_t bmacaddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
199  int set = 1;
200 uint8_t infomode = LOG_CONSOLE;
201 uint8_t raw_opt[29];
202 int raw_optcount = 0;
203 struct arg_list *x_opt;
204 in_addr_t server = 0;
205 
206 static option_val_t *msgopt_list = NULL;
207 static option_val_t options_list[] = {
208     {"lease"          , DHCP_NUM32  | 0x33, NULL, 0},
209     {"subnet"         , DHCP_IP     | 0x01, NULL, 0},
210     {"broadcast"      , DHCP_IP     | 0x1c, NULL, 0},
211     {"router"         , DHCP_IP     | 0x03, NULL, 0},
212     {"ipttl"          , DHCP_NUM8   | 0x17, NULL, 0},
213     {"mtu"            , DHCP_NUM16  | 0x1a, NULL, 0},
214     {"hostname"       , DHCP_STRING | 0x0c, NULL, 0},
215     {"domain"         , DHCP_STRING | 0x0f, NULL, 0},
216     {"search"         , DHCP_STRLST | 0x77, NULL, 0},
217     {"nisdomain"      , DHCP_STRING | 0x28, NULL, 0},
218     {"timezone"       , DHCP_NUM32  | 0x02, NULL, 0},
219     {"tftp"           , DHCP_STRING | 0x42, NULL, 0},
220     {"bootfile"       , DHCP_STRING | 0x43, NULL, 0},
221     {"bootsize"       , DHCP_NUM16  | 0x0d, NULL, 0},
222     {"rootpath"       , DHCP_STRING | 0x11, NULL, 0},
223     {"wpad"           , DHCP_STRING | 0xfc, NULL, 0},
224     {"serverid"       , DHCP_IP     | 0x36, NULL, 0},
225     {"message"        , DHCP_STRING | 0x38, NULL, 0},
226     {"vlanid"         , DHCP_NUM32  | 0x84, NULL, 0},
227     {"vlanpriority"   , DHCP_NUM32  | 0x85, NULL, 0},
228     {"dns"            , DHCP_IPLIST | 0x06, NULL, 0},
229     {"wins"           , DHCP_IPLIST | 0x2c, NULL, 0},
230     {"nissrv"         , DHCP_IPLIST | 0x29, NULL, 0},
231     {"ntpsrv"         , DHCP_IPLIST | 0x2a, NULL, 0},
232     {"lprsrv"         , DHCP_IPLIST | 0x09, NULL, 0},
233     {"swapsrv"        , DHCP_IP     | 0x10, NULL, 0},
234     {"routes"         , DHCP_STCRTS | 0x21, NULL, 0},
235     {"staticroutes"   , DHCP_STCRTS | 0x79, NULL, 0},
236     {"msstaticroutes" , DHCP_STCRTS | 0xf9, NULL, 0},
237 };
238 
239 static  struct sock_filter filter_instr[] = {
240     BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
241     BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
242     BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
243     BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
244     BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
245     BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
246     BPF_STMT(BPF_RET|BPF_K, 0xffffffff), BPF_STMT(BPF_RET|BPF_K, 0),
247 };
248 
249 static  struct sock_fprog filter_prog = {
250     .len = ARRAY_LEN(filter_instr),
251     .filter = (struct sock_filter *) filter_instr,
252 };
253 
254 // calculate options size.
dhcp_opt_size(uint8_t * optionptr)255 static int dhcp_opt_size(uint8_t *optionptr)
256 {
257   int i = 0;
258   for(;optionptr[i] != 0xff; i++) if(optionptr[i] != 0x00) i += optionptr[i + 1] + 2 -1;
259   return i;
260 }
261 
262 // calculates checksum for dhcp messages.
dhcp_checksum(void * addr,int count)263 static uint16_t dhcp_checksum(void *addr, int count)
264 {
265   int32_t sum = 0;
266   uint16_t tmp = 0, *source = (uint16_t *)addr;
267 
268   while (count > 1)  {
269     sum += *source++;
270     count -= 2;
271   }
272   if (count > 0) {
273     *(uint8_t*)&tmp = *(uint8_t*)source;
274     sum += tmp;
275   }
276   while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
277   return ~sum;
278 }
279 
280 // gets information of INTERFACE and updates IFINDEX, MAC and IP
get_interface(char * interface,int * ifindex,uint32_t * oip,uint8_t * mac)281 static int get_interface( char *interface, int *ifindex, uint32_t *oip, uint8_t *mac)
282 {
283   struct ifreq req;
284   struct sockaddr_in *ip;
285   int fd = xsocket(AF_INET, SOCK_RAW, IPPROTO_RAW);
286 
287   req.ifr_addr.sa_family = AF_INET;
288   xstrncpy(req.ifr_name, interface, IFNAMSIZ);
289   req.ifr_name[IFNAMSIZ-1] = '\0';
290 
291   xioctl(fd, SIOCGIFFLAGS, &req);
292   if (!(req.ifr_flags & IFF_UP)) return -1;
293 
294   if (oip) {
295     xioctl(fd, SIOCGIFADDR, &req);
296     ip = (struct sockaddr_in*) &req.ifr_addr;
297     dbg("IP %s\n", inet_ntoa(ip->sin_addr));
298     *oip = ntohl(ip->sin_addr.s_addr);
299   }
300   if (ifindex) {
301     xioctl(fd, SIOCGIFINDEX, &req);
302     dbg("Adapter index %d\n", req.ifr_ifindex);
303     *ifindex = req.ifr_ifindex;
304   }
305   if (mac) {
306     xioctl(fd, SIOCGIFHWADDR, &req);
307     memcpy(mac, req.ifr_hwaddr.sa_data, 6);
308     dbg("MAC %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
309   }
310   close(fd);
311   return 0;
312 }
313 
314 /*
315  *logs messeges to syslog or console
316  *opening the log is still left with applet.
317  *FIXME: move to more relevent lib. probably libc.c
318  */
infomsg(uint8_t infomode,char * s,...)319 static void infomsg(uint8_t infomode,  char *s, ...)
320 {
321   int used;
322   char *msg;
323   va_list p, t;
324 
325   if (infomode == LOG_SILENT) return;
326   va_start(p, s);
327   va_copy(t, p);
328   used = vsnprintf(NULL, 0, s, t);
329   used++;
330   va_end(t);
331 
332   msg = xmalloc(used);
333   vsnprintf(msg, used, s, p);
334   va_end(p);
335 
336   if (infomode & LOG_SYSTEM) syslog(LOG_INFO, "%s", msg);
337   if (infomode & LOG_CONSOLE) printf("%s\n", msg);
338   free(msg);
339 }
340 
341 /*
342  * Writes self PID in file PATH
343  * FIXME: libc implementation only writes in /var/run
344  * this is more generic as some implemenation may provide
345  * arguments to write in specific file. as dhcpd does.
346  */
write_pid(char * path)347 static void write_pid(char *path)
348 {
349   int pidfile = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
350   if (pidfile > 0) {
351     char pidbuf[12];
352 
353     sprintf(pidbuf, "%u", (unsigned)getpid());
354     write(pidfile, pidbuf, strlen(pidbuf));
355     close(pidfile);
356   }
357 }
358 
359 // String STR to UINT32 conversion strored in VAR
strtou32(char * str)360 static long strtou32( char *str)
361 {
362   char *endptr = NULL;
363   int base = 10;
364   errno=0;
365   if (str[0]=='0' && (str[1]=='x' || str[1]=='X')) {
366     base = 16;
367     str+=2;
368   }
369   long ret_val = strtol(str, &endptr, base);
370   if (errno) return -1;
371   else if (endptr && (*endptr!='\0'||endptr == str)) return -1;
372   return ret_val;
373 }
374 
375 // IP String STR to binary data.
striptovar(char * str,void * var)376 static int striptovar( char *str, void *var)
377 {
378   in_addr_t addr;
379   if(!str) error_exit("NULL address string.");
380   addr = inet_addr(str);
381   if(addr == -1) error_exit("Wrong address %s.",str );
382   *((uint32_t*)(var)) = (uint32_t)addr;
383   return 0;
384 }
385 
386 // String to dhcp option conversion
strtoopt(char * str,uint8_t optonly)387 static int strtoopt( char *str, uint8_t optonly)
388 {
389   char *option, *valstr, *grp, *tp;
390   long optcode = 0, convtmp;
391   uint16_t flag = 0;
392   uint32_t mask, nip, router;
393   int count, size = ARRAY_LEN(options_list);
394 
395   if (!*str) return 0;
396   option = strtok((char*)str, ":");
397   if (!option) return -1;
398 
399   dbg("-x option : %s ", option);
400   optcode = strtou32(option);
401 
402   if (optcode > 0 && optcode < 256) {         // raw option
403     for (count = 0; count < size; count++) {
404       if ((options_list[count].code & 0X00FF) == optcode) {
405         flag = (options_list[count].code & 0XFF00);
406         break;
407       }
408     }
409     if (count == size) error_exit("Obsolete OR Unknown Option : %s", option);
410   } else {    // string option
411     for (count = 0; count < size; count++) {
412       if (!strcmp(options_list[count].key, option)) {
413         flag = (options_list[count].code & 0XFF00);
414         optcode = (options_list[count].code & 0X00FF);
415         break;
416       }
417     }
418     if (count == size) error_exit("Obsolete OR Unknown Option : %s", option);
419   }
420   if (!flag || !optcode) return -1;
421   if (optonly) return optcode;
422 
423   valstr = strtok(NULL, "\n");
424   if (!valstr) error_exit("option %s has no value defined.\n", option);
425   dbg(" value : %-20s \n ", valstr);
426   switch (flag) {
427   case DHCP_NUM32:
428     options_list[count].len = sizeof(uint32_t);
429     options_list[count].val = xmalloc(sizeof(uint32_t));
430     convtmp = strtou32(valstr);
431     if (convtmp < 0) error_exit("Invalid/wrong formated number %s", valstr);
432     convtmp = htonl(convtmp);
433     memcpy(options_list[count].val, &convtmp, sizeof(uint32_t));
434     break;
435   case DHCP_NUM16:
436     options_list[count].len = sizeof(uint16_t);
437     options_list[count].val = xmalloc(sizeof(uint16_t));
438     convtmp = strtou32(valstr);
439     if (convtmp < 0) error_exit("Invalid/malformed number %s", valstr);
440     convtmp = htons(convtmp);
441     memcpy(options_list[count].val, &convtmp, sizeof(uint16_t));
442     break;
443   case DHCP_NUM8:
444     options_list[count].len = sizeof(uint8_t);
445     options_list[count].val = xmalloc(sizeof(uint8_t));
446     convtmp = strtou32(valstr);
447     if (convtmp < 0) error_exit("Invalid/malformed number %s", valstr);
448     memcpy(options_list[count].val, &convtmp, sizeof(uint8_t));
449     break;
450   case DHCP_IP:
451     options_list[count].len = sizeof(uint32_t);
452     options_list[count].val = xmalloc(sizeof(uint32_t));
453     striptovar(valstr, options_list[count].val);
454     break;
455   case DHCP_STRING:
456     options_list[count].len = strlen(valstr);
457     options_list[count].val = strdup(valstr);
458     break;
459   case DHCP_IPLIST:
460     while(valstr){
461       options_list[count].val = xrealloc(options_list[count].val, options_list[count].len + sizeof(uint32_t));
462       striptovar(valstr, ((uint8_t*)options_list[count].val)+options_list[count].len);
463       options_list[count].len += sizeof(uint32_t);
464       valstr = strtok(NULL," \t");
465     }
466     break;
467   case DHCP_STRLST:
468   case DHCP_IPPLST:
469     break;
470   case DHCP_STCRTS:
471     /* Option binary format:
472      * mask [one byte, 0..32]
473      * ip [0..4 bytes depending on mask]
474      * router [4 bytes]
475      * may be repeated
476      * staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
477      */
478     grp = strtok(valstr, ",");;
479     while(grp){
480       while(*grp == ' ' || *grp == '\t') grp++;
481       tp = strchr(grp, '/');
482       if (!tp) error_exit("malformed static route option");
483       *tp = '\0';
484       mask = strtol(++tp, &tp, 10);
485       if (striptovar(grp, (uint8_t*)&nip) < 0) error_exit("malformed static route option");
486       while(*tp == ' ' || *tp == '\t' || *tp == '-') tp++;
487       if (striptovar(tp, (uint8_t*)&router) < 0) error_exit("malformed static route option");
488       options_list[count].val = xrealloc(options_list[count].val, options_list[count].len + 1 + mask/8 + 4);
489       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &mask, 1);
490       options_list[count].len += 1;
491       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &nip, mask/8);
492       options_list[count].len += mask/8;
493       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &router, 4);
494       options_list[count].len += 4;
495       tp = NULL;
496       grp = strtok(NULL, ",");
497     }
498     break;
499   }
500   return 0;
501 }
502 
503 // Creates environment pointers from RES to use in script
fill_envp(dhcpc_result_t * res)504 static int fill_envp(dhcpc_result_t *res)
505 {
506   struct in_addr temp;
507   int size = ARRAY_LEN(options_list), count, ret = -1;
508 
509   ret = setenv("interface", state->iface, 1);
510   if (!res) return ret;
511   if (res->ipaddr.s_addr) {
512       temp.s_addr = htonl(res->ipaddr.s_addr);
513       ret = setenv("ip", inet_ntoa(temp), 1);
514       if (ret) return ret;
515   }
516   if (msgopt_list) {
517     for (count = 0; count < size; count++) {
518         if ((msgopt_list[count].len == 0) || (msgopt_list[count].val == NULL)) continue;
519         ret = setenv(msgopt_list[count].key, (char*)msgopt_list[count].val, 1);
520         if (ret) return ret;
521       }
522   }
523   return ret;
524 }
525 
526 // Executes Script NAME.
run_script(dhcpc_result_t * res,char * name)527 static void run_script(dhcpc_result_t *res,  char *name)
528 {
529   volatile int error = 0;
530   pid_t pid;
531   char *argv[3];
532   struct stat sts;
533   char *script = (toys.optflags & FLAG_s) ? TT.script
534     : "/usr/share/dhcp/default.script";
535 
536   if (stat(script, &sts) == -1 && errno == ENOENT) return;
537   if (fill_envp(res)) {
538     dbg("Failed to create environment variables.");
539     return;
540   }
541   dbg("Executing %s %s\n", script, name);
542   argv[0] = (char*) script;
543   argv[1] = (char*) name;
544   argv[2] = NULL;
545   fflush(NULL);
546 
547   pid = vfork();
548   if (pid < 0) {
549     dbg("Fork failed.\n");
550     return;
551   }
552   if (!pid) {
553     execvp(argv[0], argv);
554     error = errno;
555     _exit(111);
556   }
557   if (error) {
558     waitpid(pid, NULL,0);
559     errno = error;
560     perror_msg("script exec failed");
561   }
562   dbg("script complete.\n");
563 }
564 
565 // returns a randome ID
getxid(void)566 static uint32_t getxid(void)
567 {
568   uint32_t randnum;
569   int fd = xopen("/dev/urandom", O_RDONLY);
570   xreadall(fd, &randnum, sizeof(randnum));
571   xclose(fd);
572   return randnum;
573 }
574 
575 // opens socket in raw mode.
mode_raw(void)576 static int mode_raw(void)
577 {
578   state->mode = MODE_OFF;
579   struct sockaddr_ll sock;
580 
581   if (state->sockfd > 0) close(state->sockfd);
582   dbg("Opening raw socket on ifindex %d\n", state->ifindex);
583 
584   state->sockfd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
585   if (state->sockfd < 0) {
586     dbg("MODE RAW : socket fail ERROR : %d\n", state->sockfd);
587     return -1;
588   }
589   dbg("Got raw socket fd %d\n", state->sockfd);
590   memset(&sock, 0, sizeof(sock));
591   sock.sll_family = AF_PACKET;
592   sock.sll_protocol = htons(ETH_P_IP);
593   sock.sll_ifindex = state->ifindex;
594 
595   if (bind(state->sockfd, (struct sockaddr *) &sock, sizeof(sock))) {
596     dbg("MODE RAW : bind fail.\n");
597     close(state->sockfd);
598     return -1;
599   }
600   state->mode = MODE_RAW;
601   if (setsockopt(state->sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) < 0)
602     dbg("MODE RAW : filter attach fail.\n");
603 
604   dbg("MODE RAW : success\n");
605   return 0;
606 }
607 
608 // opens UDP socket
mode_app(void)609 static int mode_app(void)
610 {
611   struct sockaddr_in addr;
612   struct ifreq ifr;
613 
614   state->mode = MODE_OFF;
615   if (state->sockfd > 0) close(state->sockfd);
616 
617   dbg("Opening listen socket on *:%d %s\n", DHCPC_CLIENT_PORT, state->iface);
618   state->sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
619   if (state->sockfd < 0) {
620     dbg("MODE APP : socket fail ERROR: %d\n", state->sockfd);
621     return -1;
622   }
623   setsockopt(state->sockfd, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set));
624   if (setsockopt(state->sockfd, SOL_SOCKET, SO_BROADCAST, &set, sizeof(set)) == -1) {
625     dbg("MODE APP : brodcast failed.\n");
626     close(state->sockfd);
627     return -1;
628   }
629   xstrncpy(ifr.ifr_name, state->iface, IFNAMSIZ);
630   ifr.ifr_name[IFNAMSIZ -1] = '\0';
631   setsockopt(state->sockfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
632 
633   memset(&addr, 0, sizeof(addr));
634   addr.sin_family = AF_INET;
635   addr.sin_port = htons(DHCPC_CLIENT_PORT);
636   addr.sin_addr.s_addr = INADDR_ANY ;
637 
638   if (bind(state->sockfd, (struct sockaddr *) &addr, sizeof(addr))) {
639     close(state->sockfd);
640     dbg("MODE APP : bind failed.\n");
641     return -1;
642   }
643   state->mode = MODE_APP;
644   dbg("MODE APP : success\n");
645   return 0;
646 }
647 
read_raw(void)648 static int read_raw(void)
649 {
650   dhcp_raw_t packet;
651   uint16_t check;
652   int bytes = 0;
653 
654   memset(&packet, 0, sizeof(packet));
655   if ((bytes = read(state->sockfd, &packet, sizeof(packet))) < 0) {
656     dbg("\tPacket read error, ignoring\n");
657     return bytes;
658   }
659   if (bytes < (int) (sizeof(packet.iph) + sizeof(packet.udph))) {
660     dbg("\tPacket is too short, ignoring\n");
661     return -2;
662   }
663   if (bytes < ntohs(packet.iph.tot_len)) {
664     dbg("\tOversized packet, ignoring\n");
665     return -2;
666   }
667   // ignore any extra garbage bytes
668   bytes = ntohs(packet.iph.tot_len);
669   // make sure its the right packet for us, and that it passes sanity checks
670   if (packet.iph.protocol != IPPROTO_UDP || packet.iph.version != IPVERSION
671    || packet.iph.ihl != (sizeof(packet.iph) >> 2)
672    || packet.udph.dest != htons(DHCPC_CLIENT_PORT)
673    || ntohs(packet.udph.len) != (uint16_t)(bytes - sizeof(packet.iph))) {
674     dbg("\tUnrelated/bogus packet, ignoring\n");
675     return -2;
676   }
677   // verify IP checksum
678   check = packet.iph.check;
679   packet.iph.check = 0;
680   if (check != dhcp_checksum(&packet.iph, sizeof(packet.iph))) {
681     dbg("\tBad IP header checksum, ignoring\n");
682     return -2;
683   }
684   memset(&packet.iph, 0, ((size_t) &((struct iphdr *)0)->protocol));
685   packet.iph.tot_len = packet.udph.len;
686   check = packet.udph.check;
687   packet.udph.check = 0;
688   if (check && check != dhcp_checksum(&packet, bytes)) {
689     dbg("\tPacket with bad UDP checksum received, ignoring\n");
690     return -2;
691   }
692   memcpy(&state->pdhcp, &packet.dhcp, bytes - (sizeof(packet.iph) + sizeof(packet.udph)));
693   if (state->pdhcp.cookie != htonl(DHCP_MAGIC)) {
694     dbg("\tPacket with bad magic, ignoring\n");
695     return -2;
696   }
697   return bytes - sizeof(packet.iph) - sizeof(packet.udph);
698 }
699 
read_app(void)700 static int read_app(void)
701 {
702   int ret;
703 
704   memset(&state->pdhcp, 0, sizeof(dhcp_msg_t));
705   if ((ret = read(state->sockfd, &state->pdhcp, sizeof(dhcp_msg_t))) < 0) {
706     dbg("Packet read error, ignoring\n");
707     return ret; /* returns -1 */
708   }
709   if (state->pdhcp.cookie != htonl(DHCP_MAGIC)) {
710     dbg("Packet with bad magic, ignoring\n");
711     return -2;
712   }
713   return ret;
714 }
715 
716 // Sends data through raw socket.
send_raw(void)717 static int send_raw(void)
718 {
719   struct sockaddr_ll dest_sll;
720   dhcp_raw_t packet;
721   unsigned padding;
722   int fd, result = -1;
723 
724   memset(&packet, 0, sizeof(dhcp_raw_t));
725   memcpy(&packet.dhcp, &state->pdhcp, sizeof(dhcp_msg_t));
726 
727   if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
728     dbg("SEND RAW: socket failed\n");
729     return result;
730   }
731   memset(&dest_sll, 0, sizeof(dest_sll));
732   dest_sll.sll_family = AF_PACKET;
733   dest_sll.sll_protocol = htons(ETH_P_IP);
734   dest_sll.sll_ifindex = state->ifindex;
735   dest_sll.sll_halen = 6;
736   memcpy(dest_sll.sll_addr, bmacaddr , 6);
737 
738   if (bind(fd, (struct sockaddr *) &dest_sll, sizeof(dest_sll)) < 0) {
739     dbg("SEND RAW: bind failed\n");
740     close(fd);
741     return result;
742   }
743   padding = 308 - 1 - dhcp_opt_size(state->pdhcp.options);
744   packet.iph.protocol = IPPROTO_UDP;
745   packet.iph.saddr = INADDR_ANY;
746   packet.iph.daddr = INADDR_BROADCAST;
747   packet.udph.source = htons(DHCPC_CLIENT_PORT);
748   packet.udph.dest = htons(DHCPC_SERVER_PORT);
749   packet.udph.len = htons(sizeof(dhcp_raw_t) - sizeof(struct iphdr) - padding);
750   packet.iph.tot_len = packet.udph.len;
751   packet.udph.check = dhcp_checksum(&packet, sizeof(dhcp_raw_t) - padding);
752   packet.iph.tot_len = htons(sizeof(dhcp_raw_t) - padding);
753   packet.iph.ihl = sizeof(packet.iph) >> 2;
754   packet.iph.version = IPVERSION;
755   packet.iph.ttl = IPDEFTTL;
756   packet.iph.check = dhcp_checksum(&packet.iph, sizeof(packet.iph));
757 
758   result = sendto(fd, &packet, sizeof(dhcp_raw_t) - padding, 0,
759       (struct sockaddr *) &dest_sll, sizeof(dest_sll));
760 
761   close(fd);
762   if (result < 0) dbg("SEND RAW: PACKET send error\n");
763   return result;
764 }
765 
766 // Sends data through UDP socket.
send_app(void)767 static int send_app(void)
768 {
769   struct sockaddr_in cli;
770   int fd, ret = -1;
771 
772   if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
773     dbg("SEND APP: sock failed.\n");
774     return ret;
775   }
776   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set));
777 
778   memset(&cli, 0, sizeof(cli));
779   cli.sin_family = AF_INET;
780   cli.sin_port = htons(DHCPC_CLIENT_PORT);
781   cli.sin_addr.s_addr = state->pdhcp.ciaddr;
782   if (bind(fd, (struct sockaddr *)&cli, sizeof(cli)) == -1) {
783     dbg("SEND APP: bind failed.\n");
784     goto error_fd;
785   }
786   memset(&cli, 0, sizeof(cli));
787   cli.sin_family = AF_INET;
788   cli.sin_port = htons(DHCPC_SERVER_PORT);
789   cli.sin_addr.s_addr = state->serverid.s_addr;
790   if (connect(fd, (struct sockaddr *)&cli, sizeof(cli)) == -1) {
791     dbg("SEND APP: connect failed.\n");
792     goto error_fd;
793   }
794   int padding = 308 - 1 - dhcp_opt_size(state->pdhcp.options);
795   if((ret = write(fd, &state->pdhcp, sizeof(dhcp_msg_t) - padding)) < 0) {
796     dbg("SEND APP: write failed error %d\n", ret);
797     goto error_fd;
798   }
799   dbg("SEND APP: write success wrote %d\n", ret);
800 error_fd:
801   close(fd);
802   return ret;
803 }
804 
805 // Generic signal handler real handling is done in main funcrion.
signal_handler(int sig)806 static void signal_handler(int sig)
807 {
808   unsigned char ch = sig;
809   if (write(sigfd.wr, &ch, 1) != 1) dbg("can't send signal\n");
810 }
811 
812 // signal setup for SIGUSR1 SIGUSR2 SIGTERM
setup_signal()813 static int setup_signal()
814 {
815   if (pipe((int *)&sigfd) < 0) {
816     dbg("signal pipe failed\n");
817     return -1;
818   }
819   fcntl(sigfd.wr , F_SETFD, FD_CLOEXEC);
820   fcntl(sigfd.rd , F_SETFD, FD_CLOEXEC);
821   int flags = fcntl(sigfd.wr, F_GETFL);
822   fcntl(sigfd.wr, F_SETFL, flags | O_NONBLOCK);
823   signal(SIGUSR1, signal_handler);
824   signal(SIGUSR2, signal_handler);
825   signal(SIGTERM, signal_handler);
826 
827   return 0;
828 }
829 
830 // adds client id to dhcp packet
dhcpc_addclientid(uint8_t * optptr)831 static uint8_t *dhcpc_addclientid(uint8_t *optptr)
832 {
833   *optptr++ = DHCP_OPTION_CLIENTID;
834   *optptr++ = 7;
835   *optptr++ = 1;
836   memcpy(optptr, &state->macaddr, 6);
837   return optptr + 6;
838 }
839 
840 // adds messege type to dhcp packet
dhcpc_addmsgtype(uint8_t * optptr,uint8_t type)841 static uint8_t *dhcpc_addmsgtype(uint8_t *optptr, uint8_t type)
842 {
843   *optptr++ = DHCP_OPTION_MSG_TYPE;
844   *optptr++ = 1;
845   *optptr++ = type;
846   return optptr;
847 }
848 
849 // adds max size to dhcp packet
dhcpc_addmaxsize(uint8_t * optptr,uint16_t size)850 static uint8_t *dhcpc_addmaxsize(uint8_t *optptr, uint16_t size)
851 {
852   *optptr++ = DHCP_OPTION_MAX_SIZE;
853   *optptr++ = 2;
854   memcpy(optptr, &size, 2);
855   return optptr + 2;
856 }
857 
dhcpc_addstropt(uint8_t * optptr,uint8_t opcode,char * str,int len)858 static uint8_t *dhcpc_addstropt(uint8_t *optptr, uint8_t opcode, char* str, int len)
859 {
860   *optptr++ = opcode;
861   *optptr++ = len;
862   memcpy(optptr, str, len);
863   return optptr + len;
864 }
865 
866 // adds server id to dhcp packet.
dhcpc_addserverid(struct in_addr * serverid,uint8_t * optptr)867 static uint8_t *dhcpc_addserverid(struct in_addr *serverid, uint8_t *optptr)
868 {
869   *optptr++ = DHCP_OPTION_SERVER_ID;
870   *optptr++ = 4;
871   memcpy(optptr, &serverid->s_addr, 4);
872   return optptr + 4;
873 }
874 
875 // adds requested ip address to dhcp packet.
dhcpc_addreqipaddr(struct in_addr * ipaddr,uint8_t * optptr)876 static uint8_t *dhcpc_addreqipaddr(struct in_addr *ipaddr, uint8_t *optptr)
877 {
878   *optptr++ = DHCP_OPTION_REQ_IPADDR;
879   *optptr++ = 4;
880   memcpy(optptr, &ipaddr->s_addr, 4);
881   return optptr + 4;
882 }
883 
884 // adds hostname to dhcp packet.
dhcpc_addfdnname(uint8_t * optptr,char * hname)885 static uint8_t *dhcpc_addfdnname(uint8_t *optptr, char *hname)
886 {
887   int size = strlen(hname);
888 
889   *optptr++ = DHCP_OPTION_FQDN;
890   *optptr++ = size + 3;
891   *optptr++ = 0x1;  //flags
892   optptr += 2;      // two blank bytes
893   strcpy((char*)optptr, hname); // name
894 
895   return optptr + size;
896 }
897 
898 // adds request options using -o,-O flag to dhcp packet
dhcpc_addreqoptions(uint8_t * optptr)899 static uint8_t *dhcpc_addreqoptions(uint8_t *optptr)
900 {
901   uint8_t *len;
902 
903   *optptr++ = DHCP_OPTION_REQ_LIST;
904   len = optptr;
905   *len = 0;
906   optptr++;
907 
908   if (!(toys.optflags & FLAG_o)) {
909     *len = 4;
910     *optptr++ = DHCP_OPTION_SUBNET_MASK;
911     *optptr++ = DHCP_OPTION_ROUTER;
912     *optptr++ = DHCP_OPTION_DNS_SERVER;
913     *optptr++ = DHCP_OPTION_BROADCAST;
914   }
915   if (toys.optflags & FLAG_O) {
916     memcpy(optptr++, raw_opt, raw_optcount);
917     *len += raw_optcount;
918   }
919   return optptr;
920 }
921 
dhcpc_addend(uint8_t * optptr)922 static uint8_t *dhcpc_addend(uint8_t *optptr)
923 {
924   *optptr++ = DHCP_OPTION_END;
925   return optptr;
926 }
927 
928 // Sets values of -x options in dhcp discover and request packet.
set_xopt(uint8_t * optptr)929 static uint8_t* set_xopt(uint8_t *optptr)
930 {
931   int count;
932   int size = ARRAY_LEN(options_list);
933   for (count = 0; count < size; count++) {
934     if ((options_list[count].len == 0) || (options_list[count].val == NULL)) continue;
935     *optptr++ = (uint8_t) (options_list[count].code & 0x00FF);
936     *optptr++ = (uint8_t) options_list[count].len;
937     memcpy(optptr, options_list[count].val, options_list[count].len);
938     optptr += options_list[count].len;
939   }
940   return optptr;
941 }
942 
get_option_serverid(uint8_t * opt,dhcpc_result_t * presult)943 static uint32_t get_option_serverid (uint8_t *opt, dhcpc_result_t *presult)
944 {
945   uint32_t var = 0;
946   while (*opt != DHCP_OPTION_SERVER_ID) {
947     if (*opt == DHCP_OPTION_END) return var;
948     opt += opt[1] + 2;
949   }
950   memcpy(&var, opt+2, sizeof(uint32_t));
951   state->serverid.s_addr = var;
952   presult->serverid.s_addr = state->serverid.s_addr;
953   presult->serverid.s_addr = ntohl(presult->serverid.s_addr);
954   return var;
955 }
956 
get_option_msgtype(uint8_t * opt)957 static uint8_t get_option_msgtype(uint8_t *opt)
958 {
959   uint32_t var = 0;
960   while (*opt != DHCP_OPTION_MSG_TYPE) {
961     if (*opt == DHCP_OPTION_END) return var;
962     opt += opt[1] + 2;
963   }
964   memcpy(&var, opt+2, sizeof(uint8_t));
965   return var;
966 }
967 
get_option_lease(uint8_t * opt,dhcpc_result_t * presult)968 static uint8_t get_option_lease(uint8_t *opt, dhcpc_result_t *presult)
969 {
970   uint32_t var = 0;
971   while (*opt != DHCP_OPTION_LEASE_TIME) {
972     if (*opt == DHCP_OPTION_END) return var;
973     opt += opt[1] + 2;
974   }
975   memcpy(&var, opt+2, sizeof(uint32_t));
976   var = htonl(var);
977   presult->lease_time = var;
978   return var;
979 }
980 
981 
982 // sends dhcp msg of MSGTYPE
dhcpc_sendmsg(int msgtype)983 static int dhcpc_sendmsg(int msgtype)
984 {
985   uint8_t *pend;
986   struct in_addr rqsd;
987   char *vendor;
988 
989   // Create the common message header settings
990   memset(&state->pdhcp, 0, sizeof(dhcp_msg_t));
991   state->pdhcp.op = DHCP_REQUEST;
992   state->pdhcp.htype = DHCP_HTYPE_ETHERNET;
993   state->pdhcp.hlen = 6;
994   state->pdhcp.xid = xid;
995   memcpy(state->pdhcp.chaddr, state->macaddr, 6);
996   memset(&state->pdhcp.chaddr[6], 0, 10);
997   state->pdhcp.cookie = htonl(DHCP_MAGIC);;
998 
999   // Add the common header options
1000   pend = state->pdhcp.options;
1001   pend = dhcpc_addmsgtype(pend, msgtype);
1002 
1003   if (!(toys.optflags & FLAG_C)) pend = dhcpc_addclientid(pend);
1004   // Handle the message specific settings
1005   switch (msgtype) {
1006   case DHCPDISCOVER: // Broadcast DISCOVER message to all servers
1007     state->pdhcp.flags = htons(BOOTP_BROADCAST); //  Broadcast bit.
1008     if (toys.optflags & FLAG_r) {
1009       inet_aton(TT.req_ip, &rqsd);
1010       pend = dhcpc_addreqipaddr(&rqsd, pend);
1011     }
1012     pend = dhcpc_addmaxsize(pend, htons(sizeof(dhcp_raw_t)));
1013     vendor = (toys.optflags & FLAG_V) ? TT.vendor_cls : "toybox\0";
1014     pend = dhcpc_addstropt(pend, DHCP_OPTION_VENDOR, vendor, strlen(vendor));
1015     if (toys.optflags & FLAG_H) pend = dhcpc_addstropt(pend, DHCP_OPTION_HOST_NAME, TT.hostname, strlen(TT.hostname));
1016     if (toys.optflags & FLAG_F) pend = dhcpc_addfdnname(pend, TT.fdn_name);
1017     if (!(toys.optflags & FLAG_o) || (toys.optflags & FLAG_O))
1018       pend = dhcpc_addreqoptions(pend);
1019     if (toys.optflags & FLAG_x) pend = set_xopt(pend);
1020     break;
1021   case DHCPREQUEST: // Send REQUEST message to the server that sent the *first* OFFER
1022     state->pdhcp.flags = htons(BOOTP_BROADCAST); //  Broadcast bit.
1023     if (state->status == STATE_RENEWING) memcpy(&state->pdhcp.ciaddr, &state->ipaddr.s_addr, 4);
1024     pend = dhcpc_addmaxsize(pend, htons(sizeof(dhcp_raw_t)));
1025     rqsd.s_addr = htonl(server);
1026     pend = dhcpc_addserverid(&rqsd, pend);
1027     pend = dhcpc_addreqipaddr(&state->ipaddr, pend);
1028     vendor = (toys.optflags & FLAG_V) ? TT.vendor_cls : "toybox\0";
1029     pend = dhcpc_addstropt(pend, DHCP_OPTION_VENDOR, vendor, strlen(vendor));
1030     if (toys.optflags & FLAG_H) pend = dhcpc_addstropt(pend, DHCP_OPTION_HOST_NAME, TT.hostname, strlen(TT.hostname));
1031     if (toys.optflags & FLAG_F) pend = dhcpc_addfdnname(pend, TT.fdn_name);
1032     if (!(toys.optflags & FLAG_o) || (toys.optflags & FLAG_O))
1033       pend = dhcpc_addreqoptions(pend);
1034     if (toys.optflags & FLAG_x) pend = set_xopt(pend);
1035     break;
1036   case DHCPRELEASE: // Send RELEASE message to the server.
1037     memcpy(&state->pdhcp.ciaddr, &state->ipaddr.s_addr, 4);
1038     rqsd.s_addr = htonl(server);
1039     pend = dhcpc_addserverid(&rqsd, pend);
1040     break;
1041   default:
1042     return -1;
1043   }
1044   pend = dhcpc_addend(pend);
1045 
1046   if (state->mode == MODE_APP) return send_app();
1047   return send_raw();
1048 }
1049 
1050 /*
1051  * parses options from received dhcp packet at OPTPTR and
1052  * stores result in PRESULT or MSGOPT_LIST
1053  */
dhcpc_parseoptions(dhcpc_result_t * presult,uint8_t * optptr)1054 static uint8_t dhcpc_parseoptions(dhcpc_result_t *presult, uint8_t *optptr)
1055 {
1056   uint8_t type = 0, *options, overloaded = 0;;
1057   uint16_t flag = 0;
1058   uint32_t convtmp = 0;
1059   char *dest, *pfx;
1060   struct in_addr addr;
1061   int count, optlen, size = ARRAY_LEN(options_list);
1062 
1063   if (toys.optflags & FLAG_x) {
1064     if(msgopt_list){
1065       for (count = 0; count < size; count++){
1066         if(msgopt_list[count].val) free(msgopt_list[count].val);
1067         msgopt_list[count].val = NULL;
1068         msgopt_list[count].len = 0;
1069       }
1070     } else {
1071      msgopt_list = xmalloc(sizeof(options_list));
1072      memcpy(msgopt_list, options_list, sizeof(options_list));
1073      for (count = 0; count < size; count++) {
1074          msgopt_list[count].len = 0;
1075          msgopt_list[count].val = NULL;
1076      }
1077     }
1078   } else {
1079     msgopt_list = options_list;
1080     for (count = 0; count < size; count++) {
1081       msgopt_list[count].len = 0;
1082       if(msgopt_list[count].val) free(msgopt_list[count].val);
1083       msgopt_list[count].val = NULL;
1084     }
1085   }
1086 
1087   while (*optptr != DHCP_OPTION_END) {
1088     if (*optptr == DHCP_OPTION_PADDING) {
1089       optptr++;
1090       continue;
1091     }
1092     if (*optptr == DHCP_OPTION_OVERLOAD) {
1093       overloaded = optptr[2];
1094       optptr += optptr[1] + 2;
1095       continue;
1096     }
1097     for (count = 0, flag = 0; count < size; count++) {
1098       if ((msgopt_list[count].code & 0X00FF) == *optptr) {
1099         flag = (msgopt_list[count].code & 0XFF00);
1100         break;
1101       }
1102     }
1103     switch (flag) {
1104     case DHCP_NUM32:
1105       memcpy(&convtmp, &optptr[2], sizeof(uint32_t));
1106       convtmp = htonl(convtmp);
1107       sprintf(toybuf, "%u", convtmp);
1108       msgopt_list[count].val = strdup(toybuf);
1109       msgopt_list[count].len = strlen(toybuf);
1110       break;
1111     case DHCP_NUM16:
1112       memcpy(&convtmp, &optptr[2], sizeof(uint16_t));
1113       convtmp = htons(convtmp);
1114       sprintf(toybuf, "%u", convtmp);
1115       msgopt_list[count].val = strdup(toybuf);
1116       msgopt_list[count].len = strlen(toybuf);
1117       break;
1118     case DHCP_NUM8:
1119       memcpy(&convtmp, &optptr[2], sizeof(uint8_t));
1120       sprintf(toybuf, "%u", convtmp);
1121       msgopt_list[count].val = strdup(toybuf);
1122       msgopt_list[count].len = strlen(toybuf);
1123       break;
1124     case DHCP_IP:
1125       memcpy(&convtmp, &optptr[2], sizeof(uint32_t));
1126       addr.s_addr = convtmp;
1127       sprintf(toybuf, "%s", inet_ntoa(addr));
1128       msgopt_list[count].val = strdup(toybuf);
1129       msgopt_list[count].len = strlen(toybuf);
1130       break;
1131     case DHCP_STRING:
1132       sprintf(toybuf, "%.*s", optptr[1], &optptr[2]);
1133       msgopt_list[count].val = strdup(toybuf);
1134       msgopt_list[count].len = strlen(toybuf);
1135       break;
1136     case DHCP_IPLIST:
1137       optlen = optptr[1];
1138       dest = toybuf;
1139       while (optlen) {
1140         memcpy(&convtmp, &optptr[2], sizeof(uint32_t));
1141         addr.s_addr = convtmp;
1142         dest += sprintf(dest, "%s ", inet_ntoa(addr));
1143         optlen -= 4;
1144       }
1145       *(dest - 1) = '\0';
1146       msgopt_list[count].val = strdup(toybuf);
1147       msgopt_list[count].len = strlen(toybuf);
1148       break;
1149     case DHCP_STRLST: //FIXME: do smthing.
1150     case DHCP_IPPLST:
1151       break;
1152     case DHCP_STCRTS:
1153       pfx = "";
1154       dest = toybuf;
1155       options = &optptr[2];
1156       optlen = optptr[1];
1157 
1158       while (optlen >= 1 + 4) {
1159         uint32_t nip = 0;
1160         int bytes;
1161         uint8_t *p_tmp;
1162         unsigned mask = *options;
1163 
1164         if (mask > 32) break;
1165         optlen--;
1166         p_tmp = (void*) &nip;
1167         bytes = (mask + 7) / 8;
1168         while (--bytes >= 0) {
1169           *p_tmp++ = *options++;
1170           optlen--;
1171         }
1172         if (optlen < 4) break;
1173         dest += sprintf(dest, "%s%u.%u.%u.%u", pfx, ((uint8_t*) &nip)[0],
1174             ((uint8_t*) &nip)[1], ((uint8_t*) &nip)[2], ((uint8_t*) &nip)[3]);
1175         pfx = " ";
1176         dest += sprintf(dest, "/%u ", mask);
1177         dest += sprintf(dest, "%u.%u.%u.%u", options[0], options[1], options[2], options[3]);
1178         options += 4;
1179         optlen -= 4;
1180       }
1181       msgopt_list[count].val = strdup(toybuf);
1182       msgopt_list[count].len = strlen(toybuf);
1183       break;
1184     default: break;
1185     }
1186     optptr += optptr[1] + 2;
1187   }
1188   if ((overloaded == 1) || (overloaded == 3)) dhcpc_parseoptions(presult, optptr);
1189   if ((overloaded == 2) || (overloaded == 3)) dhcpc_parseoptions(presult, optptr);
1190   return type;
1191 }
1192 
1193 // parses recvd messege to check that it was for us.
dhcpc_parsemsg(dhcpc_result_t * presult)1194 static uint8_t dhcpc_parsemsg(dhcpc_result_t *presult)
1195 {
1196   if (state->pdhcp.op == DHCP_REPLY
1197       && !memcmp(state->pdhcp.chaddr, state->macaddr, 6)
1198       && !memcmp(&state->pdhcp.xid, &xid, sizeof(xid))) {
1199     memcpy(&presult->ipaddr.s_addr, &state->pdhcp.yiaddr, 4);
1200     presult->ipaddr.s_addr = ntohl(presult->ipaddr.s_addr);
1201     return get_option_msgtype(state->pdhcp.options);
1202   }
1203   return 0;
1204 }
1205 
1206 // Sends a IP renew request.
renew(void)1207 static void renew(void)
1208 {
1209   infomsg(infomode, "Performing a DHCP renew");
1210   switch (state->status) {
1211   case STATE_INIT:
1212     break;
1213   case STATE_BOUND:
1214     mode_raw();
1215   case STATE_RENEWING:    // FALLTHROUGH
1216   case STATE_REBINDING:   // FALLTHROUGH
1217     state->status = STATE_RENEW_REQUESTED;
1218     break;
1219   case STATE_RENEW_REQUESTED:
1220     run_script(NULL, "deconfig");
1221   case STATE_REQUESTING:           // FALLTHROUGH
1222   case STATE_RELEASED:             // FALLTHROUGH
1223     mode_raw();
1224     state->status = STATE_INIT;
1225     break;
1226   default: break;
1227   }
1228 }
1229 
1230 // Sends a IP release request.
release(void)1231 static void release(void)
1232 {
1233   char buffer[sizeof("255.255.255.255\0")];
1234   struct in_addr temp_addr;
1235 
1236   mode_app();
1237   // send release packet
1238   if (state->status == STATE_BOUND || state->status == STATE_RENEWING || state->status == STATE_REBINDING) {
1239     temp_addr.s_addr = htonl(server);
1240     xstrncpy(buffer, inet_ntoa(temp_addr), sizeof(buffer));
1241     temp_addr.s_addr = state->ipaddr.s_addr;
1242     infomsg( infomode, "Unicasting a release of %s to %s", inet_ntoa(temp_addr), buffer);
1243     dhcpc_sendmsg(DHCPRELEASE);
1244     run_script(NULL, "deconfig");
1245   }
1246   infomsg(infomode, "Entering released state");
1247   close(state->sockfd);
1248   state->sockfd = -1;
1249   state->mode = MODE_OFF;
1250   state->status = STATE_RELEASED;
1251 }
1252 
free_option_stores(void)1253 static void free_option_stores(void)
1254 {
1255   int count, size = ARRAY_LEN(options_list);
1256   for (count = 0; count < size; count++)
1257     if (options_list[count].val) free(options_list[count].val);
1258   if (toys.optflags & FLAG_x) {
1259     for (count = 0; count < size; count++)
1260         if (msgopt_list[count].val) free(msgopt_list[count].val);
1261     free(msgopt_list);
1262   }
1263 }
1264 
dhcp_main(void)1265 void dhcp_main(void)
1266 {
1267   struct timeval tv;
1268   int retval, bufflen = 0;
1269   dhcpc_result_t result;
1270   uint8_t packets = 0, retries = 0;
1271   uint32_t timeout = 0, waited = 0;
1272   fd_set rfds;
1273 
1274   xid = 0;
1275   setlinebuf(stdout);
1276   dbg = dummy;
1277   if (toys.optflags & FLAG_v) dbg = xprintf;
1278   if (toys.optflags & FLAG_p) write_pid(TT.pidfile);
1279   retries = TT.retries;
1280   if (toys.optflags & FLAG_S) {
1281       openlog("UDHCPC :", LOG_PID, LOG_DAEMON);
1282       infomode |= LOG_SYSTEM;
1283   }
1284   infomsg(infomode, "dhcp started");
1285   if (toys.optflags & FLAG_O) {
1286     while (TT.req_opt) {
1287       raw_opt[raw_optcount] = (uint8_t) strtoopt(TT.req_opt->arg, 1);
1288       raw_optcount++;
1289       TT.req_opt = TT.req_opt->next;
1290     }
1291   }
1292   if (toys.optflags & FLAG_x) {
1293     while (TT.pkt_opt) {
1294       (void) strtoopt(TT.pkt_opt->arg, 0);
1295       TT.pkt_opt = TT.pkt_opt->next;
1296     }
1297   }
1298   memset(&result, 0, sizeof(dhcpc_result_t));
1299   state = (dhcpc_state_t*) xmalloc(sizeof(dhcpc_state_t));
1300   memset(state, 0, sizeof(dhcpc_state_t));
1301   state->iface = (toys.optflags & FLAG_i) ? TT.iface : "eth0";
1302 
1303   if (get_interface(state->iface, &state->ifindex, NULL, state->macaddr))
1304     perror_exit("Failed to get interface %s", state->iface);
1305 
1306   run_script(NULL, "deconfig");
1307   setup_signal();
1308   state->status = STATE_INIT;
1309   mode_raw();
1310   fcntl(state->sockfd, F_SETFD, FD_CLOEXEC);
1311 
1312   for (;;) {
1313     FD_ZERO(&rfds);
1314     if (state->sockfd >= 0) FD_SET(state->sockfd, &rfds);
1315     FD_SET(sigfd.rd, &rfds);
1316     tv.tv_sec = timeout - waited;
1317     tv.tv_usec = 0;
1318     retval = 0;
1319 
1320     int maxfd = (sigfd.rd > state->sockfd)? sigfd.rd : state->sockfd;
1321     dbg("select wait ....\n");
1322     uint32_t timestmp = time(NULL);
1323     if((retval = select(maxfd + 1, &rfds, NULL, NULL, &tv)) < 0) {
1324       if (errno == EINTR) {
1325         waited += (unsigned) time(NULL) - timestmp;
1326         continue;
1327       }
1328       perror_exit("Error in select");
1329     }
1330     if (!retval) { // Timed out
1331       if (get_interface(state->iface, &state->ifindex, NULL, state->macaddr))
1332         error_exit("Interface lost %s\n", state->iface);
1333 
1334       switch (state->status) {
1335       case STATE_INIT:
1336         if (packets < retries) {
1337           if (!packets) xid = getxid();
1338           run_script(NULL, "deconfig");
1339           infomsg(infomode, "Sending discover...");
1340           dhcpc_sendmsg(DHCPDISCOVER);
1341           server = 0;
1342           timeout = TT.timeout;
1343           waited = 0;
1344           packets++;
1345           continue;
1346         }
1347 lease_fail:
1348         run_script(NULL,"leasefail");
1349         if (toys.optflags & FLAG_n) {
1350           infomsg(infomode, "Lease failed. Exiting");
1351           goto ret_with_sockfd;
1352         }
1353         if (toys.optflags & FLAG_b) {
1354           infomsg(infomode, "Lease failed. Going Daemon mode");
1355           daemon(0, 0);
1356           if (toys.optflags & FLAG_p) write_pid(TT.pidfile);
1357           toys.optflags &= ~FLAG_b;
1358           toys.optflags |= FLAG_f;
1359         }
1360         timeout = TT.tryagain;
1361         waited = 0;
1362         packets = 0;
1363         continue;
1364       case STATE_REQUESTING:
1365         if (packets < retries) {
1366           memcpy(&state->ipaddr.s_addr,&state->pdhcp.yiaddr, 4);
1367           dhcpc_sendmsg(DHCPREQUEST);
1368           infomsg(infomode, "Sending select for %d.%d.%d.%d...",
1369               (result.ipaddr.s_addr >> 24) & 0xff, (result.ipaddr.s_addr >> 16) & 0xff, (result.ipaddr.s_addr >> 8) & 0xff, (result.ipaddr.s_addr) & 0xff);
1370           timeout = TT.timeout;
1371           waited = 0;
1372           packets++;
1373           continue;
1374         }
1375         mode_raw();
1376         state->status = STATE_INIT;
1377         goto lease_fail;
1378       case STATE_BOUND:
1379         state->status = STATE_RENEWING;
1380         dbg("Entering renew state\n");
1381         // FALLTHROUGH
1382       case STATE_RENEW_REQUESTED:   // FALLTHROUGH
1383       case STATE_RENEWING:
1384 renew_requested:
1385         if (timeout > 60) {
1386           dhcpc_sendmsg(DHCPREQUEST);
1387           timeout >>= 1;
1388           waited = 0;
1389           continue;
1390         }
1391         dbg("Entering rebinding state\n");
1392         state->status = STATE_REBINDING;
1393         // FALLTHROUGH
1394       case STATE_REBINDING:
1395         mode_raw();
1396         if (timeout > 0) {
1397           dhcpc_sendmsg(DHCPREQUEST);
1398           timeout >>= 1;
1399           waited = 0;
1400           continue;
1401         }
1402         infomsg(infomode, "Lease lost, entering INIT state");
1403         run_script(NULL, "deconfig");
1404         state->status = STATE_INIT;
1405         timeout = 0;
1406         waited = 0;
1407         packets = 0;
1408         continue;
1409       default: break;
1410       }
1411       timeout = INT_MAX;
1412       waited = 0;
1413       continue;
1414     }
1415     if (FD_ISSET(sigfd.rd, &rfds)) { // Some Activity on RDFDs : is signal
1416       unsigned char sig;
1417       if (read(sigfd.rd, &sig, 1) != 1) {
1418         dbg("signal read failed.\n");
1419         continue;
1420       }
1421       switch (sig) {
1422       case SIGUSR1:
1423         infomsg(infomode, "Received SIGUSR1");
1424         renew();
1425         packets = 0;
1426         waited = 0;
1427         if (state->status == STATE_RENEW_REQUESTED) goto renew_requested;
1428         if (state->status == STATE_INIT) timeout = 0;
1429         continue;
1430       case SIGUSR2:
1431         infomsg(infomode, "Received SIGUSR2");
1432         release();
1433         timeout = INT_MAX;
1434         waited = 0;
1435         packets = 0;
1436         continue;
1437       case SIGTERM:
1438         infomsg(infomode, "Received SIGTERM");
1439         if (toys.optflags & FLAG_R) release();
1440         goto ret_with_sockfd;
1441       default: break;
1442       }
1443     }
1444     if (FD_ISSET(state->sockfd, &rfds)) { // Some Activity on RDFDs : is socket
1445       dbg("main sock read\n");
1446       uint8_t msgType;
1447       if (state->mode == MODE_RAW) bufflen = read_raw();
1448       if (state->mode == MODE_APP) bufflen = read_app();
1449       if (bufflen < 0) {
1450         if (state->mode == MODE_RAW) mode_raw();
1451         if (state->mode == MODE_APP) mode_app();
1452         continue;
1453       }
1454       waited += time(NULL) - timestmp;
1455       memset(&result, 0, sizeof(dhcpc_result_t));
1456       msgType = dhcpc_parsemsg(&result);
1457       if (msgType != DHCPNAK && result.ipaddr.s_addr == 0 ) continue;       // no ip for me ignore
1458       if (!msgType || !get_option_serverid(state->pdhcp.options, &result)) continue; //no server id ignore
1459       if (msgType == DHCPOFFER && server == 0) server = result.serverid.s_addr; // select the server
1460       if (result.serverid.s_addr != server) continue; // not from the server we requested ignore
1461       dhcpc_parseoptions(&result, state->pdhcp.options);
1462       get_option_lease(state->pdhcp.options, &result);
1463 
1464       switch (state->status) {
1465       case STATE_INIT:
1466         if (msgType == DHCPOFFER) {
1467           state->status = STATE_REQUESTING;
1468           mode_raw();
1469           timeout = 0;
1470           waited = 0;
1471           packets = 0;
1472         }
1473         continue;
1474       case STATE_REQUESTING:         // FALLTHROUGH
1475       case STATE_RENEWING:           // FALLTHROUGH
1476       case STATE_RENEW_REQUESTED:    // FALLTHROUGH
1477       case STATE_REBINDING:
1478         if (msgType == DHCPACK) {
1479           timeout = result.lease_time / 2;
1480           run_script(&result, state->status == STATE_REQUESTING ? "bound" : "renew");
1481           state->status = STATE_BOUND;
1482           infomsg(infomode, "Lease of %d.%d.%d.%d obtained, lease time %d from server %d.%d.%d.%d",
1483               (result.ipaddr.s_addr >> 24) & 0xff, (result.ipaddr.s_addr >> 16) & 0xff, (result.ipaddr.s_addr >> 8) & 0xff, (result.ipaddr.s_addr) & 0xff,
1484               result.lease_time,
1485               (result.serverid.s_addr >> 24) & 0xff, (result.serverid.s_addr >> 16) & 0xff, (result.serverid.s_addr >> 8) & 0xff, (result.serverid.s_addr) & 0xff);
1486           if (toys.optflags & FLAG_q) {
1487             if (toys.optflags & FLAG_R) release();
1488             goto ret_with_sockfd;
1489           }
1490           toys.optflags &= ~FLAG_n;
1491           if (!(toys.optflags & FLAG_f)) {
1492             daemon(0, 0);
1493             toys.optflags |= FLAG_f;
1494             if (toys.optflags & FLAG_p) write_pid(TT.pidfile);
1495           }
1496           waited = 0;
1497           continue;
1498         } else if (msgType == DHCPNAK) {
1499           dbg("NACK received.\n");
1500           run_script(&result, "nak");
1501           if (state->status != STATE_REQUESTING) run_script(NULL, "deconfig");
1502           mode_raw();
1503           sleep(3);
1504           state->status = STATE_INIT;
1505           state->ipaddr.s_addr = 0;
1506           server = 0;
1507           timeout = 0;
1508           packets = 0;
1509           waited = 0;
1510         }
1511         continue;
1512       default: break;
1513       }
1514     }
1515   }
1516 ret_with_sockfd:
1517   if (CFG_TOYBOX_FREE) {
1518     free_option_stores();
1519     if (state->sockfd > 0) close(state->sockfd);
1520     free(state);
1521   }
1522 }
1523