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 g_source_remove(dhcp_client->listener_watch);
781 dhcp_client->listener_channel = NULL;
782 dhcp_client->listen_mode = L_NONE;
783 dhcp_client->listener_sockfd = -1;
784 dhcp_client->listener_watch = 0;
787 if (listen_mode == L_NONE)
790 if (listen_mode == L2)
791 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
792 else if (listen_mode == L3)
793 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
794 dhcp_client->interface);
795 else if (listen_mode == L_ARP)
796 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
800 if (listener_sockfd < 0)
803 listener_channel = g_io_channel_unix_new(listener_sockfd);
804 if (listener_channel == NULL) {
805 /* Failed to create listener channel */
806 close(listener_sockfd);
810 dhcp_client->listen_mode = listen_mode;
811 dhcp_client->listener_sockfd = listener_sockfd;
812 dhcp_client->listener_channel = listener_channel;
814 g_io_channel_set_close_on_unref(listener_channel, TRUE);
815 dhcp_client->listener_watch =
816 g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
817 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
818 listener_event, dhcp_client,
820 g_io_channel_unref(dhcp_client->listener_channel);
825 static void start_request(GDHCPClient *dhcp_client)
827 debug(dhcp_client, "start request (retries %d)",
828 dhcp_client->retry_times);
830 if (dhcp_client->retry_times == REQUEST_RETRIES) {
831 dhcp_client->state = INIT_SELECTING;
832 ipv4ll_start(dhcp_client);
837 if (dhcp_client->retry_times == 0) {
838 dhcp_client->state = REQUESTING;
839 switch_listening_mode(dhcp_client, L2);
842 send_select(dhcp_client);
844 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
851 static uint32_t get_lease(struct dhcp_packet *packet)
854 uint32_t lease_seconds;
856 option_u8 = dhcp_get_option(packet, DHCP_LEASE_TIME);
857 if (option_u8 == NULL)
860 lease_seconds = dhcp_get_unaligned((uint32_t *) option_u8);
861 lease_seconds = ntohl(lease_seconds);
862 /* paranoia: must not be prone to overflows */
863 lease_seconds &= 0x0fffffff;
864 if (lease_seconds < 10)
867 return lease_seconds;
870 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
872 debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
874 if (dhcp_client->timeout > 0) {
875 g_source_remove(dhcp_client->timeout);
876 dhcp_client->timeout = 0;
879 dhcp_client->retry_times = retry_times;
880 dhcp_client->requested_ip = 0;
881 switch_listening_mode(dhcp_client, L2);
883 g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
886 static gboolean start_rebound_timeout(gpointer user_data)
888 GDHCPClient *dhcp_client = user_data;
890 debug(dhcp_client, "start rebound timeout");
892 switch_listening_mode(dhcp_client, L2);
894 dhcp_client->lease_seconds >>= 1;
896 /* We need to have enough time to receive ACK package*/
897 if (dhcp_client->lease_seconds <= 6) {
899 /* ip need to be cleared */
900 if (dhcp_client->lease_lost_cb != NULL)
901 dhcp_client->lease_lost_cb(dhcp_client,
902 dhcp_client->lease_lost_data);
904 restart_dhcp(dhcp_client, 0);
906 send_rebound(dhcp_client);
908 dhcp_client->timeout =
909 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
910 dhcp_client->lease_seconds >> 1,
911 start_rebound_timeout,
919 static void start_rebound(GDHCPClient *dhcp_client)
921 debug(dhcp_client, "start rebound");
923 dhcp_client->state = REBINDING;
925 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
926 dhcp_client->lease_seconds >> 1,
927 start_rebound_timeout,
932 static gboolean start_renew_timeout(gpointer user_data)
934 GDHCPClient *dhcp_client = user_data;
936 debug(dhcp_client, "start renew timeout");
938 dhcp_client->state = RENEWING;
940 dhcp_client->lease_seconds >>= 1;
942 switch_listening_mode(dhcp_client, L3);
943 if (dhcp_client->lease_seconds <= 60)
944 start_rebound(dhcp_client);
946 send_renew(dhcp_client);
948 if (dhcp_client->timeout > 0)
949 g_source_remove(dhcp_client->timeout);
951 dhcp_client->timeout =
952 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
953 dhcp_client->lease_seconds >> 1,
962 static void start_bound(GDHCPClient *dhcp_client)
964 debug(dhcp_client, "start bound");
966 dhcp_client->state = BOUND;
968 if (dhcp_client->timeout > 0)
969 g_source_remove(dhcp_client->timeout);
971 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
972 dhcp_client->lease_seconds >> 1,
973 start_renew_timeout, dhcp_client,
977 static gboolean restart_dhcp_timeout(gpointer user_data)
979 GDHCPClient *dhcp_client = user_data;
981 debug(dhcp_client, "restart DHCP timeout");
983 dhcp_client->ack_retry_times++;
985 restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
990 static char *get_ip(uint32_t ip)
996 return g_strdup(inet_ntoa(addr));
999 /* get a rough idea of how long an option will be */
1000 static const uint8_t len_of_option_as_string[] = {
1001 [OPTION_IP] = sizeof("255.255.255.255 "),
1002 [OPTION_STRING] = 1,
1003 [OPTION_U8] = sizeof("255 "),
1004 [OPTION_U16] = sizeof("65535 "),
1005 [OPTION_U32] = sizeof("4294967295 "),
1008 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
1010 return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
1013 /* Create "opt_value1 option_value2 ..." string */
1014 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
1016 unsigned upper_length;
1020 len = option[OPT_LEN - OPT_DATA];
1021 type &= OPTION_TYPE_MASK;
1022 optlen = dhcp_option_lengths[type];
1025 upper_length = len_of_option_as_string[type] *
1026 ((unsigned)len / (unsigned)optlen);
1027 dest = ret = malloc(upper_length + 1);
1031 while (len >= optlen) {
1034 dest += sprint_nip(dest, "", option);
1037 uint16_t val_u16 = dhcp_get_unaligned(
1038 (uint16_t *) option);
1039 dest += sprintf(dest, "%u", ntohs(val_u16));
1043 uint32_t val_u32 = dhcp_get_unaligned(
1044 (uint32_t *) option);
1045 dest += sprintf(dest, type == OPTION_U32 ? "%lu" :
1046 "%ld", (unsigned long) ntohl(val_u32));
1050 memcpy(dest, option, len);
1067 static GList *get_option_value_list(char *value, GDHCPOptionType type)
1075 if (type == OPTION_STRING)
1076 return g_list_append(list, g_strdup(value));
1078 while ((pos = strchr(pos, ' ')) != NULL) {
1081 list = g_list_append(list, g_strdup(value));
1086 list = g_list_append(list, g_strdup(value));
1091 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
1093 GDHCPOptionType type;
1094 GList *list, *value_list;
1099 for (list = dhcp_client->request_list; list; list = list->next) {
1100 code = (uint8_t) GPOINTER_TO_INT(list->data);
1102 option = dhcp_get_option(packet, code);
1103 if (option == NULL) {
1104 g_hash_table_remove(dhcp_client->code_value_hash,
1105 GINT_TO_POINTER((int) code));
1109 type = dhcp_get_code_type(code);
1111 option_value = malloc_option_value_string(option, type);
1112 if (option_value == NULL)
1113 g_hash_table_remove(dhcp_client->code_value_hash,
1114 GINT_TO_POINTER((int) code));
1116 value_list = get_option_value_list(option_value, type);
1118 g_free(option_value);
1120 if (value_list == NULL)
1121 g_hash_table_remove(dhcp_client->code_value_hash,
1122 GINT_TO_POINTER((int) code));
1124 g_hash_table_insert(dhcp_client->code_value_hash,
1125 GINT_TO_POINTER((int) code), value_list);
1129 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1132 GDHCPClient *dhcp_client = user_data;
1133 struct dhcp_packet packet;
1134 uint8_t *message_type, *option_u8;
1137 if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
1138 dhcp_client->listener_watch = 0;
1142 if (dhcp_client->listen_mode == L_NONE)
1145 if (dhcp_client->listen_mode == L2)
1146 re = dhcp_recv_l2_packet(&packet, dhcp_client->listener_sockfd);
1147 else if (dhcp_client->listen_mode == L3)
1148 re = dhcp_recv_l3_packet(&packet, dhcp_client->listener_sockfd);
1149 else if (dhcp_client->listen_mode == L_ARP) {
1150 re = ipv4ll_recv_arp_packet(dhcp_client);
1159 if (check_package_owner(dhcp_client, &packet) == FALSE)
1162 message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
1163 if (message_type == NULL)
1164 /* No message type option, ignore package */
1167 debug(dhcp_client, "received DHCP packet (current state %d)",
1168 dhcp_client->state);
1170 switch (dhcp_client->state) {
1171 case INIT_SELECTING:
1172 if (*message_type != DHCPOFFER)
1175 g_source_remove(dhcp_client->timeout);
1176 dhcp_client->timeout = 0;
1177 dhcp_client->retry_times = 0;
1179 option_u8 = dhcp_get_option(&packet, DHCP_SERVER_ID);
1180 dhcp_client->server_ip =
1181 dhcp_get_unaligned((uint32_t *) option_u8);
1182 dhcp_client->requested_ip = packet.yiaddr;
1184 dhcp_client->state = REQUESTING;
1186 start_request(dhcp_client);
1192 if (*message_type == DHCPACK) {
1193 dhcp_client->retry_times = 0;
1195 if (dhcp_client->timeout > 0)
1196 g_source_remove(dhcp_client->timeout);
1197 dhcp_client->timeout = 0;
1199 dhcp_client->lease_seconds = get_lease(&packet);
1201 get_request(dhcp_client, &packet);
1203 switch_listening_mode(dhcp_client, L_NONE);
1205 g_free(dhcp_client->assigned_ip);
1206 dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1208 /* Address should be set up here */
1209 if (dhcp_client->lease_available_cb != NULL)
1210 dhcp_client->lease_available_cb(dhcp_client,
1211 dhcp_client->lease_available_data);
1213 start_bound(dhcp_client);
1214 } else if (*message_type == DHCPNAK) {
1215 dhcp_client->retry_times = 0;
1217 if (dhcp_client->timeout > 0)
1218 g_source_remove(dhcp_client->timeout);
1220 dhcp_client->timeout = g_timeout_add_seconds_full(
1222 restart_dhcp_timeout,
1232 debug(dhcp_client, "processed DHCP packet (new state %d)",
1233 dhcp_client->state);
1238 static gboolean discover_timeout(gpointer user_data)
1240 GDHCPClient *dhcp_client = user_data;
1242 dhcp_client->retry_times++;
1245 * We do not send the REQUESTED IP option if we are retrying because
1246 * if the server is non-authoritative it will ignore the request if the
1247 * option is present.
1249 g_dhcp_client_start(dhcp_client, NULL);
1254 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
1256 GDHCPClient *dhcp_client = dhcp_data;
1258 debug(dhcp_client, "back to MONITOR mode");
1260 dhcp_client->conflicts = 0;
1261 dhcp_client->state = IPV4LL_MONITOR;
1266 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
1268 GDHCPClient *dhcp_client = dhcp_data;
1271 debug(dhcp_client, "request timeout (retries %d)",
1272 dhcp_client->retry_times);
1274 if (dhcp_client->retry_times != ANNOUNCE_NUM){
1275 dhcp_client->retry_times++;
1276 send_announce_packet(dhcp_client);
1280 ip = htonl(dhcp_client->requested_ip);
1281 debug(dhcp_client, "switching to monitor mode");
1282 dhcp_client->state = IPV4LL_MONITOR;
1283 dhcp_client->assigned_ip = get_ip(ip);
1285 if (dhcp_client->ipv4ll_available_cb != NULL)
1286 dhcp_client->ipv4ll_available_cb(dhcp_client,
1287 dhcp_client->ipv4ll_available_data);
1288 dhcp_client->conflicts = 0;
1293 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
1296 GDHCPClient *dhcp_client = dhcp_data;
1298 debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
1299 dhcp_client->retry_times);
1301 if (dhcp_client->retry_times == PROBE_NUM) {
1302 dhcp_client->state = IPV4LL_ANNOUNCE;
1303 dhcp_client->retry_times = 0;
1305 dhcp_client->retry_times++;
1306 send_announce_packet(dhcp_client);
1309 dhcp_client->retry_times++;
1310 send_probe_packet(dhcp_client);
1315 int g_dhcp_client_start(GDHCPClient *dhcp_client, const char *last_address)
1320 if (dhcp_client->retry_times == DISCOVER_RETRIES) {
1321 ipv4ll_start(dhcp_client);
1325 if (dhcp_client->retry_times == 0) {
1326 g_free(dhcp_client->assigned_ip);
1327 dhcp_client->assigned_ip = NULL;
1329 dhcp_client->state = INIT_SELECTING;
1330 re = switch_listening_mode(dhcp_client, L2);
1334 dhcp_client->xid = rand();
1337 if (last_address == NULL) {
1340 addr = inet_addr(last_address);
1341 if (addr == 0xFFFFFFFF) {
1344 g_free(dhcp_client->last_address);
1345 dhcp_client->last_address = g_strdup(last_address);
1348 send_discover(dhcp_client, addr);
1350 dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1358 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
1360 switch_listening_mode(dhcp_client, L_NONE);
1362 if (dhcp_client->state == BOUND ||
1363 dhcp_client->state == RENEWING ||
1364 dhcp_client->state == REBINDING)
1365 send_release(dhcp_client, dhcp_client->server_ip,
1366 dhcp_client->requested_ip);
1368 if (dhcp_client->timeout > 0) {
1369 g_source_remove(dhcp_client->timeout);
1370 dhcp_client->timeout = 0;
1373 if (dhcp_client->listener_watch > 0) {
1374 g_source_remove(dhcp_client->listener_watch);
1375 dhcp_client->listener_watch = 0;
1378 dhcp_client->listener_channel = NULL;
1380 dhcp_client->retry_times = 0;
1381 dhcp_client->ack_retry_times = 0;
1383 dhcp_client->requested_ip = 0;
1384 dhcp_client->state = RELEASED;
1385 dhcp_client->lease_seconds = 0;
1388 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
1389 unsigned char option_code)
1391 return g_hash_table_lookup(dhcp_client->code_value_hash,
1392 GINT_TO_POINTER((int) option_code));
1395 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
1396 GDHCPClientEvent event,
1397 GDHCPClientEventFunc func,
1401 case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
1402 dhcp_client->lease_available_cb = func;
1403 dhcp_client->lease_available_data = data;
1405 case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
1406 dhcp_client->ipv4ll_available_cb = func;
1407 dhcp_client->ipv4ll_available_data = data;
1409 case G_DHCP_CLIENT_EVENT_NO_LEASE:
1410 dhcp_client->no_lease_cb = func;
1411 dhcp_client->no_lease_data = data;
1413 case G_DHCP_CLIENT_EVENT_LEASE_LOST:
1414 dhcp_client->lease_lost_cb = func;
1415 dhcp_client->lease_lost_data = data;
1417 case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
1418 dhcp_client->ipv4ll_lost_cb = func;
1419 dhcp_client->ipv4ll_lost_data = data;
1421 case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
1422 dhcp_client->address_conflict_cb = func;
1423 dhcp_client->address_conflict_data = data;
1428 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
1430 return dhcp_client->ifindex;
1433 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
1435 return g_strdup(dhcp_client->assigned_ip);
1438 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
1440 GList *option = NULL;
1442 switch (dhcp_client->state) {
1444 case IPV4LL_MONITOR:
1445 return g_strdup("255.255.0.0");
1449 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
1451 return g_strdup(option->data);
1452 case INIT_SELECTING:
1456 case IPV4LL_ANNOUNCE:
1462 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
1463 unsigned char option_code)
1465 if (g_list_find(dhcp_client->request_list,
1466 GINT_TO_POINTER((int) option_code)) == NULL)
1467 dhcp_client->request_list = g_list_prepend(
1468 dhcp_client->request_list,
1469 (GINT_TO_POINTER((int) option_code)));
1471 return G_DHCP_CLIENT_ERROR_NONE;
1474 static uint8_t *alloc_dhcp_option(int code, const char *str, int extra)
1477 int len = strnlen(str, 255);
1479 storage = malloc(len + extra + OPT_DATA);
1480 storage[OPT_CODE] = code;
1481 storage[OPT_LEN] = len + extra;
1482 memcpy(storage + extra + OPT_DATA, str, len);
1487 /* Now only support send hostname */
1488 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
1489 unsigned char option_code, const char *option_value)
1491 uint8_t *binary_option;
1493 if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
1494 binary_option = alloc_dhcp_option(option_code,
1497 g_hash_table_insert(dhcp_client->send_value_hash,
1498 GINT_TO_POINTER((int) option_code), binary_option);
1501 return G_DHCP_CLIENT_ERROR_NONE;
1504 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
1506 if (dhcp_client == NULL)
1509 __sync_fetch_and_add(&dhcp_client->ref_count, 1);
1514 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
1516 if (dhcp_client == NULL)
1519 if (__sync_fetch_and_sub(&dhcp_client->ref_count, 1) != 1)
1522 g_dhcp_client_stop(dhcp_client);
1524 g_free(dhcp_client->interface);
1525 g_free(dhcp_client->assigned_ip);
1526 g_free(dhcp_client->last_address);
1528 g_list_free(dhcp_client->request_list);
1529 g_list_free(dhcp_client->require_list);
1531 g_hash_table_destroy(dhcp_client->code_value_hash);
1532 g_hash_table_destroy(dhcp_client->send_value_hash);
1534 g_free(dhcp_client);
1537 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
1538 GDHCPDebugFunc func, gpointer user_data)
1540 if (dhcp_client == NULL)
1543 dhcp_client->debug_func = func;
1544 dhcp_client->debug_data = user_data;