3 * DHCP client library with GLib integration
5 * Copyright (C) 2009-2012 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
32 #include <sys/ioctl.h>
33 #include <arpa/inet.h>
35 #include <netpacket/packet.h>
36 #include <netinet/if_ether.h>
37 #include <net/ethernet.h>
40 #include <linux/filter.h>
48 #define DISCOVER_TIMEOUT 3
49 #define DISCOVER_RETRIES 10
51 #define REQUEST_TIMEOUT 3
52 #define REQUEST_RETRIES 5
54 typedef enum _listen_mode {
61 typedef enum _dhcp_client_state {
86 uint8_t mac_address[6];
89 uint32_t requested_ip;
92 uint32_t lease_seconds;
93 ListenMode listen_mode;
96 uint8_t ack_retry_times;
100 GIOChannel *listener_channel;
103 GHashTable *code_value_hash;
104 GHashTable *send_value_hash;
105 GDHCPClientEventFunc lease_available_cb;
106 gpointer lease_available_data;
107 GDHCPClientEventFunc ipv4ll_available_cb;
108 gpointer ipv4ll_available_data;
109 GDHCPClientEventFunc no_lease_cb;
110 gpointer no_lease_data;
111 GDHCPClientEventFunc lease_lost_cb;
112 gpointer lease_lost_data;
113 GDHCPClientEventFunc ipv4ll_lost_cb;
114 gpointer ipv4ll_lost_data;
115 GDHCPClientEventFunc address_conflict_cb;
116 gpointer address_conflict_data;
117 GDHCPDebugFunc debug_func;
119 GDHCPClientEventFunc information_req_cb;
120 gpointer information_req_data;
121 GDHCPClientEventFunc solicitation_cb;
122 gpointer solicitation_data;
123 GDHCPClientEventFunc advertise_cb;
124 gpointer advertise_data;
125 GDHCPClientEventFunc request_cb;
126 gpointer request_data;
127 GDHCPClientEventFunc renew_cb;
129 GDHCPClientEventFunc rebind_cb;
130 gpointer rebind_data;
131 GDHCPClientEventFunc release_cb;
132 gpointer release_data;
136 unsigned char *server_duid;
138 uint16_t status_code;
141 struct in6_addr ia_na;
142 struct in6_addr ia_ta;
149 static inline void debug(GDHCPClient *client, const char *format, ...)
154 if (client->debug_func == NULL)
157 va_start(ap, format);
159 if (vsnprintf(str, sizeof(str), format, ap) > 0)
160 client->debug_func(str, client->debug_data);
165 /* Initialize the packet with the proper defaults */
166 static void init_packet(GDHCPClient *dhcp_client, gpointer pkt, char type)
168 if (dhcp_client->type == G_DHCP_IPV6)
169 dhcpv6_init_header(pkt, type);
171 struct dhcp_packet *packet = pkt;
173 dhcp_init_header(packet, type);
174 memcpy(packet->chaddr, dhcp_client->mac_address, 6);
178 static void add_request_options(GDHCPClient *dhcp_client,
179 struct dhcp_packet *packet)
184 int end = dhcp_end_option(packet->options);
186 for (list = dhcp_client->request_list; list; list = list->next) {
187 code = (uint8_t) GPOINTER_TO_INT(list->data);
189 packet->options[end + OPT_DATA + len] = code;
194 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
195 packet->options[end + OPT_LEN] = len;
196 packet->options[end + OPT_DATA + len] = DHCP_END;
203 unsigned char **ptr_buf;
206 static void add_dhcpv6_binary_option(gpointer key, gpointer value,
209 uint8_t *option = value;
211 struct hash_params *params = user_data;
213 /* option[0][1] contains option code */
214 len = option[2] << 8 | option[3];
216 if ((*params->ptr_buf + len + 2 + 2) > (params->buf + params->max_buf))
219 memcpy(*params->ptr_buf, option, len + 2 + 2);
220 (*params->ptr_buf) += len + 2 + 2;
223 static void add_dhcpv6_send_options(GDHCPClient *dhcp_client,
224 unsigned char *buf, int max_buf,
225 unsigned char **ptr_buf)
227 struct hash_params params = {
233 if (dhcp_client->type == G_DHCP_IPV4)
236 g_hash_table_foreach(dhcp_client->send_value_hash,
237 add_dhcpv6_binary_option, ¶ms);
239 *ptr_buf = *params.ptr_buf;
242 static void copy_option(uint8_t *buf, uint16_t code, uint16_t len,
246 buf[1] = code & 0xff;
249 if (len > 0 && msg != NULL)
250 memcpy(&buf[4], msg, len);
253 static void add_dhcpv6_request_options(GDHCPClient *dhcp_client,
254 struct dhcpv6_packet *packet,
255 unsigned char *buf, int max_buf,
256 unsigned char **ptr_buf)
262 if (dhcp_client->type == G_DHCP_IPV4)
265 for (list = dhcp_client->request_list; list; list = list->next) {
266 code = (uint16_t) GPOINTER_TO_INT(list->data);
269 case G_DHCPV6_CLIENTID:
270 if (dhcp_client->duid == NULL)
273 len = 2 + 2 + dhcp_client->duid_len;
274 if ((*ptr_buf + len) > (buf + max_buf)) {
275 debug(dhcp_client, "Too long dhcpv6 message "
276 "when writing client id option");
280 copy_option(*ptr_buf, G_DHCPV6_CLIENTID,
281 dhcp_client->duid_len, dhcp_client->duid);
285 case G_DHCPV6_SERVERID:
286 if (dhcp_client->server_duid == NULL)
289 len = 2 + 2 + dhcp_client->server_duid_len;
290 if ((*ptr_buf + len) > (buf + max_buf)) {
291 debug(dhcp_client, "Too long dhcpv6 message "
292 "when writing server id option");
296 copy_option(*ptr_buf, G_DHCPV6_SERVERID,
297 dhcp_client->server_duid_len,
298 dhcp_client->server_duid);
302 case G_DHCPV6_RAPID_COMMIT:
304 if ((*ptr_buf + len) > (buf + max_buf)) {
305 debug(dhcp_client, "Too long dhcpv6 message "
306 "when writing rapid commit option");
310 copy_option(*ptr_buf, G_DHCPV6_RAPID_COMMIT, 0, 0);
317 case G_DHCPV6_DNS_SERVERS:
320 case G_DHCPV6_SNTP_SERVERS:
329 static void add_binary_option(gpointer key, gpointer value, gpointer user_data)
331 uint8_t *option = value;
332 struct dhcp_packet *packet = user_data;
334 dhcp_add_binary_option(packet, option);
337 static void add_send_options(GDHCPClient *dhcp_client,
338 struct dhcp_packet *packet)
340 g_hash_table_foreach(dhcp_client->send_value_hash,
341 add_binary_option, packet);
345 * Return an RFC 951- and 2131-complaint BOOTP 'secs' value that
346 * represents the number of seconds elapsed from the start of
347 * attempting DHCP to satisfy some DHCP servers that allow for an
348 * "authoritative" reply before responding.
350 static uint16_t dhcp_attempt_secs(GDHCPClient *dhcp_client)
352 return htons(MIN(time(NULL) - dhcp_client->start, UINT16_MAX));
355 static int send_discover(GDHCPClient *dhcp_client, uint32_t requested)
357 struct dhcp_packet packet;
359 debug(dhcp_client, "sending DHCP discover request");
361 init_packet(dhcp_client, &packet, DHCPDISCOVER);
363 packet.xid = dhcp_client->xid;
364 packet.secs = dhcp_attempt_secs(dhcp_client);
367 dhcp_add_option_uint32(&packet, DHCP_REQUESTED_IP, requested);
369 /* Explicitly saying that we want RFC-compliant packets helps
370 * some buggy DHCP servers to NOT send bigger packets */
371 dhcp_add_option_uint16(&packet, DHCP_MAX_SIZE, 576);
373 add_request_options(dhcp_client, &packet);
375 add_send_options(dhcp_client, &packet);
377 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
378 INADDR_BROADCAST, SERVER_PORT,
379 MAC_BCAST_ADDR, dhcp_client->ifindex);
382 static int send_select(GDHCPClient *dhcp_client)
384 struct dhcp_packet packet;
386 debug(dhcp_client, "sending DHCP select request");
388 init_packet(dhcp_client, &packet, DHCPREQUEST);
390 packet.xid = dhcp_client->xid;
391 packet.secs = dhcp_attempt_secs(dhcp_client);
393 dhcp_add_option_uint32(&packet, DHCP_REQUESTED_IP,
394 dhcp_client->requested_ip);
395 dhcp_add_option_uint32(&packet, DHCP_SERVER_ID,
396 dhcp_client->server_ip);
398 add_request_options(dhcp_client, &packet);
400 add_send_options(dhcp_client, &packet);
402 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
403 INADDR_BROADCAST, SERVER_PORT,
404 MAC_BCAST_ADDR, dhcp_client->ifindex);
407 static int send_renew(GDHCPClient *dhcp_client)
409 struct dhcp_packet packet;
411 debug(dhcp_client, "sending DHCP renew request");
413 init_packet(dhcp_client , &packet, DHCPREQUEST);
414 packet.xid = dhcp_client->xid;
415 packet.ciaddr = htonl(dhcp_client->requested_ip);
417 add_request_options(dhcp_client, &packet);
419 add_send_options(dhcp_client, &packet);
421 return dhcp_send_kernel_packet(&packet,
422 dhcp_client->requested_ip, CLIENT_PORT,
423 dhcp_client->server_ip, SERVER_PORT);
426 static int send_rebound(GDHCPClient *dhcp_client)
428 struct dhcp_packet packet;
430 debug(dhcp_client, "sending DHCP rebound request");
432 init_packet(dhcp_client , &packet, DHCPREQUEST);
433 packet.xid = dhcp_client->xid;
434 packet.ciaddr = htonl(dhcp_client->requested_ip);
436 add_request_options(dhcp_client, &packet);
438 add_send_options(dhcp_client, &packet);
440 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
441 INADDR_BROADCAST, SERVER_PORT,
442 MAC_BCAST_ADDR, dhcp_client->ifindex);
445 static int send_release(GDHCPClient *dhcp_client,
446 uint32_t server, uint32_t ciaddr)
448 struct dhcp_packet packet;
450 debug(dhcp_client, "sending DHCP release request");
452 init_packet(dhcp_client, &packet, DHCPRELEASE);
454 packet.ciaddr = htonl(ciaddr);
456 dhcp_add_option_uint32(&packet, DHCP_SERVER_ID, server);
458 return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
459 server, SERVER_PORT);
462 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data);
463 static int switch_listening_mode(GDHCPClient *dhcp_client,
464 ListenMode listen_mode);
466 static gboolean send_probe_packet(gpointer dhcp_data)
468 GDHCPClient *dhcp_client;
471 dhcp_client = dhcp_data;
472 /* if requested_ip is not valid, pick a new address*/
473 if (dhcp_client->requested_ip == 0) {
474 debug(dhcp_client, "pick a new random address");
475 dhcp_client->requested_ip = ipv4ll_random_ip(0);
478 debug(dhcp_client, "sending IPV4LL probe request");
480 if (dhcp_client->retry_times == 1) {
481 dhcp_client->state = IPV4LL_PROBE;
482 switch_listening_mode(dhcp_client, L_ARP);
484 ipv4ll_send_arp_packet(dhcp_client->mac_address, 0,
485 dhcp_client->requested_ip, dhcp_client->ifindex);
487 if (dhcp_client->retry_times < PROBE_NUM) {
488 /*add a random timeout in range of PROBE_MIN to PROBE_MAX*/
489 timeout = ipv4ll_random_delay_ms(PROBE_MAX-PROBE_MIN);
490 timeout += PROBE_MIN*1000;
492 timeout = (ANNOUNCE_WAIT * 1000);
494 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
496 ipv4ll_probe_timeout,
502 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data);
503 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data);
505 static gboolean send_announce_packet(gpointer dhcp_data)
507 GDHCPClient *dhcp_client;
509 dhcp_client = dhcp_data;
511 debug(dhcp_client, "sending IPV4LL announce request");
513 ipv4ll_send_arp_packet(dhcp_client->mac_address,
514 dhcp_client->requested_ip,
515 dhcp_client->requested_ip,
516 dhcp_client->ifindex);
518 if (dhcp_client->timeout > 0)
519 g_source_remove(dhcp_client->timeout);
520 dhcp_client->timeout = 0;
522 if (dhcp_client->state == IPV4LL_DEFEND) {
523 dhcp_client->timeout =
524 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
526 ipv4ll_defend_timeout,
531 dhcp_client->timeout =
532 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
534 ipv4ll_announce_timeout,
540 static void get_interface_mac_address(int index, uint8_t *mac_address)
545 sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
547 perror("Open socket error");
551 memset(&ifr, 0, sizeof(ifr));
552 ifr.ifr_ifindex = index;
554 err = ioctl(sk, SIOCGIFNAME, &ifr);
556 perror("Get interface name error");
560 err = ioctl(sk, SIOCGIFHWADDR, &ifr);
562 perror("Get mac address error");
566 memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
572 void g_dhcpv6_client_set_retransmit(GDHCPClient *dhcp_client)
574 if (dhcp_client == NULL)
577 dhcp_client->retransmit = TRUE;
580 void g_dhcpv6_client_clear_retransmit(GDHCPClient *dhcp_client)
582 if (dhcp_client == NULL)
585 dhcp_client->retransmit = FALSE;
588 int g_dhcpv6_create_duid(GDHCPDuidType duid_type, int index, int type,
589 unsigned char **duid, int *duid_len)
594 case G_DHCPV6_DUID_LLT:
595 *duid_len = 2 + 2 + 4 + ETH_ALEN;
596 *duid = g_try_malloc(*duid_len);
602 get_interface_mac_address(index, &(*duid)[2 + 2 + 4]);
605 duid_time = time(NULL) - DUID_TIME_EPOCH;
606 (*duid)[4] = duid_time >> 24;
607 (*duid)[5] = duid_time >> 16;
608 (*duid)[6] = duid_time >> 8;
609 (*duid)[7] = duid_time & 0xff;
611 case G_DHCPV6_DUID_EN:
613 case G_DHCPV6_DUID_LL:
614 *duid_len = 2 + 2 + ETH_ALEN;
615 *duid = g_try_malloc(*duid_len);
621 get_interface_mac_address(index, &(*duid)[2 + 2]);
630 int g_dhcpv6_client_set_duid(GDHCPClient *dhcp_client, unsigned char *duid,
633 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
636 g_free(dhcp_client->duid);
638 dhcp_client->duid = duid;
639 dhcp_client->duid_len = duid_len;
644 uint32_t g_dhcpv6_client_get_iaid(GDHCPClient *dhcp_client)
646 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
649 return dhcp_client->iaid;
652 void g_dhcpv6_client_create_iaid(GDHCPClient *dhcp_client, int index,
657 get_interface_mac_address(index, buf);
659 memcpy(iaid, &buf[2], 4);
660 dhcp_client->iaid = iaid[0] << 24 |
661 iaid[1] << 16 | iaid[2] << 8 | iaid[3];
664 int g_dhcpv6_client_get_timeouts(GDHCPClient *dhcp_client,
665 uint32_t *T1, uint32_t *T2,
666 time_t *last_renew, time_t *last_rebind,
669 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
673 *T1 = dhcp_client->T1;
676 *T2 = dhcp_client->T2;
678 if (last_renew != NULL)
679 *last_renew = dhcp_client->last_renew;
681 if (last_rebind != NULL)
682 *last_rebind = dhcp_client->last_rebind;
685 *expire = dhcp_client->expire;
690 static uint8_t *create_iaaddr(GDHCPClient *dhcp_client, uint8_t *buf,
694 buf[1] = G_DHCPV6_IAADDR;
697 memcpy(&buf[4], &dhcp_client->ia_na, 16);
698 memset(&buf[20], 0, 4); /* preferred */
699 memset(&buf[24], 0, 4); /* valid */
703 static void put_iaid(GDHCPClient *dhcp_client, int index, uint8_t *buf)
707 iaid = g_dhcpv6_client_get_iaid(dhcp_client);
709 g_dhcpv6_client_create_iaid(dhcp_client, index, buf);
719 int g_dhcpv6_client_set_ia(GDHCPClient *dhcp_client, int index,
720 int code, uint32_t *T1, uint32_t *T2,
723 if (code == G_DHCPV6_IA_TA) {
724 uint8_t ia_options[4];
726 put_iaid(dhcp_client, index, ia_options);
728 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_TA);
729 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_TA,
730 ia_options, sizeof(ia_options));
732 } else if (code == G_DHCPV6_IA_NA) {
734 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_NA);
736 if (add_iaaddr == TRUE) {
737 #define IAADDR_LEN (16+4+4)
738 uint8_t ia_options[4+4+4+2+2+IAADDR_LEN];
740 put_iaid(dhcp_client, index, ia_options);
743 ia_options[4] = *T1 >> 24;
744 ia_options[5] = *T1 >> 16;
745 ia_options[6] = *T1 >> 8;
748 memset(&ia_options[4], 0x00, 4);
751 ia_options[8] = *T2 >> 24;
752 ia_options[9] = *T2 >> 16;
753 ia_options[10] = *T2 >> 8;
754 ia_options[11] = *T2;
756 memset(&ia_options[8], 0x00, 4);
758 create_iaaddr(dhcp_client, &ia_options[12],
761 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
762 ia_options, sizeof(ia_options));
764 uint8_t ia_options[4+4+4];
766 put_iaid(dhcp_client, index, ia_options);
768 memset(&ia_options[4], 0x00, 4); /* T1 (4 bytes) */
769 memset(&ia_options[8], 0x00, 4); /* T2 (4 bytes) */
771 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
772 ia_options, sizeof(ia_options));
781 int g_dhcpv6_client_set_oro(GDHCPClient *dhcp_client, int args, ...)
784 int i, j, len = sizeof(uint16_t) * args;
787 values = g_try_malloc(len);
792 for (i = 0, j = 0; i < args; i++) {
793 uint16_t value = va_arg(va, int);
794 values[j++] = value >> 8;
795 values[j++] = value & 0xff;
799 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_ORO, values, len);
806 static int send_dhcpv6_msg(GDHCPClient *dhcp_client, int type, char *msg)
808 struct dhcpv6_packet *packet;
809 uint8_t buf[MAX_DHCPV6_PKT_SIZE];
813 memset(buf, 0, sizeof(buf));
814 packet = (struct dhcpv6_packet *)&buf[0];
815 ptr = buf + sizeof(struct dhcpv6_packet);
817 init_packet(dhcp_client, packet, type);
819 dhcp_client->xid = packet->transaction_id[0] << 16 |
820 packet->transaction_id[1] << 8 |
821 packet->transaction_id[2];
823 debug(dhcp_client, "sending DHCPv6 %s message xid 0x%04x", msg,
826 max_buf = MAX_DHCPV6_PKT_SIZE - sizeof(struct dhcpv6_packet);
828 add_dhcpv6_request_options(dhcp_client, packet, buf, max_buf, &ptr);
830 add_dhcpv6_send_options(dhcp_client, buf, max_buf, &ptr);
832 ret = dhcpv6_send_packet(dhcp_client->ifindex, packet, ptr - buf);
834 debug(dhcp_client, "sent %d pkt %p len %d", ret, packet, ptr - buf);
838 static int send_solicitation(GDHCPClient *dhcp_client)
840 return send_dhcpv6_msg(dhcp_client, DHCPV6_SOLICIT, "solicit");
843 static int send_dhcpv6_request(GDHCPClient *dhcp_client)
845 return send_dhcpv6_msg(dhcp_client, DHCPV6_REQUEST, "request");
848 static int send_dhcpv6_renew(GDHCPClient *dhcp_client)
850 return send_dhcpv6_msg(dhcp_client, DHCPV6_RENEW, "renew");
853 static int send_dhcpv6_rebind(GDHCPClient *dhcp_client)
855 return send_dhcpv6_msg(dhcp_client, DHCPV6_REBIND, "rebind");
858 static int send_dhcpv6_release(GDHCPClient *dhcp_client)
860 return send_dhcpv6_msg(dhcp_client, DHCPV6_RELEASE, "release");
863 static int send_information_req(GDHCPClient *dhcp_client)
865 return send_dhcpv6_msg(dhcp_client, DHCPV6_INFORMATION_REQ,
869 static void remove_value(gpointer data, gpointer user_data)
875 static void remove_option_value(gpointer data)
877 GList *option_value = data;
879 g_list_foreach(option_value, remove_value, NULL);
882 GDHCPClient *g_dhcp_client_new(GDHCPType type,
883 int ifindex, GDHCPClientError *error)
885 GDHCPClient *dhcp_client;
888 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
892 dhcp_client = g_try_new0(GDHCPClient, 1);
893 if (dhcp_client == NULL) {
894 *error = G_DHCP_CLIENT_ERROR_NOMEM;
898 dhcp_client->interface = get_interface_name(ifindex);
899 if (dhcp_client->interface == NULL) {
900 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
904 if (interface_is_up(ifindex) == FALSE) {
905 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
909 get_interface_mac_address(ifindex, dhcp_client->mac_address);
911 dhcp_client->listener_sockfd = -1;
912 dhcp_client->listener_channel = NULL;
913 dhcp_client->listen_mode = L_NONE;
914 dhcp_client->ref_count = 1;
915 dhcp_client->type = type;
916 dhcp_client->ifindex = ifindex;
917 dhcp_client->lease_available_cb = NULL;
918 dhcp_client->ipv4ll_available_cb = NULL;
919 dhcp_client->no_lease_cb = NULL;
920 dhcp_client->lease_lost_cb = NULL;
921 dhcp_client->ipv4ll_lost_cb = NULL;
922 dhcp_client->address_conflict_cb = NULL;
923 dhcp_client->listener_watch = 0;
924 dhcp_client->retry_times = 0;
925 dhcp_client->ack_retry_times = 0;
926 dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
927 g_direct_equal, NULL, remove_option_value);
928 dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
929 g_direct_equal, NULL, g_free);
930 dhcp_client->request_list = NULL;
931 dhcp_client->require_list = NULL;
932 dhcp_client->duid = NULL;
933 dhcp_client->duid_len = 0;
934 dhcp_client->last_renew = dhcp_client->last_rebind = time(NULL);
935 dhcp_client->expire = 0;
937 *error = G_DHCP_CLIENT_ERROR_NONE;
942 g_free(dhcp_client->interface);
947 #define SERVER_AND_CLIENT_PORTS ((67 << 16) + 68)
949 static int dhcp_l2_socket(int ifindex)
952 struct sockaddr_ll sock;
957 * I've selected not to see LL header, so BPF doesn't see it, too.
958 * The filter may also pass non-IP and non-ARP packets, but we do
959 * a more complete check when receiving the message in userspace.
961 * and filter shamelessly stolen from:
963 * http://www.flamewarmaster.de/software/dhcpclient/
965 * There are a few other interesting ideas on that page (look under
966 * "Motivation"). Use of netlink events is most interesting. Think
967 * of various network servers listening for events and reconfiguring.
968 * That would obsolete sending HUP signals and/or make use of restarts.
970 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
973 * TODO: make conditional?
975 static const struct sock_filter filter_instr[] = {
977 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
978 /* L5, L1, is UDP? */
979 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
980 /* ugly check for arp on ethernet-like and IPv4 */
981 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
982 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
984 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
985 /* check udp source and destination ports */
986 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
988 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
990 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
991 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
994 static const struct sock_fprog filter_prog = {
995 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
996 /* casting const away: */
997 .filter = (struct sock_filter *) filter_instr,
1000 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IP));
1004 if (SERVER_PORT == 67 && CLIENT_PORT == 68)
1005 /* Use only if standard ports are in use */
1006 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
1007 sizeof(filter_prog));
1009 memset(&sock, 0, sizeof(sock));
1010 sock.sll_family = AF_PACKET;
1011 sock.sll_protocol = htons(ETH_P_IP);
1012 sock.sll_ifindex = ifindex;
1014 if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
1022 static gboolean sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
1024 if (packet->ip.protocol != IPPROTO_UDP)
1027 if (packet->ip.version != IPVERSION)
1030 if (packet->ip.ihl != sizeof(packet->ip) >> 2)
1033 if (packet->udp.dest != htons(CLIENT_PORT))
1036 if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
1042 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd)
1045 struct ip_udp_dhcp_packet packet;
1048 memset(&packet, 0, sizeof(packet));
1050 bytes = read(fd, &packet, sizeof(packet));
1054 if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
1057 if (bytes < ntohs(packet.ip.tot_len))
1058 /* packet is bigger than sizeof(packet), we did partial read */
1061 /* ignore any extra garbage bytes */
1062 bytes = ntohs(packet.ip.tot_len);
1064 if (sanity_check(&packet, bytes) == FALSE)
1067 check = packet.ip.check;
1068 packet.ip.check = 0;
1069 if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
1072 /* verify UDP checksum. IP header has to be modified for this */
1073 memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
1074 /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
1075 packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
1076 check = packet.udp.check;
1077 packet.udp.check = 0;
1078 if (check && check != dhcp_checksum(&packet, bytes))
1081 memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
1082 sizeof(packet.udp)));
1084 if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
1087 return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
1090 static void ipv4ll_start(GDHCPClient *dhcp_client)
1095 if (dhcp_client->timeout > 0) {
1096 g_source_remove(dhcp_client->timeout);
1097 dhcp_client->timeout = 0;
1100 switch_listening_mode(dhcp_client, L_NONE);
1101 dhcp_client->type = G_DHCP_IPV4LL;
1102 dhcp_client->retry_times = 0;
1103 dhcp_client->requested_ip = 0;
1105 /*try to start with a based mac address ip*/
1106 seed = (dhcp_client->mac_address[4] << 8 | dhcp_client->mac_address[4]);
1107 dhcp_client->requested_ip = ipv4ll_random_ip(seed);
1109 /*first wait a random delay to avoid storm of arp request on boot*/
1110 timeout = ipv4ll_random_delay_ms(PROBE_WAIT);
1112 dhcp_client->retry_times++;
1113 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
1120 static void ipv4ll_stop(GDHCPClient *dhcp_client)
1123 switch_listening_mode(dhcp_client, L_NONE);
1125 if (dhcp_client->timeout > 0)
1126 g_source_remove(dhcp_client->timeout);
1128 if (dhcp_client->listener_watch > 0) {
1129 g_source_remove(dhcp_client->listener_watch);
1130 dhcp_client->listener_watch = 0;
1133 dhcp_client->state = IPV4LL_PROBE;
1134 dhcp_client->retry_times = 0;
1135 dhcp_client->requested_ip = 0;
1137 g_free(dhcp_client->assigned_ip);
1138 dhcp_client->assigned_ip = NULL;
1141 static int ipv4ll_recv_arp_packet(GDHCPClient *dhcp_client)
1144 struct ether_arp arp;
1145 uint32_t ip_requested;
1146 int source_conflict;
1147 int target_conflict;
1149 memset(&arp, 0, sizeof(arp));
1150 bytes = read(dhcp_client->listener_sockfd, &arp, sizeof(arp));
1154 if (arp.arp_op != htons(ARPOP_REPLY) &&
1155 arp.arp_op != htons(ARPOP_REQUEST))
1158 ip_requested = htonl(dhcp_client->requested_ip);
1159 source_conflict = !memcmp(arp.arp_spa, &ip_requested,
1160 sizeof(ip_requested));
1162 target_conflict = !memcmp(arp.arp_tpa, &ip_requested,
1163 sizeof(ip_requested));
1165 if (!source_conflict && !target_conflict)
1168 dhcp_client->conflicts++;
1170 debug(dhcp_client, "IPV4LL conflict detected");
1172 if (dhcp_client->state == IPV4LL_MONITOR) {
1173 if (!source_conflict)
1175 dhcp_client->state = IPV4LL_DEFEND;
1176 debug(dhcp_client, "DEFEND mode conflicts : %d",
1177 dhcp_client->conflicts);
1178 /*Try to defend with a single announce*/
1179 send_announce_packet(dhcp_client);
1183 if (dhcp_client->state == IPV4LL_DEFEND) {
1184 if (!source_conflict)
1186 else if (dhcp_client->ipv4ll_lost_cb != NULL)
1187 dhcp_client->ipv4ll_lost_cb(dhcp_client,
1188 dhcp_client->ipv4ll_lost_data);
1191 ipv4ll_stop(dhcp_client);
1193 if (dhcp_client->conflicts < MAX_CONFLICTS) {
1194 /*restart whole state machine*/
1195 dhcp_client->retry_times++;
1196 dhcp_client->timeout =
1197 g_timeout_add_full(G_PRIORITY_HIGH,
1198 ipv4ll_random_delay_ms(PROBE_WAIT),
1203 /* Here we got a lot of conflicts, RFC3927 states that we have
1204 * to wait RATE_LIMIT_INTERVAL before retrying,
1205 * but we just report failure.
1207 else if (dhcp_client->no_lease_cb != NULL)
1208 dhcp_client->no_lease_cb(dhcp_client,
1209 dhcp_client->no_lease_data);
1214 static gboolean check_package_owner(GDHCPClient *dhcp_client, gpointer pkt)
1216 if (dhcp_client->type == G_DHCP_IPV6) {
1217 struct dhcpv6_packet *packet6 = pkt;
1220 if (packet6 == NULL)
1223 xid = packet6->transaction_id[0] << 16 |
1224 packet6->transaction_id[1] << 8 |
1225 packet6->transaction_id[2];
1227 if (xid != dhcp_client->xid)
1230 struct dhcp_packet *packet = pkt;
1232 if (packet->xid != dhcp_client->xid)
1235 if (packet->hlen != 6)
1238 if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
1245 static void start_request(GDHCPClient *dhcp_client);
1247 static gboolean request_timeout(gpointer user_data)
1249 GDHCPClient *dhcp_client = user_data;
1251 debug(dhcp_client, "request timeout (retries %d)",
1252 dhcp_client->retry_times);
1254 dhcp_client->retry_times++;
1256 start_request(dhcp_client);
1261 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1262 gpointer user_data);
1264 static int switch_listening_mode(GDHCPClient *dhcp_client,
1265 ListenMode listen_mode)
1267 GIOChannel *listener_channel;
1268 int listener_sockfd;
1270 if (dhcp_client->listen_mode == listen_mode)
1273 debug(dhcp_client, "switch listening mode (%d ==> %d)",
1274 dhcp_client->listen_mode, listen_mode);
1276 if (dhcp_client->listen_mode != L_NONE) {
1277 if (dhcp_client->listener_watch > 0)
1278 g_source_remove(dhcp_client->listener_watch);
1279 dhcp_client->listener_channel = NULL;
1280 dhcp_client->listen_mode = L_NONE;
1281 dhcp_client->listener_sockfd = -1;
1282 dhcp_client->listener_watch = 0;
1285 if (listen_mode == L_NONE)
1288 if (listen_mode == L2)
1289 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
1290 else if (listen_mode == L3) {
1291 if (dhcp_client->type == G_DHCP_IPV6)
1292 listener_sockfd = dhcp_l3_socket(DHCPV6_CLIENT_PORT,
1293 dhcp_client->interface,
1296 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
1297 dhcp_client->interface,
1299 } else if (listen_mode == L_ARP)
1300 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
1304 if (listener_sockfd < 0)
1307 listener_channel = g_io_channel_unix_new(listener_sockfd);
1308 if (listener_channel == NULL) {
1309 /* Failed to create listener channel */
1310 close(listener_sockfd);
1314 dhcp_client->listen_mode = listen_mode;
1315 dhcp_client->listener_sockfd = listener_sockfd;
1316 dhcp_client->listener_channel = listener_channel;
1318 g_io_channel_set_close_on_unref(listener_channel, TRUE);
1319 dhcp_client->listener_watch =
1320 g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
1321 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1322 listener_event, dhcp_client,
1324 g_io_channel_unref(dhcp_client->listener_channel);
1329 static void start_request(GDHCPClient *dhcp_client)
1331 debug(dhcp_client, "start request (retries %d)",
1332 dhcp_client->retry_times);
1334 if (dhcp_client->retry_times == REQUEST_RETRIES) {
1335 dhcp_client->state = INIT_SELECTING;
1336 ipv4ll_start(dhcp_client);
1341 if (dhcp_client->retry_times == 0) {
1342 dhcp_client->state = REQUESTING;
1343 switch_listening_mode(dhcp_client, L2);
1346 send_select(dhcp_client);
1348 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1355 static uint32_t get_lease(struct dhcp_packet *packet)
1358 uint32_t lease_seconds;
1360 option = dhcp_get_option(packet, DHCP_LEASE_TIME);
1364 lease_seconds = get_be32(option);
1365 /* paranoia: must not be prone to overflows */
1366 lease_seconds &= 0x0fffffff;
1367 if (lease_seconds < 10)
1370 return lease_seconds;
1373 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
1375 debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
1377 if (dhcp_client->timeout > 0) {
1378 g_source_remove(dhcp_client->timeout);
1379 dhcp_client->timeout = 0;
1382 dhcp_client->retry_times = retry_times;
1383 dhcp_client->requested_ip = 0;
1384 dhcp_client->state = INIT_SELECTING;
1385 switch_listening_mode(dhcp_client, L2);
1387 g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
1390 static gboolean start_rebound_timeout(gpointer user_data)
1392 GDHCPClient *dhcp_client = user_data;
1394 debug(dhcp_client, "start rebound timeout");
1396 switch_listening_mode(dhcp_client, L2);
1398 dhcp_client->lease_seconds >>= 1;
1400 /* We need to have enough time to receive ACK package*/
1401 if (dhcp_client->lease_seconds <= 6) {
1403 /* ip need to be cleared */
1404 if (dhcp_client->lease_lost_cb != NULL)
1405 dhcp_client->lease_lost_cb(dhcp_client,
1406 dhcp_client->lease_lost_data);
1408 restart_dhcp(dhcp_client, 0);
1410 send_rebound(dhcp_client);
1412 dhcp_client->timeout =
1413 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1414 dhcp_client->lease_seconds >> 1,
1415 start_rebound_timeout,
1423 static void start_rebound(GDHCPClient *dhcp_client)
1425 debug(dhcp_client, "start rebound");
1427 dhcp_client->state = REBINDING;
1429 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1430 dhcp_client->lease_seconds >> 1,
1431 start_rebound_timeout,
1436 static gboolean start_renew_timeout(gpointer user_data)
1438 GDHCPClient *dhcp_client = user_data;
1440 debug(dhcp_client, "start renew timeout");
1442 dhcp_client->state = RENEWING;
1444 dhcp_client->lease_seconds >>= 1;
1446 switch_listening_mode(dhcp_client, L3);
1447 if (dhcp_client->lease_seconds <= 60)
1448 start_rebound(dhcp_client);
1450 send_renew(dhcp_client);
1452 if (dhcp_client->timeout > 0)
1453 g_source_remove(dhcp_client->timeout);
1455 dhcp_client->timeout =
1456 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1457 dhcp_client->lease_seconds >> 1,
1458 start_renew_timeout,
1466 static void start_bound(GDHCPClient *dhcp_client)
1468 debug(dhcp_client, "start bound");
1470 dhcp_client->state = BOUND;
1472 if (dhcp_client->timeout > 0)
1473 g_source_remove(dhcp_client->timeout);
1475 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1476 dhcp_client->lease_seconds >> 1,
1477 start_renew_timeout, dhcp_client,
1481 static gboolean restart_dhcp_timeout(gpointer user_data)
1483 GDHCPClient *dhcp_client = user_data;
1485 debug(dhcp_client, "restart DHCP timeout");
1487 dhcp_client->ack_retry_times++;
1489 restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
1494 static char *get_ip(uint32_t ip)
1496 struct in_addr addr;
1500 return g_strdup(inet_ntoa(addr));
1503 /* get a rough idea of how long an option will be */
1504 static const uint8_t len_of_option_as_string[] = {
1505 [OPTION_IP] = sizeof("255.255.255.255 "),
1506 [OPTION_STRING] = 1,
1507 [OPTION_U8] = sizeof("255 "),
1508 [OPTION_U16] = sizeof("65535 "),
1509 [OPTION_U32] = sizeof("4294967295 "),
1512 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
1514 return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
1517 /* Create "opt_value1 option_value2 ..." string */
1518 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
1520 unsigned upper_length;
1524 len = option[OPT_LEN - OPT_DATA];
1525 type &= OPTION_TYPE_MASK;
1526 optlen = dhcp_option_lengths[type];
1529 upper_length = len_of_option_as_string[type] *
1530 ((unsigned)len / (unsigned)optlen);
1531 dest = ret = g_malloc(upper_length + 1);
1535 while (len >= optlen) {
1538 dest += sprint_nip(dest, "", option);
1541 uint16_t val_u16 = get_be16(option);
1542 dest += sprintf(dest, "%u", val_u16);
1546 uint32_t val_u32 = get_be32(option);
1547 dest += sprintf(dest, "%u", val_u32);
1551 memcpy(dest, option, len);
1568 static GList *get_option_value_list(char *value, GDHCPOptionType type)
1576 if (type == OPTION_STRING)
1577 return g_list_append(list, g_strdup(value));
1579 while ((pos = strchr(pos, ' ')) != NULL) {
1582 list = g_list_append(list, g_strdup(value));
1587 list = g_list_append(list, g_strdup(value));
1592 static inline uint32_t get_uint32(unsigned char *value)
1594 return value[0] << 24 | value[1] << 16 |
1595 value[2] << 8 | value[3];
1598 static inline uint16_t get_uint16(unsigned char *value)
1600 return value[0] << 8 | value[1];
1603 static GList *get_addresses(GDHCPClient *dhcp_client,
1605 unsigned char *value,
1609 struct in6_addr addr;
1610 uint32_t iaid, T1 = 0, T2 = 0, preferred = 0, valid = 0;
1611 uint16_t option_len, option_code, st = 0, max_len;
1612 int addr_count = 0, i, pos;
1616 if (value == NULL || len < 4)
1619 iaid = get_uint32(&value[0]);
1620 if (dhcp_client->iaid != iaid)
1623 if (code == G_DHCPV6_IA_NA) {
1624 T1 = get_uint32(&value[4]);
1625 T2 = get_uint32(&value[8]);
1628 /* RFC 3315, 22.4 */
1638 max_len = len - pos;
1640 /* We have more sub-options in this packet. */
1642 option = dhcpv6_get_sub_option(&value[pos], max_len,
1643 &option_code, &option_len);
1645 debug(dhcp_client, "pos %d option %p code %d len %d",
1646 pos, option, option_code, option_len);
1654 switch (option_code) {
1655 case G_DHCPV6_IAADDR:
1657 memcpy(&addr, &option[0], sizeof(addr));
1659 preferred = get_uint32(&option[i]);
1661 valid = get_uint32(&option[i]);
1666 case G_DHCPV6_STATUS_CODE:
1667 st = get_uint16(&option[0]);
1668 debug(dhcp_client, "error code %d", st);
1669 if (option_len > 2) {
1670 str = g_strndup((gchar *)&option[2],
1672 debug(dhcp_client, "error text: %s", str);
1680 pos += 2 + 2 + option_len;
1682 } while (option != NULL);
1684 if (addr_count > 0 && st == 0) {
1685 /* We only support one address atm */
1686 char addr_str[INET6_ADDRSTRLEN + 1];
1688 if (preferred > valid)
1689 /* RFC 3315, 22.6 */
1692 dhcp_client->T1 = T1;
1693 dhcp_client->T2 = T2;
1695 inet_ntop(AF_INET6, &addr, addr_str, INET6_ADDRSTRLEN);
1696 debug(dhcp_client, "count %d addr %s T1 %u T2 %u",
1697 addr_count, addr_str, T1, T2);
1699 list = g_list_append(list, g_strdup(addr_str));
1701 if (code == G_DHCPV6_IA_NA)
1702 memcpy(&dhcp_client->ia_na, &addr,
1703 sizeof(struct in6_addr));
1705 memcpy(&dhcp_client->ia_ta, &addr,
1706 sizeof(struct in6_addr));
1708 g_dhcpv6_client_set_expire(dhcp_client, valid);
1714 static GList *get_dhcpv6_option_value_list(GDHCPClient *dhcp_client,
1716 unsigned char *value,
1727 case G_DHCPV6_DNS_SERVERS: /* RFC 3646, chapter 3 */
1728 case G_DHCPV6_SNTP_SERVERS: /* RFC 4075, chapter 4 */
1731 "%s server list length (%d) is invalid",
1732 code == G_DHCPV6_DNS_SERVERS ? "DNS" : "SNTP",
1736 for (i = 0; i < len; i += 16) {
1738 str = g_try_malloc0(INET6_ADDRSTRLEN+1);
1742 if (inet_ntop(AF_INET6, &value[i], str,
1743 INET6_ADDRSTRLEN) == NULL)
1746 list = g_list_append(list, str);
1750 case G_DHCPV6_IA_NA: /* RFC 3315, chapter 22.4 */
1751 case G_DHCPV6_IA_TA: /* RFC 3315, chapter 22.5 */
1752 list = get_addresses(dhcp_client, code, len, value, status);
1762 static void get_dhcpv6_request(GDHCPClient *dhcp_client,
1763 struct dhcpv6_packet *packet,
1764 uint16_t pkt_len, uint16_t *status)
1766 GList *list, *value_list;
1769 uint16_t option_len;
1771 for (list = dhcp_client->request_list; list; list = list->next) {
1772 code = (uint16_t) GPOINTER_TO_INT(list->data);
1774 option = dhcpv6_get_option(packet, pkt_len, code, &option_len,
1776 if (option == NULL) {
1777 g_hash_table_remove(dhcp_client->code_value_hash,
1778 GINT_TO_POINTER((int) code));
1782 value_list = get_dhcpv6_option_value_list(dhcp_client, code,
1783 option_len, option, status);
1785 debug(dhcp_client, "code %d %p len %d list %p", code, option,
1786 option_len, value_list);
1788 if (value_list == NULL)
1789 g_hash_table_remove(dhcp_client->code_value_hash,
1790 GINT_TO_POINTER((int) code));
1792 g_hash_table_insert(dhcp_client->code_value_hash,
1793 GINT_TO_POINTER((int) code), value_list);
1797 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
1799 GDHCPOptionType type;
1800 GList *list, *value_list;
1805 for (list = dhcp_client->request_list; list; list = list->next) {
1806 code = (uint8_t) GPOINTER_TO_INT(list->data);
1808 option = dhcp_get_option(packet, code);
1809 if (option == NULL) {
1810 g_hash_table_remove(dhcp_client->code_value_hash,
1811 GINT_TO_POINTER((int) code));
1815 type = dhcp_get_code_type(code);
1817 option_value = malloc_option_value_string(option, type);
1818 if (option_value == NULL)
1819 g_hash_table_remove(dhcp_client->code_value_hash,
1820 GINT_TO_POINTER((int) code));
1822 value_list = get_option_value_list(option_value, type);
1824 g_free(option_value);
1826 if (value_list == NULL)
1827 g_hash_table_remove(dhcp_client->code_value_hash,
1828 GINT_TO_POINTER((int) code));
1830 g_hash_table_insert(dhcp_client->code_value_hash,
1831 GINT_TO_POINTER((int) code), value_list);
1835 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1838 GDHCPClient *dhcp_client = user_data;
1839 struct dhcp_packet packet;
1840 struct dhcpv6_packet *packet6 = NULL;
1841 uint8_t *message_type = NULL, *client_id = NULL, *option,
1843 uint16_t option_len = 0, status = 0;
1846 unsigned char buf[MAX_DHCPV6_PKT_SIZE];
1847 uint16_t pkt_len = 0;
1851 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1852 dhcp_client->listener_watch = 0;
1856 if (dhcp_client->listen_mode == L_NONE)
1861 if (dhcp_client->listen_mode == L2)
1862 re = dhcp_recv_l2_packet(&packet,
1863 dhcp_client->listener_sockfd);
1864 else if (dhcp_client->listen_mode == L3) {
1865 if (dhcp_client->type == G_DHCP_IPV6) {
1866 re = dhcpv6_recv_l3_packet(&packet6, buf, sizeof(buf),
1867 dhcp_client->listener_sockfd);
1870 xid = packet6->transaction_id[0] << 16 |
1871 packet6->transaction_id[1] << 8 |
1872 packet6->transaction_id[2];
1874 re = dhcp_recv_l3_packet(&packet,
1875 dhcp_client->listener_sockfd);
1878 } else if (dhcp_client->listen_mode == L_ARP) {
1879 ipv4ll_recv_arp_packet(dhcp_client);
1888 if (check_package_owner(dhcp_client, pkt) == FALSE)
1891 if (dhcp_client->type == G_DHCP_IPV6) {
1892 if (packet6 == NULL)
1896 client_id = dhcpv6_get_option(packet6, pkt_len,
1897 G_DHCPV6_CLIENTID, &option_len, &count);
1899 if (client_id == NULL || count == 0 || option_len == 0 ||
1900 memcmp(dhcp_client->duid, client_id,
1901 dhcp_client->duid_len) != 0) {
1903 "client duid error, discarding msg %p/%d/%d",
1904 client_id, option_len, count);
1908 option = dhcpv6_get_option(packet6, pkt_len,
1909 G_DHCPV6_STATUS_CODE, &option_len, NULL);
1910 if (option != 0 && option_len > 0) {
1911 status = option[0]<<8 | option[1];
1913 debug(dhcp_client, "error code %d", status);
1914 if (option_len > 2) {
1915 gchar *txt = g_strndup(
1916 (gchar *)&option[2],
1918 debug(dhcp_client, "error text: %s",
1923 dhcp_client->status_code = status;
1925 dhcp_client->status_code = 0;
1928 message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
1929 if (message_type == NULL)
1933 if (message_type == NULL && client_id == NULL)
1934 /* No message type / client id option, ignore package */
1937 debug(dhcp_client, "received DHCP packet xid 0x%04x "
1938 "(current state %d)", xid, dhcp_client->state);
1940 switch (dhcp_client->state) {
1941 case INIT_SELECTING:
1942 if (*message_type != DHCPOFFER)
1945 g_source_remove(dhcp_client->timeout);
1946 dhcp_client->timeout = 0;
1947 dhcp_client->retry_times = 0;
1949 option = dhcp_get_option(&packet, DHCP_SERVER_ID);
1950 dhcp_client->server_ip = get_be32(option);
1951 dhcp_client->requested_ip = ntohl(packet.yiaddr);
1953 dhcp_client->state = REQUESTING;
1955 start_request(dhcp_client);
1961 if (*message_type == DHCPACK) {
1962 dhcp_client->retry_times = 0;
1964 if (dhcp_client->timeout > 0)
1965 g_source_remove(dhcp_client->timeout);
1966 dhcp_client->timeout = 0;
1968 dhcp_client->lease_seconds = get_lease(&packet);
1970 get_request(dhcp_client, &packet);
1972 switch_listening_mode(dhcp_client, L_NONE);
1974 g_free(dhcp_client->assigned_ip);
1975 dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1977 /* Address should be set up here */
1978 if (dhcp_client->lease_available_cb != NULL)
1979 dhcp_client->lease_available_cb(dhcp_client,
1980 dhcp_client->lease_available_data);
1982 start_bound(dhcp_client);
1983 } else if (*message_type == DHCPNAK) {
1984 dhcp_client->retry_times = 0;
1986 if (dhcp_client->timeout > 0)
1987 g_source_remove(dhcp_client->timeout);
1989 dhcp_client->timeout = g_timeout_add_seconds_full(
1991 restart_dhcp_timeout,
1998 if (dhcp_client->type != G_DHCP_IPV6)
2001 if (packet6->message != DHCPV6_REPLY &&
2002 packet6->message != DHCPV6_ADVERTISE)
2006 server_id = dhcpv6_get_option(packet6, pkt_len,
2007 G_DHCPV6_SERVERID, &option_len, &count);
2008 if (server_id == NULL || count != 1 || option_len == 0) {
2009 /* RFC 3315, 15.10 */
2011 "server duid error, discarding msg %p/%d/%d",
2012 server_id, option_len, count);
2015 dhcp_client->server_duid = g_try_malloc(option_len);
2016 if (dhcp_client->server_duid == NULL)
2018 memcpy(dhcp_client->server_duid, server_id, option_len);
2019 dhcp_client->server_duid_len = option_len;
2021 if (packet6->message == DHCPV6_REPLY) {
2022 uint8_t *rapid_commit;
2025 rapid_commit = dhcpv6_get_option(packet6, pkt_len,
2026 G_DHCPV6_RAPID_COMMIT,
2027 &option_len, &count);
2028 if (rapid_commit == NULL || option_len == 0 ||
2030 /* RFC 3315, 17.1.4 */
2034 switch_listening_mode(dhcp_client, L_NONE);
2036 if (dhcp_client->status_code == 0)
2037 get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2038 &dhcp_client->status_code);
2040 if (packet6->message == DHCPV6_ADVERTISE) {
2041 if (dhcp_client->advertise_cb != NULL)
2042 dhcp_client->advertise_cb(dhcp_client,
2043 dhcp_client->advertise_data);
2047 if (dhcp_client->solicitation_cb != NULL) {
2049 * The dhcp_client might not be valid after the
2050 * callback call so just return immediately.
2052 dhcp_client->solicitation_cb(dhcp_client,
2053 dhcp_client->solicitation_data);
2057 case INFORMATION_REQ:
2062 if (dhcp_client->type != G_DHCP_IPV6)
2065 if (packet6->message != DHCPV6_REPLY)
2070 server_id = dhcpv6_get_option(packet6, pkt_len,
2071 G_DHCPV6_SERVERID, &option_len, &count);
2072 if (server_id == NULL || count != 1 || option_len == 0 ||
2073 (dhcp_client->server_duid_len > 0 &&
2074 memcmp(dhcp_client->server_duid, server_id,
2075 dhcp_client->server_duid_len) != 0)) {
2076 /* RFC 3315, 15.10 */
2078 "server duid error, discarding msg %p/%d/%d",
2079 server_id, option_len, count);
2083 switch_listening_mode(dhcp_client, L_NONE);
2085 dhcp_client->status_code = 0;
2086 get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2087 &dhcp_client->status_code);
2089 if (dhcp_client->information_req_cb != NULL) {
2091 * The dhcp_client might not be valid after the
2092 * callback call so just return immediately.
2094 dhcp_client->information_req_cb(dhcp_client,
2095 dhcp_client->information_req_data);
2098 if (dhcp_client->request_cb != NULL) {
2099 dhcp_client->request_cb(dhcp_client,
2100 dhcp_client->request_data);
2103 if (dhcp_client->renew_cb != NULL) {
2104 dhcp_client->renew_cb(dhcp_client,
2105 dhcp_client->renew_data);
2108 if (dhcp_client->rebind_cb != NULL) {
2109 dhcp_client->rebind_cb(dhcp_client,
2110 dhcp_client->rebind_data);
2113 if (dhcp_client->release_cb != NULL) {
2114 dhcp_client->release_cb(dhcp_client,
2115 dhcp_client->release_data);
2123 debug(dhcp_client, "processed DHCP packet (new state %d)",
2124 dhcp_client->state);
2129 static gboolean discover_timeout(gpointer user_data)
2131 GDHCPClient *dhcp_client = user_data;
2133 dhcp_client->retry_times++;
2136 * We do not send the REQUESTED IP option if we are retrying because
2137 * if the server is non-authoritative it will ignore the request if the
2138 * option is present.
2140 g_dhcp_client_start(dhcp_client, NULL);
2145 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
2147 GDHCPClient *dhcp_client = dhcp_data;
2149 debug(dhcp_client, "back to MONITOR mode");
2151 dhcp_client->conflicts = 0;
2152 dhcp_client->state = IPV4LL_MONITOR;
2157 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
2159 GDHCPClient *dhcp_client = dhcp_data;
2162 debug(dhcp_client, "request timeout (retries %d)",
2163 dhcp_client->retry_times);
2165 if (dhcp_client->retry_times != ANNOUNCE_NUM){
2166 dhcp_client->retry_times++;
2167 send_announce_packet(dhcp_client);
2171 ip = htonl(dhcp_client->requested_ip);
2172 debug(dhcp_client, "switching to monitor mode");
2173 dhcp_client->state = IPV4LL_MONITOR;
2174 dhcp_client->assigned_ip = get_ip(ip);
2176 if (dhcp_client->ipv4ll_available_cb != NULL)
2177 dhcp_client->ipv4ll_available_cb(dhcp_client,
2178 dhcp_client->ipv4ll_available_data);
2179 dhcp_client->conflicts = 0;
2184 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
2187 GDHCPClient *dhcp_client = dhcp_data;
2189 debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
2190 dhcp_client->retry_times);
2192 if (dhcp_client->retry_times == PROBE_NUM) {
2193 dhcp_client->state = IPV4LL_ANNOUNCE;
2194 dhcp_client->retry_times = 0;
2196 dhcp_client->retry_times++;
2197 send_announce_packet(dhcp_client);
2200 dhcp_client->retry_times++;
2201 send_probe_packet(dhcp_client);
2206 int g_dhcp_client_start(GDHCPClient *dhcp_client, const char *last_address)
2211 if (dhcp_client->type == G_DHCP_IPV6) {
2212 if (dhcp_client->information_req_cb) {
2213 dhcp_client->state = INFORMATION_REQ;
2214 re = switch_listening_mode(dhcp_client, L3);
2216 switch_listening_mode(dhcp_client, L_NONE);
2217 dhcp_client->state = 0;
2220 send_information_req(dhcp_client);
2222 } else if (dhcp_client->solicitation_cb) {
2223 dhcp_client->state = SOLICITATION;
2224 re = switch_listening_mode(dhcp_client, L3);
2226 switch_listening_mode(dhcp_client, L_NONE);
2227 dhcp_client->state = 0;
2230 send_solicitation(dhcp_client);
2232 } else if (dhcp_client->request_cb) {
2233 dhcp_client->state = REQUEST;
2234 re = switch_listening_mode(dhcp_client, L3);
2236 switch_listening_mode(dhcp_client, L_NONE);
2237 dhcp_client->state = 0;
2240 send_dhcpv6_request(dhcp_client);
2242 } else if (dhcp_client->renew_cb) {
2243 dhcp_client->state = RENEW;
2244 re = switch_listening_mode(dhcp_client, L3);
2246 switch_listening_mode(dhcp_client, L_NONE);
2247 dhcp_client->state = 0;
2250 send_dhcpv6_renew(dhcp_client);
2252 } else if (dhcp_client->rebind_cb) {
2253 dhcp_client->state = REBIND;
2254 re = switch_listening_mode(dhcp_client, L3);
2256 switch_listening_mode(dhcp_client, L_NONE);
2257 dhcp_client->state = 0;
2260 send_dhcpv6_rebind(dhcp_client);
2262 } else if (dhcp_client->release_cb) {
2263 dhcp_client->state = RENEW;
2264 re = switch_listening_mode(dhcp_client, L3);
2266 switch_listening_mode(dhcp_client, L_NONE);
2267 dhcp_client->state = 0;
2270 send_dhcpv6_release(dhcp_client);
2276 if (dhcp_client->retry_times == DISCOVER_RETRIES) {
2277 ipv4ll_start(dhcp_client);
2281 if (dhcp_client->retry_times == 0) {
2282 g_free(dhcp_client->assigned_ip);
2283 dhcp_client->assigned_ip = NULL;
2285 dhcp_client->state = INIT_SELECTING;
2286 re = switch_listening_mode(dhcp_client, L2);
2290 dhcp_client->xid = rand();
2291 dhcp_client->start = time(NULL);
2294 if (last_address == NULL) {
2297 addr = inet_addr(last_address);
2298 if (addr == 0xFFFFFFFF) {
2301 g_free(dhcp_client->last_address);
2302 dhcp_client->last_address = g_strdup(last_address);
2305 send_discover(dhcp_client, addr);
2307 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
2315 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
2317 switch_listening_mode(dhcp_client, L_NONE);
2319 if (dhcp_client->state == BOUND ||
2320 dhcp_client->state == RENEWING ||
2321 dhcp_client->state == REBINDING)
2322 send_release(dhcp_client, dhcp_client->server_ip,
2323 dhcp_client->requested_ip);
2325 if (dhcp_client->timeout > 0) {
2326 g_source_remove(dhcp_client->timeout);
2327 dhcp_client->timeout = 0;
2330 if (dhcp_client->listener_watch > 0) {
2331 g_source_remove(dhcp_client->listener_watch);
2332 dhcp_client->listener_watch = 0;
2335 dhcp_client->listener_channel = NULL;
2337 dhcp_client->retry_times = 0;
2338 dhcp_client->ack_retry_times = 0;
2340 dhcp_client->requested_ip = 0;
2341 dhcp_client->state = RELEASED;
2342 dhcp_client->lease_seconds = 0;
2345 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
2346 unsigned char option_code)
2348 return g_hash_table_lookup(dhcp_client->code_value_hash,
2349 GINT_TO_POINTER((int) option_code));
2352 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
2353 GDHCPClientEvent event,
2354 GDHCPClientEventFunc func,
2358 case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
2359 dhcp_client->lease_available_cb = func;
2360 dhcp_client->lease_available_data = data;
2362 case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
2363 if (dhcp_client->type == G_DHCP_IPV6)
2365 dhcp_client->ipv4ll_available_cb = func;
2366 dhcp_client->ipv4ll_available_data = data;
2368 case G_DHCP_CLIENT_EVENT_NO_LEASE:
2369 dhcp_client->no_lease_cb = func;
2370 dhcp_client->no_lease_data = data;
2372 case G_DHCP_CLIENT_EVENT_LEASE_LOST:
2373 dhcp_client->lease_lost_cb = func;
2374 dhcp_client->lease_lost_data = data;
2376 case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
2377 if (dhcp_client->type == G_DHCP_IPV6)
2379 dhcp_client->ipv4ll_lost_cb = func;
2380 dhcp_client->ipv4ll_lost_data = data;
2382 case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
2383 dhcp_client->address_conflict_cb = func;
2384 dhcp_client->address_conflict_data = data;
2386 case G_DHCP_CLIENT_EVENT_INFORMATION_REQ:
2387 if (dhcp_client->type == G_DHCP_IPV4)
2389 dhcp_client->information_req_cb = func;
2390 dhcp_client->information_req_data = data;
2392 case G_DHCP_CLIENT_EVENT_SOLICITATION:
2393 if (dhcp_client->type == G_DHCP_IPV4)
2395 dhcp_client->solicitation_cb = func;
2396 dhcp_client->solicitation_data = data;
2398 case G_DHCP_CLIENT_EVENT_ADVERTISE:
2399 if (dhcp_client->type == G_DHCP_IPV4)
2401 dhcp_client->advertise_cb = func;
2402 dhcp_client->advertise_data = data;
2404 case G_DHCP_CLIENT_EVENT_REQUEST:
2405 if (dhcp_client->type == G_DHCP_IPV4)
2407 dhcp_client->request_cb = func;
2408 dhcp_client->request_data = data;
2410 case G_DHCP_CLIENT_EVENT_RENEW:
2411 if (dhcp_client->type == G_DHCP_IPV4)
2413 dhcp_client->renew_cb = func;
2414 dhcp_client->renew_data = data;
2416 case G_DHCP_CLIENT_EVENT_REBIND:
2417 if (dhcp_client->type == G_DHCP_IPV4)
2419 dhcp_client->rebind_cb = func;
2420 dhcp_client->rebind_data = data;
2422 case G_DHCP_CLIENT_EVENT_RELEASE:
2423 if (dhcp_client->type == G_DHCP_IPV4)
2425 dhcp_client->release_cb = func;
2426 dhcp_client->release_data = data;
2431 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
2433 return dhcp_client->ifindex;
2436 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
2438 return g_strdup(dhcp_client->assigned_ip);
2441 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
2443 GList *option = NULL;
2445 if (dhcp_client->type == G_DHCP_IPV6)
2448 switch (dhcp_client->state) {
2450 case IPV4LL_MONITOR:
2451 return g_strdup("255.255.0.0");
2455 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
2457 return g_strdup(option->data);
2458 case INIT_SELECTING:
2462 case IPV4LL_ANNOUNCE:
2463 case INFORMATION_REQ:
2474 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
2475 unsigned int option_code)
2477 if (g_list_find(dhcp_client->request_list,
2478 GINT_TO_POINTER((int) option_code)) == NULL)
2479 dhcp_client->request_list = g_list_prepend(
2480 dhcp_client->request_list,
2481 (GINT_TO_POINTER((int) option_code)));
2483 return G_DHCP_CLIENT_ERROR_NONE;
2486 void g_dhcp_client_clear_requests(GDHCPClient *dhcp_client)
2488 g_list_free(dhcp_client->request_list);
2489 dhcp_client->request_list = NULL;
2492 void g_dhcp_client_clear_values(GDHCPClient *dhcp_client)
2494 g_hash_table_remove_all(dhcp_client->send_value_hash);
2497 static uint8_t *alloc_dhcp_option(int code, const uint8_t *data, unsigned size)
2501 storage = g_try_malloc(size + OPT_DATA);
2502 if (storage == NULL)
2505 storage[OPT_CODE] = code;
2506 storage[OPT_LEN] = size;
2507 memcpy(&storage[OPT_DATA], data, size);
2512 static uint8_t *alloc_dhcp_data_option(int code, const uint8_t *data, unsigned size)
2514 return alloc_dhcp_option(code, data, MIN(size, 255));
2517 static uint8_t *alloc_dhcp_string_option(int code, const char *str)
2519 return alloc_dhcp_data_option(code, (const uint8_t *)str, strlen(str));
2522 GDHCPClientError g_dhcp_client_set_id(GDHCPClient *dhcp_client)
2524 const unsigned maclen = 6;
2525 const unsigned idlen = maclen + 1;
2526 const uint8_t option_code = G_DHCP_CLIENT_ID;
2527 uint8_t idbuf[idlen];
2528 uint8_t *data_option;
2530 idbuf[0] = ARPHRD_ETHER;
2532 memcpy(&idbuf[1], dhcp_client->mac_address, maclen);
2534 data_option = alloc_dhcp_data_option(option_code, idbuf, idlen);
2535 if (data_option == NULL)
2536 return G_DHCP_CLIENT_ERROR_NOMEM;
2538 g_hash_table_insert(dhcp_client->send_value_hash,
2539 GINT_TO_POINTER((int) option_code), data_option);
2541 return G_DHCP_CLIENT_ERROR_NONE;
2544 /* Now only support send hostname */
2545 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
2546 unsigned char option_code, const char *option_value)
2548 uint8_t *binary_option;
2550 if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
2551 binary_option = alloc_dhcp_string_option(option_code,
2553 if (binary_option == NULL)
2554 return G_DHCP_CLIENT_ERROR_NOMEM;
2556 g_hash_table_insert(dhcp_client->send_value_hash,
2557 GINT_TO_POINTER((int) option_code), binary_option);
2560 return G_DHCP_CLIENT_ERROR_NONE;
2563 static uint8_t *alloc_dhcpv6_option(uint16_t code, uint8_t *option,
2568 storage = g_malloc(2 + 2 + len);
2569 if (storage == NULL)
2572 storage[0] = code >> 8;
2573 storage[1] = code & 0xff;
2574 storage[2] = len >> 8;
2575 storage[3] = len & 0xff;
2576 memcpy(storage + 2 + 2, option, len);
2581 void g_dhcpv6_client_set_send(GDHCPClient *dhcp_client,
2582 uint16_t option_code,
2583 uint8_t *option_value,
2584 uint16_t option_len)
2586 if (option_value != NULL) {
2587 uint8_t *binary_option;
2589 debug(dhcp_client, "setting option %d to %p len %d",
2590 option_code, option_value, option_len);
2592 binary_option = alloc_dhcpv6_option(option_code, option_value,
2594 if (binary_option != NULL)
2595 g_hash_table_insert(dhcp_client->send_value_hash,
2596 GINT_TO_POINTER((int) option_code),
2601 void g_dhcpv6_client_reset_renew(GDHCPClient *dhcp_client)
2603 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2606 dhcp_client->last_renew = time(NULL);
2609 void g_dhcpv6_client_reset_rebind(GDHCPClient *dhcp_client)
2611 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2614 dhcp_client->last_rebind = time(NULL);
2617 void g_dhcpv6_client_set_expire(GDHCPClient *dhcp_client, uint32_t timeout)
2619 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2622 dhcp_client->expire = time(NULL) + timeout;
2625 uint16_t g_dhcpv6_client_get_status(GDHCPClient *dhcp_client)
2627 if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2630 return dhcp_client->status_code;
2633 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
2635 if (dhcp_client == NULL)
2638 __sync_fetch_and_add(&dhcp_client->ref_count, 1);
2643 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
2645 if (dhcp_client == NULL)
2648 if (__sync_fetch_and_sub(&dhcp_client->ref_count, 1) != 1)
2651 g_dhcp_client_stop(dhcp_client);
2653 g_free(dhcp_client->interface);
2654 g_free(dhcp_client->assigned_ip);
2655 g_free(dhcp_client->last_address);
2656 g_free(dhcp_client->duid);
2657 g_free(dhcp_client->server_duid);
2659 g_list_free(dhcp_client->request_list);
2660 g_list_free(dhcp_client->require_list);
2662 g_hash_table_destroy(dhcp_client->code_value_hash);
2663 g_hash_table_destroy(dhcp_client->send_value_hash);
2665 g_free(dhcp_client);
2668 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
2669 GDHCPDebugFunc func, gpointer user_data)
2671 if (dhcp_client == NULL)
2674 dhcp_client->debug_func = func;
2675 dhcp_client->debug_data = user_data;