Remove unused timer code from DHCP library
[platform/upstream/connman.git] / gdhcp / client.c
1 /*
2  *
3  *  DHCP client library with GLib integration
4  *
5  *  Copyright (C) 2009-2010  Intel Corporation. All rights reserved.
6  *
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.
10  *
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.
15  *
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
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/ioctl.h>
32 #include <arpa/inet.h>
33
34 #include <netpacket/packet.h>
35 #include <net/ethernet.h>
36 #include <net/if_arp.h>
37
38 #include <linux/if.h>
39 #include <linux/filter.h>
40
41 #include <glib.h>
42
43 #include "gdhcp.h"
44 #include "common.h"
45
46 #define DISCOVER_TIMEOUT 3
47 #define DISCOVER_RETRIES 3
48
49 #define REQUEST_TIMEOUT 3
50 #define REQUEST_RETRIES 3
51
52 typedef enum _listen_mode {
53         L_NONE,
54         L2,
55         L3,
56 } ListenMode;
57
58 typedef enum _dhcp_client_state {
59         INIT_SELECTING,
60         REQUESTING,
61         BOUND,
62         RENEWING,
63         REBINDING,
64         RELEASED,
65 } ClientState;
66
67 struct _GDHCPClient {
68         gint ref_count;
69         GDHCPType type;
70         ClientState state;
71         int ifindex;
72         char *interface;
73         uint8_t mac_address[6];
74         uint32_t xid;
75         uint32_t server_ip;
76         uint32_t requested_ip;
77         char *assigned_ip;
78         uint32_t lease_seconds;
79         ListenMode listen_mode;
80         int listener_sockfd;
81         uint8_t retry_times;
82         uint8_t ack_retry_times;
83         guint timeout;
84         guint listener_watch;
85         GIOChannel *listener_channel;
86         GList *require_list;
87         GList *request_list;
88         GHashTable *code_value_hash;
89         GHashTable *send_value_hash;
90         GDHCPClientEventFunc lease_available_cb;
91         gpointer lease_available_data;
92         GDHCPClientEventFunc no_lease_cb;
93         gpointer no_lease_data;
94         GDHCPClientEventFunc lease_lost_cb;
95         gpointer lease_lost_data;
96         GDHCPClientEventFunc address_conflict_cb;
97         gpointer address_conflict_data;
98         GDHCPDebugFunc debug_func;
99         gpointer debug_data;
100 };
101
102 static inline void debug(GDHCPClient *client, const char *format, ...)
103 {
104         char str[256];
105         va_list ap;
106
107         if (client->debug_func == NULL)
108                 return;
109
110         va_start(ap, format);
111
112         if (vsnprintf(str, sizeof(str), format, ap) > 0)
113                 client->debug_func(str, client->debug_data);
114
115         va_end(ap);
116 }
117
118 /* Initialize the packet with the proper defaults */
119 static void init_packet(GDHCPClient *dhcp_client,
120                 struct dhcp_packet *packet, char type)
121 {
122         dhcp_init_header(packet, type);
123
124         memcpy(packet->chaddr, dhcp_client->mac_address, 6);
125 }
126
127 static void add_request_options(GDHCPClient *dhcp_client,
128                                 struct dhcp_packet *packet)
129 {
130         int len = 0;
131         GList *list;
132         uint8_t code;
133         int end = dhcp_end_option(packet->options);
134
135         for (list = dhcp_client->request_list; list; list = list->next) {
136                 code = (uint8_t) GPOINTER_TO_INT(list->data);
137
138                 packet->options[end + OPT_DATA + len] = code;
139                 len++;
140         }
141
142         if (len) {
143                 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
144                 packet->options[end + OPT_LEN] = len;
145                 packet->options[end + OPT_DATA + len] = DHCP_END;
146         }
147 }
148
149 static void add_binary_option(gpointer key, gpointer value, gpointer user_data)
150 {
151         uint8_t *option = value;
152         struct dhcp_packet *packet = user_data;
153
154         dhcp_add_binary_option(packet, option);
155 }
156
157 static void add_send_options(GDHCPClient *dhcp_client,
158                                 struct dhcp_packet *packet)
159 {
160         g_hash_table_foreach(dhcp_client->send_value_hash,
161                                 add_binary_option, packet);
162 }
163
164 static int send_discover(GDHCPClient *dhcp_client, uint32_t requested)
165 {
166         struct dhcp_packet packet;
167
168         debug(dhcp_client, "sending DHCP discover request");
169
170         init_packet(dhcp_client, &packet, DHCPDISCOVER);
171
172         packet.xid = dhcp_client->xid;
173
174         if (requested)
175                 dhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
176
177         /* Explicitly saying that we want RFC-compliant packets helps
178          * some buggy DHCP servers to NOT send bigger packets */
179         dhcp_add_simple_option(&packet, DHCP_MAX_SIZE, htons(576));
180
181         add_request_options(dhcp_client, &packet);
182
183         add_send_options(dhcp_client, &packet);
184
185         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
186                                         INADDR_BROADCAST, SERVER_PORT,
187                                         MAC_BCAST_ADDR, dhcp_client->ifindex);
188 }
189
190 static int send_select(GDHCPClient *dhcp_client)
191 {
192         struct dhcp_packet packet;
193         struct in_addr addr;
194
195         debug(dhcp_client, "sending DHCP select request");
196
197         init_packet(dhcp_client, &packet, DHCPREQUEST);
198
199         packet.xid = dhcp_client->xid;
200
201         dhcp_add_simple_option(&packet, DHCP_REQUESTED_IP,
202                                         dhcp_client->requested_ip);
203         dhcp_add_simple_option(&packet, DHCP_SERVER_ID, dhcp_client->server_ip);
204
205         add_request_options(dhcp_client, &packet);
206
207         add_send_options(dhcp_client, &packet);
208
209         addr.s_addr = dhcp_client->requested_ip;
210
211         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
212                                         INADDR_BROADCAST, SERVER_PORT,
213                                         MAC_BCAST_ADDR, dhcp_client->ifindex);
214 }
215
216 static int send_renew(GDHCPClient *dhcp_client)
217 {
218         struct dhcp_packet packet;
219
220         debug(dhcp_client, "sending DHCP renew request");
221
222         init_packet(dhcp_client , &packet, DHCPREQUEST);
223         packet.xid = dhcp_client->xid;
224         packet.ciaddr = dhcp_client->requested_ip;
225
226         add_request_options(dhcp_client, &packet);
227
228         add_send_options(dhcp_client, &packet);
229
230         return dhcp_send_kernel_packet(&packet,
231                 dhcp_client->requested_ip, CLIENT_PORT,
232                 dhcp_client->server_ip, SERVER_PORT);
233 }
234
235 static int send_rebound(GDHCPClient *dhcp_client)
236 {
237         struct dhcp_packet packet;
238
239         debug(dhcp_client, "sending DHCP rebound request");
240
241         init_packet(dhcp_client , &packet, DHCPREQUEST);
242         packet.xid = dhcp_client->xid;
243         packet.ciaddr = dhcp_client->requested_ip;
244
245         add_request_options(dhcp_client, &packet);
246
247         add_send_options(dhcp_client, &packet);
248
249         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
250                                         INADDR_BROADCAST, SERVER_PORT,
251                                         MAC_BCAST_ADDR, dhcp_client->ifindex);
252 }
253
254 static int send_release(GDHCPClient *dhcp_client,
255                         uint32_t server, uint32_t ciaddr)
256 {
257         struct dhcp_packet packet;
258
259         debug(dhcp_client, "sending DHCP release request");
260
261         init_packet(dhcp_client, &packet, DHCPRELEASE);
262         packet.xid = rand();
263         packet.ciaddr = ciaddr;
264
265         dhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
266
267         return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
268                                                 server, SERVER_PORT);
269 }
270
271 static gboolean interface_is_up(int index)
272 {
273         int sk, err;
274         struct ifreq ifr;
275         gboolean ret = FALSE;
276
277         sk = socket(PF_INET, SOCK_DGRAM, 0);
278         if (sk < 0) {
279                 perror("Open socket error");
280                 return FALSE;
281         }
282
283         memset(&ifr, 0, sizeof(ifr));
284         ifr.ifr_ifindex = index;
285
286         err = ioctl(sk, SIOCGIFNAME, &ifr);
287         if (err < 0) {
288                 perror("Get interface name error");
289                 goto done;
290         }
291
292         err = ioctl(sk, SIOCGIFFLAGS, &ifr);
293         if (err < 0) {
294                 perror("Get interface flags error");
295                 goto done;
296         }
297
298         if (ifr.ifr_flags & IFF_UP)
299                 ret = TRUE;
300
301 done:
302         close(sk);
303
304         return ret;
305 }
306
307 static char *get_interface_name(int index)
308 {
309         struct ifreq ifr;
310         int sk, err;
311
312         if (index < 0)
313                 return NULL;
314
315         sk = socket(PF_INET, SOCK_DGRAM, 0);
316         if (sk < 0) {
317                 perror("Open socket error");
318                 return NULL;
319         }
320
321         memset(&ifr, 0, sizeof(ifr));
322         ifr.ifr_ifindex = index;
323
324         err = ioctl(sk, SIOCGIFNAME, &ifr);
325         if (err < 0) {
326                 perror("Get interface name error");
327                 close(sk);
328                 return NULL;
329         }
330
331         close(sk);
332
333         return g_strdup(ifr.ifr_name);
334 }
335
336 static void get_interface_mac_address(int index, uint8_t *mac_address)
337 {
338         struct ifreq ifr;
339         int sk, err;
340
341         sk = socket(PF_INET, SOCK_DGRAM, 0);
342         if (sk < 0) {
343                 perror("Open socket error");
344                 return;
345         }
346
347         memset(&ifr, 0, sizeof(ifr));
348         ifr.ifr_ifindex = index;
349
350         err = ioctl(sk, SIOCGIFNAME, &ifr);
351         if (err < 0) {
352                 perror("Get interface name error");
353                 goto done;
354         }
355
356         err = ioctl(sk, SIOCGIFHWADDR, &ifr);
357         if (err < 0) {
358                 perror("Get mac address error");
359                 goto done;
360         }
361
362         memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
363
364 done:
365         close(sk);
366 }
367
368 static void remove_value(gpointer data, gpointer user_data)
369 {
370         char *value = data;
371         g_free(value);
372 }
373
374 static void remove_option_value(gpointer data)
375 {
376         GList *option_value = data;
377
378         g_list_foreach(option_value, remove_value, NULL);
379 }
380
381 GDHCPClient *g_dhcp_client_new(GDHCPType type,
382                         int ifindex, GDHCPClientError *error)
383 {
384         GDHCPClient *dhcp_client;
385
386         if (ifindex < 0) {
387                 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
388                 return NULL;
389         }
390
391         dhcp_client = g_try_new0(GDHCPClient, 1);
392         if (dhcp_client == NULL) {
393                 *error = G_DHCP_CLIENT_ERROR_NOMEM;
394                 return NULL;
395         }
396
397         dhcp_client->interface = get_interface_name(ifindex);
398         if (dhcp_client->interface == NULL) {
399                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
400                 goto error;
401         }
402
403         if (interface_is_up(ifindex) == FALSE) {
404                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
405                 goto error;
406         }
407
408         get_interface_mac_address(ifindex, dhcp_client->mac_address);
409
410         dhcp_client->listener_sockfd = -1;
411         dhcp_client->listener_channel = NULL;
412         dhcp_client->listen_mode = L_NONE;
413         dhcp_client->ref_count = 1;
414         dhcp_client->type = type;
415         dhcp_client->ifindex = ifindex;
416         dhcp_client->lease_available_cb = NULL;
417         dhcp_client->no_lease_cb = NULL;
418         dhcp_client->lease_lost_cb = NULL;
419         dhcp_client->address_conflict_cb = NULL;
420         dhcp_client->listener_watch = 0;
421         dhcp_client->retry_times = 0;
422         dhcp_client->ack_retry_times = 0;
423         dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
424                                 g_direct_equal, NULL, remove_option_value);
425         dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
426                                 g_direct_equal, NULL, g_free);
427         dhcp_client->request_list = NULL;
428         dhcp_client->require_list = NULL;
429
430         *error = G_DHCP_CLIENT_ERROR_NONE;
431
432         return dhcp_client;
433
434 error:
435         g_free(dhcp_client->interface);
436         g_free(dhcp_client);
437         return NULL;
438 }
439
440 #define SERVER_AND_CLIENT_PORTS  ((67 << 16) + 68)
441
442 static int dhcp_l2_socket(int ifindex)
443 {
444         int fd;
445         struct sockaddr_ll sock;
446
447         /*
448          * Comment:
449          *
450          *      I've selected not to see LL header, so BPF doesn't see it, too.
451          *      The filter may also pass non-IP and non-ARP packets, but we do
452          *      a more complete check when receiving the message in userspace.
453          *
454          * and filter shamelessly stolen from:
455          *
456          *      http://www.flamewarmaster.de/software/dhcpclient/
457          *
458          * There are a few other interesting ideas on that page (look under
459          * "Motivation").  Use of netlink events is most interesting.  Think
460          * of various network servers listening for events and reconfiguring.
461          * That would obsolete sending HUP signals and/or make use of restarts.
462          *
463          * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
464          * License: GPL v2.
465          *
466          * TODO: make conditional?
467          */
468         static const struct sock_filter filter_instr[] = {
469                 /* check for udp */
470                 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
471                 /* L5, L1, is UDP? */
472                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
473                 /* ugly check for arp on ethernet-like and IPv4 */
474                 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
475                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
476                 /* skip IP header */
477                 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
478                 /* check udp source and destination ports */
479                 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
480                 /* L3, L4 */
481                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
482                 /* returns */
483                 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
484                 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
485         };
486
487         static const struct sock_fprog filter_prog = {
488                 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
489                 /* casting const away: */
490                 .filter = (struct sock_filter *) filter_instr,
491         };
492
493         fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
494         if (fd < 0)
495                 return fd;
496
497         if (SERVER_PORT == 67 && CLIENT_PORT == 68)
498                 /* Use only if standard ports are in use */
499                 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
500                                                         sizeof(filter_prog));
501
502         sock.sll_family = AF_PACKET;
503         sock.sll_protocol = htons(ETH_P_IP);
504         sock.sll_ifindex = ifindex;
505
506         if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
507                 close(fd);
508                 return -errno;
509         }
510
511         return fd;
512 }
513
514 static gboolean sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
515 {
516         if (packet->ip.protocol != IPPROTO_UDP)
517                 return FALSE;
518
519         if (packet->ip.version != IPVERSION)
520                 return FALSE;
521
522         if (packet->ip.ihl != sizeof(packet->ip) >> 2)
523                 return FALSE;
524
525         if (packet->udp.dest != htons(CLIENT_PORT))
526                 return FALSE;
527
528         if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
529                 return FALSE;
530
531         return TRUE;
532 }
533
534 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd)
535 {
536         int bytes;
537         struct ip_udp_dhcp_packet packet;
538         uint16_t check;
539
540         memset(&packet, 0, sizeof(packet));
541
542         bytes = read(fd, &packet, sizeof(packet));
543         if (bytes < 0)
544                 return -1;
545
546         if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
547                 return -1;
548
549         if (bytes < ntohs(packet.ip.tot_len))
550                 /* packet is bigger than sizeof(packet), we did partial read */
551                 return -1;
552
553         /* ignore any extra garbage bytes */
554         bytes = ntohs(packet.ip.tot_len);
555
556         if (sanity_check(&packet, bytes) == FALSE)
557                 return -1;
558
559         check = packet.ip.check;
560         packet.ip.check = 0;
561         if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
562                 return -1;
563
564         /* verify UDP checksum. IP header has to be modified for this */
565         memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
566         /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
567         packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
568         check = packet.udp.check;
569         packet.udp.check = 0;
570         if (check && check != dhcp_checksum(&packet, bytes))
571                 return -1;
572
573         memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
574                                                         sizeof(packet.udp)));
575
576         if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
577                 return -1;
578
579         return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
580 }
581
582 static gboolean check_package_owner(GDHCPClient *dhcp_client,
583                                         struct dhcp_packet *packet)
584 {
585         if (packet->xid != dhcp_client->xid)
586                 return FALSE;
587
588         if (packet->hlen != 6)
589                 return FALSE;
590
591         if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
592                 return FALSE;
593
594         return TRUE;
595 }
596
597 static void start_request(GDHCPClient *dhcp_client);
598
599 static gboolean request_timeout(gpointer user_data)
600 {
601         GDHCPClient *dhcp_client = user_data;
602
603         dhcp_client->retry_times++;
604
605         start_request(dhcp_client);
606
607         return FALSE;
608 }
609
610 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
611                                                         gpointer user_data);
612
613 static int switch_listening_mode(GDHCPClient *dhcp_client,
614                                         ListenMode listen_mode)
615 {
616         GIOChannel *listener_channel;
617         int listener_sockfd;
618
619         if (dhcp_client->listen_mode == listen_mode)
620                 return 0;
621
622         if (dhcp_client->listen_mode != L_NONE) {
623                 g_source_remove(dhcp_client->listener_watch);
624                 dhcp_client->listener_channel = NULL;
625                 dhcp_client->listen_mode = L_NONE;
626                 dhcp_client->listener_sockfd = -1;
627                 dhcp_client->listener_watch = 0;
628         }
629
630         if (listen_mode == L_NONE)
631                 return 0;
632
633         if (listen_mode == L2)
634                 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
635         else if (listen_mode == L3)
636                 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
637                                                 dhcp_client->interface);
638         else
639                 return -EIO;
640
641         if (listener_sockfd < 0)
642                 return -EIO;
643
644         listener_channel = g_io_channel_unix_new(listener_sockfd);
645         if (listener_channel == NULL) {
646                 /* Failed to create listener channel */
647                 close(listener_sockfd);
648                 return -EIO;
649         }
650
651         dhcp_client->listen_mode = listen_mode;
652         dhcp_client->listener_sockfd = listener_sockfd;
653         dhcp_client->listener_channel = listener_channel;
654
655         g_io_channel_set_close_on_unref(listener_channel, TRUE);
656         dhcp_client->listener_watch =
657                         g_io_add_watch_full(listener_channel,
658                                                 G_PRIORITY_HIGH, G_IO_IN,
659                                                 listener_event, dhcp_client,
660                                                                 NULL);
661         g_io_channel_unref(dhcp_client->listener_channel);
662
663         return 0;
664 }
665
666 static void start_request(GDHCPClient *dhcp_client)
667 {
668         if (dhcp_client->retry_times == REQUEST_RETRIES) {
669                 dhcp_client->state = INIT_SELECTING;
670
671                 if (dhcp_client->no_lease_cb != NULL)
672                         dhcp_client->no_lease_cb(dhcp_client,
673                                         dhcp_client->no_lease_data);
674
675                 return;
676         }
677
678         if (dhcp_client->retry_times == 0) {
679                 dhcp_client->state = REQUESTING;
680                 switch_listening_mode(dhcp_client, L2);
681         }
682
683         send_select(dhcp_client);
684
685         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
686                                                         REQUEST_TIMEOUT,
687                                                         request_timeout,
688                                                         dhcp_client,
689                                                         NULL);
690 }
691
692 static uint32_t get_lease(struct dhcp_packet *packet)
693 {
694         uint8_t *option_u8;
695         uint32_t lease_seconds;
696
697         option_u8 = dhcp_get_option(packet, DHCP_LEASE_TIME);
698         if (option_u8 == NULL)
699                 return 3600;
700
701         lease_seconds = dhcp_get_unaligned((uint32_t *) option_u8);
702         lease_seconds = ntohl(lease_seconds);
703         /* paranoia: must not be prone to overflows */
704         lease_seconds &= 0x0fffffff;
705         if (lease_seconds < 10)
706                 lease_seconds = 10;
707
708         return lease_seconds;
709 }
710
711 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
712 {
713         if (dhcp_client->timeout > 0) {
714                 g_source_remove(dhcp_client->timeout);
715                 dhcp_client->timeout = 0;
716         }
717
718         dhcp_client->retry_times = retry_times;
719         dhcp_client->requested_ip = 0;
720         switch_listening_mode(dhcp_client, L2);
721
722         g_dhcp_client_start(dhcp_client);
723 }
724
725 static gboolean start_rebound_timeout(gpointer user_data)
726 {
727         GDHCPClient *dhcp_client = user_data;
728
729         switch_listening_mode(dhcp_client, L2);
730
731         dhcp_client->lease_seconds >>= 1;
732
733         /* We need to have enough time to receive ACK package*/
734         if (dhcp_client->lease_seconds <= 6) {
735
736                 /* ip need to be cleared */
737                 if (dhcp_client->lease_lost_cb != NULL)
738                         dhcp_client->lease_lost_cb(dhcp_client,
739                                         dhcp_client->lease_lost_data);
740
741                 restart_dhcp(dhcp_client, 0);
742         } else {
743                 send_rebound(dhcp_client);
744
745                 dhcp_client->timeout =
746                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
747                                                 dhcp_client->lease_seconds >> 1,
748                                                         start_rebound_timeout,
749                                                                 dhcp_client,
750                                                                 NULL);
751         }
752
753         return FALSE;
754 }
755
756 static void start_rebound(GDHCPClient *dhcp_client)
757 {
758         dhcp_client->state = REBINDING;
759
760         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
761                                                 dhcp_client->lease_seconds >> 1,
762                                                         start_rebound_timeout,
763                                                                 dhcp_client,
764                                                                 NULL);
765 }
766
767 static gboolean start_renew_timeout(gpointer user_data)
768 {
769         GDHCPClient *dhcp_client = user_data;
770
771         dhcp_client->state = RENEWING;
772
773         dhcp_client->lease_seconds >>= 1;
774
775         switch_listening_mode(dhcp_client, L3);
776         if (dhcp_client->lease_seconds <= 60)
777                 start_rebound(dhcp_client);
778         else {
779                 send_renew(dhcp_client);
780
781                 dhcp_client->timeout =
782                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
783                                                 dhcp_client->lease_seconds >> 1,
784                                                         start_renew_timeout,
785                                                                 dhcp_client,
786                                                                 NULL);
787         }
788
789         return FALSE;
790 }
791
792 static void start_bound(GDHCPClient *dhcp_client)
793 {
794         dhcp_client->state = BOUND;
795
796         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
797                                         dhcp_client->lease_seconds >> 1,
798                                         start_renew_timeout, dhcp_client,
799                                                         NULL);
800 }
801
802 static gboolean restart_dhcp_timeout(gpointer user_data)
803 {
804         GDHCPClient *dhcp_client = user_data;
805
806         dhcp_client->ack_retry_times++;
807
808         restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
809
810         return FALSE;
811 }
812
813 static char *get_ip(uint32_t ip)
814 {
815         struct in_addr addr;
816
817         addr.s_addr = ip;
818
819         return g_strdup(inet_ntoa(addr));
820 }
821
822 /* get a rough idea of how long an option will be */
823 static const uint8_t len_of_option_as_string[] = {
824         [OPTION_IP] = sizeof("255.255.255.255 "),
825         [OPTION_STRING] = 1,
826         [OPTION_U8] = sizeof("255 "),
827         [OPTION_U16] = sizeof("65535 "),
828         [OPTION_U32] = sizeof("4294967295 "),
829 };
830
831 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
832 {
833         return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
834 }
835
836 /* Create "opt_value1 option_value2 ..." string */
837 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
838 {
839         unsigned upper_length;
840         int len, optlen;
841         char *dest, *ret;
842
843         len = option[OPT_LEN - OPT_DATA];
844         type &= OPTION_TYPE_MASK;
845         optlen = dhcp_option_lengths[type];
846         if (optlen == 0)
847                 return NULL;
848         upper_length = len_of_option_as_string[type] *
849                         ((unsigned)len / (unsigned)optlen);
850         dest = ret = malloc(upper_length + 1);
851         if (ret == NULL)
852                 return NULL;
853
854         while (len >= optlen) {
855                 switch (type) {
856                 case OPTION_IP:
857                         dest += sprint_nip(dest, "", option);
858                         break;
859                 case OPTION_U16: {
860                         uint16_t val_u16 = dhcp_get_unaligned(
861                                                 (uint16_t *) option);
862                         dest += sprintf(dest, "%u", ntohs(val_u16));
863                         break;
864                 }
865                 case OPTION_U32: {
866                         uint32_t val_u32 = dhcp_get_unaligned(
867                                                 (uint32_t *) option);
868                         dest += sprintf(dest, type == OPTION_U32 ? "%lu" :
869                                         "%ld", (unsigned long) ntohl(val_u32));
870                         break;
871                 }
872                 case OPTION_STRING:
873                         memcpy(dest, option, len);
874                         dest[len] = '\0';
875                         return ret;
876                 default:
877                         break;
878                 }
879                 option += optlen;
880                 len -= optlen;
881                 if (len <= 0)
882                         break;
883                 *dest++ = ' ';
884                 *dest = '\0';
885         }
886
887         return ret;
888 }
889
890 static GList *get_option_value_list(char *value)
891 {
892         char *pos = value;
893         GList *list = NULL;
894
895         while ((pos = strchr(pos, ' ')) != NULL) {
896                 *pos = '\0';
897
898                 list =  g_list_append(list, g_strdup(value));
899
900                 value = ++pos;
901         }
902
903         list =  g_list_append(list, g_strdup(value));
904
905         return list;
906 }
907
908 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
909 {
910         GDHCPOptionType type;
911         GList *list, *value_list;
912         char *option_value;
913         uint8_t *option;
914         uint8_t code;
915
916         for (list = dhcp_client->request_list; list; list = list->next) {
917                 code = (uint8_t) GPOINTER_TO_INT(list->data);
918
919                 option = dhcp_get_option(packet, code);
920                 if (option == NULL) {
921                         g_hash_table_remove(dhcp_client->code_value_hash,
922                                                 GINT_TO_POINTER((int) code));
923                         continue;
924                 }
925
926                 type =  dhcp_get_code_type(code);
927
928                 option_value = malloc_option_value_string(option, type);
929                 if (option_value == NULL)
930                         g_hash_table_remove(dhcp_client->code_value_hash,
931                                                 GINT_TO_POINTER((int) code));
932
933                 value_list = get_option_value_list(option_value);
934
935                 g_free(option_value);
936
937                 if (value_list == NULL)
938                         g_hash_table_remove(dhcp_client->code_value_hash,
939                                                 GINT_TO_POINTER((int) code));
940                 else
941                         g_hash_table_insert(dhcp_client->code_value_hash,
942                                 GINT_TO_POINTER((int) code), value_list);
943         }
944 }
945
946 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
947                                                         gpointer user_data)
948 {
949         GDHCPClient *dhcp_client = user_data;
950         struct dhcp_packet packet;
951         uint8_t *message_type, *option_u8;
952         int re;
953
954         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
955                 dhcp_client->listener_watch = 0;
956                 return FALSE;
957         }
958
959         if (dhcp_client->listen_mode == L_NONE)
960                 return FALSE;
961
962         if (dhcp_client->listen_mode == L2)
963                 re = dhcp_recv_l2_packet(&packet, dhcp_client->listener_sockfd);
964         else if (dhcp_client->listen_mode == L3)
965                 re = dhcp_recv_l3_packet(&packet, dhcp_client->listener_sockfd);
966         else
967                 re = -EIO;
968
969         if (re < 0)
970                 return TRUE;
971
972         if (check_package_owner(dhcp_client, &packet) == FALSE)
973                 return TRUE;
974
975         message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
976         if (message_type == NULL)
977                 /* No message type option, ignore pakcage */
978                 return TRUE;
979
980         switch (dhcp_client->state) {
981         case INIT_SELECTING:
982                 if (*message_type != DHCPOFFER)
983                         return TRUE;
984
985                 g_source_remove(dhcp_client->timeout);
986                 dhcp_client->timeout = 0;
987                 dhcp_client->retry_times = 0;
988
989                 option_u8 = dhcp_get_option(&packet, DHCP_SERVER_ID);
990                 dhcp_client->server_ip =
991                                 dhcp_get_unaligned((uint32_t *) option_u8);
992                 dhcp_client->requested_ip = packet.yiaddr;
993
994                 dhcp_client->state = REQUESTING;
995
996                 start_request(dhcp_client);
997
998                 return TRUE;
999         case REQUESTING:
1000         case RENEWING:
1001         case REBINDING:
1002                 if (*message_type == DHCPACK) {
1003                         dhcp_client->retry_times = 0;
1004
1005                         if (dhcp_client->timeout > 0)
1006                                 g_source_remove(dhcp_client->timeout);
1007                         dhcp_client->timeout = 0;
1008
1009                         dhcp_client->lease_seconds = get_lease(&packet);
1010
1011                         get_request(dhcp_client, &packet);
1012
1013                         switch_listening_mode(dhcp_client, L_NONE);
1014
1015                         g_free(dhcp_client->assigned_ip);
1016                         dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1017
1018                         /* Address should be set up here */
1019                         if (dhcp_client->lease_available_cb != NULL)
1020                                 dhcp_client->lease_available_cb(dhcp_client,
1021                                         dhcp_client->lease_available_data);
1022
1023                         start_bound(dhcp_client);
1024                 } else if (*message_type == DHCPNAK) {
1025                         dhcp_client->retry_times = 0;
1026
1027                         if (dhcp_client->timeout > 0)
1028                                 g_source_remove(dhcp_client->timeout);
1029
1030                         dhcp_client->timeout = g_timeout_add_seconds_full(
1031                                                         G_PRIORITY_HIGH, 3,
1032                                                         restart_dhcp_timeout,
1033                                                         dhcp_client,
1034                                                         NULL);
1035                 }
1036
1037                 break;
1038         default:
1039                 break;
1040         }
1041
1042         return TRUE;
1043 }
1044
1045 static gboolean discover_timeout(gpointer user_data)
1046 {
1047         GDHCPClient *dhcp_client = user_data;
1048
1049         dhcp_client->retry_times++;
1050
1051         g_dhcp_client_start(dhcp_client);
1052
1053         return FALSE;
1054 }
1055
1056 int g_dhcp_client_start(GDHCPClient *dhcp_client)
1057 {
1058         int re;
1059
1060         if (dhcp_client->retry_times == DISCOVER_RETRIES) {
1061                 if (dhcp_client->no_lease_cb != NULL)
1062                         dhcp_client->no_lease_cb(dhcp_client,
1063                                         dhcp_client->no_lease_data);
1064
1065                 return 0;
1066         }
1067
1068         if (dhcp_client->retry_times == 0) {
1069                 g_free(dhcp_client->assigned_ip);
1070                 dhcp_client->assigned_ip = NULL;
1071
1072                 dhcp_client->state = INIT_SELECTING;
1073                 re = switch_listening_mode(dhcp_client, L2);
1074                 if (re != 0)
1075                         return re;
1076
1077                 dhcp_client->xid = rand();
1078         }
1079
1080         send_discover(dhcp_client, 0);
1081
1082         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1083                                                         DISCOVER_TIMEOUT,
1084                                                         discover_timeout,
1085                                                         dhcp_client,
1086                                                         NULL);
1087         return 0;
1088 }
1089
1090 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
1091 {
1092         switch_listening_mode(dhcp_client, L_NONE);
1093
1094         if (dhcp_client->state == BOUND ||
1095                         dhcp_client->state == RENEWING ||
1096                                 dhcp_client->state == REBINDING)
1097                 send_release(dhcp_client, dhcp_client->server_ip,
1098                                         dhcp_client->requested_ip);
1099
1100         if (dhcp_client->timeout > 0) {
1101                 g_source_remove(dhcp_client->timeout);
1102                 dhcp_client->timeout = 0;
1103         }
1104
1105         if (dhcp_client->listener_watch > 0) {
1106                 g_source_remove(dhcp_client->listener_watch);
1107                 dhcp_client->listener_watch = 0;
1108         }
1109
1110         dhcp_client->listener_channel = NULL;
1111
1112         dhcp_client->retry_times = 0;
1113         dhcp_client->ack_retry_times = 0;
1114
1115         dhcp_client->requested_ip = 0;
1116         dhcp_client->state = RELEASED;
1117         dhcp_client->lease_seconds = 0;
1118 }
1119
1120 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
1121                                         unsigned char option_code)
1122 {
1123         return g_hash_table_lookup(dhcp_client->code_value_hash,
1124                                         GINT_TO_POINTER((int) option_code));
1125 }
1126
1127 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
1128                                         GDHCPClientEvent event,
1129                                         GDHCPClientEventFunc func,
1130                                                         gpointer data)
1131 {
1132         switch (event) {
1133         case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
1134                 dhcp_client->lease_available_cb = func;
1135                 dhcp_client->lease_available_data = data;
1136                 return;
1137         case G_DHCP_CLIENT_EVENT_NO_LEASE:
1138                 dhcp_client->no_lease_cb = func;
1139                 dhcp_client->no_lease_data = data;
1140                 return;
1141         case G_DHCP_CLIENT_EVENT_LEASE_LOST:
1142                 dhcp_client->lease_lost_cb = func;
1143                 dhcp_client->lease_lost_data = data;
1144                 return;
1145         case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
1146                 dhcp_client->address_conflict_cb = func;
1147                 dhcp_client->address_conflict_data = data;
1148                 return;
1149         }
1150 }
1151
1152 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
1153 {
1154         return dhcp_client->ifindex;
1155 }
1156
1157 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
1158 {
1159         return g_strdup(dhcp_client->assigned_ip);
1160 }
1161
1162 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
1163                                                 unsigned char option_code)
1164 {
1165         if (g_list_find(dhcp_client->request_list,
1166                         GINT_TO_POINTER((int) option_code)) == NULL)
1167                 dhcp_client->request_list = g_list_prepend(
1168                                         dhcp_client->request_list,
1169                                         (GINT_TO_POINTER((int) option_code)));
1170
1171         return G_DHCP_CLIENT_ERROR_NONE;
1172 }
1173
1174 static uint8_t *alloc_dhcp_option(int code, const char *str, int extra)
1175 {
1176         uint8_t *storage;
1177         int len = strnlen(str, 255);
1178
1179         storage = malloc(len + extra + OPT_DATA);
1180         storage[OPT_CODE] = code;
1181         storage[OPT_LEN] = len + extra;
1182         memcpy(storage + extra + OPT_DATA, str, len);
1183
1184         return storage;
1185 }
1186
1187 static const char *get_hostname(const char *host)
1188 {
1189         char local_host_name[HOST_NAME_MAX + 1];
1190
1191         if (g_strcmp0("<hostname>", host) != 0)
1192                 return g_strdup(host);
1193
1194         if (gethostname(local_host_name, HOST_NAME_MAX) != 0)
1195                 return NULL;
1196
1197         local_host_name[HOST_NAME_MAX] = 0;
1198
1199         return g_strdup(local_host_name);
1200 }
1201
1202 /* Now only support send hostname */
1203 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
1204                 unsigned char option_code, const char *option_value)
1205 {
1206         uint8_t *binary_option;
1207         const char *hostname;
1208
1209         if (option_code == G_DHCP_HOST_NAME) {
1210                 hostname = get_hostname(option_value);
1211
1212                 binary_option = alloc_dhcp_option(option_code, hostname, 0);
1213
1214                 g_hash_table_insert(dhcp_client->send_value_hash,
1215                         GINT_TO_POINTER((int) option_code), binary_option);
1216         }
1217
1218         return G_DHCP_CLIENT_ERROR_NONE;
1219 }
1220
1221 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
1222 {
1223         if (dhcp_client == NULL)
1224                 return NULL;
1225
1226         g_atomic_int_inc(&dhcp_client->ref_count);
1227
1228         return dhcp_client;
1229 }
1230
1231 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
1232 {
1233         if (dhcp_client == NULL)
1234                 return;
1235
1236         if (g_atomic_int_dec_and_test(&dhcp_client->ref_count) == FALSE)
1237                 return;
1238
1239         g_dhcp_client_stop(dhcp_client);
1240
1241         g_free(dhcp_client->interface);
1242         g_free(dhcp_client->assigned_ip);
1243
1244         g_list_free(dhcp_client->request_list);
1245         g_list_free(dhcp_client->require_list);
1246
1247         g_hash_table_destroy(dhcp_client->code_value_hash);
1248         g_hash_table_destroy(dhcp_client->send_value_hash);
1249
1250         g_free(dhcp_client);
1251 }
1252
1253 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
1254                                 GDHCPDebugFunc func, gpointer user_data)
1255 {
1256         if (dhcp_client == NULL)
1257                 return;
1258
1259         dhcp_client->debug_func = func;
1260         dhcp_client->debug_data = user_data;
1261 }