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