0c433ddcc8632c5fdc23b404083ecf1af82db08b
[platform/upstream/connman.git] / gdhcp / common.c
1 /*
2  *  DHCP library with GLib integration
3  *
4  *  Copyright (C) 2007-2012  Intel Corporation. All rights reserved.
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License version 2 as
8  *  published by the Free Software Foundation.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <sys/ioctl.h>
30 #include <stdint.h>
31 #include <string.h>
32 #include <endian.h>
33 #include <net/if_arp.h>
34 #include <linux/if.h>
35 #include <netpacket/packet.h>
36 #include <net/ethernet.h>
37 #include <arpa/inet.h>
38
39 #include "gdhcp.h"
40 #include "common.h"
41
42 static const DHCPOption client_options[] = {
43         { OPTION_IP,                    0x01 }, /* subnet-mask */
44         { OPTION_IP | OPTION_LIST,      0x03 }, /* routers */
45         { OPTION_IP | OPTION_LIST,      0x06 }, /* domain-name-servers */
46         { OPTION_STRING,                0x0c }, /* hostname */
47         { OPTION_STRING,                0x0f }, /* domain-name */
48         { OPTION_IP | OPTION_LIST,      0x2a }, /* ntp-servers */
49         { OPTION_U32,                   0x33 }, /* dhcp-lease-time */
50         /* Options below will not be exposed to user */
51         { OPTION_IP,                    0x32 }, /* requested-ip */
52         { OPTION_U8,                    0x35 }, /* message-type */
53         { OPTION_U32,                   0x36 }, /* server-id */
54         { OPTION_U16,                   0x39 }, /* max-size */
55         { OPTION_STRING,                0x3c }, /* vendor */
56         { OPTION_STRING,                0x3d }, /* client-id */
57         { OPTION_STRING,                0xfc }, /* UNOFFICIAL proxy-pac */
58         { OPTION_UNKNOWN,               0x00 },
59 };
60
61 GDHCPOptionType dhcp_get_code_type(uint8_t code)
62 {
63         int i;
64
65         for (i = 0; client_options[i].code; i++) {
66                 if (client_options[i].code == code)
67                         return client_options[i].type;
68         }
69
70         return OPTION_UNKNOWN;
71 }
72
73 uint8_t *dhcp_get_option(struct dhcp_packet *packet, int code)
74 {
75         int len, rem;
76         uint8_t *optionptr;
77         uint8_t overload = 0;
78
79         /* option bytes: [code][len][data1][data2]..[dataLEN] */
80         optionptr = packet->options;
81         rem = sizeof(packet->options);
82
83         while (1) {
84                 if (rem <= 0)
85                         /* Bad packet, malformed option field */
86                         return NULL;
87
88                 if (optionptr[OPT_CODE] == DHCP_PADDING) {
89                         rem--;
90                         optionptr++;
91
92                         continue;
93                 }
94
95                 if (optionptr[OPT_CODE] == DHCP_END) {
96                         if (overload & FILE_FIELD) {
97                                 overload &= ~FILE_FIELD;
98
99                                 optionptr = packet->file;
100                                 rem = sizeof(packet->file);
101
102                                 continue;
103                         } else if (overload & SNAME_FIELD) {
104                                 overload &= ~SNAME_FIELD;
105
106                                 optionptr = packet->sname;
107                                 rem = sizeof(packet->sname);
108
109                                 continue;
110                         }
111
112                         break;
113                 }
114
115                 len = 2 + optionptr[OPT_LEN];
116
117                 rem -= len;
118                 if (rem < 0)
119                         continue; /* complain and return NULL */
120
121                 if (optionptr[OPT_CODE] == code)
122                         return optionptr + OPT_DATA;
123
124                 if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD)
125                         overload |= optionptr[OPT_DATA];
126
127                 optionptr += len;
128         }
129
130         return NULL;
131 }
132
133 int dhcp_end_option(uint8_t *optionptr)
134 {
135         int i = 0;
136
137         while (optionptr[i] != DHCP_END) {
138                 if (optionptr[i] != DHCP_PADDING)
139                         i += optionptr[i + OPT_LEN] + OPT_DATA - 1;
140
141                 i++;
142         }
143
144         return i;
145 }
146
147 uint8_t *dhcpv6_get_option(struct dhcpv6_packet *packet, uint16_t pkt_len,
148                         int code, uint16_t *option_len, int *option_count)
149 {
150         int rem, count = 0;
151         uint8_t *optionptr, *found = NULL;
152         uint16_t opt_code, opt_len, len;
153
154         optionptr = packet->options;
155         rem = pkt_len - 1 - 3;
156
157         if (rem <= 0)
158                 goto bad_packet;
159
160         while (1) {
161                 opt_code = optionptr[0] << 8 | optionptr[1];
162                 opt_len = len = optionptr[2] << 8 | optionptr[3];
163                 len += 2 + 2; /* skip code and len */
164
165                 if (len < 4)
166                         goto bad_packet;
167
168                 rem -= len;
169                 if (rem < 0)
170                         break;
171
172                 if (opt_code == code) {
173                         if (option_len != NULL)
174                                 *option_len = opt_len;
175                         if (rem < 0)
176                                 goto bad_packet;
177                         else
178                                 found = optionptr + 2 + 2;
179                         count++;
180                 }
181
182                 if (rem == 0)
183                         break;
184
185                 optionptr += len;
186         }
187
188         if (option_count != NULL)
189                 *option_count = count;
190
191         return found;
192
193 bad_packet:
194         if (option_len != NULL)
195                 *option_len = 0;
196         if (option_count != NULL)
197                 *option_count = 0;
198         return NULL;
199 }
200
201 uint8_t *dhcpv6_get_sub_option(unsigned char *option, uint16_t max_len,
202                         uint16_t *option_code, uint16_t *option_len)
203 {
204         int rem;
205         uint16_t code, len;
206
207         rem = max_len - 2 - 2;
208
209         if (rem <= 0)
210                 /* Bad option */
211                 return NULL;
212
213         code = option[0] << 8 | option[1];
214         len = option[2] << 8 | option[3];
215
216         rem -= len;
217         if (rem < 0)
218                 return NULL;
219
220         *option_code = code;
221         *option_len = len;
222
223         return &option[4];
224 }
225
226 /*
227  * Add an option (supplied in binary form) to the options.
228  * Option format: [code][len][data1][data2]..[dataLEN]
229  */
230 void dhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt)
231 {
232         unsigned len;
233         uint8_t *optionptr = packet->options;
234         unsigned end = dhcp_end_option(optionptr);
235
236         len = OPT_DATA + addopt[OPT_LEN];
237
238         /* end position + (option code/length + addopt length) + end option */
239         if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE)
240                 /* option did not fit into the packet */
241                 return;
242
243         memcpy(optionptr + end, addopt, len);
244
245         optionptr[end + len] = DHCP_END;
246 }
247
248 /*
249  * Add an option (supplied in binary form) to the options.
250  * Option format: [code][len][data1][data2]..[dataLEN]
251  */
252 void dhcpv6_add_binary_option(struct dhcpv6_packet *packet, uint16_t max_len,
253                                 uint16_t *pkt_len, uint8_t *addopt)
254 {
255         unsigned len;
256         uint8_t *optionptr = packet->options;
257
258         len = 2 + 2 + (addopt[2] << 8 | addopt[3]);
259
260         /* end position + (option code/length + addopt length) */
261         if (*pkt_len + len >= max_len)
262                 /* option did not fit into the packet */
263                 return;
264
265         memcpy(optionptr + *pkt_len, addopt, len);
266         *pkt_len += len;
267 }
268
269 static GDHCPOptionType check_option(uint8_t code, uint8_t data_len)
270 {
271         GDHCPOptionType type = dhcp_get_code_type(code);
272         uint8_t len;
273
274         if (type == OPTION_UNKNOWN)
275                 return type;
276
277         len = dhcp_option_lengths[type & OPTION_TYPE_MASK];
278         if (len != data_len) {
279                 printf("Invalid option len %d (expecting %d) for code 0x%x\n",
280                         data_len, len, code);
281                 return OPTION_UNKNOWN;
282         }
283
284         return type;
285 }
286
287 void dhcp_add_option_uint32(struct dhcp_packet *packet, uint8_t code,
288                                                         uint32_t data)
289 {
290         uint8_t option[6];
291
292         if (check_option(code, sizeof(data)) == OPTION_UNKNOWN)
293                 return;
294
295         option[OPT_CODE] = code;
296         option[OPT_LEN] = sizeof(data);
297         put_be32(data, option + OPT_DATA);
298
299         dhcp_add_binary_option(packet, option);
300
301         return;
302 }
303
304 void dhcp_add_option_uint16(struct dhcp_packet *packet, uint8_t code,
305                                                         uint16_t data)
306 {
307         uint8_t option[6];
308
309         if (check_option(code, sizeof(data)) == OPTION_UNKNOWN)
310                 return;
311
312         option[OPT_CODE] = code;
313         option[OPT_LEN] = sizeof(data);
314         put_be16(data, option + OPT_DATA);
315
316         dhcp_add_binary_option(packet, option);
317
318         return;
319 }
320
321 void dhcp_add_option_uint8(struct dhcp_packet *packet, uint8_t code,
322                                                         uint8_t data)
323 {
324         uint8_t option[6];
325
326         if (check_option(code, sizeof(data)) == OPTION_UNKNOWN)
327                 return;
328
329         option[OPT_CODE] = code;
330         option[OPT_LEN] = sizeof(data);
331         option[OPT_DATA] = data;
332
333         dhcp_add_binary_option(packet, option);
334
335         return;
336 }
337
338 void dhcp_init_header(struct dhcp_packet *packet, char type)
339 {
340         memset(packet, 0, sizeof(*packet));
341
342         packet->op = BOOTREQUEST;
343
344         switch (type) {
345         case DHCPOFFER:
346         case DHCPACK:
347         case DHCPNAK:
348                 packet->op = BOOTREPLY;
349         }
350
351         packet->htype = 1;
352         packet->hlen = 6;
353         packet->cookie = htonl(DHCP_MAGIC);
354         packet->options[0] = DHCP_END;
355
356         dhcp_add_option_uint8(packet, DHCP_MESSAGE_TYPE, type);
357 }
358
359 void dhcpv6_init_header(struct dhcpv6_packet *packet, uint8_t type)
360 {
361         int id;
362
363         memset(packet, 0, sizeof(*packet));
364
365         packet->message = type;
366
367         id = random();
368
369         packet->transaction_id[0] = (id >> 16) & 0xff;
370         packet->transaction_id[1] = (id >> 8) & 0xff;
371         packet->transaction_id[2] = id & 0xff;
372 }
373
374 static gboolean check_vendor(uint8_t  *option_vendor, const char *vendor)
375 {
376         uint8_t vendor_length = sizeof(vendor) - 1;
377
378         if (option_vendor[OPT_LEN - OPT_DATA] != vendor_length)
379                 return FALSE;
380
381         if (memcmp(option_vendor, vendor, vendor_length) != 0)
382                 return FALSE;
383
384         return TRUE;
385 }
386
387 static void check_broken_vendor(struct dhcp_packet *packet)
388 {
389         uint8_t *vendor;
390
391         if (packet->op != BOOTREQUEST)
392                 return;
393
394         vendor = dhcp_get_option(packet, DHCP_VENDOR);
395         if (vendor == NULL)
396                 return;
397
398         if (check_vendor(vendor, "MSFT 98") == TRUE)
399                 packet->flags |= htons(BROADCAST_FLAG);
400 }
401
402 int dhcp_recv_l3_packet(struct dhcp_packet *packet, int fd)
403 {
404         int n;
405
406         memset(packet, 0, sizeof(*packet));
407
408         n = read(fd, packet, sizeof(*packet));
409         if (n < 0)
410                 return -errno;
411
412         if (packet->cookie != htonl(DHCP_MAGIC))
413                 return -EPROTO;
414
415         check_broken_vendor(packet);
416
417         return n;
418 }
419
420 int dhcpv6_recv_l3_packet(struct dhcpv6_packet **packet, unsigned char *buf,
421                         int buf_len, int fd)
422 {
423         int n;
424
425         n = read(fd, buf, buf_len);
426         if (n < 0)
427                 return -errno;
428
429         *packet = (struct dhcpv6_packet *)buf;
430
431         return n;
432 }
433
434 /* TODO: Use glib checksum */
435 uint16_t dhcp_checksum(void *addr, int count)
436 {
437         /*
438          * Compute Internet Checksum for "count" bytes
439          * beginning at location "addr".
440          */
441         int32_t sum = 0;
442         uint16_t *source = (uint16_t *) addr;
443
444         while (count > 1)  {
445                 /*  This is the inner loop */
446                 sum += *source++;
447                 count -= 2;
448         }
449
450         /*  Add left-over byte, if any */
451         if (count > 0) {
452                 /* Make sure that the left-over byte is added correctly both
453                  * with little and big endian hosts */
454                 uint16_t tmp = 0;
455                 *(uint8_t *) &tmp = *(uint8_t *) source;
456                 sum += tmp;
457         }
458         /*  Fold 32-bit sum to 16 bits */
459         while (sum >> 16)
460                 sum = (sum & 0xffff) + (sum >> 16);
461
462         return ~sum;
463 }
464
465 #define IN6ADDR_ALL_DHCP_RELAY_AGENTS_AND_SERVERS_MC_INIT \
466         { { { 0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0x1,0,0x2 } } } /* ff02::1:2 */
467 static const struct in6_addr in6addr_all_dhcp_relay_agents_and_servers_mc =
468         IN6ADDR_ALL_DHCP_RELAY_AGENTS_AND_SERVERS_MC_INIT;
469
470 /* from netinet/in.h */
471 struct in6_pktinfo {
472         struct in6_addr ipi6_addr;  /* src/dst IPv6 address */
473         unsigned int ipi6_ifindex;  /* send/recv interface index */
474 };
475
476 int dhcpv6_send_packet(int index, struct dhcpv6_packet *dhcp_pkt, int len)
477 {
478         struct msghdr m;
479         struct iovec v;
480         struct in6_pktinfo *pktinfo;
481         struct cmsghdr *cmsg;
482         int fd, ret;
483         struct sockaddr_in6 dst;
484         void *control_buf;
485         size_t control_buf_len;
486
487         fd = socket(PF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
488         if (fd < 0)
489                 return -errno;
490
491         memset(&dst, 0, sizeof(dst));
492         dst.sin6_family = AF_INET6;
493         dst.sin6_port = htons(DHCPV6_SERVER_PORT);
494
495         dst.sin6_addr = in6addr_all_dhcp_relay_agents_and_servers_mc;
496
497         control_buf_len = CMSG_SPACE(sizeof(struct in6_pktinfo));
498         control_buf = g_try_malloc0(control_buf_len);
499         if (control_buf == NULL) {
500                 close(fd);
501                 return -ENOMEM;
502         }
503
504         memset(&m, 0, sizeof(m));
505         memset(&v, 0, sizeof(v));
506
507         m.msg_name = &dst;
508         m.msg_namelen = sizeof(dst);
509
510         v.iov_base = (char *)dhcp_pkt;
511         v.iov_len = len;
512         m.msg_iov = &v;
513         m.msg_iovlen = 1;
514
515         m.msg_control = control_buf;
516         m.msg_controllen = control_buf_len;
517         cmsg = CMSG_FIRSTHDR(&m);
518         cmsg->cmsg_level = IPPROTO_IPV6;
519         cmsg->cmsg_type = IPV6_PKTINFO;
520         cmsg->cmsg_len = CMSG_LEN(sizeof(*pktinfo));
521
522         pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
523         memset(pktinfo, 0, sizeof(*pktinfo));
524         pktinfo->ipi6_ifindex = index;
525         m.msg_controllen = cmsg->cmsg_len;
526
527         ret = sendmsg(fd, &m, 0);
528         if (ret < 0)
529                 perror("DHCPv6 msg send failed");
530
531         g_free(control_buf);
532         close(fd);
533
534         return ret;
535 }
536
537 int dhcp_send_raw_packet(struct dhcp_packet *dhcp_pkt,
538                 uint32_t source_ip, int source_port, uint32_t dest_ip,
539                         int dest_port, const uint8_t *dest_arp, int ifindex)
540 {
541         struct sockaddr_ll dest;
542         struct ip_udp_dhcp_packet packet;
543         int fd, n;
544
545         enum {
546                 IP_UPD_DHCP_SIZE = sizeof(struct ip_udp_dhcp_packet) -
547                                                 EXTEND_FOR_BUGGY_SERVERS,
548                 UPD_DHCP_SIZE = IP_UPD_DHCP_SIZE -
549                                 offsetof(struct ip_udp_dhcp_packet, udp),
550         };
551
552         fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IP));
553         if (fd < 0)
554                 return -errno;
555
556         memset(&dest, 0, sizeof(dest));
557         memset(&packet, 0, sizeof(packet));
558         packet.data = *dhcp_pkt;
559
560         dest.sll_family = AF_PACKET;
561         dest.sll_protocol = htons(ETH_P_IP);
562         dest.sll_ifindex = ifindex;
563         dest.sll_halen = 6;
564         memcpy(dest.sll_addr, dest_arp, 6);
565         if (bind(fd, (struct sockaddr *)&dest, sizeof(dest)) < 0) {
566                 close(fd);
567                 return -errno;
568         }
569
570         packet.ip.protocol = IPPROTO_UDP;
571         packet.ip.saddr = source_ip;
572         packet.ip.daddr = dest_ip;
573         packet.udp.source = htons(source_port);
574         packet.udp.dest = htons(dest_port);
575         /* size, excluding IP header: */
576         packet.udp.len = htons(UPD_DHCP_SIZE);
577         /* for UDP checksumming, ip.len is set to UDP packet len */
578         packet.ip.tot_len = packet.udp.len;
579         packet.udp.check = dhcp_checksum(&packet, IP_UPD_DHCP_SIZE);
580         /* but for sending, it is set to IP packet len */
581         packet.ip.tot_len = htons(IP_UPD_DHCP_SIZE);
582         packet.ip.ihl = sizeof(packet.ip) >> 2;
583         packet.ip.version = IPVERSION;
584         packet.ip.ttl = IPDEFTTL;
585         packet.ip.check = dhcp_checksum(&packet.ip, sizeof(packet.ip));
586
587         /*
588          * Currently we send full-sized DHCP packets (zero padded).
589          * If you need to change this: last byte of the packet is
590          * packet.data.options[dhcp_end_option(packet.data.options)]
591          */
592         n = sendto(fd, &packet, IP_UPD_DHCP_SIZE, 0,
593                         (struct sockaddr *) &dest, sizeof(dest));
594         close(fd);
595
596         if (n < 0)
597                 return -errno;
598
599         return n;
600 }
601
602 int dhcp_send_kernel_packet(struct dhcp_packet *dhcp_pkt,
603                                 uint32_t source_ip, int source_port,
604                                 uint32_t dest_ip, int dest_port)
605 {
606         struct sockaddr_in client;
607         int fd, n, opt = 1;
608
609         enum {
610                 DHCP_SIZE = sizeof(struct dhcp_packet) -
611                                         EXTEND_FOR_BUGGY_SERVERS,
612         };
613
614         fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
615         if (fd < 0)
616                 return -errno;
617
618         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
619
620         memset(&client, 0, sizeof(client));
621         client.sin_family = AF_INET;
622         client.sin_port = htons(source_port);
623         client.sin_addr.s_addr = htonl(source_ip);
624         if (bind(fd, (struct sockaddr *) &client, sizeof(client)) < 0) {
625                 close(fd);
626                 return -errno;
627         }
628
629         memset(&client, 0, sizeof(client));
630         client.sin_family = AF_INET;
631         client.sin_port = htons(dest_port);
632         client.sin_addr.s_addr = htonl(dest_ip);
633         if (connect(fd, (struct sockaddr *) &client, sizeof(client)) < 0) {
634                 close(fd);
635                 return -errno;
636         }
637
638         n = write(fd, dhcp_pkt, DHCP_SIZE);
639
640         close(fd);
641
642         if (n < 0)
643                 return -errno;
644
645         return n;
646 }
647
648 int dhcp_l3_socket(int port, const char *interface, int family)
649 {
650         int fd, opt = 1, len;
651         struct sockaddr_in addr4;
652         struct sockaddr_in6 addr6;
653         struct sockaddr *addr;
654
655         fd = socket(family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
656         if (fd < 0)
657                 return -errno;
658
659         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
660
661         if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE,
662                                 interface, strlen(interface) + 1) < 0) {
663                 close(fd);
664                 return -1;
665         }
666
667         if (family == AF_INET) {
668                 memset(&addr4, 0, sizeof(addr4));
669                 addr4.sin_family = family;
670                 addr4.sin_port = htons(port);
671                 addr = (struct sockaddr *)&addr4;
672                 len = sizeof(addr4);
673         } else if (family == AF_INET6) {
674                 memset(&addr6, 0, sizeof(addr6));
675                 addr6.sin6_family = family;
676                 addr6.sin6_port = htons(port);
677                 addr = (struct sockaddr *)&addr6;
678                 len = sizeof(addr6);
679         } else {
680                 close(fd);
681                 return -EINVAL;
682         }
683
684         if (bind(fd, addr, len) != 0) {
685                 close(fd);
686                 return -1;
687         }
688
689         return fd;
690 }
691
692 char *get_interface_name(int index)
693 {
694         struct ifreq ifr;
695         int sk, err;
696
697         if (index < 0)
698                 return NULL;
699
700         sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
701         if (sk < 0) {
702                 perror("Open socket error");
703                 return NULL;
704         }
705
706         memset(&ifr, 0, sizeof(ifr));
707         ifr.ifr_ifindex = index;
708
709         err = ioctl(sk, SIOCGIFNAME, &ifr);
710         if (err < 0) {
711                 perror("Get interface name error");
712                 close(sk);
713                 return NULL;
714         }
715
716         close(sk);
717
718         return g_strdup(ifr.ifr_name);
719 }
720
721 gboolean interface_is_up(int index)
722 {
723         int sk, err;
724         struct ifreq ifr;
725         gboolean ret = FALSE;
726
727         sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
728         if (sk < 0) {
729                 perror("Open socket error");
730                 return FALSE;
731         }
732
733         memset(&ifr, 0, sizeof(ifr));
734         ifr.ifr_ifindex = index;
735
736         err = ioctl(sk, SIOCGIFNAME, &ifr);
737         if (err < 0) {
738                 perror("Get interface name error");
739                 goto done;
740         }
741
742         err = ioctl(sk, SIOCGIFFLAGS, &ifr);
743         if (err < 0) {
744                 perror("Get interface flags error");
745                 goto done;
746         }
747
748         if (ifr.ifr_flags & IFF_UP)
749                 ret = TRUE;
750
751 done:
752         close(sk);
753
754         return ret;
755 }