Add more debug statements to DHCP library
[framework/connectivity/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 5
48
49 #define REQUEST_TIMEOUT 3
50 #define REQUEST_RETRIES 5
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         debug(dhcp_client, "request timeout (retries %d)",
604                                         dhcp_client->retry_times);
605
606         dhcp_client->retry_times++;
607
608         start_request(dhcp_client);
609
610         return FALSE;
611 }
612
613 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
614                                                         gpointer user_data);
615
616 static int switch_listening_mode(GDHCPClient *dhcp_client,
617                                         ListenMode listen_mode)
618 {
619         GIOChannel *listener_channel;
620         int listener_sockfd;
621
622         debug(dhcp_client, "switch listening mode (%d ==> %d)",
623                                 dhcp_client->listen_mode, listen_mode);
624
625         if (dhcp_client->listen_mode == listen_mode)
626                 return 0;
627
628         if (dhcp_client->listen_mode != L_NONE) {
629                 g_source_remove(dhcp_client->listener_watch);
630                 dhcp_client->listener_channel = NULL;
631                 dhcp_client->listen_mode = L_NONE;
632                 dhcp_client->listener_sockfd = -1;
633                 dhcp_client->listener_watch = 0;
634         }
635
636         if (listen_mode == L_NONE)
637                 return 0;
638
639         if (listen_mode == L2)
640                 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
641         else if (listen_mode == L3)
642                 listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
643                                                 dhcp_client->interface);
644         else
645                 return -EIO;
646
647         if (listener_sockfd < 0)
648                 return -EIO;
649
650         listener_channel = g_io_channel_unix_new(listener_sockfd);
651         if (listener_channel == NULL) {
652                 /* Failed to create listener channel */
653                 close(listener_sockfd);
654                 return -EIO;
655         }
656
657         dhcp_client->listen_mode = listen_mode;
658         dhcp_client->listener_sockfd = listener_sockfd;
659         dhcp_client->listener_channel = listener_channel;
660
661         g_io_channel_set_close_on_unref(listener_channel, TRUE);
662         dhcp_client->listener_watch =
663                         g_io_add_watch_full(listener_channel,
664                                                 G_PRIORITY_HIGH, G_IO_IN,
665                                                 listener_event, dhcp_client,
666                                                                 NULL);
667         g_io_channel_unref(dhcp_client->listener_channel);
668
669         return 0;
670 }
671
672 static void start_request(GDHCPClient *dhcp_client)
673 {
674         debug(dhcp_client, "start request (retries %d)",
675                                         dhcp_client->retry_times);
676
677         if (dhcp_client->retry_times == REQUEST_RETRIES) {
678                 dhcp_client->state = INIT_SELECTING;
679
680                 if (dhcp_client->no_lease_cb != NULL)
681                         dhcp_client->no_lease_cb(dhcp_client,
682                                         dhcp_client->no_lease_data);
683
684                 return;
685         }
686
687         if (dhcp_client->retry_times == 0) {
688                 dhcp_client->state = REQUESTING;
689                 switch_listening_mode(dhcp_client, L2);
690         }
691
692         send_select(dhcp_client);
693
694         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
695                                                         REQUEST_TIMEOUT,
696                                                         request_timeout,
697                                                         dhcp_client,
698                                                         NULL);
699 }
700
701 static uint32_t get_lease(struct dhcp_packet *packet)
702 {
703         uint8_t *option_u8;
704         uint32_t lease_seconds;
705
706         option_u8 = dhcp_get_option(packet, DHCP_LEASE_TIME);
707         if (option_u8 == NULL)
708                 return 3600;
709
710         lease_seconds = dhcp_get_unaligned((uint32_t *) option_u8);
711         lease_seconds = ntohl(lease_seconds);
712         /* paranoia: must not be prone to overflows */
713         lease_seconds &= 0x0fffffff;
714         if (lease_seconds < 10)
715                 lease_seconds = 10;
716
717         return lease_seconds;
718 }
719
720 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
721 {
722         debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
723
724         if (dhcp_client->timeout > 0) {
725                 g_source_remove(dhcp_client->timeout);
726                 dhcp_client->timeout = 0;
727         }
728
729         dhcp_client->retry_times = retry_times;
730         dhcp_client->requested_ip = 0;
731         switch_listening_mode(dhcp_client, L2);
732
733         g_dhcp_client_start(dhcp_client);
734 }
735
736 static gboolean start_rebound_timeout(gpointer user_data)
737 {
738         GDHCPClient *dhcp_client = user_data;
739
740         debug(dhcp_client, "start rebound timeout");
741
742         switch_listening_mode(dhcp_client, L2);
743
744         dhcp_client->lease_seconds >>= 1;
745
746         /* We need to have enough time to receive ACK package*/
747         if (dhcp_client->lease_seconds <= 6) {
748
749                 /* ip need to be cleared */
750                 if (dhcp_client->lease_lost_cb != NULL)
751                         dhcp_client->lease_lost_cb(dhcp_client,
752                                         dhcp_client->lease_lost_data);
753
754                 restart_dhcp(dhcp_client, 0);
755         } else {
756                 send_rebound(dhcp_client);
757
758                 dhcp_client->timeout =
759                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
760                                                 dhcp_client->lease_seconds >> 1,
761                                                         start_rebound_timeout,
762                                                                 dhcp_client,
763                                                                 NULL);
764         }
765
766         return FALSE;
767 }
768
769 static void start_rebound(GDHCPClient *dhcp_client)
770 {
771         debug(dhcp_client, "start rebound");
772
773         dhcp_client->state = REBINDING;
774
775         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
776                                                 dhcp_client->lease_seconds >> 1,
777                                                         start_rebound_timeout,
778                                                                 dhcp_client,
779                                                                 NULL);
780 }
781
782 static gboolean start_renew_timeout(gpointer user_data)
783 {
784         GDHCPClient *dhcp_client = user_data;
785
786         debug(dhcp_client, "start renew timeout");
787
788         dhcp_client->state = RENEWING;
789
790         dhcp_client->lease_seconds >>= 1;
791
792         switch_listening_mode(dhcp_client, L3);
793         if (dhcp_client->lease_seconds <= 60)
794                 start_rebound(dhcp_client);
795         else {
796                 send_renew(dhcp_client);
797
798                 dhcp_client->timeout =
799                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
800                                                 dhcp_client->lease_seconds >> 1,
801                                                         start_renew_timeout,
802                                                                 dhcp_client,
803                                                                 NULL);
804         }
805
806         return FALSE;
807 }
808
809 static void start_bound(GDHCPClient *dhcp_client)
810 {
811         debug(dhcp_client, "start bound");
812
813         dhcp_client->state = BOUND;
814
815         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
816                                         dhcp_client->lease_seconds >> 1,
817                                         start_renew_timeout, dhcp_client,
818                                                         NULL);
819 }
820
821 static gboolean restart_dhcp_timeout(gpointer user_data)
822 {
823         GDHCPClient *dhcp_client = user_data;
824
825         debug(dhcp_client, "restart DHCP timeout");
826
827         dhcp_client->ack_retry_times++;
828
829         restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
830
831         return FALSE;
832 }
833
834 static char *get_ip(uint32_t ip)
835 {
836         struct in_addr addr;
837
838         addr.s_addr = ip;
839
840         return g_strdup(inet_ntoa(addr));
841 }
842
843 /* get a rough idea of how long an option will be */
844 static const uint8_t len_of_option_as_string[] = {
845         [OPTION_IP] = sizeof("255.255.255.255 "),
846         [OPTION_STRING] = 1,
847         [OPTION_U8] = sizeof("255 "),
848         [OPTION_U16] = sizeof("65535 "),
849         [OPTION_U32] = sizeof("4294967295 "),
850 };
851
852 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
853 {
854         return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
855 }
856
857 /* Create "opt_value1 option_value2 ..." string */
858 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
859 {
860         unsigned upper_length;
861         int len, optlen;
862         char *dest, *ret;
863
864         len = option[OPT_LEN - OPT_DATA];
865         type &= OPTION_TYPE_MASK;
866         optlen = dhcp_option_lengths[type];
867         if (optlen == 0)
868                 return NULL;
869         upper_length = len_of_option_as_string[type] *
870                         ((unsigned)len / (unsigned)optlen);
871         dest = ret = malloc(upper_length + 1);
872         if (ret == NULL)
873                 return NULL;
874
875         while (len >= optlen) {
876                 switch (type) {
877                 case OPTION_IP:
878                         dest += sprint_nip(dest, "", option);
879                         break;
880                 case OPTION_U16: {
881                         uint16_t val_u16 = dhcp_get_unaligned(
882                                                 (uint16_t *) option);
883                         dest += sprintf(dest, "%u", ntohs(val_u16));
884                         break;
885                 }
886                 case OPTION_U32: {
887                         uint32_t val_u32 = dhcp_get_unaligned(
888                                                 (uint32_t *) option);
889                         dest += sprintf(dest, type == OPTION_U32 ? "%lu" :
890                                         "%ld", (unsigned long) ntohl(val_u32));
891                         break;
892                 }
893                 case OPTION_STRING:
894                         memcpy(dest, option, len);
895                         dest[len] = '\0';
896                         return ret;
897                 default:
898                         break;
899                 }
900                 option += optlen;
901                 len -= optlen;
902                 if (len <= 0)
903                         break;
904                 *dest++ = ' ';
905                 *dest = '\0';
906         }
907
908         return ret;
909 }
910
911 static GList *get_option_value_list(char *value)
912 {
913         char *pos = value;
914         GList *list = NULL;
915
916         while ((pos = strchr(pos, ' ')) != NULL) {
917                 *pos = '\0';
918
919                 list =  g_list_append(list, g_strdup(value));
920
921                 value = ++pos;
922         }
923
924         list =  g_list_append(list, g_strdup(value));
925
926         return list;
927 }
928
929 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
930 {
931         GDHCPOptionType type;
932         GList *list, *value_list;
933         char *option_value;
934         uint8_t *option;
935         uint8_t code;
936
937         for (list = dhcp_client->request_list; list; list = list->next) {
938                 code = (uint8_t) GPOINTER_TO_INT(list->data);
939
940                 option = dhcp_get_option(packet, code);
941                 if (option == NULL) {
942                         g_hash_table_remove(dhcp_client->code_value_hash,
943                                                 GINT_TO_POINTER((int) code));
944                         continue;
945                 }
946
947                 type =  dhcp_get_code_type(code);
948
949                 option_value = malloc_option_value_string(option, type);
950                 if (option_value == NULL)
951                         g_hash_table_remove(dhcp_client->code_value_hash,
952                                                 GINT_TO_POINTER((int) code));
953
954                 value_list = get_option_value_list(option_value);
955
956                 g_free(option_value);
957
958                 if (value_list == NULL)
959                         g_hash_table_remove(dhcp_client->code_value_hash,
960                                                 GINT_TO_POINTER((int) code));
961                 else
962                         g_hash_table_insert(dhcp_client->code_value_hash,
963                                 GINT_TO_POINTER((int) code), value_list);
964         }
965 }
966
967 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
968                                                         gpointer user_data)
969 {
970         GDHCPClient *dhcp_client = user_data;
971         struct dhcp_packet packet;
972         uint8_t *message_type, *option_u8;
973         int re;
974
975         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
976                 dhcp_client->listener_watch = 0;
977                 return FALSE;
978         }
979
980         if (dhcp_client->listen_mode == L_NONE)
981                 return FALSE;
982
983         if (dhcp_client->listen_mode == L2)
984                 re = dhcp_recv_l2_packet(&packet, dhcp_client->listener_sockfd);
985         else if (dhcp_client->listen_mode == L3)
986                 re = dhcp_recv_l3_packet(&packet, dhcp_client->listener_sockfd);
987         else
988                 re = -EIO;
989
990         if (re < 0)
991                 return TRUE;
992
993         if (check_package_owner(dhcp_client, &packet) == FALSE)
994                 return TRUE;
995
996         message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
997         if (message_type == NULL)
998                 /* No message type option, ignore pakcage */
999                 return TRUE;
1000
1001         debug(dhcp_client, "received DHCP packet (current state %d)",
1002                                                         dhcp_client->state);
1003
1004         switch (dhcp_client->state) {
1005         case INIT_SELECTING:
1006                 if (*message_type != DHCPOFFER)
1007                         return TRUE;
1008
1009                 g_source_remove(dhcp_client->timeout);
1010                 dhcp_client->timeout = 0;
1011                 dhcp_client->retry_times = 0;
1012
1013                 option_u8 = dhcp_get_option(&packet, DHCP_SERVER_ID);
1014                 dhcp_client->server_ip =
1015                                 dhcp_get_unaligned((uint32_t *) option_u8);
1016                 dhcp_client->requested_ip = packet.yiaddr;
1017
1018                 dhcp_client->state = REQUESTING;
1019
1020                 start_request(dhcp_client);
1021
1022                 return TRUE;
1023         case REQUESTING:
1024         case RENEWING:
1025         case REBINDING:
1026                 if (*message_type == DHCPACK) {
1027                         dhcp_client->retry_times = 0;
1028
1029                         if (dhcp_client->timeout > 0)
1030                                 g_source_remove(dhcp_client->timeout);
1031                         dhcp_client->timeout = 0;
1032
1033                         dhcp_client->lease_seconds = get_lease(&packet);
1034
1035                         get_request(dhcp_client, &packet);
1036
1037                         switch_listening_mode(dhcp_client, L_NONE);
1038
1039                         g_free(dhcp_client->assigned_ip);
1040                         dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1041
1042                         /* Address should be set up here */
1043                         if (dhcp_client->lease_available_cb != NULL)
1044                                 dhcp_client->lease_available_cb(dhcp_client,
1045                                         dhcp_client->lease_available_data);
1046
1047                         start_bound(dhcp_client);
1048                 } else if (*message_type == DHCPNAK) {
1049                         dhcp_client->retry_times = 0;
1050
1051                         if (dhcp_client->timeout > 0)
1052                                 g_source_remove(dhcp_client->timeout);
1053
1054                         dhcp_client->timeout = g_timeout_add_seconds_full(
1055                                                         G_PRIORITY_HIGH, 3,
1056                                                         restart_dhcp_timeout,
1057                                                         dhcp_client,
1058                                                         NULL);
1059                 }
1060
1061                 break;
1062         default:
1063                 break;
1064         }
1065
1066         debug(dhcp_client, "processed DHCP packet (new state %d)",
1067                                                         dhcp_client->state);
1068
1069         return TRUE;
1070 }
1071
1072 static gboolean discover_timeout(gpointer user_data)
1073 {
1074         GDHCPClient *dhcp_client = user_data;
1075
1076         dhcp_client->retry_times++;
1077
1078         g_dhcp_client_start(dhcp_client);
1079
1080         return FALSE;
1081 }
1082
1083 int g_dhcp_client_start(GDHCPClient *dhcp_client)
1084 {
1085         int re;
1086
1087         if (dhcp_client->retry_times == DISCOVER_RETRIES) {
1088                 if (dhcp_client->no_lease_cb != NULL)
1089                         dhcp_client->no_lease_cb(dhcp_client,
1090                                         dhcp_client->no_lease_data);
1091
1092                 return 0;
1093         }
1094
1095         if (dhcp_client->retry_times == 0) {
1096                 g_free(dhcp_client->assigned_ip);
1097                 dhcp_client->assigned_ip = NULL;
1098
1099                 dhcp_client->state = INIT_SELECTING;
1100                 re = switch_listening_mode(dhcp_client, L2);
1101                 if (re != 0)
1102                         return re;
1103
1104                 dhcp_client->xid = rand();
1105         }
1106
1107         send_discover(dhcp_client, 0);
1108
1109         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1110                                                         DISCOVER_TIMEOUT,
1111                                                         discover_timeout,
1112                                                         dhcp_client,
1113                                                         NULL);
1114         return 0;
1115 }
1116
1117 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
1118 {
1119         switch_listening_mode(dhcp_client, L_NONE);
1120
1121         if (dhcp_client->state == BOUND ||
1122                         dhcp_client->state == RENEWING ||
1123                                 dhcp_client->state == REBINDING)
1124                 send_release(dhcp_client, dhcp_client->server_ip,
1125                                         dhcp_client->requested_ip);
1126
1127         if (dhcp_client->timeout > 0) {
1128                 g_source_remove(dhcp_client->timeout);
1129                 dhcp_client->timeout = 0;
1130         }
1131
1132         if (dhcp_client->listener_watch > 0) {
1133                 g_source_remove(dhcp_client->listener_watch);
1134                 dhcp_client->listener_watch = 0;
1135         }
1136
1137         dhcp_client->listener_channel = NULL;
1138
1139         dhcp_client->retry_times = 0;
1140         dhcp_client->ack_retry_times = 0;
1141
1142         dhcp_client->requested_ip = 0;
1143         dhcp_client->state = RELEASED;
1144         dhcp_client->lease_seconds = 0;
1145 }
1146
1147 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
1148                                         unsigned char option_code)
1149 {
1150         return g_hash_table_lookup(dhcp_client->code_value_hash,
1151                                         GINT_TO_POINTER((int) option_code));
1152 }
1153
1154 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
1155                                         GDHCPClientEvent event,
1156                                         GDHCPClientEventFunc func,
1157                                                         gpointer data)
1158 {
1159         switch (event) {
1160         case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
1161                 dhcp_client->lease_available_cb = func;
1162                 dhcp_client->lease_available_data = data;
1163                 return;
1164         case G_DHCP_CLIENT_EVENT_NO_LEASE:
1165                 dhcp_client->no_lease_cb = func;
1166                 dhcp_client->no_lease_data = data;
1167                 return;
1168         case G_DHCP_CLIENT_EVENT_LEASE_LOST:
1169                 dhcp_client->lease_lost_cb = func;
1170                 dhcp_client->lease_lost_data = data;
1171                 return;
1172         case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
1173                 dhcp_client->address_conflict_cb = func;
1174                 dhcp_client->address_conflict_data = data;
1175                 return;
1176         }
1177 }
1178
1179 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
1180 {
1181         return dhcp_client->ifindex;
1182 }
1183
1184 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
1185 {
1186         return g_strdup(dhcp_client->assigned_ip);
1187 }
1188
1189 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
1190                                                 unsigned char option_code)
1191 {
1192         if (g_list_find(dhcp_client->request_list,
1193                         GINT_TO_POINTER((int) option_code)) == NULL)
1194                 dhcp_client->request_list = g_list_prepend(
1195                                         dhcp_client->request_list,
1196                                         (GINT_TO_POINTER((int) option_code)));
1197
1198         return G_DHCP_CLIENT_ERROR_NONE;
1199 }
1200
1201 static uint8_t *alloc_dhcp_option(int code, const char *str, int extra)
1202 {
1203         uint8_t *storage;
1204         int len = strnlen(str, 255);
1205
1206         storage = malloc(len + extra + OPT_DATA);
1207         storage[OPT_CODE] = code;
1208         storage[OPT_LEN] = len + extra;
1209         memcpy(storage + extra + OPT_DATA, str, len);
1210
1211         return storage;
1212 }
1213
1214 /* Now only support send hostname */
1215 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
1216                 unsigned char option_code, const char *option_value)
1217 {
1218         uint8_t *binary_option;
1219
1220         if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
1221                 binary_option = alloc_dhcp_option(option_code,
1222                                                         option_value, 0);
1223
1224                 g_hash_table_insert(dhcp_client->send_value_hash,
1225                         GINT_TO_POINTER((int) option_code), binary_option);
1226         }
1227
1228         return G_DHCP_CLIENT_ERROR_NONE;
1229 }
1230
1231 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
1232 {
1233         if (dhcp_client == NULL)
1234                 return NULL;
1235
1236         g_atomic_int_inc(&dhcp_client->ref_count);
1237
1238         return dhcp_client;
1239 }
1240
1241 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
1242 {
1243         if (dhcp_client == NULL)
1244                 return;
1245
1246         if (g_atomic_int_dec_and_test(&dhcp_client->ref_count) == FALSE)
1247                 return;
1248
1249         g_dhcp_client_stop(dhcp_client);
1250
1251         g_free(dhcp_client->interface);
1252         g_free(dhcp_client->assigned_ip);
1253
1254         g_list_free(dhcp_client->request_list);
1255         g_list_free(dhcp_client->require_list);
1256
1257         g_hash_table_destroy(dhcp_client->code_value_hash);
1258         g_hash_table_destroy(dhcp_client->send_value_hash);
1259
1260         g_free(dhcp_client);
1261 }
1262
1263 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
1264                                 GDHCPDebugFunc func, gpointer user_data)
1265 {
1266         if (dhcp_client == NULL)
1267                 return;
1268
1269         dhcp_client->debug_func = func;
1270         dhcp_client->debug_data = user_data;
1271 }