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;
115 static inline void debug(GDHCPClient *client, const char *format, ...)
120 if (client->debug_func == NULL)
123 va_start(ap, format);
125 if (vsnprintf(str, sizeof(str), format, ap) > 0)
126 client->debug_func(str, client->debug_data);
131 /* Initialize the packet with the proper defaults */
132 static void init_packet(GDHCPClient *dhcp_client,
133 struct dhcp_packet *packet, char type)
135 dhcp_init_header(packet, type);
137 memcpy(packet->chaddr, dhcp_client->mac_address, 6);
140 static void add_request_options(GDHCPClient *dhcp_client,
141 struct dhcp_packet *packet)
146 int end = dhcp_end_option(packet->options);
148 for (list = dhcp_client->request_list; list; list = list->next) {
149 code = (uint8_t) GPOINTER_TO_INT(list->data);
151 packet->options[end + OPT_DATA + len] = code;
156 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
157 packet->options[end + OPT_LEN] = len;
158 packet->options[end + OPT_DATA + len] = DHCP_END;
162 static void add_binary_option(gpointer key, gpointer value, gpointer user_data)
164 uint8_t *option = value;
165 struct dhcp_packet *packet = user_data;
167 dhcp_add_binary_option(packet, option);
170 static void add_send_options(GDHCPClient *dhcp_client,
171 struct dhcp_packet *packet)
173 g_hash_table_foreach(dhcp_client->send_value_hash,
174 add_binary_option, packet);
177 static int send_discover(GDHCPClient *dhcp_client, uint32_t requested)
179 struct dhcp_packet packet;
181 debug(dhcp_client, "sending DHCP discover request");
183 init_packet(dhcp_client, &packet, DHCPDISCOVER);
185 packet.xid = dhcp_client->xid;
188 dhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
190 /* Explicitly saying that we want RFC-compliant packets helps
191 * some buggy DHCP servers to NOT send bigger packets */
192 dhcp_add_simple_option(&packet, DHCP_MAX_SIZE, htons(576));
194 add_request_options(dhcp_client, &packet);
196 add_send_options(dhcp_client, &packet);
198 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
199 INADDR_BROADCAST, SERVER_PORT,
200 MAC_BCAST_ADDR, dhcp_client->ifindex);
203 static int send_select(GDHCPClient *dhcp_client)
205 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 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
222 INADDR_BROADCAST, SERVER_PORT,
223 MAC_BCAST_ADDR, dhcp_client->ifindex);
226 static int send_renew(GDHCPClient *dhcp_client)
228 struct dhcp_packet packet;
230 debug(dhcp_client, "sending DHCP renew request");
232 init_packet(dhcp_client , &packet, DHCPREQUEST);
233 packet.xid = dhcp_client->xid;
234 packet.ciaddr = dhcp_client->requested_ip;
236 add_request_options(dhcp_client, &packet);
238 add_send_options(dhcp_client, &packet);
240 return dhcp_send_kernel_packet(&packet,
241 dhcp_client->requested_ip, CLIENT_PORT,
242 dhcp_client->server_ip, SERVER_PORT);
245 static int send_rebound(GDHCPClient *dhcp_client)
247 struct dhcp_packet packet;
249 debug(dhcp_client, "sending DHCP rebound request");
251 init_packet(dhcp_client , &packet, DHCPREQUEST);
252 packet.xid = dhcp_client->xid;
253 packet.ciaddr = dhcp_client->requested_ip;
255 add_request_options(dhcp_client, &packet);
257 add_send_options(dhcp_client, &packet);
259 return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
260 INADDR_BROADCAST, SERVER_PORT,
261 MAC_BCAST_ADDR, dhcp_client->ifindex);
264 static int send_release(GDHCPClient *dhcp_client,
265 uint32_t server, uint32_t ciaddr)
267 struct dhcp_packet packet;
269 debug(dhcp_client, "sending DHCP release request");
271 init_packet(dhcp_client, &packet, DHCPRELEASE);
273 packet.ciaddr = ciaddr;
275 dhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
277 return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
278 server, SERVER_PORT);
281 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data);
282 static int switch_listening_mode(GDHCPClient *dhcp_client,
283 ListenMode listen_mode);
285 static gboolean send_probe_packet(gpointer dhcp_data)
287 GDHCPClient *dhcp_client;
290 dhcp_client = dhcp_data;
291 /* if requested_ip is not valid, pick a new address*/
292 if (dhcp_client->requested_ip == 0) {
293 debug(dhcp_client, "pick a new random address");
294 dhcp_client->requested_ip = ipv4ll_random_ip(0);
297 debug(dhcp_client, "sending IPV4LL probe request");
299 if (dhcp_client->retry_times == 1) {
300 dhcp_client->state = IPV4LL_PROBE;
301 switch_listening_mode(dhcp_client, L_ARP);
303 ipv4ll_send_arp_packet(dhcp_client->mac_address, 0,
304 dhcp_client->requested_ip, dhcp_client->ifindex);
306 if (dhcp_client->retry_times < PROBE_NUM) {
307 /*add a random timeout in range of PROBE_MIN to PROBE_MAX*/
308 timeout = ipv4ll_random_delay_ms(PROBE_MAX-PROBE_MIN);
309 timeout += PROBE_MIN*1000;
311 timeout = (ANNOUNCE_WAIT * 1000);
313 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
315 ipv4ll_probe_timeout,
321 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data);
322 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data);
324 static gboolean send_announce_packet(gpointer dhcp_data)
326 GDHCPClient *dhcp_client;
328 dhcp_client = dhcp_data;
330 debug(dhcp_client, "sending IPV4LL announce request");
332 ipv4ll_send_arp_packet(dhcp_client->mac_address,
333 dhcp_client->requested_ip,
334 dhcp_client->requested_ip,
335 dhcp_client->ifindex);
337 if (dhcp_client->timeout > 0)
338 g_source_remove(dhcp_client->timeout);
339 dhcp_client->timeout = 0;
341 if (dhcp_client->state == IPV4LL_DEFEND) {
342 dhcp_client->timeout =
343 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
345 ipv4ll_defend_timeout,
350 dhcp_client->timeout =
351 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
353 ipv4ll_announce_timeout,
359 static void get_interface_mac_address(int index, uint8_t *mac_address)
364 sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
366 perror("Open socket error");
370 memset(&ifr, 0, sizeof(ifr));
371 ifr.ifr_ifindex = index;
373 err = ioctl(sk, SIOCGIFNAME, &ifr);
375 perror("Get interface name error");
379 err = ioctl(sk, SIOCGIFHWADDR, &ifr);
381 perror("Get mac address error");
385 memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
391 static void remove_value(gpointer data, gpointer user_data)
397 static void remove_option_value(gpointer data)
399 GList *option_value = data;
401 g_list_foreach(option_value, remove_value, NULL);
404 GDHCPClient *g_dhcp_client_new(GDHCPType type,
405 int ifindex, GDHCPClientError *error)
407 GDHCPClient *dhcp_client;
410 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
414 dhcp_client = g_try_new0(GDHCPClient, 1);
415 if (dhcp_client == NULL) {
416 *error = G_DHCP_CLIENT_ERROR_NOMEM;
420 dhcp_client->interface = get_interface_name(ifindex);
421 if (dhcp_client->interface == NULL) {
422 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
426 if (interface_is_up(ifindex) == FALSE) {
427 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
431 get_interface_mac_address(ifindex, dhcp_client->mac_address);
433 dhcp_client->listener_sockfd = -1;
434 dhcp_client->listener_channel = NULL;
435 dhcp_client->listen_mode = L_NONE;
436 dhcp_client->ref_count = 1;
437 dhcp_client->type = type;
438 dhcp_client->ifindex = ifindex;
439 dhcp_client->lease_available_cb = NULL;
440 dhcp_client->ipv4ll_available_cb = NULL;
441 dhcp_client->no_lease_cb = NULL;
442 dhcp_client->lease_lost_cb = NULL;
443 dhcp_client->ipv4ll_lost_cb = NULL;
444 dhcp_client->address_conflict_cb = NULL;
445 dhcp_client->listener_watch = 0;
446 dhcp_client->retry_times = 0;
447 dhcp_client->ack_retry_times = 0;
448 dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
449 g_direct_equal, NULL, remove_option_value);
450 dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
451 g_direct_equal, NULL, g_free);
452 dhcp_client->request_list = NULL;
453 dhcp_client->require_list = NULL;
455 *error = G_DHCP_CLIENT_ERROR_NONE;
460 g_free(dhcp_client->interface);
465 #define SERVER_AND_CLIENT_PORTS ((67 << 16) + 68)
467 static int dhcp_l2_socket(int ifindex)
470 struct sockaddr_ll sock;
475 * I've selected not to see LL header, so BPF doesn't see it, too.
476 * The filter may also pass non-IP and non-ARP packets, but we do
477 * a more complete check when receiving the message in userspace.
479 * and filter shamelessly stolen from:
481 * http://www.flamewarmaster.de/software/dhcpclient/
483 * There are a few other interesting ideas on that page (look under
484 * "Motivation"). Use of netlink events is most interesting. Think
485 * of various network servers listening for events and reconfiguring.
486 * That would obsolete sending HUP signals and/or make use of restarts.
488 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
491 * TODO: make conditional?
493 static const struct sock_filter filter_instr[] = {
495 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
496 /* L5, L1, is UDP? */
497 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
498 /* ugly check for arp on ethernet-like and IPv4 */
499 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
500 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
502 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
503 /* check udp source and destination ports */
504 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
506 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
508 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
509 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
512 static const struct sock_fprog filter_prog = {
513 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
514 /* casting const away: */
515 .filter = (struct sock_filter *) filter_instr,
518 fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IP));
522 if (SERVER_PORT == 67 && CLIENT_PORT == 68)
523 /* Use only if standard ports are in use */
524 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
525 sizeof(filter_prog));
527 memset(&sock, 0, sizeof(sock));
528 sock.sll_family = AF_PACKET;
529 sock.sll_protocol = htons(ETH_P_IP);
530 sock.sll_ifindex = ifindex;
532 if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
540 static gboolean sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
542 if (packet->ip.protocol != IPPROTO_UDP)
545 if (packet->ip.version != IPVERSION)
548 if (packet->ip.ihl != sizeof(packet->ip) >> 2)
551 if (packet->udp.dest != htons(CLIENT_PORT))
554 if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
560 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd)
563 struct ip_udp_dhcp_packet packet;
566 memset(&packet, 0, sizeof(packet));
568 bytes = read(fd, &packet, sizeof(packet));
572 if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
575 if (bytes < ntohs(packet.ip.tot_len))
576 /* packet is bigger than sizeof(packet), we did partial read */
579 /* ignore any extra garbage bytes */
580 bytes = ntohs(packet.ip.tot_len);
582 if (sanity_check(&packet, bytes) == FALSE)
585 check = packet.ip.check;
587 if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
590 /* verify UDP checksum. IP header has to be modified for this */
591 memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
592 /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
593 packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
594 check = packet.udp.check;
595 packet.udp.check = 0;
596 if (check && check != dhcp_checksum(&packet, bytes))
599 memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
600 sizeof(packet.udp)));
602 if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
605 return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
608 static void ipv4ll_start(GDHCPClient *dhcp_client)
613 if (dhcp_client->timeout > 0) {
614 g_source_remove(dhcp_client->timeout);
615 dhcp_client->timeout = 0;
618 switch_listening_mode(dhcp_client, L_NONE);
619 dhcp_client->type = G_DHCP_IPV4LL;
620 dhcp_client->retry_times = 0;
621 dhcp_client->requested_ip = 0;
623 /*try to start with a based mac address ip*/
624 seed = (dhcp_client->mac_address[4] << 8 | dhcp_client->mac_address[4]);
625 dhcp_client->requested_ip = ipv4ll_random_ip(seed);
627 /*first wait a random delay to avoid storm of arp request on boot*/
628 timeout = ipv4ll_random_delay_ms(PROBE_WAIT);
630 dhcp_client->retry_times++;
631 dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
638 static void ipv4ll_stop(GDHCPClient *dhcp_client)
641 switch_listening_mode(dhcp_client, L_NONE);
643 if (dhcp_client->timeout > 0)
644 g_source_remove(dhcp_client->timeout);
646 if (dhcp_client->listener_watch > 0) {
647 g_source_remove(dhcp_client->listener_watch);
648 dhcp_client->listener_watch = 0;
651 dhcp_client->state = IPV4LL_PROBE;
652 dhcp_client->retry_times = 0;
653 dhcp_client->requested_ip = 0;
655 g_free(dhcp_client->assigned_ip);
656 dhcp_client->assigned_ip = NULL;
659 static int ipv4ll_recv_arp_packet(GDHCPClient *dhcp_client)
662 struct ether_arp arp;
663 uint32_t ip_requested;
667 memset(&arp, 0, sizeof(arp));
669 bytes = read(dhcp_client->listener_sockfd, &arp, sizeof(arp));
673 if (arp.arp_op != htons(ARPOP_REPLY) &&
674 arp.arp_op != htons(ARPOP_REQUEST))
677 ip_requested = ntohl(dhcp_client->requested_ip);
678 source_conflict = !memcmp(arp.arp_spa, &ip_requested,
679 sizeof(ip_requested));
681 target_conflict = !memcmp(arp.arp_tpa, &ip_requested,
682 sizeof(ip_requested));
684 if (!source_conflict && !target_conflict)
687 dhcp_client->conflicts++;
689 debug(dhcp_client, "IPV4LL conflict detected");
691 if (dhcp_client->state == IPV4LL_MONITOR) {
692 if (!source_conflict)
694 dhcp_client->state = IPV4LL_DEFEND;
695 debug(dhcp_client, "DEFEND mode conflicts : %d",
696 dhcp_client->conflicts);
697 /*Try to defend with a single announce*/
698 send_announce_packet(dhcp_client);
702 if (dhcp_client->state == IPV4LL_DEFEND) {
703 if (!source_conflict)
705 else if (dhcp_client->ipv4ll_lost_cb != NULL)
706 dhcp_client->ipv4ll_lost_cb(dhcp_client,
707 dhcp_client->ipv4ll_lost_data);
710 ipv4ll_stop(dhcp_client);
712 if (dhcp_client->conflicts < MAX_CONFLICTS) {
713 /*restart whole state machine*/
714 dhcp_client->retry_times++;
715 dhcp_client->timeout =
716 g_timeout_add_full(G_PRIORITY_HIGH,
717 ipv4ll_random_delay_ms(PROBE_WAIT),
722 /* Here we got a lot of conflicts, RFC3927 states that we have
723 * to wait RATE_LIMIT_INTERVAL before retrying,
724 * but we just report failure.
726 else if (dhcp_client->no_lease_cb != NULL)
727 dhcp_client->no_lease_cb(dhcp_client,
728 dhcp_client->no_lease_data);
733 static gboolean check_package_owner(GDHCPClient *dhcp_client,
734 struct dhcp_packet *packet)
736 if (packet->xid != dhcp_client->xid)
739 if (packet->hlen != 6)
742 if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
748 static void start_request(GDHCPClient *dhcp_client);
750 static gboolean request_timeout(gpointer user_data)
752 GDHCPClient *dhcp_client = user_data;
754 debug(dhcp_client, "request timeout (retries %d)",
755 dhcp_client->retry_times);
757 dhcp_client->retry_times++;
759 start_request(dhcp_client);
764 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
767 static int switch_listening_mode(GDHCPClient *dhcp_client,
768 ListenMode listen_mode)
770 GIOChannel *listener_channel;
773 debug(dhcp_client, "switch listening mode (%d ==> %d)",
774 dhcp_client->listen_mode, listen_mode);
776 if (dhcp_client->listen_mode == listen_mode)
779 if (dhcp_client->listen_mode != L_NONE) {
780 if (dhcp_client->listener_watch > 0)
781 g_source_remove(dhcp_client->listener_watch);
782 dhcp_client->listener_channel = NULL;
783 dhcp_client->listen_mode = L_NONE;
784 dhcp_client->listener_sockfd = -1;
785 dhcp_client->listener_watch = 0;
788 if (listen_mode == L_NONE)
791 if (listen_mode == L2)
792 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
793 else if (listen_mode == L3)
794 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
795 dhcp_client->interface);
796 else if (listen_mode == L_ARP)
797 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
801 if (listener_sockfd < 0)
804 listener_channel = g_io_channel_unix_new(listener_sockfd);
805 if (listener_channel == NULL) {
806 /* Failed to create listener channel */
807 close(listener_sockfd);
811 dhcp_client->listen_mode = listen_mode;
812 dhcp_client->listener_sockfd = listener_sockfd;
813 dhcp_client->listener_channel = listener_channel;
815 g_io_channel_set_close_on_unref(listener_channel, TRUE);
816 dhcp_client->listener_watch =
817 g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
818 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
819 listener_event, dhcp_client,
821 g_io_channel_unref(dhcp_client->listener_channel);
826 static void start_request(GDHCPClient *dhcp_client)
828 debug(dhcp_client, "start request (retries %d)",
829 dhcp_client->retry_times);
831 if (dhcp_client->retry_times == REQUEST_RETRIES) {
832 dhcp_client->state = INIT_SELECTING;
833 ipv4ll_start(dhcp_client);
838 if (dhcp_client->retry_times == 0) {
839 dhcp_client->state = REQUESTING;
840 switch_listening_mode(dhcp_client, L2);
843 send_select(dhcp_client);
845 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
852 static uint32_t get_lease(struct dhcp_packet *packet)
855 uint32_t lease_seconds;
857 option_u8 = dhcp_get_option(packet, DHCP_LEASE_TIME);
858 if (option_u8 == NULL)
861 lease_seconds = dhcp_get_unaligned((uint32_t *) option_u8);
862 lease_seconds = ntohl(lease_seconds);
863 /* paranoia: must not be prone to overflows */
864 lease_seconds &= 0x0fffffff;
865 if (lease_seconds < 10)
868 return lease_seconds;
871 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
873 debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
875 if (dhcp_client->timeout > 0) {
876 g_source_remove(dhcp_client->timeout);
877 dhcp_client->timeout = 0;
880 dhcp_client->retry_times = retry_times;
881 dhcp_client->requested_ip = 0;
882 switch_listening_mode(dhcp_client, L2);
884 g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
887 static gboolean start_rebound_timeout(gpointer user_data)
889 GDHCPClient *dhcp_client = user_data;
891 debug(dhcp_client, "start rebound timeout");
893 switch_listening_mode(dhcp_client, L2);
895 dhcp_client->lease_seconds >>= 1;
897 /* We need to have enough time to receive ACK package*/
898 if (dhcp_client->lease_seconds <= 6) {
900 /* ip need to be cleared */
901 if (dhcp_client->lease_lost_cb != NULL)
902 dhcp_client->lease_lost_cb(dhcp_client,
903 dhcp_client->lease_lost_data);
905 restart_dhcp(dhcp_client, 0);
907 send_rebound(dhcp_client);
909 dhcp_client->timeout =
910 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
911 dhcp_client->lease_seconds >> 1,
912 start_rebound_timeout,
920 static void start_rebound(GDHCPClient *dhcp_client)
922 debug(dhcp_client, "start rebound");
924 dhcp_client->state = REBINDING;
926 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
927 dhcp_client->lease_seconds >> 1,
928 start_rebound_timeout,
933 static gboolean start_renew_timeout(gpointer user_data)
935 GDHCPClient *dhcp_client = user_data;
937 debug(dhcp_client, "start renew timeout");
939 dhcp_client->state = RENEWING;
941 dhcp_client->lease_seconds >>= 1;
943 switch_listening_mode(dhcp_client, L3);
944 if (dhcp_client->lease_seconds <= 60)
945 start_rebound(dhcp_client);
947 send_renew(dhcp_client);
949 if (dhcp_client->timeout > 0)
950 g_source_remove(dhcp_client->timeout);
952 dhcp_client->timeout =
953 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
954 dhcp_client->lease_seconds >> 1,
963 static void start_bound(GDHCPClient *dhcp_client)
965 debug(dhcp_client, "start bound");
967 dhcp_client->state = BOUND;
969 if (dhcp_client->timeout > 0)
970 g_source_remove(dhcp_client->timeout);
972 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
973 dhcp_client->lease_seconds >> 1,
974 start_renew_timeout, dhcp_client,
978 static gboolean restart_dhcp_timeout(gpointer user_data)
980 GDHCPClient *dhcp_client = user_data;
982 debug(dhcp_client, "restart DHCP timeout");
984 dhcp_client->ack_retry_times++;
986 restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
991 static char *get_ip(uint32_t ip)
997 return g_strdup(inet_ntoa(addr));
1000 /* get a rough idea of how long an option will be */
1001 static const uint8_t len_of_option_as_string[] = {
1002 [OPTION_IP] = sizeof("255.255.255.255 "),
1003 [OPTION_STRING] = 1,
1004 [OPTION_U8] = sizeof("255 "),
1005 [OPTION_U16] = sizeof("65535 "),
1006 [OPTION_U32] = sizeof("4294967295 "),
1009 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
1011 return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
1014 /* Create "opt_value1 option_value2 ..." string */
1015 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
1017 unsigned upper_length;
1021 len = option[OPT_LEN - OPT_DATA];
1022 type &= OPTION_TYPE_MASK;
1023 optlen = dhcp_option_lengths[type];
1026 upper_length = len_of_option_as_string[type] *
1027 ((unsigned)len / (unsigned)optlen);
1028 dest = ret = malloc(upper_length + 1);
1032 while (len >= optlen) {
1035 dest += sprint_nip(dest, "", option);
1038 uint16_t val_u16 = dhcp_get_unaligned(
1039 (uint16_t *) option);
1040 dest += sprintf(dest, "%u", ntohs(val_u16));
1044 uint32_t val_u32 = dhcp_get_unaligned(
1045 (uint32_t *) option);
1046 dest += sprintf(dest, type == OPTION_U32 ? "%lu" :
1047 "%ld", (unsigned long) ntohl(val_u32));
1051 memcpy(dest, option, len);
1068 static GList *get_option_value_list(char *value, GDHCPOptionType type)
1076 if (type == OPTION_STRING)
1077 return g_list_append(list, g_strdup(value));
1079 while ((pos = strchr(pos, ' ')) != NULL) {
1082 list = g_list_append(list, g_strdup(value));
1087 list = g_list_append(list, g_strdup(value));
1092 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
1094 GDHCPOptionType type;
1095 GList *list, *value_list;
1100 for (list = dhcp_client->request_list; list; list = list->next) {
1101 code = (uint8_t) GPOINTER_TO_INT(list->data);
1103 option = dhcp_get_option(packet, code);
1104 if (option == NULL) {
1105 g_hash_table_remove(dhcp_client->code_value_hash,
1106 GINT_TO_POINTER((int) code));
1110 type = dhcp_get_code_type(code);
1112 option_value = malloc_option_value_string(option, type);
1113 if (option_value == NULL)
1114 g_hash_table_remove(dhcp_client->code_value_hash,
1115 GINT_TO_POINTER((int) code));
1117 value_list = get_option_value_list(option_value, type);
1119 g_free(option_value);
1121 if (value_list == NULL)
1122 g_hash_table_remove(dhcp_client->code_value_hash,
1123 GINT_TO_POINTER((int) code));
1125 g_hash_table_insert(dhcp_client->code_value_hash,
1126 GINT_TO_POINTER((int) code), value_list);
1130 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1133 GDHCPClient *dhcp_client = user_data;
1134 struct dhcp_packet packet;
1135 uint8_t *message_type, *option_u8;
1138 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1139 dhcp_client->listener_watch = 0;
1143 if (dhcp_client->listen_mode == L_NONE)
1146 if (dhcp_client->listen_mode == L2)
1147 re = dhcp_recv_l2_packet(&packet, dhcp_client->listener_sockfd);
1148 else if (dhcp_client->listen_mode == L3)
1149 re = dhcp_recv_l3_packet(&packet, dhcp_client->listener_sockfd);
1150 else if (dhcp_client->listen_mode == L_ARP) {
1151 re = ipv4ll_recv_arp_packet(dhcp_client);
1160 if (check_package_owner(dhcp_client, &packet) == FALSE)
1163 message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
1164 if (message_type == NULL)
1165 /* No message type option, ignore package */
1168 debug(dhcp_client, "received DHCP packet (current state %d)",
1169 dhcp_client->state);
1171 switch (dhcp_client->state) {
1172 case INIT_SELECTING:
1173 if (*message_type != DHCPOFFER)
1176 g_source_remove(dhcp_client->timeout);
1177 dhcp_client->timeout = 0;
1178 dhcp_client->retry_times = 0;
1180 option_u8 = dhcp_get_option(&packet, DHCP_SERVER_ID);
1181 dhcp_client->server_ip =
1182 dhcp_get_unaligned((uint32_t *) option_u8);
1183 dhcp_client->requested_ip = packet.yiaddr;
1185 dhcp_client->state = REQUESTING;
1187 start_request(dhcp_client);
1193 if (*message_type == DHCPACK) {
1194 dhcp_client->retry_times = 0;
1196 if (dhcp_client->timeout > 0)
1197 g_source_remove(dhcp_client->timeout);
1198 dhcp_client->timeout = 0;
1200 dhcp_client->lease_seconds = get_lease(&packet);
1202 get_request(dhcp_client, &packet);
1204 switch_listening_mode(dhcp_client, L_NONE);
1206 g_free(dhcp_client->assigned_ip);
1207 dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1209 /* Address should be set up here */
1210 if (dhcp_client->lease_available_cb != NULL)
1211 dhcp_client->lease_available_cb(dhcp_client,
1212 dhcp_client->lease_available_data);
1214 start_bound(dhcp_client);
1215 } else if (*message_type == DHCPNAK) {
1216 dhcp_client->retry_times = 0;
1218 if (dhcp_client->timeout > 0)
1219 g_source_remove(dhcp_client->timeout);
1221 dhcp_client->timeout = g_timeout_add_seconds_full(
1223 restart_dhcp_timeout,
1233 debug(dhcp_client, "processed DHCP packet (new state %d)",
1234 dhcp_client->state);
1239 static gboolean discover_timeout(gpointer user_data)
1241 GDHCPClient *dhcp_client = user_data;
1243 dhcp_client->retry_times++;
1246 * We do not send the REQUESTED IP option if we are retrying because
1247 * if the server is non-authoritative it will ignore the request if the
1248 * option is present.
1250 g_dhcp_client_start(dhcp_client, NULL);
1255 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
1257 GDHCPClient *dhcp_client = dhcp_data;
1259 debug(dhcp_client, "back to MONITOR mode");
1261 dhcp_client->conflicts = 0;
1262 dhcp_client->state = IPV4LL_MONITOR;
1267 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
1269 GDHCPClient *dhcp_client = dhcp_data;
1272 debug(dhcp_client, "request timeout (retries %d)",
1273 dhcp_client->retry_times);
1275 if (dhcp_client->retry_times != ANNOUNCE_NUM){
1276 dhcp_client->retry_times++;
1277 send_announce_packet(dhcp_client);
1281 ip = htonl(dhcp_client->requested_ip);
1282 debug(dhcp_client, "switching to monitor mode");
1283 dhcp_client->state = IPV4LL_MONITOR;
1284 dhcp_client->assigned_ip = get_ip(ip);
1286 if (dhcp_client->ipv4ll_available_cb != NULL)
1287 dhcp_client->ipv4ll_available_cb(dhcp_client,
1288 dhcp_client->ipv4ll_available_data);
1289 dhcp_client->conflicts = 0;
1294 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
1297 GDHCPClient *dhcp_client = dhcp_data;
1299 debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
1300 dhcp_client->retry_times);
1302 if (dhcp_client->retry_times == PROBE_NUM) {
1303 dhcp_client->state = IPV4LL_ANNOUNCE;
1304 dhcp_client->retry_times = 0;
1306 dhcp_client->retry_times++;
1307 send_announce_packet(dhcp_client);
1310 dhcp_client->retry_times++;
1311 send_probe_packet(dhcp_client);
1316 int g_dhcp_client_start(GDHCPClient *dhcp_client, const char *last_address)
1321 if (dhcp_client->retry_times == DISCOVER_RETRIES) {
1322 ipv4ll_start(dhcp_client);
1326 if (dhcp_client->retry_times == 0) {
1327 g_free(dhcp_client->assigned_ip);
1328 dhcp_client->assigned_ip = NULL;
1330 dhcp_client->state = INIT_SELECTING;
1331 re = switch_listening_mode(dhcp_client, L2);
1335 dhcp_client->xid = rand();
1338 if (last_address == NULL) {
1341 addr = inet_addr(last_address);
1342 if (addr == 0xFFFFFFFF) {
1345 g_free(dhcp_client->last_address);
1346 dhcp_client->last_address = g_strdup(last_address);
1349 send_discover(dhcp_client, addr);
1351 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1359 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
1361 switch_listening_mode(dhcp_client, L_NONE);
1363 if (dhcp_client->state == BOUND ||
1364 dhcp_client->state == RENEWING ||
1365 dhcp_client->state == REBINDING)
1366 send_release(dhcp_client, dhcp_client->server_ip,
1367 dhcp_client->requested_ip);
1369 if (dhcp_client->timeout > 0) {
1370 g_source_remove(dhcp_client->timeout);
1371 dhcp_client->timeout = 0;
1374 if (dhcp_client->listener_watch > 0) {
1375 g_source_remove(dhcp_client->listener_watch);
1376 dhcp_client->listener_watch = 0;
1379 dhcp_client->listener_channel = NULL;
1381 dhcp_client->retry_times = 0;
1382 dhcp_client->ack_retry_times = 0;
1384 dhcp_client->requested_ip = 0;
1385 dhcp_client->state = RELEASED;
1386 dhcp_client->lease_seconds = 0;
1389 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
1390 unsigned char option_code)
1392 return g_hash_table_lookup(dhcp_client->code_value_hash,
1393 GINT_TO_POINTER((int) option_code));
1396 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
1397 GDHCPClientEvent event,
1398 GDHCPClientEventFunc func,
1402 case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
1403 dhcp_client->lease_available_cb = func;
1404 dhcp_client->lease_available_data = data;
1406 case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
1407 dhcp_client->ipv4ll_available_cb = func;
1408 dhcp_client->ipv4ll_available_data = data;
1410 case G_DHCP_CLIENT_EVENT_NO_LEASE:
1411 dhcp_client->no_lease_cb = func;
1412 dhcp_client->no_lease_data = data;
1414 case G_DHCP_CLIENT_EVENT_LEASE_LOST:
1415 dhcp_client->lease_lost_cb = func;
1416 dhcp_client->lease_lost_data = data;
1418 case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
1419 dhcp_client->ipv4ll_lost_cb = func;
1420 dhcp_client->ipv4ll_lost_data = data;
1422 case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
1423 dhcp_client->address_conflict_cb = func;
1424 dhcp_client->address_conflict_data = data;
1429 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
1431 return dhcp_client->ifindex;
1434 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
1436 return g_strdup(dhcp_client->assigned_ip);
1439 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
1441 GList *option = NULL;
1443 switch (dhcp_client->state) {
1445 case IPV4LL_MONITOR:
1446 return g_strdup("255.255.0.0");
1450 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
1452 return g_strdup(option->data);
1453 case INIT_SELECTING:
1457 case IPV4LL_ANNOUNCE:
1463 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
1464 unsigned char option_code)
1466 if (g_list_find(dhcp_client->request_list,
1467 GINT_TO_POINTER((int) option_code)) == NULL)
1468 dhcp_client->request_list = g_list_prepend(
1469 dhcp_client->request_list,
1470 (GINT_TO_POINTER((int) option_code)));
1472 return G_DHCP_CLIENT_ERROR_NONE;
1475 static uint8_t *alloc_dhcp_option(int code, const char *str, int extra)
1478 int len = strnlen(str, 255);
1480 storage = malloc(len + extra + OPT_DATA);
1481 storage[OPT_CODE] = code;
1482 storage[OPT_LEN] = len + extra;
1483 memcpy(storage + extra + OPT_DATA, str, len);
1488 /* Now only support send hostname */
1489 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
1490 unsigned char option_code, const char *option_value)
1492 uint8_t *binary_option;
1494 if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
1495 binary_option = alloc_dhcp_option(option_code,
1498 g_hash_table_insert(dhcp_client->send_value_hash,
1499 GINT_TO_POINTER((int) option_code), binary_option);
1502 return G_DHCP_CLIENT_ERROR_NONE;
1505 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
1507 if (dhcp_client == NULL)
1510 __sync_fetch_and_add(&dhcp_client->ref_count, 1);
1515 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
1517 if (dhcp_client == NULL)
1520 if (__sync_fetch_and_sub(&dhcp_client->ref_count, 1) != 1)
1523 g_dhcp_client_stop(dhcp_client);
1525 g_free(dhcp_client->interface);
1526 g_free(dhcp_client->assigned_ip);
1527 g_free(dhcp_client->last_address);
1529 g_list_free(dhcp_client->request_list);
1530 g_list_free(dhcp_client->require_list);
1532 g_hash_table_destroy(dhcp_client->code_value_hash);
1533 g_hash_table_destroy(dhcp_client->send_value_hash);
1535 g_free(dhcp_client);
1538 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
1539 GDHCPDebugFunc func, gpointer user_data)
1541 if (dhcp_client == NULL)
1544 dhcp_client->debug_func = func;
1545 dhcp_client->debug_data = user_data;