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#<0T#<0t#<0s: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 flag_get(f,v,d) ((toys.optflags & f) ? v : d)
75 #define flag_chk(f)     ((toys.optflags & f) ? 1 : 0)
76 
77 #define STATE_INIT            0
78 #define STATE_REQUESTING      1
79 #define STATE_BOUND           2
80 #define STATE_RENEWING        3
81 #define STATE_REBINDING       4
82 #define STATE_RENEW_REQUESTED 5
83 #define STATE_RELEASED        6
84 
85 #define BOOTP_BROADCAST   0x8000
86 #define DHCP_MAGIC        0x63825363
87 
88 #define DHCP_REQUEST          1
89 #define DHCP_REPLY            2
90 #define DHCP_HTYPE_ETHERNET   1
91 
92 #define DHCPC_SERVER_PORT     67
93 #define DHCPC_CLIENT_PORT     68
94 
95 #define DHCPDISCOVER      1
96 #define DHCPOFFER         2
97 #define DHCPREQUEST       3
98 #define DHCPACK           5
99 #define DHCPNAK           6
100 #define DHCPRELEASE       7
101 
102 #define DHCP_OPTION_PADDING     0x00
103 #define DHCP_OPTION_SUBNET_MASK 0x01
104 #define DHCP_OPTION_ROUTER      0x03
105 #define DHCP_OPTION_DNS_SERVER  0x06
106 #define DHCP_OPTION_HOST_NAME   0x0c
107 #define DHCP_OPTION_BROADCAST   0x1c
108 #define DHCP_OPTION_REQ_IPADDR  0x32
109 #define DHCP_OPTION_LEASE_TIME  0x33
110 #define DHCP_OPTION_OVERLOAD    0x34
111 #define DHCP_OPTION_MSG_TYPE    0x35
112 #define DHCP_OPTION_SERVER_ID   0x36
113 #define DHCP_OPTION_REQ_LIST    0x37
114 #define DHCP_OPTION_MAX_SIZE    0x39
115 #define DHCP_OPTION_CLIENTID    0x3D
116 #define DHCP_OPTION_VENDOR      0x3C
117 #define DHCP_OPTION_FQDN        0x51
118 #define DHCP_OPTION_END         0xFF
119 
120 #define DHCP_NUM8           (1<<8)
121 #define DHCP_NUM16          (1<<9)
122 #define DHCP_NUM32          DHCP_NUM16 | DHCP_NUM8
123 #define DHCP_STRING         (1<<10)
124 #define DHCP_STRLST         (1<<11)
125 #define DHCP_IP             (1<<12)
126 #define DHCP_IPLIST         (1<<13)
127 #define DHCP_IPPLST         (1<<14)
128 #define DHCP_STCRTS         (1<<15)
129 
130 #define LOG_SILENT          0x0
131 #define LOG_CONSOLE         0x1
132 #define LOG_SYSTEM          0x2
133 
134 #define MODE_OFF        0
135 #define MODE_RAW        1
136 #define MODE_APP        2
137 
138 static void (*dbg)(char *format, ...);
dummy(char * format,...)139 static void dummy(char *format, ...){
140 	return;
141 }
142 
143 typedef struct dhcpc_result_s {
144   struct in_addr serverid;
145   struct in_addr ipaddr;
146   struct in_addr netmask;
147   struct in_addr dnsaddr;
148   struct in_addr default_router;
149   uint32_t lease_time;
150 } dhcpc_result_t;
151 
152 typedef struct __attribute__((packed)) dhcp_msg_s {
153   uint8_t op;
154   uint8_t htype;
155   uint8_t hlen;
156   uint8_t hops;
157   uint32_t xid;
158   uint16_t secs;
159   uint16_t flags;
160   uint32_t ciaddr;
161   uint32_t yiaddr;
162   uint32_t nsiaddr;
163   uint32_t ngiaddr;
164   uint8_t chaddr[16];
165   uint8_t sname[64];
166   uint8_t file[128];
167   uint32_t cookie;
168   uint8_t options[308];
169 } dhcp_msg_t;
170 
171 typedef struct __attribute__((packed)) dhcp_raw_s {
172   struct iphdr iph;
173   struct udphdr udph;
174   dhcp_msg_t dhcp;
175 } dhcp_raw_t;
176 
177 typedef struct dhcpc_state_s {
178   uint8_t macaddr[6];
179    char *iface;
180   int ifindex;
181   int sockfd;
182   int status;
183   int mode;
184   uint32_t mask;
185   struct in_addr ipaddr;
186   struct in_addr serverid;
187   dhcp_msg_t pdhcp;
188 } dhcpc_state_t;
189 
190 typedef struct option_val_s {
191   char *key;
192   uint16_t code;
193   void *val;
194   size_t len;
195 } option_val_t;
196 
197 struct fd_pair { int rd; int wr; };
198 static uint32_t xid;
199 static dhcpc_state_t *state;
200 static struct fd_pair sigfd;
201 uint8_t bmacaddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
202  int set = 1;
203 uint8_t infomode = LOG_CONSOLE;
204 uint8_t raw_opt[29];
205 int raw_optcount = 0;
206 struct arg_list *x_opt;
207 in_addr_t server = 0;
208 
209 static option_val_t *msgopt_list = NULL;
210 static option_val_t options_list[] = {
211     {"lease"          , DHCP_NUM32  | 0x33, NULL, 0},
212     {"subnet"         , DHCP_IP     | 0x01, NULL, 0},
213     {"broadcast"      , DHCP_IP     | 0x1c, NULL, 0},
214     {"router"         , DHCP_IP     | 0x03, NULL, 0},
215     {"ipttl"          , DHCP_NUM8   | 0x17, NULL, 0},
216     {"mtu"            , DHCP_NUM16  | 0x1a, NULL, 0},
217     {"hostname"       , DHCP_STRING | 0x0c, NULL, 0},
218     {"domain"         , DHCP_STRING | 0x0f, NULL, 0},
219     {"search"         , DHCP_STRLST | 0x77, NULL, 0},
220     {"nisdomain"      , DHCP_STRING | 0x28, NULL, 0},
221     {"timezone"       , DHCP_NUM32  | 0x02, NULL, 0},
222     {"tftp"           , DHCP_STRING | 0x42, NULL, 0},
223     {"bootfile"       , DHCP_STRING | 0x43, NULL, 0},
224     {"bootsize"       , DHCP_NUM16  | 0x0d, NULL, 0},
225     {"rootpath"       , DHCP_STRING | 0x11, NULL, 0},
226     {"wpad"           , DHCP_STRING | 0xfc, NULL, 0},
227     {"serverid"       , DHCP_IP     | 0x36, NULL, 0},
228     {"message"        , DHCP_STRING | 0x38, NULL, 0},
229     {"vlanid"         , DHCP_NUM32  | 0x84, NULL, 0},
230     {"vlanpriority"   , DHCP_NUM32  | 0x85, NULL, 0},
231     {"dns"            , DHCP_IPLIST | 0x06, NULL, 0},
232     {"wins"           , DHCP_IPLIST | 0x2c, NULL, 0},
233     {"nissrv"         , DHCP_IPLIST | 0x29, NULL, 0},
234     {"ntpsrv"         , DHCP_IPLIST | 0x2a, NULL, 0},
235     {"lprsrv"         , DHCP_IPLIST | 0x09, NULL, 0},
236     {"swapsrv"        , DHCP_IP     | 0x10, NULL, 0},
237     {"routes"         , DHCP_STCRTS | 0x21, NULL, 0},
238     {"staticroutes"   , DHCP_STCRTS | 0x79, NULL, 0},
239     {"msstaticroutes" , DHCP_STCRTS | 0xf9, NULL, 0},
240 };
241 
242 static  struct sock_filter filter_instr[] = {
243     BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
244     BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
245     BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
246     BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
247     BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
248     BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
249     BPF_STMT(BPF_RET|BPF_K, 0xffffffff), BPF_STMT(BPF_RET|BPF_K, 0),
250 };
251 
252 static  struct sock_fprog filter_prog = {
253     .len = ARRAY_LEN(filter_instr),
254     .filter = (struct sock_filter *) filter_instr,
255 };
256 
257 // calculate options size.
dhcp_opt_size(uint8_t * optionptr)258 static int dhcp_opt_size(uint8_t *optionptr)
259 {
260   int i = 0;
261   for(;optionptr[i] != 0xff; i++) if(optionptr[i] != 0x00) i += optionptr[i + 1] + 2 -1;
262   return i;
263 }
264 
265 // calculates checksum for dhcp messages.
dhcp_checksum(void * addr,int count)266 static uint16_t dhcp_checksum(void *addr, int count)
267 {
268   int32_t sum = 0;
269   uint16_t tmp = 0, *source = (uint16_t *)addr;
270 
271   while (count > 1)  {
272     sum += *source++;
273     count -= 2;
274   }
275   if (count > 0) {
276     *(uint8_t*)&tmp = *(uint8_t*)source;
277     sum += tmp;
278   }
279   while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
280   return ~sum;
281 }
282 
283 // gets information of INTERFACE and updates IFINDEX, MAC and IP
get_interface(char * interface,int * ifindex,uint32_t * oip,uint8_t * mac)284 static int get_interface( char *interface, int *ifindex, uint32_t *oip, uint8_t *mac)
285 {
286   struct ifreq req;
287   struct sockaddr_in *ip;
288   int fd = xsocket(AF_INET, SOCK_RAW, IPPROTO_RAW);
289 
290   req.ifr_addr.sa_family = AF_INET;
291   xstrncpy(req.ifr_name, interface, IFNAMSIZ);
292   req.ifr_name[IFNAMSIZ-1] = '\0';
293 
294   xioctl(fd, SIOCGIFFLAGS, &req);
295   if (!(req.ifr_flags & IFF_UP)) return -1;
296 
297   if (oip) {
298     xioctl(fd, SIOCGIFADDR, &req);
299     ip = (struct sockaddr_in*) &req.ifr_addr;
300     dbg("IP %s\n", inet_ntoa(ip->sin_addr));
301     *oip = ntohl(ip->sin_addr.s_addr);
302   }
303   if (ifindex) {
304     xioctl(fd, SIOCGIFINDEX, &req);
305     dbg("Adapter index %d\n", req.ifr_ifindex);
306     *ifindex = req.ifr_ifindex;
307   }
308   if (mac) {
309     xioctl(fd, SIOCGIFHWADDR, &req);
310     memcpy(mac, req.ifr_hwaddr.sa_data, 6);
311     dbg("MAC %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
312   }
313   close(fd);
314   return 0;
315 }
316 
317 /*
318  *logs messeges to syslog or console
319  *opening the log is still left with applet.
320  *FIXME: move to more relevent lib. probably libc.c
321  */
infomsg(uint8_t infomode,char * s,...)322 static void infomsg(uint8_t infomode,  char *s, ...)
323 {
324   int used;
325   char *msg;
326   va_list p, t;
327 
328   if (infomode == LOG_SILENT) return;
329   va_start(p, s);
330   va_copy(t, p);
331   used = vsnprintf(NULL, 0, s, t);
332   used++;
333   va_end(t);
334 
335   msg = xmalloc(used);
336   vsnprintf(msg, used, s, p);
337   va_end(p);
338 
339   if (infomode & LOG_SYSTEM) syslog(LOG_INFO, "%s", msg);
340   if (infomode & LOG_CONSOLE) printf("%s\n", msg);
341   free(msg);
342 }
343 
344 /*
345  * Writes self PID in file PATH
346  * FIXME: libc implementation only writes in /var/run
347  * this is more generic as some implemenation may provide
348  * arguments to write in specific file. as dhcpd does.
349  */
write_pid(char * path)350 static void write_pid(char *path)
351 {
352   int pidfile = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
353   if (pidfile > 0) {
354     char pidbuf[12];
355 
356     sprintf(pidbuf, "%u", (unsigned)getpid());
357     write(pidfile, pidbuf, strlen(pidbuf));
358     close(pidfile);
359   }
360 }
361 
362 // String STR to UINT32 conversion strored in VAR
strtou32(char * str)363 static long strtou32( char *str)
364 {
365   char *endptr = NULL;
366   int base = 10;
367   errno=0;
368   if (str[0]=='0' && (str[1]=='x' || str[1]=='X')) {
369     base = 16;
370     str+=2;
371   }
372   long ret_val = strtol(str, &endptr, base);
373   if (errno) return -1;
374   else if (endptr && (*endptr!='\0'||endptr == str)) return -1;
375   return ret_val;
376 }
377 
378 // IP String STR to binary data.
striptovar(char * str,void * var)379 static int striptovar( char *str, void *var)
380 {
381   in_addr_t addr;
382   if(!str) error_exit("NULL address string.");
383   addr = inet_addr(str);
384   if(addr == -1) error_exit("Wrong address %s.",str );
385   *((uint32_t*)(var)) = (uint32_t)addr;
386   return 0;
387 }
388 
389 // String to dhcp option conversion
strtoopt(char * str,uint8_t optonly)390 static int strtoopt( char *str, uint8_t optonly)
391 {
392   char *option, *valstr, *grp, *tp;
393   long optcode = 0, convtmp;
394   uint16_t flag = 0;
395   uint32_t mask, nip, router;
396   int count, size = ARRAY_LEN(options_list);
397 
398   if (!*str) return 0;
399   option = strtok((char*)str, ":");
400   if (!option) return -1;
401 
402   dbg("-x option : %s ", option);
403   optcode = strtou32(option);
404 
405   if (optcode > 0 && optcode < 256) {         // raw option
406     for (count = 0; count < size; count++) {
407       if ((options_list[count].code & 0X00FF) == optcode) {
408         flag = (options_list[count].code & 0XFF00);
409         break;
410       }
411     }
412     if (count == size) error_exit("Obsolete OR Unknown Option : %s", option);
413   } else {    // string option
414     for (count = 0; count < size; count++) {
415       if (!strcmp(options_list[count].key, option)) {
416         flag = (options_list[count].code & 0XFF00);
417         optcode = (options_list[count].code & 0X00FF);
418         break;
419       }
420     }
421     if (count == size) error_exit("Obsolete OR Unknown Option : %s", option);
422   }
423   if (!flag || !optcode) return -1;
424   if (optonly) return optcode;
425 
426   valstr = strtok(NULL, "\n");
427   if (!valstr) error_exit("option %s has no value defined.\n", option);
428   dbg(" value : %-20s \n ", valstr);
429   switch (flag) {
430   case DHCP_NUM32:
431     options_list[count].len = sizeof(uint32_t);
432     options_list[count].val = xmalloc(sizeof(uint32_t));
433     convtmp = strtou32(valstr);
434     if (convtmp < 0) error_exit("Invalid/wrong formated number %s", valstr);
435     convtmp = htonl(convtmp);
436     memcpy(options_list[count].val, &convtmp, sizeof(uint32_t));
437     break;
438   case DHCP_NUM16:
439     options_list[count].len = sizeof(uint16_t);
440     options_list[count].val = xmalloc(sizeof(uint16_t));
441     convtmp = strtou32(valstr);
442     if (convtmp < 0) error_exit("Invalid/malformed number %s", valstr);
443     convtmp = htons(convtmp);
444     memcpy(options_list[count].val, &convtmp, sizeof(uint16_t));
445     break;
446   case DHCP_NUM8:
447     options_list[count].len = sizeof(uint8_t);
448     options_list[count].val = xmalloc(sizeof(uint8_t));
449     convtmp = strtou32(valstr);
450     if (convtmp < 0) error_exit("Invalid/malformed number %s", valstr);
451     memcpy(options_list[count].val, &convtmp, sizeof(uint8_t));
452     break;
453   case DHCP_IP:
454     options_list[count].len = sizeof(uint32_t);
455     options_list[count].val = xmalloc(sizeof(uint32_t));
456     striptovar(valstr, options_list[count].val);
457     break;
458   case DHCP_STRING:
459     options_list[count].len = strlen(valstr);
460     options_list[count].val = strdup(valstr);
461     break;
462   case DHCP_IPLIST:
463     while(valstr){
464       options_list[count].val = xrealloc(options_list[count].val, options_list[count].len + sizeof(uint32_t));
465       striptovar(valstr, ((uint8_t*)options_list[count].val)+options_list[count].len);
466       options_list[count].len += sizeof(uint32_t);
467       valstr = strtok(NULL," \t");
468     }
469     break;
470   case DHCP_STRLST:
471   case DHCP_IPPLST:
472     break;
473   case DHCP_STCRTS:
474     /* Option binary format:
475      * mask [one byte, 0..32]
476      * ip [0..4 bytes depending on mask]
477      * router [4 bytes]
478      * may be repeated
479      * staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
480      */
481     grp = strtok(valstr, ",");;
482     while(grp){
483       while(*grp == ' ' || *grp == '\t') grp++;
484       tp = strchr(grp, '/');
485       if (!tp) error_exit("malformed static route option");
486       *tp = '\0';
487       mask = strtol(++tp, &tp, 10);
488       if (striptovar(grp, (uint8_t*)&nip) < 0) error_exit("malformed static route option");
489       while(*tp == ' ' || *tp == '\t' || *tp == '-') tp++;
490       if (striptovar(tp, (uint8_t*)&router) < 0) error_exit("malformed static route option");
491       options_list[count].val = xrealloc(options_list[count].val, options_list[count].len + 1 + mask/8 + 4);
492       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &mask, 1);
493       options_list[count].len += 1;
494       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &nip, mask/8);
495       options_list[count].len += mask/8;
496       memcpy(((uint8_t*)options_list[count].val)+options_list[count].len, &router, 4);
497       options_list[count].len += 4;
498       tp = NULL;
499       grp = strtok(NULL, ",");
500     }
501     break;
502   }
503   return 0;
504 }
505 
506 // Creates environment pointers from RES to use in script
fill_envp(dhcpc_result_t * res)507 static int fill_envp(dhcpc_result_t *res)
508 {
509   struct in_addr temp;
510   int size = ARRAY_LEN(options_list), count, ret = -1;
511 
512   ret = setenv("interface", state->iface, 1);
513   if (!res) return ret;
514   if (res->ipaddr.s_addr) {
515       temp.s_addr = htonl(res->ipaddr.s_addr);
516       ret = setenv("ip", inet_ntoa(temp), 1);
517       if (ret) return ret;
518   }
519   if (msgopt_list) {
520     for (count = 0; count < size; count++) {
521         if ((msgopt_list[count].len == 0) || (msgopt_list[count].val == NULL)) continue;
522         ret = setenv(msgopt_list[count].key, (char*)msgopt_list[count].val, 1);
523         if (ret) return ret;
524       }
525   }
526   return ret;
527 }
528 
529 // Executes Script NAME.
run_script(dhcpc_result_t * res,char * name)530 static void run_script(dhcpc_result_t *res,  char *name)
531 {
532   volatile int error = 0;
533   pid_t pid;
534   char *argv[3];
535   struct stat sts;
536   char *script = flag_get(FLAG_s, TT.script, "/usr/share/dhcp/default.script");
537 
538   if (stat(script, &sts) == -1 && errno == ENOENT) return;
539   if (fill_envp(res)) {
540     dbg("Failed to create environment variables.");
541     return;
542   }
543   dbg("Executing %s %s\n", script, name);
544   argv[0] = (char*) script;
545   argv[1] = (char*) name;
546   argv[2] = NULL;
547   fflush(NULL);
548 
549   pid = vfork();
550   if (pid < 0) {
551     dbg("Fork failed.\n");
552     return;
553   }
554   if (!pid) {
555     execvp(argv[0], argv);
556     error = errno;
557     _exit(111);
558   }
559   if (error) {
560     waitpid(pid, NULL,0);
561     errno = error;
562     perror_msg("script exec failed");
563   }
564   dbg("script complete.\n");
565 }
566 
567 // returns a randome ID
getxid(void)568 static uint32_t getxid(void)
569 {
570   uint32_t randnum;
571   int fd = xopen("/dev/urandom", O_RDONLY);
572   xreadall(fd, &randnum, sizeof(randnum));
573   xclose(fd);
574   return randnum;
575 }
576 
577 // opens socket in raw mode.
mode_raw(void)578 static int mode_raw(void)
579 {
580   state->mode = MODE_OFF;
581   struct sockaddr_ll sock;
582 
583   if (state->sockfd > 0) close(state->sockfd);
584   dbg("Opening raw socket on ifindex %d\n", state->ifindex);
585 
586   state->sockfd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
587   if (state->sockfd < 0) {
588     dbg("MODE RAW : socket fail ERROR : %d\n", state->sockfd);
589     return -1;
590   }
591   dbg("Got raw socket fd %d\n", state->sockfd);
592   memset(&sock, 0, sizeof(sock));
593   sock.sll_family = AF_PACKET;
594   sock.sll_protocol = htons(ETH_P_IP);
595   sock.sll_ifindex = state->ifindex;
596 
597   if (bind(state->sockfd, (struct sockaddr *) &sock, sizeof(sock))) {
598     dbg("MODE RAW : bind fail.\n");
599     close(state->sockfd);
600     return -1;
601   }
602   state->mode = MODE_RAW;
603   if (setsockopt(state->sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) < 0)
604     dbg("MODE RAW : filter attach fail.\n");
605 
606   dbg("MODE RAW : success\n");
607   return 0;
608 }
609 
610 // opens UDP socket
mode_app(void)611 static int mode_app(void)
612 {
613   struct sockaddr_in addr;
614   struct ifreq ifr;
615 
616   state->mode = MODE_OFF;
617   if (state->sockfd > 0) close(state->sockfd);
618 
619   dbg("Opening listen socket on *:%d %s\n", DHCPC_CLIENT_PORT, state->iface);
620   state->sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
621   if (state->sockfd < 0) {
622     dbg("MODE APP : socket fail ERROR: %d\n", state->sockfd);
623     return -1;
624   }
625   setsockopt(state->sockfd, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set));
626   if (setsockopt(state->sockfd, SOL_SOCKET, SO_BROADCAST, &set, sizeof(set)) == -1) {
627     dbg("MODE APP : brodcast failed.\n");
628     close(state->sockfd);
629     return -1;
630   }
631   xstrncpy(ifr.ifr_name, state->iface, IFNAMSIZ);
632   ifr.ifr_name[IFNAMSIZ -1] = '\0';
633   setsockopt(state->sockfd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
634 
635   memset(&addr, 0, sizeof(addr));
636   addr.sin_family = AF_INET;
637   addr.sin_port = htons(DHCPC_CLIENT_PORT);
638   addr.sin_addr.s_addr = INADDR_ANY ;
639 
640   if (bind(state->sockfd, (struct sockaddr *) &addr, sizeof(addr))) {
641     close(state->sockfd);
642     dbg("MODE APP : bind failed.\n");
643     return -1;
644   }
645   state->mode = MODE_APP;
646   dbg("MODE APP : success\n");
647   return 0;
648 }
649 
read_raw(void)650 static int read_raw(void)
651 {
652   dhcp_raw_t packet;
653   uint16_t check;
654   int bytes = 0;
655 
656   memset(&packet, 0, sizeof(packet));
657   if ((bytes = read(state->sockfd, &packet, sizeof(packet))) < 0) {
658     dbg("\tPacket read error, ignoring\n");
659     return bytes;
660   }
661   if (bytes < (int) (sizeof(packet.iph) + sizeof(packet.udph))) {
662     dbg("\tPacket is too short, ignoring\n");
663     return -2;
664   }
665   if (bytes < ntohs(packet.iph.tot_len)) {
666     dbg("\tOversized packet, ignoring\n");
667     return -2;
668   }
669   // ignore any extra garbage bytes
670   bytes = ntohs(packet.iph.tot_len);
671   // make sure its the right packet for us, and that it passes sanity checks
672   if (packet.iph.protocol != IPPROTO_UDP || packet.iph.version != IPVERSION
673    || packet.iph.ihl != (sizeof(packet.iph) >> 2)
674    || packet.udph.dest != htons(DHCPC_CLIENT_PORT)
675    || ntohs(packet.udph.len) != (uint16_t)(bytes - sizeof(packet.iph))) {
676     dbg("\tUnrelated/bogus packet, ignoring\n");
677     return -2;
678   }
679   // verify IP checksum
680   check = packet.iph.check;
681   packet.iph.check = 0;
682   if (check != dhcp_checksum(&packet.iph, sizeof(packet.iph))) {
683     dbg("\tBad IP header checksum, ignoring\n");
684     return -2;
685   }
686   memset(&packet.iph, 0, ((size_t) &((struct iphdr *)0)->protocol));
687   packet.iph.tot_len = packet.udph.len;
688   check = packet.udph.check;
689   packet.udph.check = 0;
690   if (check && check != dhcp_checksum(&packet, bytes)) {
691     dbg("\tPacket with bad UDP checksum received, ignoring\n");
692     return -2;
693   }
694   memcpy(&state->pdhcp, &packet.dhcp, bytes - (sizeof(packet.iph) + sizeof(packet.udph)));
695   if (state->pdhcp.cookie != htonl(DHCP_MAGIC)) {
696     dbg("\tPacket with bad magic, ignoring\n");
697     return -2;
698   }
699   return bytes - sizeof(packet.iph) - sizeof(packet.udph);
700 }
701 
read_app(void)702 static int read_app(void)
703 {
704   int ret;
705 
706   memset(&state->pdhcp, 0, sizeof(dhcp_msg_t));
707   if ((ret = read(state->sockfd, &state->pdhcp, sizeof(dhcp_msg_t))) < 0) {
708     dbg("Packet read error, ignoring\n");
709     return ret; /* returns -1 */
710   }
711   if (state->pdhcp.cookie != htonl(DHCP_MAGIC)) {
712     dbg("Packet with bad magic, ignoring\n");
713     return -2;
714   }
715   return ret;
716 }
717 
718 // Sends data through raw socket.
send_raw(void)719 static int send_raw(void)
720 {
721   struct sockaddr_ll dest_sll;
722   dhcp_raw_t packet;
723   unsigned padding;
724   int fd, result = -1;
725 
726   memset(&packet, 0, sizeof(dhcp_raw_t));
727   memcpy(&packet.dhcp, &state->pdhcp, sizeof(dhcp_msg_t));
728 
729   if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
730     dbg("SEND RAW: socket failed\n");
731     return result;
732   }
733   memset(&dest_sll, 0, sizeof(dest_sll));
734   dest_sll.sll_family = AF_PACKET;
735   dest_sll.sll_protocol = htons(ETH_P_IP);
736   dest_sll.sll_ifindex = state->ifindex;
737   dest_sll.sll_halen = 6;
738   memcpy(dest_sll.sll_addr, bmacaddr , 6);
739 
740   if (bind(fd, (struct sockaddr *) &dest_sll, sizeof(dest_sll)) < 0) {
741     dbg("SEND RAW: bind failed\n");
742     close(fd);
743     return result;
744   }
745   padding = 308 - 1 - dhcp_opt_size(state->pdhcp.options);
746   packet.iph.protocol = IPPROTO_UDP;
747   packet.iph.saddr = INADDR_ANY;
748   packet.iph.daddr = INADDR_BROADCAST;
749   packet.udph.source = htons(DHCPC_CLIENT_PORT);
750   packet.udph.dest = htons(DHCPC_SERVER_PORT);
751   packet.udph.len = htons(sizeof(dhcp_raw_t) - sizeof(struct iphdr) - padding);
752   packet.iph.tot_len = packet.udph.len;
753   packet.udph.check = dhcp_checksum(&packet, sizeof(dhcp_raw_t) - padding);
754   packet.iph.tot_len = htons(sizeof(dhcp_raw_t) - padding);
755   packet.iph.ihl = sizeof(packet.iph) >> 2;
756   packet.iph.version = IPVERSION;
757   packet.iph.ttl = IPDEFTTL;
758   packet.iph.check = dhcp_checksum(&packet.iph, sizeof(packet.iph));
759 
760   result = sendto(fd, &packet, sizeof(dhcp_raw_t) - padding, 0,
761       (struct sockaddr *) &dest_sll, sizeof(dest_sll));
762 
763   close(fd);
764   if (result < 0) dbg("SEND RAW: PACKET send error\n");
765   return result;
766 }
767 
768 // Sends data through UDP socket.
send_app(void)769 static int send_app(void)
770 {
771   struct sockaddr_in cli;
772   int fd, ret = -1;
773 
774   if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
775     dbg("SEND APP: sock failed.\n");
776     return ret;
777   }
778   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set));
779 
780   memset(&cli, 0, sizeof(cli));
781   cli.sin_family = AF_INET;
782   cli.sin_port = htons(DHCPC_CLIENT_PORT);
783   cli.sin_addr.s_addr = state->pdhcp.ciaddr;
784   if (bind(fd, (struct sockaddr *)&cli, sizeof(cli)) == -1) {
785     dbg("SEND APP: bind failed.\n");
786     goto error_fd;
787   }
788   memset(&cli, 0, sizeof(cli));
789   cli.sin_family = AF_INET;
790   cli.sin_port = htons(DHCPC_SERVER_PORT);
791   cli.sin_addr.s_addr = state->serverid.s_addr;
792   if (connect(fd, (struct sockaddr *)&cli, sizeof(cli)) == -1) {
793     dbg("SEND APP: connect failed.\n");
794     goto error_fd;
795   }
796   int padding = 308 - 1 - dhcp_opt_size(state->pdhcp.options);
797   if((ret = write(fd, &state->pdhcp, sizeof(dhcp_msg_t) - padding)) < 0) {
798     dbg("SEND APP: write failed error %d\n", ret);
799     goto error_fd;
800   }
801   dbg("SEND APP: write success wrote %d\n", ret);
802 error_fd:
803   close(fd);
804   return ret;
805 }
806 
807 // Generic signal handler real handling is done in main funcrion.
signal_handler(int sig)808 static void signal_handler(int sig)
809 {
810   unsigned char ch = sig;
811   if (write(sigfd.wr, &ch, 1) != 1) dbg("can't send signal\n");
812 }
813 
814 // signal setup for SIGUSR1 SIGUSR2 SIGTERM
setup_signal()815 static int setup_signal()
816 {
817   if (pipe((int *)&sigfd) < 0) {
818     dbg("signal pipe failed\n");
819     return -1;
820   }
821   fcntl(sigfd.wr , F_SETFD, FD_CLOEXEC);
822   fcntl(sigfd.rd , F_SETFD, FD_CLOEXEC);
823   int flags = fcntl(sigfd.wr, F_GETFL);
824   fcntl(sigfd.wr, F_SETFL, flags | O_NONBLOCK);
825   signal(SIGUSR1, signal_handler);
826   signal(SIGUSR2, signal_handler);
827   signal(SIGTERM, signal_handler);
828 
829   return 0;
830 }
831 
832 // adds client id to dhcp packet
dhcpc_addclientid(uint8_t * optptr)833 static uint8_t *dhcpc_addclientid(uint8_t *optptr)
834 {
835   *optptr++ = DHCP_OPTION_CLIENTID;
836   *optptr++ = 7;
837   *optptr++ = 1;
838   memcpy(optptr, &state->macaddr, 6);
839   return optptr + 6;
840 }
841 
842 // adds messege type to dhcp packet
dhcpc_addmsgtype(uint8_t * optptr,uint8_t type)843 static uint8_t *dhcpc_addmsgtype(uint8_t *optptr, uint8_t type)
844 {
845   *optptr++ = DHCP_OPTION_MSG_TYPE;
846   *optptr++ = 1;
847   *optptr++ = type;
848   return optptr;
849 }
850 
851 // adds max size to dhcp packet
dhcpc_addmaxsize(uint8_t * optptr,uint16_t size)852 static uint8_t *dhcpc_addmaxsize(uint8_t *optptr, uint16_t size)
853 {
854   *optptr++ = DHCP_OPTION_MAX_SIZE;
855   *optptr++ = 2;
856   memcpy(optptr, &size, 2);
857   return optptr + 2;
858 }
859 
dhcpc_addstropt(uint8_t * optptr,uint8_t opcode,char * str,int len)860 static uint8_t *dhcpc_addstropt(uint8_t *optptr, uint8_t opcode, char* str, int len)
861 {
862   *optptr++ = opcode;
863   *optptr++ = len;
864   memcpy(optptr, str, len);
865   return optptr + len;
866 }
867 
868 // adds server id to dhcp packet.
dhcpc_addserverid(struct in_addr * serverid,uint8_t * optptr)869 static uint8_t *dhcpc_addserverid(struct in_addr *serverid, uint8_t *optptr)
870 {
871   *optptr++ = DHCP_OPTION_SERVER_ID;
872   *optptr++ = 4;
873   memcpy(optptr, &serverid->s_addr, 4);
874   return optptr + 4;
875 }
876 
877 // adds requested ip address to dhcp packet.
dhcpc_addreqipaddr(struct in_addr * ipaddr,uint8_t * optptr)878 static uint8_t *dhcpc_addreqipaddr(struct in_addr *ipaddr, uint8_t *optptr)
879 {
880   *optptr++ = DHCP_OPTION_REQ_IPADDR;
881   *optptr++ = 4;
882   memcpy(optptr, &ipaddr->s_addr, 4);
883   return optptr + 4;
884 }
885 
886 // adds hostname to dhcp packet.
dhcpc_addfdnname(uint8_t * optptr,char * hname)887 static uint8_t *dhcpc_addfdnname(uint8_t *optptr, char *hname)
888 {
889   int size = strlen(hname);
890 
891   *optptr++ = DHCP_OPTION_FQDN;
892   *optptr++ = size + 3;
893   *optptr++ = 0x1;  //flags
894   optptr += 2;      // two blank bytes
895   strcpy((char*)optptr, hname); // name
896 
897   return optptr + size;
898 }
899 
900 // adds request options using -o,-O flag to dhcp packet
dhcpc_addreqoptions(uint8_t * optptr)901 static uint8_t *dhcpc_addreqoptions(uint8_t *optptr)
902 {
903   uint8_t *len;
904 
905   *optptr++ = DHCP_OPTION_REQ_LIST;
906   len = optptr;
907   *len = 0;
908   optptr++;
909 
910   if (!flag_chk(FLAG_o)) {
911     *len = 4;
912     *optptr++ = DHCP_OPTION_SUBNET_MASK;
913     *optptr++ = DHCP_OPTION_ROUTER;
914     *optptr++ = DHCP_OPTION_DNS_SERVER;
915     *optptr++ = DHCP_OPTION_BROADCAST;
916   }
917   if (flag_chk(FLAG_O)) {
918     memcpy(optptr++, raw_opt, raw_optcount);
919     *len += raw_optcount;
920   }
921   return optptr;
922 }
923 
dhcpc_addend(uint8_t * optptr)924 static uint8_t *dhcpc_addend(uint8_t *optptr)
925 {
926   *optptr++ = DHCP_OPTION_END;
927   return optptr;
928 }
929 
930 // Sets values of -x options in dhcp discover and request packet.
set_xopt(uint8_t * optptr)931 static uint8_t* set_xopt(uint8_t *optptr)
932 {
933   int count;
934   int size = ARRAY_LEN(options_list);
935   for (count = 0; count < size; count++) {
936     if ((options_list[count].len == 0) || (options_list[count].val == NULL)) continue;
937     *optptr++ = (uint8_t) (options_list[count].code & 0x00FF);
938     *optptr++ = (uint8_t) options_list[count].len;
939     memcpy(optptr, options_list[count].val, options_list[count].len);
940     optptr += options_list[count].len;
941   }
942   return optptr;
943 }
944 
get_option_serverid(uint8_t * opt,dhcpc_result_t * presult)945 static uint32_t get_option_serverid (uint8_t *opt, dhcpc_result_t *presult)
946 {
947   uint32_t var = 0;
948   while (*opt != DHCP_OPTION_SERVER_ID) {
949     if (*opt == DHCP_OPTION_END) return var;
950     opt += opt[1] + 2;
951   }
952   memcpy(&var, opt+2, sizeof(uint32_t));
953   state->serverid.s_addr = var;
954   presult->serverid.s_addr = state->serverid.s_addr;
955   presult->serverid.s_addr = ntohl(presult->serverid.s_addr);
956   return var;
957 }
958 
get_option_msgtype(uint8_t * opt)959 static uint8_t get_option_msgtype(uint8_t *opt)
960 {
961   uint32_t var = 0;
962   while (*opt != DHCP_OPTION_MSG_TYPE) {
963     if (*opt == DHCP_OPTION_END) return var;
964     opt += opt[1] + 2;
965   }
966   memcpy(&var, opt+2, sizeof(uint8_t));
967   return var;
968 }
969 
get_option_lease(uint8_t * opt,dhcpc_result_t * presult)970 static uint8_t get_option_lease(uint8_t *opt, dhcpc_result_t *presult)
971 {
972   uint32_t var = 0;
973   while (*opt != DHCP_OPTION_LEASE_TIME) {
974     if (*opt == DHCP_OPTION_END) return var;
975     opt += opt[1] + 2;
976   }
977   memcpy(&var, opt+2, sizeof(uint32_t));
978   var = htonl(var);
979   presult->lease_time = var;
980   return var;
981 }
982 
983 
984 // sends dhcp msg of MSGTYPE
dhcpc_sendmsg(int msgtype)985 static int dhcpc_sendmsg(int msgtype)
986 {
987   uint8_t *pend;
988   struct in_addr rqsd;
989   char *vendor;
990 
991   // Create the common message header settings
992   memset(&state->pdhcp, 0, sizeof(dhcp_msg_t));
993   state->pdhcp.op = DHCP_REQUEST;
994   state->pdhcp.htype = DHCP_HTYPE_ETHERNET;
995   state->pdhcp.hlen = 6;
996   state->pdhcp.xid = xid;
997   memcpy(state->pdhcp.chaddr, state->macaddr, 6);
998   memset(&state->pdhcp.chaddr[6], 0, 10);
999   state->pdhcp.cookie = htonl(DHCP_MAGIC);;
1000 
1001   // Add the common header options
1002   pend = state->pdhcp.options;
1003   pend = dhcpc_addmsgtype(pend, msgtype);
1004 
1005   if (!flag_chk(FLAG_C)) pend = dhcpc_addclientid(pend);
1006   // Handle the message specific settings
1007   switch (msgtype) {
1008   case DHCPDISCOVER: // Broadcast DISCOVER message to all servers
1009     state->pdhcp.flags = htons(BOOTP_BROADCAST); //  Broadcast bit.
1010     if (flag_chk(FLAG_r)) {
1011       inet_aton(TT.req_ip, &rqsd);
1012       pend = dhcpc_addreqipaddr(&rqsd, pend);
1013     }
1014     pend = dhcpc_addmaxsize(pend, htons(sizeof(dhcp_raw_t)));
1015     vendor = flag_get(FLAG_V, TT.vendor_cls, "toybox\0");
1016     pend = dhcpc_addstropt(pend, DHCP_OPTION_VENDOR, vendor, strlen(vendor));
1017     if (flag_chk(FLAG_H)) pend = dhcpc_addstropt(pend, DHCP_OPTION_HOST_NAME, TT.hostname, strlen(TT.hostname));
1018     if (flag_chk(FLAG_F)) pend = dhcpc_addfdnname(pend, TT.fdn_name);
1019     if ((!flag_chk(FLAG_o)) || flag_chk(FLAG_O)) pend = dhcpc_addreqoptions(pend);
1020     if (flag_chk(FLAG_x)) pend = set_xopt(pend);
1021     break;
1022   case DHCPREQUEST: // Send REQUEST message to the server that sent the *first* OFFER
1023     state->pdhcp.flags = htons(BOOTP_BROADCAST); //  Broadcast bit.
1024     if (state->status == STATE_RENEWING) memcpy(&state->pdhcp.ciaddr, &state->ipaddr.s_addr, 4);
1025     pend = dhcpc_addmaxsize(pend, htons(sizeof(dhcp_raw_t)));
1026     rqsd.s_addr = htonl(server);
1027     pend = dhcpc_addserverid(&rqsd, pend);
1028     pend = dhcpc_addreqipaddr(&state->ipaddr, pend);
1029     vendor = flag_get(FLAG_V, TT.vendor_cls, "toybox\0");
1030     pend = dhcpc_addstropt(pend, DHCP_OPTION_VENDOR, vendor, strlen(vendor));
1031     if (flag_chk(FLAG_H)) pend = dhcpc_addstropt(pend, DHCP_OPTION_HOST_NAME, TT.hostname, strlen(TT.hostname));
1032     if (flag_chk(FLAG_F)) pend = dhcpc_addfdnname(pend, TT.fdn_name);
1033     if ((!flag_chk(FLAG_o)) || flag_chk(FLAG_O)) pend = dhcpc_addreqoptions(pend);
1034     if (flag_chk(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 (flag_chk(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(flag_chk(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 (flag_chk(FLAG_v)) dbg = xprintf;
1278   if (flag_chk(FLAG_p)) write_pid(TT.pidfile);
1279   retries = flag_get(FLAG_t, TT.retries, 3);
1280   if (flag_chk(FLAG_S)) {
1281       openlog("UDHCPC :", LOG_PID, LOG_DAEMON);
1282       infomode |= LOG_SYSTEM;
1283   }
1284   infomsg(infomode, "dhcp started");
1285   if (flag_chk(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 (flag_chk(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 = flag_get(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 = flag_get(FLAG_T, TT.timeout, 3);
1343           waited = 0;
1344           packets++;
1345           continue;
1346         }
1347 lease_fail:
1348         run_script(NULL,"leasefail");
1349         if (flag_chk(FLAG_n)) {
1350           infomsg(infomode, "Lease failed. Exiting");
1351           goto ret_with_sockfd;
1352         }
1353         if (flag_chk(FLAG_b)) {
1354           infomsg(infomode, "Lease failed. Going Daemon mode");
1355           daemon(0, 0);
1356           if (flag_chk(FLAG_p)) write_pid(TT.pidfile);
1357           toys.optflags &= ~FLAG_b;
1358           toys.optflags |= FLAG_f;
1359         }
1360         timeout = flag_get(FLAG_A, TT.tryagain, 20);
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 = flag_get(FLAG_T, TT.timeout, 3);
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 (flag_chk(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 (flag_chk(FLAG_q)) {
1487             if (flag_chk(FLAG_R)) release();
1488             goto ret_with_sockfd;
1489           }
1490           toys.optflags &= ~FLAG_n;
1491           if (!flag_chk(FLAG_f)) {
1492             daemon(0, 0);
1493             toys.optflags |= FLAG_f;
1494             if (flag_chk(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