3 * DHCP client library with GLib integration
5 * Copyright (C) 2009-2010 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 {
80 uint8_t mac_address[6];
83 uint32_t requested_ip;
85 uint32_t lease_seconds;
86 ListenMode listen_mode;
89 uint8_t ack_retry_times;
93 GIOChannel *listener_channel;
96 GHashTable *code_value_hash;
97 GHashTable *send_value_hash;
98 GDHCPClientEventFunc lease_available_cb;
99 gpointer lease_available_data;
100 GDHCPClientEventFunc ipv4ll_available_cb;
101 gpointer ipv4ll_available_data;
102 GDHCPClientEventFunc no_lease_cb;
103 gpointer no_lease_data;
104 GDHCPClientEventFunc lease_lost_cb;
105 gpointer lease_lost_data;
106 GDHCPClientEventFunc ipv4ll_lost_cb;
107 gpointer ipv4ll_lost_data;
108 GDHCPClientEventFunc address_conflict_cb;
109 gpointer address_conflict_data;
110 GDHCPDebugFunc debug_func;
114 static inline void debug(GDHCPClient *client, const char *format, ...)
119 if (client->debug_func == NULL)
122 va_start(ap, format);
124 if (vsnprintf(str, sizeof(str), format, ap) > 0)
125 client->debug_func(str, client->debug_data);
130 /* Initialize the packet with the proper defaults */
131 static void init_packet(GDHCPClient *dhcp_client,
132 struct dhcp_packet *packet, char type)
134 dhcp_init_header(packet, type);
136 memcpy(packet->chaddr, dhcp_client->mac_address, 6);
139 static void add_request_options(GDHCPClient *dhcp_client,
140 struct dhcp_packet *packet)
145 int end = dhcp_end_option(packet->options);
147 for (list = dhcp_client->request_list; list; list = list->next) {
148 code = (uint8_t) GPOINTER_TO_INT(list->data);
150 packet->options[end + OPT_DATA + len] = code;
155 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
156 packet->options[end + OPT_LEN] = len;
157 packet->options[end + OPT_DATA + len] = DHCP_END;
161 static void add_binary_option(gpointer key, gpointer value, gpointer user_data)
163 uint8_t *option = value;
164 struct dhcp_packet *packet = user_data;
166 dhcp_add_binary_option(packet, option);
169 static void add_send_options(GDHCPClient *dhcp_client,
170 struct dhcp_packet *packet)
172 g_hash_table_foreach(dhcp_client->send_value_hash,
173 add_binary_option, packet);
176 static int send_discover(GDHCPClient *dhcp_client, uint32_t requested)
178 struct dhcp_packet packet;
180 debug(dhcp_client, "sending DHCP discover request");
182 init_packet(dhcp_client, &packet, DHCPDISCOVER);
184 packet.xid = dhcp_client->xid;
187 dhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
189 /* Explicitly saying that we want RFC-compliant packets helps
190 * some buggy DHCP servers to NOT send bigger packets */
191 dhcp_add_simple_option(&packet, DHCP_MAX_SIZE, htons(576));
193 add_request_options(dhcp_client, &packet);
195 add_send_options(dhcp_client, &packet);
197 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
198 INADDR_BROADCAST, SERVER_PORT,
199 MAC_BCAST_ADDR, dhcp_client->ifindex);
202 static int send_select(GDHCPClient *dhcp_client)
204 struct dhcp_packet packet;
207 debug(dhcp_client, "sending DHCP select request");
209 init_packet(dhcp_client, &packet, DHCPREQUEST);
211 packet.xid = dhcp_client->xid;
213 dhcp_add_simple_option(&packet, DHCP_REQUESTED_IP,
214 dhcp_client->requested_ip);
215 dhcp_add_simple_option(&packet, DHCP_SERVER_ID, dhcp_client->server_ip);
217 add_request_options(dhcp_client, &packet);
219 add_send_options(dhcp_client, &packet);
221 addr.s_addr = dhcp_client->requested_ip;
223 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
224 INADDR_BROADCAST, SERVER_PORT,
225 MAC_BCAST_ADDR, dhcp_client->ifindex);
228 static int send_renew(GDHCPClient *dhcp_client)
230 struct dhcp_packet packet;
232 debug(dhcp_client, "sending DHCP renew request");
234 init_packet(dhcp_client , &packet, DHCPREQUEST);
235 packet.xid = dhcp_client->xid;
236 packet.ciaddr = dhcp_client->requested_ip;
238 add_request_options(dhcp_client, &packet);
240 add_send_options(dhcp_client, &packet);
242 return dhcp_send_kernel_packet(&packet,
243 dhcp_client->requested_ip, CLIENT_PORT,
244 dhcp_client->server_ip, SERVER_PORT);
247 static int send_rebound(GDHCPClient *dhcp_client)
249 struct dhcp_packet packet;
251 debug(dhcp_client, "sending DHCP rebound request");
253 init_packet(dhcp_client , &packet, DHCPREQUEST);
254 packet.xid = dhcp_client->xid;
255 packet.ciaddr = dhcp_client->requested_ip;
257 add_request_options(dhcp_client, &packet);
259 add_send_options(dhcp_client, &packet);
261 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
262 INADDR_BROADCAST, SERVER_PORT,
263 MAC_BCAST_ADDR, dhcp_client->ifindex);
266 static int send_release(GDHCPClient *dhcp_client,
267 uint32_t server, uint32_t ciaddr)
269 struct dhcp_packet packet;
271 debug(dhcp_client, "sending DHCP release request");
273 init_packet(dhcp_client, &packet, DHCPRELEASE);
275 packet.ciaddr = ciaddr;
277 dhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
279 return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
280 server, SERVER_PORT);
283 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data);
284 static int switch_listening_mode(GDHCPClient *dhcp_client,
285 ListenMode listen_mode);
287 static gboolean send_probe_packet(gpointer dhcp_data)
289 GDHCPClient *dhcp_client;
292 dhcp_client = dhcp_data;
293 /* if requested_ip is not valid, pick a new address*/
294 if (dhcp_client->requested_ip == 0) {
295 debug(dhcp_client, "pick a new random address");
296 dhcp_client->requested_ip = ipv4ll_random_ip(0);
299 debug(dhcp_client, "sending IPV4LL probe request");
301 if (dhcp_client->retry_times == 1) {
302 dhcp_client->state = IPV4LL_PROBE;
303 switch_listening_mode(dhcp_client, L_ARP);
305 ipv4ll_send_arp_packet(dhcp_client->mac_address, 0,
306 dhcp_client->requested_ip, dhcp_client->ifindex);
308 if (dhcp_client->retry_times < PROBE_NUM) {
309 /*add a random timeout in range of PROBE_MIN to PROBE_MAX*/
310 timeout = ipv4ll_random_delay_ms(PROBE_MAX-PROBE_MIN);
311 timeout += PROBE_MIN*1000;
313 timeout = (ANNOUNCE_WAIT * 1000);
315 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
317 ipv4ll_probe_timeout,
323 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data);
324 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data);
326 static gboolean send_announce_packet(gpointer dhcp_data)
328 GDHCPClient *dhcp_client;
330 dhcp_client = dhcp_data;
332 debug(dhcp_client, "sending IPV4LL announce request");
334 ipv4ll_send_arp_packet(dhcp_client->mac_address,
335 dhcp_client->requested_ip,
336 dhcp_client->requested_ip,
337 dhcp_client->ifindex);
339 if (dhcp_client->timeout > 0)
340 g_source_remove(dhcp_client->timeout);
341 dhcp_client->timeout = 0;
343 if (dhcp_client->state == IPV4LL_DEFEND) {
344 dhcp_client->timeout =
345 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
347 ipv4ll_defend_timeout,
352 dhcp_client->timeout =
353 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
355 ipv4ll_announce_timeout,
361 static void get_interface_mac_address(int index, uint8_t *mac_address)
366 sk = socket(PF_INET, SOCK_DGRAM, 0);
368 perror("Open socket error");
372 memset(&ifr, 0, sizeof(ifr));
373 ifr.ifr_ifindex = index;
375 err = ioctl(sk, SIOCGIFNAME, &ifr);
377 perror("Get interface name error");
381 err = ioctl(sk, SIOCGIFHWADDR, &ifr);
383 perror("Get mac address error");
387 memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
393 static void remove_value(gpointer data, gpointer user_data)
399 static void remove_option_value(gpointer data)
401 GList *option_value = data;
403 g_list_foreach(option_value, remove_value, NULL);
406 GDHCPClient *g_dhcp_client_new(GDHCPType type,
407 int ifindex, GDHCPClientError *error)
409 GDHCPClient *dhcp_client;
412 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
416 dhcp_client = g_try_new0(GDHCPClient, 1);
417 if (dhcp_client == NULL) {
418 *error = G_DHCP_CLIENT_ERROR_NOMEM;
422 dhcp_client->interface = get_interface_name(ifindex);
423 if (dhcp_client->interface == NULL) {
424 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
428 if (interface_is_up(ifindex) == FALSE) {
429 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
433 get_interface_mac_address(ifindex, dhcp_client->mac_address);
435 dhcp_client->listener_sockfd = -1;
436 dhcp_client->listener_channel = NULL;
437 dhcp_client->listen_mode = L_NONE;
438 dhcp_client->ref_count = 1;
439 dhcp_client->type = type;
440 dhcp_client->ifindex = ifindex;
441 dhcp_client->lease_available_cb = NULL;
442 dhcp_client->ipv4ll_available_cb = NULL;
443 dhcp_client->no_lease_cb = NULL;
444 dhcp_client->lease_lost_cb = NULL;
445 dhcp_client->ipv4ll_lost_cb = NULL;
446 dhcp_client->address_conflict_cb = NULL;
447 dhcp_client->listener_watch = 0;
448 dhcp_client->retry_times = 0;
449 dhcp_client->ack_retry_times = 0;
450 dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
451 g_direct_equal, NULL, remove_option_value);
452 dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
453 g_direct_equal, NULL, g_free);
454 dhcp_client->request_list = NULL;
455 dhcp_client->require_list = NULL;
457 *error = G_DHCP_CLIENT_ERROR_NONE;
462 g_free(dhcp_client->interface);
467 #define SERVER_AND_CLIENT_PORTS ((67 << 16) + 68)
469 static int dhcp_l2_socket(int ifindex)
472 struct sockaddr_ll sock;
477 * I've selected not to see LL header, so BPF doesn't see it, too.
478 * The filter may also pass non-IP and non-ARP packets, but we do
479 * a more complete check when receiving the message in userspace.
481 * and filter shamelessly stolen from:
483 * http://www.flamewarmaster.de/software/dhcpclient/
485 * There are a few other interesting ideas on that page (look under
486 * "Motivation"). Use of netlink events is most interesting. Think
487 * of various network servers listening for events and reconfiguring.
488 * That would obsolete sending HUP signals and/or make use of restarts.
490 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
493 * TODO: make conditional?
495 static const struct sock_filter filter_instr[] = {
497 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
498 /* L5, L1, is UDP? */
499 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
500 /* ugly check for arp on ethernet-like and IPv4 */
501 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
502 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
504 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
505 /* check udp source and destination ports */
506 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
508 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
510 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
511 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
514 static const struct sock_fprog filter_prog = {
515 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
516 /* casting const away: */
517 .filter = (struct sock_filter *) filter_instr,
520 fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
524 if (SERVER_PORT == 67 && CLIENT_PORT == 68)
525 /* Use only if standard ports are in use */
526 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
527 sizeof(filter_prog));
529 memset(&sock, 0, sizeof(sock));
530 sock.sll_family = AF_PACKET;
531 sock.sll_protocol = htons(ETH_P_IP);
532 sock.sll_ifindex = ifindex;
534 if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
542 static gboolean sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
544 if (packet->ip.protocol != IPPROTO_UDP)
547 if (packet->ip.version != IPVERSION)
550 if (packet->ip.ihl != sizeof(packet->ip) >> 2)
553 if (packet->udp.dest != htons(CLIENT_PORT))
556 if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
562 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd)
565 struct ip_udp_dhcp_packet packet;
568 memset(&packet, 0, sizeof(packet));
570 bytes = read(fd, &packet, sizeof(packet));
574 if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
577 if (bytes < ntohs(packet.ip.tot_len))
578 /* packet is bigger than sizeof(packet), we did partial read */
581 /* ignore any extra garbage bytes */
582 bytes = ntohs(packet.ip.tot_len);
584 if (sanity_check(&packet, bytes) == FALSE)
587 check = packet.ip.check;
589 if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
592 /* verify UDP checksum. IP header has to be modified for this */
593 memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
594 /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
595 packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
596 check = packet.udp.check;
597 packet.udp.check = 0;
598 if (check && check != dhcp_checksum(&packet, bytes))
601 memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
602 sizeof(packet.udp)));
604 if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
607 return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
610 static void ipv4ll_start(GDHCPClient *dhcp_client)
615 if (dhcp_client->timeout > 0) {
616 g_source_remove(dhcp_client->timeout);
617 dhcp_client->timeout = 0;
620 switch_listening_mode(dhcp_client, L_NONE);
621 dhcp_client->type = G_DHCP_IPV4LL;
622 dhcp_client->retry_times = 0;
623 dhcp_client->requested_ip = 0;
625 /*try to start with a based mac address ip*/
626 seed = (dhcp_client->mac_address[4] << 8 | dhcp_client->mac_address[4]);
627 dhcp_client->requested_ip = ipv4ll_random_ip(seed);
629 /*first wait a random delay to avoid storm of arp request on boot*/
630 timeout = ipv4ll_random_delay_ms(PROBE_WAIT);
632 dhcp_client->retry_times++;
633 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
640 static void ipv4ll_stop(GDHCPClient *dhcp_client)
643 switch_listening_mode(dhcp_client, L_NONE);
645 if (dhcp_client->timeout > 0)
646 g_source_remove(dhcp_client->timeout);
648 if (dhcp_client->listener_watch > 0) {
649 g_source_remove(dhcp_client->listener_watch);
650 dhcp_client->listener_watch = 0;
653 dhcp_client->state = IPV4LL_PROBE;
654 dhcp_client->retry_times = 0;
655 dhcp_client->requested_ip = 0;
657 g_free(dhcp_client->assigned_ip);
658 dhcp_client->assigned_ip = NULL;
661 static int ipv4ll_recv_arp_packet(GDHCPClient *dhcp_client)
664 struct ether_arp arp;
665 uint32_t ip_requested;
669 memset(&arp, 0, sizeof(arp));
671 bytes = read(dhcp_client->listener_sockfd, &arp, sizeof(arp));
675 if (arp.arp_op != htons(ARPOP_REPLY) &&
676 arp.arp_op != htons(ARPOP_REQUEST))
679 ip_requested = ntohl(dhcp_client->requested_ip);
680 source_conflict = !memcmp(arp.arp_spa, &ip_requested,
681 sizeof(ip_requested));
683 target_conflict = !memcmp(arp.arp_tpa, &ip_requested,
684 sizeof(ip_requested));
686 if (!source_conflict && !target_conflict)
689 dhcp_client->conflicts++;
691 debug(dhcp_client, "IPV4LL conflict detected");
693 if (dhcp_client->state == IPV4LL_MONITOR) {
694 if (!source_conflict)
696 dhcp_client->state = IPV4LL_DEFEND;
697 debug(dhcp_client, "DEFEND mode conflicts : %d",
698 dhcp_client->conflicts);
699 /*Try to defend with a single announce*/
700 send_announce_packet(dhcp_client);
704 if (dhcp_client->state == IPV4LL_DEFEND) {
705 if (!source_conflict)
707 else if (dhcp_client->ipv4ll_lost_cb != NULL)
708 dhcp_client->ipv4ll_lost_cb(dhcp_client,
709 dhcp_client->ipv4ll_lost_data);
712 ipv4ll_stop(dhcp_client);
714 if (dhcp_client->conflicts < MAX_CONFLICTS) {
715 /*restart whole state machine*/
716 dhcp_client->retry_times++;
717 dhcp_client->timeout =
718 g_timeout_add_full(G_PRIORITY_HIGH,
719 ipv4ll_random_delay_ms(PROBE_WAIT),
724 /* Here we got a lot of conflicts, RFC3927 states that we have
725 * to wait RATE_LIMIT_INTERVAL before retrying,
726 * but we just report failure.
728 else if (dhcp_client->no_lease_cb != NULL)
729 dhcp_client->no_lease_cb(dhcp_client,
730 dhcp_client->no_lease_data);
735 static gboolean check_package_owner(GDHCPClient *dhcp_client,
736 struct dhcp_packet *packet)
738 if (packet->xid != dhcp_client->xid)
741 if (packet->hlen != 6)
744 if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
750 static void start_request(GDHCPClient *dhcp_client);
752 static gboolean request_timeout(gpointer user_data)
754 GDHCPClient *dhcp_client = user_data;
756 debug(dhcp_client, "request timeout (retries %d)",
757 dhcp_client->retry_times);
759 dhcp_client->retry_times++;
761 start_request(dhcp_client);
766 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
769 static int switch_listening_mode(GDHCPClient *dhcp_client,
770 ListenMode listen_mode)
772 GIOChannel *listener_channel;
775 debug(dhcp_client, "switch listening mode (%d ==> %d)",
776 dhcp_client->listen_mode, listen_mode);
778 if (dhcp_client->listen_mode == listen_mode)
781 if (dhcp_client->listen_mode != L_NONE) {
782 g_source_remove(dhcp_client->listener_watch);
783 dhcp_client->listener_channel = NULL;
784 dhcp_client->listen_mode = L_NONE;
785 dhcp_client->listener_sockfd = -1;
786 dhcp_client->listener_watch = 0;
789 if (listen_mode == L_NONE)
792 if (listen_mode == L2)
793 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
794 else if (listen_mode == L3)
795 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
796 dhcp_client->interface);
797 else if (listen_mode == L_ARP)
798 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
802 if (listener_sockfd < 0)
805 listener_channel = g_io_channel_unix_new(listener_sockfd);
806 if (listener_channel == NULL) {
807 /* Failed to create listener channel */
808 close(listener_sockfd);
812 dhcp_client->listen_mode = listen_mode;
813 dhcp_client->listener_sockfd = listener_sockfd;
814 dhcp_client->listener_channel = listener_channel;
816 g_io_channel_set_close_on_unref(listener_channel, TRUE);
817 dhcp_client->listener_watch =
818 g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
819 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
820 listener_event, dhcp_client,
822 g_io_channel_unref(dhcp_client->listener_channel);
827 static void start_request(GDHCPClient *dhcp_client)
829 debug(dhcp_client, "start request (retries %d)",
830 dhcp_client->retry_times);
832 if (dhcp_client->retry_times == REQUEST_RETRIES) {
833 dhcp_client->state = INIT_SELECTING;
834 ipv4ll_start(dhcp_client);
839 if (dhcp_client->retry_times == 0) {
840 dhcp_client->state = REQUESTING;
841 switch_listening_mode(dhcp_client, L2);
844 send_select(dhcp_client);
846 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
853 static uint32_t get_lease(struct dhcp_packet *packet)
856 uint32_t lease_seconds;
858 option_u8 = dhcp_get_option(packet, DHCP_LEASE_TIME);
859 if (option_u8 == NULL)
862 lease_seconds = dhcp_get_unaligned((uint32_t *) option_u8);
863 lease_seconds = ntohl(lease_seconds);
864 /* paranoia: must not be prone to overflows */
865 lease_seconds &= 0x0fffffff;
866 if (lease_seconds < 10)
869 return lease_seconds;
872 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
874 debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
876 if (dhcp_client->timeout > 0) {
877 g_source_remove(dhcp_client->timeout);
878 dhcp_client->timeout = 0;
881 dhcp_client->retry_times = retry_times;
882 dhcp_client->requested_ip = 0;
883 switch_listening_mode(dhcp_client, L2);
885 g_dhcp_client_start(dhcp_client);
888 static gboolean start_rebound_timeout(gpointer user_data)
890 GDHCPClient *dhcp_client = user_data;
892 debug(dhcp_client, "start rebound timeout");
894 switch_listening_mode(dhcp_client, L2);
896 dhcp_client->lease_seconds >>= 1;
898 /* We need to have enough time to receive ACK package*/
899 if (dhcp_client->lease_seconds <= 6) {
901 /* ip need to be cleared */
902 if (dhcp_client->lease_lost_cb != NULL)
903 dhcp_client->lease_lost_cb(dhcp_client,
904 dhcp_client->lease_lost_data);
906 restart_dhcp(dhcp_client, 0);
908 send_rebound(dhcp_client);
910 dhcp_client->timeout =
911 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
912 dhcp_client->lease_seconds >> 1,
913 start_rebound_timeout,
921 static void start_rebound(GDHCPClient *dhcp_client)
923 debug(dhcp_client, "start rebound");
925 dhcp_client->state = REBINDING;
927 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
928 dhcp_client->lease_seconds >> 1,
929 start_rebound_timeout,
934 static gboolean start_renew_timeout(gpointer user_data)
936 GDHCPClient *dhcp_client = user_data;
938 debug(dhcp_client, "start renew timeout");
940 dhcp_client->state = RENEWING;
942 dhcp_client->lease_seconds >>= 1;
944 switch_listening_mode(dhcp_client, L3);
945 if (dhcp_client->lease_seconds <= 60)
946 start_rebound(dhcp_client);
948 send_renew(dhcp_client);
950 dhcp_client->timeout =
951 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
952 dhcp_client->lease_seconds >> 1,
961 static void start_bound(GDHCPClient *dhcp_client)
963 debug(dhcp_client, "start bound");
965 dhcp_client->state = BOUND;
967 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
968 dhcp_client->lease_seconds >> 1,
969 start_renew_timeout, dhcp_client,
973 static gboolean restart_dhcp_timeout(gpointer user_data)
975 GDHCPClient *dhcp_client = user_data;
977 debug(dhcp_client, "restart DHCP timeout");
979 dhcp_client->ack_retry_times++;
981 restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
986 static char *get_ip(uint32_t ip)
992 return g_strdup(inet_ntoa(addr));
995 /* get a rough idea of how long an option will be */
996 static const uint8_t len_of_option_as_string[] = {
997 [OPTION_IP] = sizeof("255.255.255.255 "),
999 [OPTION_U8] = sizeof("255 "),
1000 [OPTION_U16] = sizeof("65535 "),
1001 [OPTION_U32] = sizeof("4294967295 "),
1004 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
1006 return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
1009 /* Create "opt_value1 option_value2 ..." string */
1010 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
1012 unsigned upper_length;
1016 len = option[OPT_LEN - OPT_DATA];
1017 type &= OPTION_TYPE_MASK;
1018 optlen = dhcp_option_lengths[type];
1021 upper_length = len_of_option_as_string[type] *
1022 ((unsigned)len / (unsigned)optlen);
1023 dest = ret = malloc(upper_length + 1);
1027 while (len >= optlen) {
1030 dest += sprint_nip(dest, "", option);
1033 uint16_t val_u16 = dhcp_get_unaligned(
1034 (uint16_t *) option);
1035 dest += sprintf(dest, "%u", ntohs(val_u16));
1039 uint32_t val_u32 = dhcp_get_unaligned(
1040 (uint32_t *) option);
1041 dest += sprintf(dest, type == OPTION_U32 ? "%lu" :
1042 "%ld", (unsigned long) ntohl(val_u32));
1046 memcpy(dest, option, len);
1063 static GList *get_option_value_list(char *value, GDHCPOptionType type)
1071 if (type == OPTION_STRING)
1072 return g_list_append(list, g_strdup(value));
1074 while ((pos = strchr(pos, ' ')) != NULL) {
1077 list = g_list_append(list, g_strdup(value));
1082 list = g_list_append(list, g_strdup(value));
1087 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
1089 GDHCPOptionType type;
1090 GList *list, *value_list;
1095 for (list = dhcp_client->request_list; list; list = list->next) {
1096 code = (uint8_t) GPOINTER_TO_INT(list->data);
1098 option = dhcp_get_option(packet, code);
1099 if (option == NULL) {
1100 g_hash_table_remove(dhcp_client->code_value_hash,
1101 GINT_TO_POINTER((int) code));
1105 type = dhcp_get_code_type(code);
1107 option_value = malloc_option_value_string(option, type);
1108 if (option_value == NULL)
1109 g_hash_table_remove(dhcp_client->code_value_hash,
1110 GINT_TO_POINTER((int) code));
1112 value_list = get_option_value_list(option_value, type);
1114 g_free(option_value);
1116 if (value_list == NULL)
1117 g_hash_table_remove(dhcp_client->code_value_hash,
1118 GINT_TO_POINTER((int) code));
1120 g_hash_table_insert(dhcp_client->code_value_hash,
1121 GINT_TO_POINTER((int) code), value_list);
1125 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1128 GDHCPClient *dhcp_client = user_data;
1129 struct dhcp_packet packet;
1130 uint8_t *message_type, *option_u8;
1133 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1134 dhcp_client->listener_watch = 0;
1138 if (dhcp_client->listen_mode == L_NONE)
1141 if (dhcp_client->listen_mode == L2)
1142 re = dhcp_recv_l2_packet(&packet, dhcp_client->listener_sockfd);
1143 else if (dhcp_client->listen_mode == L3)
1144 re = dhcp_recv_l3_packet(&packet, dhcp_client->listener_sockfd);
1145 else if (dhcp_client->listen_mode == L_ARP) {
1146 re = ipv4ll_recv_arp_packet(dhcp_client);
1155 if (check_package_owner(dhcp_client, &packet) == FALSE)
1158 message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
1159 if (message_type == NULL)
1160 /* No message type option, ignore package */
1163 debug(dhcp_client, "received DHCP packet (current state %d)",
1164 dhcp_client->state);
1166 switch (dhcp_client->state) {
1167 case INIT_SELECTING:
1168 if (*message_type != DHCPOFFER)
1171 g_source_remove(dhcp_client->timeout);
1172 dhcp_client->timeout = 0;
1173 dhcp_client->retry_times = 0;
1175 option_u8 = dhcp_get_option(&packet, DHCP_SERVER_ID);
1176 dhcp_client->server_ip =
1177 dhcp_get_unaligned((uint32_t *) option_u8);
1178 dhcp_client->requested_ip = packet.yiaddr;
1180 dhcp_client->state = REQUESTING;
1182 start_request(dhcp_client);
1188 if (*message_type == DHCPACK) {
1189 dhcp_client->retry_times = 0;
1191 if (dhcp_client->timeout > 0)
1192 g_source_remove(dhcp_client->timeout);
1193 dhcp_client->timeout = 0;
1195 dhcp_client->lease_seconds = get_lease(&packet);
1197 get_request(dhcp_client, &packet);
1199 switch_listening_mode(dhcp_client, L_NONE);
1201 g_free(dhcp_client->assigned_ip);
1202 dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1204 /* Address should be set up here */
1205 if (dhcp_client->lease_available_cb != NULL)
1206 dhcp_client->lease_available_cb(dhcp_client,
1207 dhcp_client->lease_available_data);
1209 start_bound(dhcp_client);
1210 } else if (*message_type == DHCPNAK) {
1211 dhcp_client->retry_times = 0;
1213 if (dhcp_client->timeout > 0)
1214 g_source_remove(dhcp_client->timeout);
1216 dhcp_client->timeout = g_timeout_add_seconds_full(
1218 restart_dhcp_timeout,
1228 debug(dhcp_client, "processed DHCP packet (new state %d)",
1229 dhcp_client->state);
1234 static gboolean discover_timeout(gpointer user_data)
1236 GDHCPClient *dhcp_client = user_data;
1238 dhcp_client->retry_times++;
1240 g_dhcp_client_start(dhcp_client);
1245 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
1247 GDHCPClient *dhcp_client = dhcp_data;
1249 debug(dhcp_client, "back to MONITOR mode");
1251 dhcp_client->conflicts = 0;
1252 dhcp_client->state = IPV4LL_MONITOR;
1257 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
1259 GDHCPClient *dhcp_client = dhcp_data;
1262 debug(dhcp_client, "request timeout (retries %d)",
1263 dhcp_client->retry_times);
1265 if (dhcp_client->retry_times != ANNOUNCE_NUM){
1266 dhcp_client->retry_times++;
1267 send_announce_packet(dhcp_client);
1271 ip = htonl(dhcp_client->requested_ip);
1272 debug(dhcp_client, "switching to monitor mode");
1273 dhcp_client->state = IPV4LL_MONITOR;
1274 dhcp_client->assigned_ip = get_ip(ip);
1276 if (dhcp_client->ipv4ll_available_cb != NULL)
1277 dhcp_client->ipv4ll_available_cb(dhcp_client,
1278 dhcp_client->ipv4ll_available_data);
1279 dhcp_client->conflicts = 0;
1284 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
1287 GDHCPClient *dhcp_client = dhcp_data;
1289 debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
1290 dhcp_client->retry_times);
1292 if (dhcp_client->retry_times == PROBE_NUM) {
1293 dhcp_client->state = IPV4LL_ANNOUNCE;
1294 dhcp_client->retry_times = 0;
1296 dhcp_client->retry_times++;
1297 send_announce_packet(dhcp_client);
1300 dhcp_client->retry_times++;
1301 send_probe_packet(dhcp_client);
1306 int g_dhcp_client_start(GDHCPClient *dhcp_client)
1310 if (dhcp_client->retry_times == DISCOVER_RETRIES) {
1311 ipv4ll_start(dhcp_client);
1315 if (dhcp_client->retry_times == 0) {
1316 g_free(dhcp_client->assigned_ip);
1317 dhcp_client->assigned_ip = NULL;
1319 dhcp_client->state = INIT_SELECTING;
1320 re = switch_listening_mode(dhcp_client, L2);
1324 dhcp_client->xid = rand();
1327 send_discover(dhcp_client, 0);
1329 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1337 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
1339 switch_listening_mode(dhcp_client, L_NONE);
1341 if (dhcp_client->state == BOUND ||
1342 dhcp_client->state == RENEWING ||
1343 dhcp_client->state == REBINDING)
1344 send_release(dhcp_client, dhcp_client->server_ip,
1345 dhcp_client->requested_ip);
1347 if (dhcp_client->timeout > 0) {
1348 g_source_remove(dhcp_client->timeout);
1349 dhcp_client->timeout = 0;
1352 if (dhcp_client->listener_watch > 0) {
1353 g_source_remove(dhcp_client->listener_watch);
1354 dhcp_client->listener_watch = 0;
1357 dhcp_client->listener_channel = NULL;
1359 dhcp_client->retry_times = 0;
1360 dhcp_client->ack_retry_times = 0;
1362 dhcp_client->requested_ip = 0;
1363 dhcp_client->state = RELEASED;
1364 dhcp_client->lease_seconds = 0;
1367 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
1368 unsigned char option_code)
1370 return g_hash_table_lookup(dhcp_client->code_value_hash,
1371 GINT_TO_POINTER((int) option_code));
1374 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
1375 GDHCPClientEvent event,
1376 GDHCPClientEventFunc func,
1380 case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
1381 dhcp_client->lease_available_cb = func;
1382 dhcp_client->lease_available_data = data;
1384 case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
1385 dhcp_client->ipv4ll_available_cb = func;
1386 dhcp_client->ipv4ll_available_data = data;
1388 case G_DHCP_CLIENT_EVENT_NO_LEASE:
1389 dhcp_client->no_lease_cb = func;
1390 dhcp_client->no_lease_data = data;
1392 case G_DHCP_CLIENT_EVENT_LEASE_LOST:
1393 dhcp_client->lease_lost_cb = func;
1394 dhcp_client->lease_lost_data = data;
1396 case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
1397 dhcp_client->ipv4ll_lost_cb = func;
1398 dhcp_client->ipv4ll_lost_data = data;
1400 case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
1401 dhcp_client->address_conflict_cb = func;
1402 dhcp_client->address_conflict_data = data;
1407 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
1409 return dhcp_client->ifindex;
1412 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
1414 return g_strdup(dhcp_client->assigned_ip);
1417 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
1419 GList *option = NULL;
1421 switch (dhcp_client->state) {
1423 case IPV4LL_MONITOR:
1424 return g_strdup("255.255.0.0");
1428 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
1430 return g_strdup(option->data);
1431 case INIT_SELECTING:
1435 case IPV4LL_ANNOUNCE:
1441 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
1442 unsigned char option_code)
1444 if (g_list_find(dhcp_client->request_list,
1445 GINT_TO_POINTER((int) option_code)) == NULL)
1446 dhcp_client->request_list = g_list_prepend(
1447 dhcp_client->request_list,
1448 (GINT_TO_POINTER((int) option_code)));
1450 return G_DHCP_CLIENT_ERROR_NONE;
1453 static uint8_t *alloc_dhcp_option(int code, const char *str, int extra)
1456 int len = strnlen(str, 255);
1458 storage = malloc(len + extra + OPT_DATA);
1459 storage[OPT_CODE] = code;
1460 storage[OPT_LEN] = len + extra;
1461 memcpy(storage + extra + OPT_DATA, str, len);
1466 /* Now only support send hostname */
1467 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
1468 unsigned char option_code, const char *option_value)
1470 uint8_t *binary_option;
1472 if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
1473 binary_option = alloc_dhcp_option(option_code,
1476 g_hash_table_insert(dhcp_client->send_value_hash,
1477 GINT_TO_POINTER((int) option_code), binary_option);
1480 return G_DHCP_CLIENT_ERROR_NONE;
1483 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
1485 if (dhcp_client == NULL)
1488 g_atomic_int_inc(&dhcp_client->ref_count);
1493 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
1495 if (dhcp_client == NULL)
1498 if (g_atomic_int_dec_and_test(&dhcp_client->ref_count) == FALSE)
1501 g_dhcp_client_stop(dhcp_client);
1503 g_free(dhcp_client->interface);
1504 g_free(dhcp_client->assigned_ip);
1506 g_list_free(dhcp_client->request_list);
1507 g_list_free(dhcp_client->require_list);
1509 g_hash_table_destroy(dhcp_client->code_value_hash);
1510 g_hash_table_destroy(dhcp_client->send_value_hash);
1512 g_free(dhcp_client);
1515 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
1516 GDHCPDebugFunc func, gpointer user_data)
1518 if (dhcp_client == NULL)
1521 dhcp_client->debug_func = func;
1522 dhcp_client->debug_data = user_data;