Merge "[connman] Added DBus method to get scanning status." into tizen
[platform/upstream/connman.git] / gdhcp / client.c
1 /*
2  *
3  *  DHCP client library with GLib integration
4  *
5  *  Copyright (C) 2009-2014  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 #define _GNU_SOURCE
27 #include <stdio.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <arpa/inet.h>
34 #include <sys/time.h>
35 #include <resolv.h>
36
37 #include <netpacket/packet.h>
38 #include <netinet/if_ether.h>
39 #include <net/ethernet.h>
40
41 #include <linux/if.h>
42 #include <linux/filter.h>
43
44 #include <glib.h>
45
46 #include "gdhcp.h"
47 #include "common.h"
48 #include "ipv4ll.h"
49
50 #define DISCOVER_TIMEOUT 5
51 #define DISCOVER_RETRIES 6
52
53 #if defined TIZEN_EXT
54 #define REQUEST_TIMEOUT 1
55 #else
56 #define REQUEST_TIMEOUT 5
57 #endif
58 #define REQUEST_RETRIES 3
59
60 #if defined TIZEN_EXT
61 #define DISCOVER_TIMEOUT_WIFI 1
62 #define DISCOVER_RETRIES_WIFI 10
63 static int dhcp_discover_timeout = DISCOVER_TIMEOUT_WIFI;
64 static int dhcp_discover_max_retry = DISCOVER_RETRIES_WIFI;
65
66 void set_dhcp_discover_timeout(int timeout_value)
67 {
68         dhcp_discover_timeout = timeout_value;
69 }
70
71 void set_dhcp_discover_retry_count(int retry_count)
72 {
73         dhcp_discover_max_retry = retry_count;
74 }
75 #endif
76
77 typedef enum _listen_mode {
78         L_NONE,
79         L2,
80         L3,
81         L_ARP,
82 } ListenMode;
83
84 typedef enum _dhcp_client_state {
85         INIT_SELECTING,
86         REBOOTING,
87         REQUESTING,
88         BOUND,
89         RENEWING,
90         REBINDING,
91         RELEASED,
92         IPV4LL_PROBE,
93         IPV4LL_ANNOUNCE,
94         IPV4LL_MONITOR,
95         IPV4LL_DEFEND,
96         INFORMATION_REQ,
97         SOLICITATION,
98         REQUEST,
99         CONFIRM,
100         RENEW,
101         REBIND,
102         RELEASE,
103         DECLINE,
104 } ClientState;
105
106 struct _GDHCPClient {
107         int ref_count;
108         GDHCPType type;
109         ClientState state;
110         int ifindex;
111         char *interface;
112         uint8_t mac_address[6];
113         uint32_t xid;
114         uint32_t server_ip;
115         uint32_t requested_ip;
116         char *assigned_ip;
117         time_t start;
118         uint32_t lease_seconds;
119         ListenMode listen_mode;
120         int listener_sockfd;
121         uint8_t retry_times;
122         uint8_t ack_retry_times;
123         uint8_t conflicts;
124         guint timeout;
125         guint t1_timeout;
126         guint t2_timeout;
127         guint lease_timeout;
128         guint listener_watch;
129         GList *require_list;
130         GList *request_list;
131         GHashTable *code_value_hash;
132         GHashTable *send_value_hash;
133         GDHCPClientEventFunc lease_available_cb;
134         gpointer lease_available_data;
135         GDHCPClientEventFunc ipv4ll_available_cb;
136         gpointer ipv4ll_available_data;
137         GDHCPClientEventFunc no_lease_cb;
138         gpointer no_lease_data;
139         GDHCPClientEventFunc lease_lost_cb;
140         gpointer lease_lost_data;
141         GDHCPClientEventFunc ipv4ll_lost_cb;
142         gpointer ipv4ll_lost_data;
143         GDHCPClientEventFunc address_conflict_cb;
144         gpointer address_conflict_data;
145         GDHCPDebugFunc debug_func;
146         gpointer debug_data;
147         GDHCPClientEventFunc information_req_cb;
148         gpointer information_req_data;
149         GDHCPClientEventFunc solicitation_cb;
150         gpointer solicitation_data;
151         GDHCPClientEventFunc advertise_cb;
152         gpointer advertise_data;
153         GDHCPClientEventFunc request_cb;
154         gpointer request_data;
155         GDHCPClientEventFunc renew_cb;
156         gpointer renew_data;
157         GDHCPClientEventFunc rebind_cb;
158         gpointer rebind_data;
159         GDHCPClientEventFunc release_cb;
160         gpointer release_data;
161         GDHCPClientEventFunc confirm_cb;
162         gpointer confirm_data;
163         GDHCPClientEventFunc decline_cb;
164         gpointer decline_data;
165         char *last_address;
166         unsigned char *duid;
167         int duid_len;
168         unsigned char *server_duid;
169         int server_duid_len;
170         uint16_t status_code;
171         uint32_t iaid;
172         uint32_t T1, T2;
173         struct in6_addr ia_na;
174         struct in6_addr ia_ta;
175         time_t last_request;
176         uint32_t expire;
177         bool retransmit;
178         struct timeval start_time;
179         bool request_bcast;
180 #if defined TIZEN_EXT
181         gboolean init_reboot;
182 #endif
183 };
184
185 static inline void debug(GDHCPClient *client, const char *format, ...)
186 {
187         char str[256];
188         va_list ap;
189
190         if (!client->debug_func)
191                 return;
192
193         va_start(ap, format);
194
195         if (vsnprintf(str, sizeof(str), format, ap) > 0)
196                 client->debug_func(str, client->debug_data);
197
198         va_end(ap);
199 }
200
201 /* Initialize the packet with the proper defaults */
202 static void init_packet(GDHCPClient *dhcp_client, gpointer pkt, char type)
203 {
204         if (dhcp_client->type == G_DHCP_IPV6)
205                 dhcpv6_init_header(pkt, type);
206         else {
207                 struct dhcp_packet *packet = pkt;
208
209                 dhcp_init_header(packet, type);
210                 memcpy(packet->chaddr, dhcp_client->mac_address, 6);
211         }
212 }
213
214 static void add_request_options(GDHCPClient *dhcp_client,
215                                 struct dhcp_packet *packet)
216 {
217         int len = 0;
218         GList *list;
219         uint8_t code;
220         int end = dhcp_end_option(packet->options);
221
222         for (list = dhcp_client->request_list; list; list = list->next) {
223                 code = (uint8_t) GPOINTER_TO_INT(list->data);
224
225                 packet->options[end + OPT_DATA + len] = code;
226                 len++;
227         }
228
229         if (len) {
230                 packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
231                 packet->options[end + OPT_LEN] = len;
232                 packet->options[end + OPT_DATA + len] = DHCP_END;
233         }
234 }
235
236 struct hash_params {
237         unsigned char *buf;
238         int max_buf;
239         unsigned char **ptr_buf;
240 };
241
242 static void add_dhcpv6_binary_option(gpointer key, gpointer value,
243                                         gpointer user_data)
244 {
245         uint8_t *option = value;
246         uint16_t len;
247         struct hash_params *params = user_data;
248
249         /* option[0][1] contains option code */
250         len = option[2] << 8 | option[3];
251
252         if ((*params->ptr_buf + len + 2 + 2) > (params->buf + params->max_buf))
253                 return;
254
255         memcpy(*params->ptr_buf, option, len + 2 + 2);
256         (*params->ptr_buf) += len + 2 + 2;
257 }
258
259 static void add_dhcpv6_send_options(GDHCPClient *dhcp_client,
260                                 unsigned char *buf, int max_buf,
261                                 unsigned char **ptr_buf)
262 {
263         struct hash_params params = {
264                 .buf = buf,
265                 .max_buf = max_buf,
266                 .ptr_buf = ptr_buf
267         };
268
269         if (dhcp_client->type != G_DHCP_IPV6)
270                 return;
271
272         g_hash_table_foreach(dhcp_client->send_value_hash,
273                                 add_dhcpv6_binary_option, &params);
274
275         *ptr_buf = *params.ptr_buf;
276 }
277
278 static void copy_option(uint8_t *buf, uint16_t code, uint16_t len,
279                         uint8_t *msg)
280 {
281         buf[0] = code >> 8;
282         buf[1] = code & 0xff;
283         buf[2] = len >> 8;
284         buf[3] = len & 0xff;
285         if (len > 0 && msg)
286                 memcpy(&buf[4], msg, len);
287 }
288
289 static int32_t get_time_diff(struct timeval *tv)
290 {
291         struct timeval now;
292         int32_t hsec;
293
294         gettimeofday(&now, NULL);
295
296         hsec = (now.tv_sec - tv->tv_sec) * 100;
297         hsec += (now.tv_usec - tv->tv_usec) / 10000;
298
299         return hsec;
300 }
301
302 static void remove_timeouts(GDHCPClient *dhcp_client)
303 {
304
305         if (dhcp_client->timeout > 0)
306                 g_source_remove(dhcp_client->timeout);
307         if (dhcp_client->t1_timeout > 0)
308                 g_source_remove(dhcp_client->t1_timeout);
309         if (dhcp_client->t2_timeout > 0)
310                 g_source_remove(dhcp_client->t2_timeout);
311         if (dhcp_client->lease_timeout > 0)
312                 g_source_remove(dhcp_client->lease_timeout);
313
314         dhcp_client->timeout = 0;
315         dhcp_client->t1_timeout = 0;
316         dhcp_client->t2_timeout = 0;
317         dhcp_client->lease_timeout = 0;
318
319 }
320
321 static void add_dhcpv6_request_options(GDHCPClient *dhcp_client,
322                                 struct dhcpv6_packet *packet,
323                                 unsigned char *buf, int max_buf,
324                                 unsigned char **ptr_buf)
325 {
326         GList *list;
327         uint16_t code, value;
328         bool added;
329         int32_t diff;
330         int len;
331
332         if (dhcp_client->type != G_DHCP_IPV6)
333                 return;
334
335         for (list = dhcp_client->request_list; list; list = list->next) {
336                 code = (uint16_t) GPOINTER_TO_INT(list->data);
337                 added = false;
338
339                 switch (code) {
340                 case G_DHCPV6_CLIENTID:
341                         if (!dhcp_client->duid)
342                                 return;
343
344                         len = 2 + 2 + dhcp_client->duid_len;
345                         if ((*ptr_buf + len) > (buf + max_buf)) {
346                                 debug(dhcp_client, "Too long dhcpv6 message "
347                                         "when writing client id option");
348                                 return;
349                         }
350
351                         copy_option(*ptr_buf, G_DHCPV6_CLIENTID,
352                                 dhcp_client->duid_len, dhcp_client->duid);
353                         (*ptr_buf) += len;
354                         added = true;
355                         break;
356
357                 case G_DHCPV6_SERVERID:
358                         if (!dhcp_client->server_duid)
359                                 break;
360
361                         len = 2 + 2 + dhcp_client->server_duid_len;
362                         if ((*ptr_buf + len) > (buf + max_buf)) {
363                                 debug(dhcp_client, "Too long dhcpv6 message "
364                                         "when writing server id option");
365                                 return;
366                         }
367
368                         copy_option(*ptr_buf, G_DHCPV6_SERVERID,
369                                 dhcp_client->server_duid_len,
370                                 dhcp_client->server_duid);
371                         (*ptr_buf) += len;
372                         added = true;
373                         break;
374
375                 case G_DHCPV6_RAPID_COMMIT:
376                         len = 2 + 2;
377                         if ((*ptr_buf + len) > (buf + max_buf)) {
378                                 debug(dhcp_client, "Too long dhcpv6 message "
379                                         "when writing rapid commit option");
380                                 return;
381                         }
382
383                         copy_option(*ptr_buf, G_DHCPV6_RAPID_COMMIT, 0, 0);
384                         (*ptr_buf) += len;
385                         added = true;
386                         break;
387
388                 case G_DHCPV6_ORO:
389                         break;
390
391                 case G_DHCPV6_ELAPSED_TIME:
392                         if (!dhcp_client->retransmit) {
393                                 /*
394                                  * Initial message, elapsed time is 0.
395                                  */
396                                 diff = 0;
397                         } else {
398                                 diff = get_time_diff(&dhcp_client->start_time);
399                                 if (diff < 0 || diff > 0xffff)
400                                         diff = 0xffff;
401                         }
402
403                         len = 2 + 2 + 2;
404                         if ((*ptr_buf + len) > (buf + max_buf)) {
405                                 debug(dhcp_client, "Too long dhcpv6 message "
406                                         "when writing elapsed time option");
407                                 return;
408                         }
409
410                         value = htons((uint16_t)diff);
411                         copy_option(*ptr_buf, G_DHCPV6_ELAPSED_TIME,
412                                 2, (uint8_t *)&value);
413                         (*ptr_buf) += len;
414                         added = true;
415                         break;
416
417                 case G_DHCPV6_DNS_SERVERS:
418                         break;
419
420                 case G_DHCPV6_DOMAIN_LIST:
421                         break;
422
423                 case G_DHCPV6_SNTP_SERVERS:
424                         break;
425
426                 default:
427                         break;
428                 }
429
430                 if (added)
431                         debug(dhcp_client, "option %d len %d added", code, len);
432         }
433 }
434
435 static void add_binary_option(gpointer key, gpointer value, gpointer user_data)
436 {
437         uint8_t *option = value;
438         struct dhcp_packet *packet = user_data;
439
440         dhcp_add_binary_option(packet, option);
441 }
442
443 static void add_send_options(GDHCPClient *dhcp_client,
444                                 struct dhcp_packet *packet)
445 {
446         g_hash_table_foreach(dhcp_client->send_value_hash,
447                                 add_binary_option, packet);
448 }
449
450 /*
451  * Return an RFC 951- and 2131-complaint BOOTP 'secs' value that
452  * represents the number of seconds elapsed from the start of
453  * attempting DHCP to satisfy some DHCP servers that allow for an
454  * "authoritative" reply before responding.
455  */
456 static uint16_t dhcp_attempt_secs(GDHCPClient *dhcp_client)
457 {
458         return htons(MIN(time(NULL) - dhcp_client->start, UINT16_MAX));
459 }
460
461 static int send_discover(GDHCPClient *dhcp_client, uint32_t requested)
462 {
463         struct dhcp_packet packet;
464
465         debug(dhcp_client, "sending DHCP discover request");
466
467         init_packet(dhcp_client, &packet, DHCPDISCOVER);
468
469         packet.xid = dhcp_client->xid;
470         packet.secs = dhcp_attempt_secs(dhcp_client);
471
472         if (requested)
473                 dhcp_add_option_uint32(&packet, DHCP_REQUESTED_IP, requested);
474
475         /* Explicitly saying that we want RFC-compliant packets helps
476          * some buggy DHCP servers to NOT send bigger packets */
477         dhcp_add_option_uint16(&packet, DHCP_MAX_SIZE, 576);
478
479         add_request_options(dhcp_client, &packet);
480
481         add_send_options(dhcp_client, &packet);
482
483         /*
484          * If we do not get a reply to DISCOVER packet, then we try with
485          * broadcast flag set. So first packet is sent without broadcast flag,
486          * first retry is with broadcast flag, second retry is without it etc.
487          * Reason is various buggy routers/AP that either eat the other or vice
488          * versa. In the receiving side we then find out what kind of packet
489          * the server can send.
490          */
491         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
492                                 INADDR_BROADCAST, SERVER_PORT,
493                                 MAC_BCAST_ADDR, dhcp_client->ifindex,
494                                 dhcp_client->retry_times % 2);
495 }
496
497 static int send_request(GDHCPClient *dhcp_client)
498 {
499         struct dhcp_packet packet;
500
501         debug(dhcp_client, "sending DHCP request (state %d)",
502                 dhcp_client->state);
503
504         init_packet(dhcp_client, &packet, DHCPREQUEST);
505
506         packet.xid = dhcp_client->xid;
507 #if defined TIZEN_EXT
508         if (dhcp_client->init_reboot != TRUE)
509 #endif
510         packet.secs = dhcp_attempt_secs(dhcp_client);
511
512         if (dhcp_client->state == REQUESTING || dhcp_client->state == REBOOTING)
513                 dhcp_add_option_uint32(&packet, DHCP_REQUESTED_IP,
514                                 dhcp_client->requested_ip);
515
516         if (dhcp_client->state == REQUESTING)
517                 dhcp_add_option_uint32(&packet, DHCP_SERVER_ID,
518                                 dhcp_client->server_ip);
519
520         dhcp_add_option_uint16(&packet, DHCP_MAX_SIZE, 576);
521
522         add_request_options(dhcp_client, &packet);
523
524         add_send_options(dhcp_client, &packet);
525
526         if (dhcp_client->state == RENEWING || dhcp_client->state == REBINDING)
527                 packet.ciaddr = htonl(dhcp_client->requested_ip);
528
529         if (dhcp_client->state == RENEWING)
530                 return dhcp_send_kernel_packet(&packet,
531                                 dhcp_client->requested_ip, CLIENT_PORT,
532                                 dhcp_client->server_ip, SERVER_PORT);
533
534         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
535                                 INADDR_BROADCAST, SERVER_PORT,
536                                 MAC_BCAST_ADDR, dhcp_client->ifindex,
537                                 dhcp_client->request_bcast);
538 }
539
540 static int send_release(GDHCPClient *dhcp_client,
541                         uint32_t server, uint32_t ciaddr)
542 {
543         struct dhcp_packet packet;
544         uint64_t rand;
545
546         debug(dhcp_client, "sending DHCP release request");
547
548         init_packet(dhcp_client, &packet, DHCPRELEASE);
549         dhcp_get_random(&rand);
550         packet.xid = rand;
551         packet.ciaddr = htonl(ciaddr);
552
553         dhcp_add_option_uint32(&packet, DHCP_SERVER_ID, server);
554
555         return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
556                                                 server, SERVER_PORT);
557 }
558
559 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data);
560 static int switch_listening_mode(GDHCPClient *dhcp_client,
561                                         ListenMode listen_mode);
562
563 static gboolean send_probe_packet(gpointer dhcp_data)
564 {
565         GDHCPClient *dhcp_client;
566         guint timeout;
567
568         dhcp_client = dhcp_data;
569         /* if requested_ip is not valid, pick a new address*/
570         if (dhcp_client->requested_ip == 0) {
571                 debug(dhcp_client, "pick a new random address");
572                 dhcp_client->requested_ip = ipv4ll_random_ip();
573         }
574
575         debug(dhcp_client, "sending IPV4LL probe request");
576
577         if (dhcp_client->retry_times == 1) {
578                 dhcp_client->state = IPV4LL_PROBE;
579                 switch_listening_mode(dhcp_client, L_ARP);
580         }
581         ipv4ll_send_arp_packet(dhcp_client->mac_address, 0,
582                         dhcp_client->requested_ip, dhcp_client->ifindex);
583
584         if (dhcp_client->retry_times < PROBE_NUM) {
585                 /*add a random timeout in range of PROBE_MIN to PROBE_MAX*/
586                 timeout = ipv4ll_random_delay_ms(PROBE_MAX-PROBE_MIN);
587                 timeout += PROBE_MIN*1000;
588         } else
589                 timeout = (ANNOUNCE_WAIT * 1000);
590
591         dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
592                                                  timeout,
593                                                  ipv4ll_probe_timeout,
594                                                  dhcp_client,
595                                                  NULL);
596         return FALSE;
597 }
598
599 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data);
600 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data);
601
602 static gboolean send_announce_packet(gpointer dhcp_data)
603 {
604         GDHCPClient *dhcp_client;
605
606         dhcp_client = dhcp_data;
607
608         debug(dhcp_client, "sending IPV4LL announce request");
609
610         ipv4ll_send_arp_packet(dhcp_client->mac_address,
611                                 dhcp_client->requested_ip,
612                                 dhcp_client->requested_ip,
613                                 dhcp_client->ifindex);
614
615         remove_timeouts(dhcp_client);
616
617         if (dhcp_client->state == IPV4LL_DEFEND) {
618                 dhcp_client->timeout =
619                         g_timeout_add_seconds_full(G_PRIORITY_HIGH,
620                                                 DEFEND_INTERVAL,
621                                                 ipv4ll_defend_timeout,
622                                                 dhcp_client,
623                                                 NULL);
624                 return TRUE;
625         } else
626                 dhcp_client->timeout =
627                         g_timeout_add_seconds_full(G_PRIORITY_HIGH,
628                                                 ANNOUNCE_INTERVAL,
629                                                 ipv4ll_announce_timeout,
630                                                 dhcp_client,
631                                                 NULL);
632         return TRUE;
633 }
634
635 static void get_interface_mac_address(int index, uint8_t *mac_address)
636 {
637         struct ifreq ifr;
638         int sk, err;
639
640         sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
641         if (sk < 0) {
642                 perror("Open socket error");
643                 return;
644         }
645
646         memset(&ifr, 0, sizeof(ifr));
647         ifr.ifr_ifindex = index;
648
649         err = ioctl(sk, SIOCGIFNAME, &ifr);
650         if (err < 0) {
651                 perror("Get interface name error");
652                 goto done;
653         }
654
655         err = ioctl(sk, SIOCGIFHWADDR, &ifr);
656         if (err < 0) {
657                 perror("Get mac address error");
658                 goto done;
659         }
660
661         memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
662
663 done:
664         close(sk);
665 }
666
667 void g_dhcpv6_client_set_retransmit(GDHCPClient *dhcp_client)
668 {
669         if (!dhcp_client)
670                 return;
671
672         dhcp_client->retransmit = true;
673 }
674
675 void g_dhcpv6_client_clear_retransmit(GDHCPClient *dhcp_client)
676 {
677         if (!dhcp_client)
678                 return;
679
680         dhcp_client->retransmit = false;
681 }
682
683 int g_dhcpv6_create_duid(GDHCPDuidType duid_type, int index, int type,
684                         unsigned char **duid, int *duid_len)
685 {
686         time_t duid_time;
687
688         switch (duid_type) {
689         case G_DHCPV6_DUID_LLT:
690                 *duid_len = 2 + 2 + 4 + ETH_ALEN;
691                 *duid = g_try_malloc(*duid_len);
692                 if (!*duid)
693                         return -ENOMEM;
694
695                 (*duid)[0] = 0;
696                 (*duid)[1] = 1;
697                 get_interface_mac_address(index, &(*duid)[2 + 2 + 4]);
698                 (*duid)[2] = 0;
699                 (*duid)[3] = type;
700                 duid_time = time(NULL) - DUID_TIME_EPOCH;
701                 (*duid)[4] = duid_time >> 24;
702                 (*duid)[5] = duid_time >> 16;
703                 (*duid)[6] = duid_time >> 8;
704                 (*duid)[7] = duid_time & 0xff;
705                 break;
706         case G_DHCPV6_DUID_EN:
707                 return -EINVAL;
708         case G_DHCPV6_DUID_LL:
709                 *duid_len = 2 + 2 + ETH_ALEN;
710                 *duid = g_try_malloc(*duid_len);
711                 if (!*duid)
712                         return -ENOMEM;
713
714                 (*duid)[0] = 0;
715                 (*duid)[1] = 3;
716                 get_interface_mac_address(index, &(*duid)[2 + 2]);
717                 (*duid)[2] = 0;
718                 (*duid)[3] = type;
719                 break;
720         }
721
722         return 0;
723 }
724
725 static gchar *convert_to_hex(unsigned char *buf, int len)
726 {
727         gchar *ret = g_try_malloc(len * 2 + 1);
728         int i;
729
730         for (i = 0; ret && i < len; i++)
731                 g_snprintf(ret + i * 2, 3, "%02x", buf[i]);
732
733         return ret;
734 }
735
736 int g_dhcpv6_client_set_duid(GDHCPClient *dhcp_client, unsigned char *duid,
737                         int duid_len)
738 {
739         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
740                 return -EINVAL;
741
742         g_free(dhcp_client->duid);
743
744         dhcp_client->duid = duid;
745         dhcp_client->duid_len = duid_len;
746
747         if (dhcp_client->debug_func) {
748                 gchar *hex = convert_to_hex(duid, duid_len);
749                 debug(dhcp_client, "DUID(%d) %s", duid_len, hex);
750                 g_free(hex);
751         }
752
753         return 0;
754 }
755
756 int g_dhcpv6_client_set_pd(GDHCPClient *dhcp_client, uint32_t *T1,
757                         uint32_t *T2, GSList *prefixes)
758 {
759         uint8_t options[1452];
760         unsigned int max_buf = sizeof(options);
761         int len, count = g_slist_length(prefixes);
762
763         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
764                 return -EINVAL;
765
766         g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_PD);
767
768         memset(options, 0, sizeof(options));
769
770         options[0] = dhcp_client->iaid >> 24;
771         options[1] = dhcp_client->iaid >> 16;
772         options[2] = dhcp_client->iaid >> 8;
773         options[3] = dhcp_client->iaid;
774
775         if (T1) {
776                 uint32_t t = htonl(*T1);
777                 memcpy(&options[4], &t, 4);
778         }
779
780         if (T2) {
781                 uint32_t t = htonl(*T2);
782                 memcpy(&options[8], &t, 4);
783         }
784
785         len = 12;
786
787         if (count > 0) {
788                 GSList *list;
789
790                 for (list = prefixes; list; list = list->next) {
791                         GDHCPIAPrefix *prefix = list->data;
792                         uint8_t sub_option[4+4+1+16];
793
794                         if ((len + 2 + 2 + sizeof(sub_option)) >= max_buf) {
795                                 debug(dhcp_client,
796                                         "Too long dhcpv6 message "
797                                         "when writing IA prefix option");
798                                 return -EINVAL;
799                         }
800
801                         memset(&sub_option, 0, sizeof(sub_option));
802
803                         /* preferred and validity time are left zero */
804
805                         sub_option[8] = prefix->prefixlen;
806                         memcpy(&sub_option[9], &prefix->prefix, 16);
807
808                         copy_option(&options[len], G_DHCPV6_IA_PREFIX,
809                                 sizeof(sub_option), sub_option);
810                         len += 2 + 2 + sizeof(sub_option);
811                 }
812         }
813
814         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_PD,
815                                 options, len);
816
817         return 0;
818 }
819
820 uint32_t g_dhcpv6_client_get_iaid(GDHCPClient *dhcp_client)
821 {
822         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
823                 return 0;
824
825         return dhcp_client->iaid;
826 }
827
828 void g_dhcpv6_client_set_iaid(GDHCPClient *dhcp_client, uint32_t iaid)
829 {
830         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
831                 return;
832
833         dhcp_client->iaid = iaid;
834 }
835
836 void g_dhcpv6_client_create_iaid(GDHCPClient *dhcp_client, int index,
837                                 unsigned char *iaid)
838 {
839         uint8_t buf[6];
840
841         get_interface_mac_address(index, buf);
842
843         memcpy(iaid, &buf[2], 4);
844         dhcp_client->iaid = iaid[0] << 24 |
845                         iaid[1] << 16 | iaid[2] << 8 | iaid[3];
846 }
847
848 int g_dhcpv6_client_get_timeouts(GDHCPClient *dhcp_client,
849                                 uint32_t *T1, uint32_t *T2,
850                                 time_t *started,
851                                 time_t *expire)
852 {
853         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
854                 return -EINVAL;
855
856         if (T1)
857                 *T1 = (dhcp_client->expire == 0xffffffff) ? 0xffffffff:
858                         dhcp_client->T1;
859
860         if (T2)
861                 *T2 = (dhcp_client->expire == 0xffffffff) ? 0xffffffff:
862                         dhcp_client->T2;
863
864         if (started)
865                 *started = dhcp_client->last_request;
866
867         if (expire)
868                 *expire = (dhcp_client->expire == 0xffffffff) ? 0xffffffff:
869                         dhcp_client->last_request + dhcp_client->expire;
870
871         return 0;
872 }
873
874 static uint8_t *create_iaaddr(GDHCPClient *dhcp_client, uint8_t *buf,
875                                 uint16_t len)
876 {
877         buf[0] = 0;
878         buf[1] = G_DHCPV6_IAADDR;
879         buf[2] = 0;
880         buf[3] = len;
881         memcpy(&buf[4], &dhcp_client->ia_na, 16);
882         memset(&buf[20], 0, 4); /* preferred */
883         memset(&buf[24], 0, 4); /* valid */
884         return buf;
885 }
886
887 static uint8_t *append_iaaddr(GDHCPClient *dhcp_client, uint8_t *buf,
888                         const char *address)
889 {
890         struct in6_addr addr;
891
892         if (inet_pton(AF_INET6, address, &addr) != 1)
893                 return NULL;
894
895         buf[0] = 0;
896         buf[1] = G_DHCPV6_IAADDR;
897         buf[2] = 0;
898         buf[3] = 24;
899         memcpy(&buf[4], &addr, 16);
900         memset(&buf[20], 0, 4); /* preferred */
901         memset(&buf[24], 0, 4); /* valid */
902         return &buf[28];
903 }
904
905 static void put_iaid(GDHCPClient *dhcp_client, int index, uint8_t *buf)
906 {
907         uint32_t iaid;
908
909         iaid = g_dhcpv6_client_get_iaid(dhcp_client);
910         if (iaid == 0) {
911                 g_dhcpv6_client_create_iaid(dhcp_client, index, buf);
912                 return;
913         }
914
915         buf[0] = iaid >> 24;
916         buf[1] = iaid >> 16;
917         buf[2] = iaid >> 8;
918         buf[3] = iaid;
919 }
920
921 int g_dhcpv6_client_set_ia(GDHCPClient *dhcp_client, int index,
922                         int code, uint32_t *T1, uint32_t *T2,
923                         bool add_iaaddr, const char *ia_na)
924 {
925         if (code == G_DHCPV6_IA_TA) {
926                 uint8_t ia_options[4];
927
928                 put_iaid(dhcp_client, index, ia_options);
929
930                 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_TA);
931                 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_TA,
932                                         ia_options, sizeof(ia_options));
933
934         } else if (code == G_DHCPV6_IA_NA) {
935                 struct in6_addr addr;
936
937                 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_NA);
938
939                 /*
940                  * If caller has specified the IPv6 address it wishes to
941                  * to use (ia_na != NULL and address is valid), then send
942                  * the address to server.
943                  * If caller did not specify the address (ia_na == NULL) and
944                  * if the current address is not set, then we should not send
945                  * the address sub-option.
946                  */
947                 if (add_iaaddr && ((!ia_na &&
948                         !IN6_IS_ADDR_UNSPECIFIED(&dhcp_client->ia_na))
949                         || (ia_na &&
950                                 inet_pton(AF_INET6, ia_na, &addr) == 1))) {
951 #define IAADDR_LEN (16+4+4)
952                         uint8_t ia_options[4+4+4+2+2+IAADDR_LEN];
953
954                         if (ia_na)
955                                 memcpy(&dhcp_client->ia_na, &addr,
956                                                 sizeof(struct in6_addr));
957
958                         put_iaid(dhcp_client, index, ia_options);
959
960                         if (T1) {
961                                 ia_options[4] = *T1 >> 24;
962                                 ia_options[5] = *T1 >> 16;
963                                 ia_options[6] = *T1 >> 8;
964                                 ia_options[7] = *T1;
965                         } else
966                                 memset(&ia_options[4], 0x00, 4);
967
968                         if (T2) {
969                                 ia_options[8] = *T2 >> 24;
970                                 ia_options[9] = *T2 >> 16;
971                                 ia_options[10] = *T2 >> 8;
972                                 ia_options[11] = *T2;
973                         } else
974                                 memset(&ia_options[8], 0x00, 4);
975
976                         create_iaaddr(dhcp_client, &ia_options[12],
977                                         IAADDR_LEN);
978
979                         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
980                                         ia_options, sizeof(ia_options));
981                 } else {
982                         uint8_t ia_options[4+4+4];
983
984                         put_iaid(dhcp_client, index, ia_options);
985
986                         memset(&ia_options[4], 0x00, 4); /* T1 (4 bytes) */
987                         memset(&ia_options[8], 0x00, 4); /* T2 (4 bytes) */
988
989                         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
990                                         ia_options, sizeof(ia_options));
991                 }
992
993         } else
994                 return -EINVAL;
995
996         return 0;
997 }
998
999 int g_dhcpv6_client_set_ias(GDHCPClient *dhcp_client, int index,
1000                         int code, uint32_t *T1, uint32_t *T2,
1001                         GSList *addresses)
1002 {
1003         GSList *list;
1004         uint8_t *ia_options, *pos;
1005         int len, count, total_len;
1006
1007         count = g_slist_length(addresses);
1008         if (count == 0)
1009                 return -EINVAL;
1010
1011         g_dhcp_client_set_request(dhcp_client, code);
1012
1013         if (code == G_DHCPV6_IA_TA)
1014                 len = 4;         /* IAID */
1015         else if (code == G_DHCPV6_IA_NA)
1016                 len = 4 + 4 + 4; /* IAID + T1 + T2 */
1017         else
1018                 return -EINVAL;
1019
1020         total_len = len + count * (2 + 2 + 16 + 4 + 4);
1021         ia_options = g_try_malloc0(total_len);
1022         if (!ia_options)
1023                 return -ENOMEM;
1024
1025         put_iaid(dhcp_client, index, ia_options);
1026
1027         pos = &ia_options[len]; /* skip the IA_NA or IA_TA */
1028
1029         for (list = addresses; list; list = list->next) {
1030                 pos = append_iaaddr(dhcp_client, pos, list->data);
1031                 if (!pos)
1032                         break;
1033         }
1034
1035         if (code == G_DHCPV6_IA_NA) {
1036                 if (T1) {
1037                         ia_options[4] = *T1 >> 24;
1038                         ia_options[5] = *T1 >> 16;
1039                         ia_options[6] = *T1 >> 8;
1040                         ia_options[7] = *T1;
1041                 } else
1042                         memset(&ia_options[4], 0x00, 4);
1043
1044                 if (T2) {
1045                         ia_options[8] = *T2 >> 24;
1046                         ia_options[9] = *T2 >> 16;
1047                         ia_options[10] = *T2 >> 8;
1048                         ia_options[11] = *T2;
1049                 } else
1050                         memset(&ia_options[8], 0x00, 4);
1051         }
1052
1053         g_dhcpv6_client_set_send(dhcp_client, code, ia_options, total_len);
1054
1055         g_free(ia_options);
1056
1057         return 0;
1058 }
1059
1060 int g_dhcpv6_client_set_oro(GDHCPClient *dhcp_client, int args, ...)
1061 {
1062         va_list va;
1063         int i, j, len = sizeof(uint16_t) * args;
1064         uint8_t *values;
1065
1066         values = g_try_malloc(len);
1067         if (!values)
1068                 return -ENOMEM;
1069
1070         va_start(va, args);
1071         for (i = 0, j = 0; i < args; i++) {
1072                 uint16_t value = va_arg(va, int);
1073                 values[j++] = value >> 8;
1074                 values[j++] = value & 0xff;
1075         }
1076         va_end(va);
1077
1078         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_ORO, values, len);
1079
1080         g_free(values);
1081
1082         return 0;
1083 }
1084
1085 static int send_dhcpv6_msg(GDHCPClient *dhcp_client, int type, char *msg)
1086 {
1087         struct dhcpv6_packet *packet;
1088         uint8_t buf[MAX_DHCPV6_PKT_SIZE];
1089         unsigned char *ptr;
1090         int ret, max_buf;
1091
1092         memset(buf, 0, sizeof(buf));
1093         packet = (struct dhcpv6_packet *)&buf[0];
1094         ptr = buf + sizeof(struct dhcpv6_packet);
1095
1096         init_packet(dhcp_client, packet, type);
1097
1098         if (!dhcp_client->retransmit) {
1099                 dhcp_client->xid = packet->transaction_id[0] << 16 |
1100                                 packet->transaction_id[1] << 8 |
1101                                 packet->transaction_id[2];
1102                 gettimeofday(&dhcp_client->start_time, NULL);
1103         } else {
1104                 packet->transaction_id[0] = dhcp_client->xid >> 16;
1105                 packet->transaction_id[1] = dhcp_client->xid >> 8 ;
1106                 packet->transaction_id[2] = dhcp_client->xid;
1107         }
1108
1109         g_dhcp_client_set_request(dhcp_client, G_DHCPV6_ELAPSED_TIME);
1110
1111         debug(dhcp_client, "sending DHCPv6 %s message xid 0x%04x", msg,
1112                                                         dhcp_client->xid);
1113
1114         max_buf = MAX_DHCPV6_PKT_SIZE - sizeof(struct dhcpv6_packet);
1115
1116         add_dhcpv6_request_options(dhcp_client, packet, buf, max_buf, &ptr);
1117
1118         add_dhcpv6_send_options(dhcp_client, buf, max_buf, &ptr);
1119
1120         ret = dhcpv6_send_packet(dhcp_client->ifindex, packet, ptr - buf);
1121
1122         debug(dhcp_client, "sent %d pkt %p len %d", ret, packet, ptr - buf);
1123         return ret;
1124 }
1125
1126 static int send_solicitation(GDHCPClient *dhcp_client)
1127 {
1128         return send_dhcpv6_msg(dhcp_client, DHCPV6_SOLICIT, "solicit");
1129 }
1130
1131 static int send_dhcpv6_request(GDHCPClient *dhcp_client)
1132 {
1133         return send_dhcpv6_msg(dhcp_client, DHCPV6_REQUEST, "request");
1134 }
1135
1136 static int send_dhcpv6_confirm(GDHCPClient *dhcp_client)
1137 {
1138         return send_dhcpv6_msg(dhcp_client, DHCPV6_CONFIRM, "confirm");
1139 }
1140
1141 static int send_dhcpv6_renew(GDHCPClient *dhcp_client)
1142 {
1143         return send_dhcpv6_msg(dhcp_client, DHCPV6_RENEW, "renew");
1144 }
1145
1146 static int send_dhcpv6_rebind(GDHCPClient *dhcp_client)
1147 {
1148         return send_dhcpv6_msg(dhcp_client, DHCPV6_REBIND, "rebind");
1149 }
1150
1151 static int send_dhcpv6_decline(GDHCPClient *dhcp_client)
1152 {
1153         return send_dhcpv6_msg(dhcp_client, DHCPV6_DECLINE, "decline");
1154 }
1155
1156 static int send_dhcpv6_release(GDHCPClient *dhcp_client)
1157 {
1158         return send_dhcpv6_msg(dhcp_client, DHCPV6_RELEASE, "release");
1159 }
1160
1161 static int send_information_req(GDHCPClient *dhcp_client)
1162 {
1163         return send_dhcpv6_msg(dhcp_client, DHCPV6_INFORMATION_REQ,
1164                                 "information-req");
1165 }
1166
1167 static void remove_value(gpointer data, gpointer user_data)
1168 {
1169         char *value = data;
1170         g_free(value);
1171 }
1172
1173 static void remove_option_value(gpointer data)
1174 {
1175         GList *option_value = data;
1176
1177         g_list_foreach(option_value, remove_value, NULL);
1178         g_list_free(option_value);
1179 }
1180
1181 GDHCPClient *g_dhcp_client_new(GDHCPType type,
1182                         int ifindex, GDHCPClientError *error)
1183 {
1184         GDHCPClient *dhcp_client;
1185
1186         if (ifindex < 0) {
1187                 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
1188                 return NULL;
1189         }
1190
1191         dhcp_client = g_try_new0(GDHCPClient, 1);
1192         if (!dhcp_client) {
1193                 *error = G_DHCP_CLIENT_ERROR_NOMEM;
1194                 return NULL;
1195         }
1196
1197         dhcp_client->interface = get_interface_name(ifindex);
1198         if (!dhcp_client->interface) {
1199                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
1200                 goto error;
1201         }
1202
1203         if (!interface_is_up(ifindex)) {
1204                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
1205                 goto error;
1206         }
1207
1208         get_interface_mac_address(ifindex, dhcp_client->mac_address);
1209
1210         dhcp_client->listener_sockfd = -1;
1211         dhcp_client->listen_mode = L_NONE;
1212         dhcp_client->ref_count = 1;
1213         dhcp_client->type = type;
1214         dhcp_client->ifindex = ifindex;
1215         dhcp_client->lease_available_cb = NULL;
1216         dhcp_client->ipv4ll_available_cb = NULL;
1217         dhcp_client->no_lease_cb = NULL;
1218         dhcp_client->lease_lost_cb = NULL;
1219         dhcp_client->ipv4ll_lost_cb = NULL;
1220         dhcp_client->address_conflict_cb = NULL;
1221         dhcp_client->listener_watch = 0;
1222         dhcp_client->retry_times = 0;
1223         dhcp_client->ack_retry_times = 0;
1224         dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
1225                                 g_direct_equal, NULL, remove_option_value);
1226         dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
1227                                 g_direct_equal, NULL, g_free);
1228         dhcp_client->request_list = NULL;
1229         dhcp_client->require_list = NULL;
1230         dhcp_client->duid = NULL;
1231         dhcp_client->duid_len = 0;
1232         dhcp_client->last_request = time(NULL);
1233         dhcp_client->expire = 0;
1234         dhcp_client->request_bcast = false;
1235
1236         *error = G_DHCP_CLIENT_ERROR_NONE;
1237
1238         return dhcp_client;
1239
1240 error:
1241         g_free(dhcp_client->interface);
1242         g_free(dhcp_client);
1243         return NULL;
1244 }
1245
1246 #define SERVER_AND_CLIENT_PORTS  ((67 << 16) + 68)
1247
1248 static int dhcp_l2_socket(int ifindex)
1249 {
1250         int fd;
1251         struct sockaddr_ll sock;
1252
1253         /*
1254          * Comment:
1255          *
1256          *      I've selected not to see LL header, so BPF doesn't see it, too.
1257          *      The filter may also pass non-IP and non-ARP packets, but we do
1258          *      a more complete check when receiving the message in userspace.
1259          *
1260          * and filter shamelessly stolen from:
1261          *
1262          *      http://www.flamewarmaster.de/software/dhcpclient/
1263          *
1264          * There are a few other interesting ideas on that page (look under
1265          * "Motivation").  Use of netlink events is most interesting.  Think
1266          * of various network servers listening for events and reconfiguring.
1267          * That would obsolete sending HUP signals and/or make use of restarts.
1268          *
1269          * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
1270          * License: GPL v2.
1271          *
1272          * TODO: make conditional?
1273          */
1274         static const struct sock_filter filter_instr[] = {
1275                 /* check for udp */
1276                 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
1277                 /* L5, L1, is UDP? */
1278                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
1279                 /* ugly check for arp on ethernet-like and IPv4 */
1280                 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
1281                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
1282                 /* skip IP header */
1283                 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
1284                 /* check udp source and destination ports */
1285                 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
1286                 /* L3, L4 */
1287                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
1288                 /* returns */
1289                 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
1290                 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
1291         };
1292
1293         static const struct sock_fprog filter_prog = {
1294                 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
1295                 /* casting const away: */
1296                 .filter = (struct sock_filter *) filter_instr,
1297         };
1298
1299         fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IP));
1300         if (fd < 0)
1301                 return -errno;
1302
1303         if (SERVER_PORT == 67 && CLIENT_PORT == 68)
1304                 /* Use only if standard ports are in use */
1305                 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
1306                                                         sizeof(filter_prog));
1307
1308         memset(&sock, 0, sizeof(sock));
1309         sock.sll_family = AF_PACKET;
1310         sock.sll_protocol = htons(ETH_P_IP);
1311         sock.sll_ifindex = ifindex;
1312
1313         if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
1314                 int err = -errno;
1315                 close(fd);
1316                 return err;
1317         }
1318
1319         return fd;
1320 }
1321
1322 static bool sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
1323 {
1324         if (packet->ip.protocol != IPPROTO_UDP)
1325                 return false;
1326
1327         if (packet->ip.version != IPVERSION)
1328                 return false;
1329
1330         if (packet->ip.ihl != sizeof(packet->ip) >> 2)
1331                 return false;
1332
1333         if (packet->udp.dest != htons(CLIENT_PORT))
1334                 return false;
1335
1336         if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
1337                 return false;
1338
1339         return true;
1340 }
1341
1342 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd,
1343                                 struct sockaddr_in *dst_addr)
1344 {
1345         int bytes;
1346         struct ip_udp_dhcp_packet packet;
1347         uint16_t check;
1348
1349         memset(&packet, 0, sizeof(packet));
1350
1351         bytes = read(fd, &packet, sizeof(packet));
1352         if (bytes < 0)
1353                 return -1;
1354
1355         if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
1356                 return -1;
1357
1358         if (bytes < ntohs(packet.ip.tot_len))
1359                 /* packet is bigger than sizeof(packet), we did partial read */
1360                 return -1;
1361
1362         /* ignore any extra garbage bytes */
1363         bytes = ntohs(packet.ip.tot_len);
1364
1365         if (!sanity_check(&packet, bytes))
1366                 return -1;
1367
1368         check = packet.ip.check;
1369         packet.ip.check = 0;
1370         if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
1371                 return -1;
1372
1373         /* verify UDP checksum. IP header has to be modified for this */
1374         memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
1375         /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
1376         packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
1377         check = packet.udp.check;
1378         packet.udp.check = 0;
1379         if (check && check != dhcp_checksum(&packet, bytes))
1380                 return -1;
1381
1382         memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
1383                                                         sizeof(packet.udp)));
1384
1385         if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
1386                 return -1;
1387
1388         dst_addr->sin_addr.s_addr = packet.ip.daddr;
1389
1390         return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
1391 }
1392
1393 static void ipv4ll_start(GDHCPClient *dhcp_client)
1394 {
1395         guint timeout;
1396
1397         remove_timeouts(dhcp_client);
1398
1399         switch_listening_mode(dhcp_client, L_NONE);
1400         dhcp_client->retry_times = 0;
1401         dhcp_client->requested_ip = 0;
1402
1403         dhcp_client->requested_ip = ipv4ll_random_ip();
1404
1405         /*first wait a random delay to avoid storm of arp request on boot*/
1406         timeout = ipv4ll_random_delay_ms(PROBE_WAIT);
1407
1408         dhcp_client->retry_times++;
1409         dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
1410                                                 timeout,
1411                                                 send_probe_packet,
1412                                                 dhcp_client,
1413                                                 NULL);
1414 }
1415
1416 static void ipv4ll_stop(GDHCPClient *dhcp_client)
1417 {
1418
1419         switch_listening_mode(dhcp_client, L_NONE);
1420
1421         remove_timeouts(dhcp_client);
1422
1423         if (dhcp_client->listener_watch > 0) {
1424                 g_source_remove(dhcp_client->listener_watch);
1425                 dhcp_client->listener_watch = 0;
1426         }
1427
1428         dhcp_client->state = IPV4LL_PROBE;
1429         dhcp_client->retry_times = 0;
1430         dhcp_client->requested_ip = 0;
1431
1432         g_free(dhcp_client->assigned_ip);
1433         dhcp_client->assigned_ip = NULL;
1434 }
1435
1436 static int ipv4ll_recv_arp_packet(GDHCPClient *dhcp_client)
1437 {
1438         int bytes;
1439         struct ether_arp arp;
1440         uint32_t ip_requested;
1441         int source_conflict;
1442         int target_conflict;
1443
1444         memset(&arp, 0, sizeof(arp));
1445         bytes = read(dhcp_client->listener_sockfd, &arp, sizeof(arp));
1446         if (bytes < 0)
1447                 return bytes;
1448
1449         if (arp.arp_op != htons(ARPOP_REPLY) &&
1450                         arp.arp_op != htons(ARPOP_REQUEST))
1451                 return -EINVAL;
1452
1453         ip_requested = htonl(dhcp_client->requested_ip);
1454         source_conflict = !memcmp(arp.arp_spa, &ip_requested,
1455                                                 sizeof(ip_requested));
1456
1457         target_conflict = !memcmp(arp.arp_tpa, &ip_requested,
1458                                 sizeof(ip_requested));
1459
1460         if (!source_conflict && !target_conflict)
1461                 return 0;
1462
1463         dhcp_client->conflicts++;
1464
1465         debug(dhcp_client, "IPV4LL conflict detected");
1466
1467         if (dhcp_client->state == IPV4LL_MONITOR) {
1468                 if (!source_conflict)
1469                         return 0;
1470                 dhcp_client->state = IPV4LL_DEFEND;
1471                 debug(dhcp_client, "DEFEND mode conflicts : %d",
1472                         dhcp_client->conflicts);
1473                 /*Try to defend with a single announce*/
1474                 send_announce_packet(dhcp_client);
1475                 return 0;
1476         }
1477
1478         if (dhcp_client->state == IPV4LL_DEFEND) {
1479                 if (!source_conflict)
1480                         return 0;
1481                 else if (dhcp_client->ipv4ll_lost_cb)
1482                         dhcp_client->ipv4ll_lost_cb(dhcp_client,
1483                                                 dhcp_client->ipv4ll_lost_data);
1484         }
1485
1486         ipv4ll_stop(dhcp_client);
1487
1488         if (dhcp_client->conflicts < MAX_CONFLICTS) {
1489                 /*restart whole state machine*/
1490                 dhcp_client->retry_times++;
1491                 dhcp_client->timeout =
1492                         g_timeout_add_full(G_PRIORITY_HIGH,
1493                                         ipv4ll_random_delay_ms(PROBE_WAIT),
1494                                         send_probe_packet,
1495                                         dhcp_client,
1496                                         NULL);
1497         }
1498         /* Here we got a lot of conflicts, RFC3927 states that we have
1499          * to wait RATE_LIMIT_INTERVAL before retrying,
1500          * but we just report failure.
1501          */
1502         else if (dhcp_client->no_lease_cb)
1503                         dhcp_client->no_lease_cb(dhcp_client,
1504                                                 dhcp_client->no_lease_data);
1505
1506         return 0;
1507 }
1508
1509 static bool check_package_owner(GDHCPClient *dhcp_client, gpointer pkt)
1510 {
1511         if (dhcp_client->type == G_DHCP_IPV6) {
1512                 struct dhcpv6_packet *packet6 = pkt;
1513                 uint32_t xid;
1514
1515                 if (!packet6)
1516                         return false;
1517
1518                 xid = packet6->transaction_id[0] << 16 |
1519                         packet6->transaction_id[1] << 8 |
1520                         packet6->transaction_id[2];
1521
1522                 if (xid != dhcp_client->xid)
1523                         return false;
1524         } else {
1525                 struct dhcp_packet *packet = pkt;
1526
1527                 if (packet->xid != dhcp_client->xid)
1528                         return false;
1529
1530                 if (packet->hlen != 6)
1531                         return false;
1532
1533                 if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
1534                         return false;
1535         }
1536
1537         return true;
1538 }
1539
1540 static void start_request(GDHCPClient *dhcp_client);
1541
1542 static gboolean request_timeout(gpointer user_data)
1543 {
1544         GDHCPClient *dhcp_client = user_data;
1545
1546 #if defined TIZEN_EXT
1547         if (dhcp_client->init_reboot) {
1548                 debug(dhcp_client, "DHCPREQUEST of INIT-REBOOT has failed");
1549
1550                 /* Start DHCPDISCOVERY when DHCPREQUEST of INIT-REBOOT has failed */
1551                 g_dhcp_client_set_address_known(dhcp_client, FALSE);
1552
1553                 dhcp_client->retry_times = 0;
1554                 dhcp_client->requested_ip = 0;
1555
1556                 g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
1557
1558                 return FALSE;
1559         }
1560 #endif
1561         debug(dhcp_client, "request timeout (retries %d)",
1562                                         dhcp_client->retry_times);
1563
1564         dhcp_client->retry_times++;
1565
1566         start_request(dhcp_client);
1567
1568         return FALSE;
1569 }
1570
1571 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1572                                                         gpointer user_data);
1573
1574 static int switch_listening_mode(GDHCPClient *dhcp_client,
1575                                         ListenMode listen_mode)
1576 {
1577         GIOChannel *listener_channel;
1578         int listener_sockfd;
1579
1580         if (dhcp_client->listen_mode == listen_mode)
1581                 return 0;
1582
1583         debug(dhcp_client, "switch listening mode (%d ==> %d)",
1584                                 dhcp_client->listen_mode, listen_mode);
1585
1586         if (dhcp_client->listen_mode != L_NONE) {
1587                 if (dhcp_client->listener_watch > 0)
1588                         g_source_remove(dhcp_client->listener_watch);
1589                 dhcp_client->listen_mode = L_NONE;
1590                 dhcp_client->listener_sockfd = -1;
1591                 dhcp_client->listener_watch = 0;
1592         }
1593
1594         if (listen_mode == L_NONE)
1595                 return 0;
1596
1597         if (listen_mode == L2)
1598                 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
1599         else if (listen_mode == L3) {
1600                 if (dhcp_client->type == G_DHCP_IPV6)
1601                         listener_sockfd = dhcp_l3_socket(DHCPV6_CLIENT_PORT,
1602                                                         dhcp_client->interface,
1603                                                         AF_INET6);
1604                 else
1605                         listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
1606                                                         dhcp_client->interface,
1607                                                         AF_INET);
1608         } else if (listen_mode == L_ARP)
1609                 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
1610         else
1611                 return -EIO;
1612
1613         if (listener_sockfd < 0)
1614                 return -EIO;
1615
1616         listener_channel = g_io_channel_unix_new(listener_sockfd);
1617         if (!listener_channel) {
1618                 /* Failed to create listener channel */
1619                 close(listener_sockfd);
1620                 return -EIO;
1621         }
1622
1623         dhcp_client->listen_mode = listen_mode;
1624         dhcp_client->listener_sockfd = listener_sockfd;
1625
1626         g_io_channel_set_close_on_unref(listener_channel, TRUE);
1627         dhcp_client->listener_watch =
1628                         g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
1629                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1630                                                 listener_event, dhcp_client,
1631                                                                 NULL);
1632         g_io_channel_unref(listener_channel);
1633
1634         return 0;
1635 }
1636
1637 static void start_request(GDHCPClient *dhcp_client)
1638 {
1639         debug(dhcp_client, "start request (retries %d)",
1640                                         dhcp_client->retry_times);
1641
1642         if (dhcp_client->retry_times == REQUEST_RETRIES) {
1643                 if (dhcp_client->no_lease_cb)
1644                         dhcp_client->no_lease_cb(dhcp_client,
1645                                                 dhcp_client->no_lease_data);
1646                 return;
1647         }
1648
1649         if (dhcp_client->retry_times == 0) {
1650                 dhcp_client->state = REQUESTING;
1651                 switch_listening_mode(dhcp_client, L2);
1652         }
1653
1654         send_request(dhcp_client);
1655
1656         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1657                                                         REQUEST_TIMEOUT,
1658                                                         request_timeout,
1659                                                         dhcp_client,
1660                                                         NULL);
1661 }
1662
1663 static uint32_t get_lease(struct dhcp_packet *packet)
1664 {
1665         uint8_t *option;
1666         uint32_t lease_seconds;
1667
1668         option = dhcp_get_option(packet, DHCP_LEASE_TIME);
1669         if (!option)
1670                 return 3600;
1671
1672         lease_seconds = get_be32(option);
1673         /* paranoia: must not be prone to overflows */
1674         lease_seconds &= 0x0fffffff;
1675         if (lease_seconds < 10)
1676                 lease_seconds = 10;
1677
1678         return lease_seconds;
1679 }
1680
1681 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
1682 {
1683         debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
1684
1685         remove_timeouts(dhcp_client);
1686
1687         dhcp_client->retry_times = retry_times;
1688         dhcp_client->requested_ip = 0;
1689         dhcp_client->state = INIT_SELECTING;
1690         switch_listening_mode(dhcp_client, L2);
1691
1692         g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
1693 }
1694
1695 static gboolean start_expire(gpointer user_data)
1696 {
1697         GDHCPClient *dhcp_client = user_data;
1698
1699         debug(dhcp_client, "lease expired");
1700
1701         /*remove all timeouts if they are set*/
1702         remove_timeouts(dhcp_client);
1703
1704         restart_dhcp(dhcp_client, 0);
1705
1706         /* ip need to be cleared */
1707         if (dhcp_client->lease_lost_cb)
1708                 dhcp_client->lease_lost_cb(dhcp_client,
1709                                 dhcp_client->lease_lost_data);
1710
1711         return false;
1712 }
1713
1714 static gboolean continue_rebound(gpointer user_data)
1715 {
1716         GDHCPClient *dhcp_client = user_data;
1717         uint64_t rand;
1718
1719         switch_listening_mode(dhcp_client, L2);
1720         send_request(dhcp_client);
1721
1722         if (dhcp_client->t2_timeout> 0)
1723                 g_source_remove(dhcp_client->t2_timeout);
1724
1725         /*recalculate remaining rebind time*/
1726         dhcp_client->T2 >>= 1;
1727         if (dhcp_client->T2 > 60) {
1728                 dhcp_get_random(&rand);
1729                 dhcp_client->t2_timeout =
1730                         g_timeout_add_full(G_PRIORITY_HIGH,
1731                                         dhcp_client->T2 * 1000 + (rand % 2000) - 1000,
1732                                         continue_rebound,
1733                                         dhcp_client,
1734                                         NULL);
1735         }
1736
1737         return FALSE;
1738 }
1739
1740 static gboolean start_rebound(gpointer user_data)
1741 {
1742         GDHCPClient *dhcp_client = user_data;
1743
1744         /*remove renew timer*/
1745         if (dhcp_client->t1_timeout > 0)
1746                 g_source_remove(dhcp_client->t1_timeout);
1747
1748         debug(dhcp_client, "start rebound");
1749         dhcp_client->state = REBINDING;
1750
1751         /*calculate total rebind time*/
1752         dhcp_client->T2 = dhcp_client->expire - dhcp_client->T2;
1753
1754         /*send the first rebound and reschedule*/
1755         continue_rebound(user_data);
1756
1757         return FALSE;
1758 }
1759
1760 static gboolean continue_renew (gpointer user_data)
1761 {
1762         GDHCPClient *dhcp_client = user_data;
1763         uint64_t rand;
1764
1765         switch_listening_mode(dhcp_client, L3);
1766         send_request(dhcp_client);
1767
1768         if (dhcp_client->t1_timeout > 0)
1769                 g_source_remove(dhcp_client->t1_timeout);
1770
1771         dhcp_client->t1_timeout = 0;
1772
1773         dhcp_client->T1 >>= 1;
1774
1775         if (dhcp_client->T1 > 60) {
1776                 dhcp_get_random(&rand);
1777                 dhcp_client->t1_timeout = g_timeout_add_full(G_PRIORITY_HIGH,
1778                                 dhcp_client->T1 * 1000 + (rand % 2000) - 1000,
1779                                 continue_renew,
1780                                 dhcp_client,
1781                                 NULL);
1782         }
1783
1784         return FALSE;
1785 }
1786 static gboolean start_renew(gpointer user_data)
1787 {
1788         GDHCPClient *dhcp_client = user_data;
1789
1790         debug(dhcp_client, "start renew");
1791         dhcp_client->state = RENEWING;
1792
1793         /*calculate total renew period*/
1794         dhcp_client->T1 = dhcp_client->T2 - dhcp_client->T1;
1795
1796         /*send first renew and reschedule for half the remaining time.*/
1797         continue_renew(user_data);
1798
1799         return FALSE;
1800 }
1801
1802 static void start_bound(GDHCPClient *dhcp_client)
1803 {
1804         debug(dhcp_client, "start bound");
1805
1806         dhcp_client->state = BOUND;
1807
1808         remove_timeouts(dhcp_client);
1809
1810         /*
1811          *TODO: T1 and T2 should be set through options instead of
1812          * defaults as they are here.
1813          */
1814
1815         dhcp_client->T1 = dhcp_client->lease_seconds >> 1;
1816         dhcp_client->T2 = dhcp_client->lease_seconds * 0.875;
1817         dhcp_client->expire = dhcp_client->lease_seconds;
1818
1819         dhcp_client->t1_timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1820                                         dhcp_client->T1,
1821                                         start_renew, dhcp_client,
1822                                                         NULL);
1823
1824         dhcp_client->t2_timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1825                                         dhcp_client->T2,
1826                                         start_rebound, dhcp_client,
1827                                                         NULL);
1828
1829         dhcp_client->lease_timeout= g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1830                                         dhcp_client->expire,
1831                                         start_expire, dhcp_client,
1832                                                         NULL);
1833 }
1834
1835 static gboolean restart_dhcp_timeout(gpointer user_data)
1836 {
1837         GDHCPClient *dhcp_client = user_data;
1838
1839         debug(dhcp_client, "restart DHCP timeout");
1840
1841         if (dhcp_client->state == REBOOTING) {
1842                 g_free(dhcp_client->last_address);
1843                 dhcp_client->last_address = NULL;
1844                 restart_dhcp(dhcp_client, 0);
1845         } else {
1846                 dhcp_client->ack_retry_times++;
1847                 restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
1848         }
1849         return FALSE;
1850 }
1851
1852 static char *get_ip(uint32_t ip)
1853 {
1854         struct in_addr addr;
1855
1856         addr.s_addr = ip;
1857
1858         return g_strdup(inet_ntoa(addr));
1859 }
1860
1861 static GList *get_option_value_list(char *value, GDHCPOptionType type)
1862 {
1863         char *pos = value;
1864         GList *list = NULL;
1865
1866         if (!pos)
1867                 return NULL;
1868
1869         if (type == OPTION_STRING)
1870                 return g_list_append(list, g_strdup(value));
1871
1872         while ((pos = strchr(pos, ' '))) {
1873                 *pos = '\0';
1874
1875                 list = g_list_append(list, g_strdup(value));
1876
1877                 value = ++pos;
1878         }
1879
1880         list = g_list_append(list, g_strdup(value));
1881
1882         return list;
1883 }
1884
1885 static inline uint32_t get_uint32(unsigned char *value)
1886 {
1887         return value[0] << 24 | value[1] << 16 |
1888                 value[2] << 8 | value[3];
1889 }
1890
1891 static inline uint16_t get_uint16(unsigned char *value)
1892 {
1893         return value[0] << 8 | value[1];
1894 }
1895
1896 static GList *add_prefix(GDHCPClient *dhcp_client, GList *list,
1897                         struct in6_addr *addr,
1898                         unsigned char prefixlen, uint32_t preferred,
1899                         uint32_t valid)
1900 {
1901         GDHCPIAPrefix *ia_prefix;
1902
1903         ia_prefix = g_try_new(GDHCPIAPrefix, 1);
1904         if (!ia_prefix)
1905                 return list;
1906
1907         if (dhcp_client->debug_func) {
1908                 char addr_str[INET6_ADDRSTRLEN + 1];
1909                 inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
1910                 debug(dhcp_client, "prefix %s/%d preferred %u valid %u",
1911                         addr_str, prefixlen, preferred, valid);
1912         }
1913
1914         memcpy(&ia_prefix->prefix, addr, sizeof(struct in6_addr));
1915         ia_prefix->prefixlen = prefixlen;
1916         ia_prefix->preferred = preferred;
1917         ia_prefix->valid = valid;
1918         ia_prefix->expire = time(NULL) + valid;
1919
1920         return g_list_prepend(list, ia_prefix);
1921 }
1922
1923 static GList *get_addresses(GDHCPClient *dhcp_client,
1924                                 int code, int len,
1925                                 unsigned char *value,
1926                                 uint16_t *status)
1927 {
1928         GList *list = NULL;
1929         struct in6_addr addr;
1930         uint32_t iaid, T1 = 0, T2 = 0, preferred = 0, valid = 0;
1931         uint16_t option_len, option_code, st = 0, max_len;
1932         int addr_count = 0, prefix_count = 0, i, pos;
1933         unsigned char prefixlen;
1934         unsigned int shortest_valid = 0;
1935         uint8_t *option;
1936         char *str;
1937
1938         if (!value || len < 4)
1939                 return NULL;
1940
1941         iaid = get_uint32(&value[0]);
1942         if (dhcp_client->iaid != iaid)
1943                 return NULL;
1944
1945         if (code == G_DHCPV6_IA_NA || code == G_DHCPV6_IA_PD) {
1946                 T1 = get_uint32(&value[4]);
1947                 T2 = get_uint32(&value[8]);
1948
1949                 if (T1 > T2)
1950                         /* IA_NA: RFC 3315, 22.4 */
1951                         /* IA_PD: RFC 3633, ch 9 */
1952                         return NULL;
1953
1954                 pos = 12;
1955         } else
1956                 pos = 4;
1957
1958         if (len <= pos)
1959                 return NULL;
1960
1961         max_len = len - pos;
1962
1963         debug(dhcp_client, "header %d sub-option max len %d", pos, max_len);
1964
1965         /* We have more sub-options in this packet. */
1966         do {
1967                 option = dhcpv6_get_sub_option(&value[pos], max_len,
1968                                         &option_code, &option_len);
1969
1970                 debug(dhcp_client, "pos %d option %p code %d len %d",
1971                         pos, option, option_code, option_len);
1972
1973                 if (!option)
1974                         break;
1975
1976                 if (pos >= len)
1977                         break;
1978
1979                 switch (option_code) {
1980                 case G_DHCPV6_IAADDR:
1981                         i = 0;
1982                         memcpy(&addr, &option[0], sizeof(addr));
1983                         i += sizeof(addr);
1984                         preferred = get_uint32(&option[i]);
1985                         i += 4;
1986                         valid = get_uint32(&option[i]);
1987
1988                         addr_count++;
1989                         break;
1990
1991                 case G_DHCPV6_STATUS_CODE:
1992                         st = get_uint16(&option[0]);
1993                         debug(dhcp_client, "error code %d", st);
1994                         if (option_len > 2) {
1995                                 str = g_strndup((gchar *)&option[2],
1996                                                 option_len - 2);
1997                                 debug(dhcp_client, "error text: %s", str);
1998                                 g_free(str);
1999                         }
2000
2001                         *status = st;
2002                         break;
2003
2004                 case G_DHCPV6_IA_PREFIX:
2005                         i = 0;
2006                         preferred = get_uint32(&option[i]);
2007                         i += 4;
2008                         valid = get_uint32(&option[i]);
2009                         i += 4;
2010                         prefixlen = option[i];
2011                         i += 1;
2012                         memcpy(&addr, &option[i], sizeof(addr));
2013                         i += sizeof(addr);
2014                         if (preferred < valid) {
2015                                 /* RFC 3633, ch 10 */
2016                                 list = add_prefix(dhcp_client, list, &addr,
2017                                                 prefixlen, preferred, valid);
2018                                 if (shortest_valid > valid)
2019                                         shortest_valid = valid;
2020                                 prefix_count++;
2021                         }
2022                         break;
2023                 }
2024
2025                 pos += 2 + 2 + option_len;
2026
2027         } while (pos < len);
2028
2029         if (addr_count > 0 && st == 0) {
2030                 /* We only support one address atm */
2031                 char addr_str[INET6_ADDRSTRLEN + 1];
2032
2033                 if (preferred > valid)
2034                         /* RFC 3315, 22.6 */
2035                         return NULL;
2036
2037                 dhcp_client->T1 = T1;
2038                 dhcp_client->T2 = T2;
2039
2040                 inet_ntop(AF_INET6, &addr, addr_str, INET6_ADDRSTRLEN);
2041                 debug(dhcp_client, "address count %d addr %s T1 %u T2 %u",
2042                         addr_count, addr_str, T1, T2);
2043
2044                 list = g_list_append(list, g_strdup(addr_str));
2045
2046                 if (code == G_DHCPV6_IA_NA)
2047                         memcpy(&dhcp_client->ia_na, &addr,
2048                                                 sizeof(struct in6_addr));
2049                 else
2050                         memcpy(&dhcp_client->ia_ta, &addr,
2051                                                 sizeof(struct in6_addr));
2052
2053                 if (valid != dhcp_client->expire)
2054                         dhcp_client->expire = valid;
2055         }
2056
2057         if (prefix_count > 0 && list) {
2058                 /*
2059                  * This means we have a list of prefixes to delegate.
2060                  */
2061                 list = g_list_reverse(list);
2062
2063                 debug(dhcp_client, "prefix count %d T1 %u T2 %u",
2064                         prefix_count, T1, T2);
2065
2066                 dhcp_client->T1 = T1;
2067                 dhcp_client->T2 = T2;
2068
2069                 dhcp_client->expire = shortest_valid;
2070         }
2071
2072         if (status && *status != 0)
2073                 debug(dhcp_client, "status %d", *status);
2074
2075         return list;
2076 }
2077
2078 static GList *get_domains(int maxlen, unsigned char *value)
2079
2080 {
2081         GList *list = NULL;
2082         int pos = 0;
2083         unsigned char *c;
2084         char dns_name[NS_MAXDNAME + 1];
2085
2086         if (!value || maxlen < 3)
2087                 return NULL;
2088
2089         while (pos < maxlen) {
2090                 strncpy(dns_name, (char *)&value[pos], NS_MAXDNAME);
2091
2092                 c = (unsigned char *)dns_name;
2093                 while (c && *c) {
2094                         int jump;
2095                         jump = *c;
2096                         *c = '.';
2097                         c += jump + 1;
2098                 }
2099                 list = g_list_prepend(list, g_strdup(&dns_name[1]));
2100                 pos += (char *)c - dns_name + 1;
2101         }
2102
2103         return g_list_reverse(list);
2104 }
2105
2106 static GList *get_dhcpv6_option_value_list(GDHCPClient *dhcp_client,
2107                                         int code, int len,
2108                                         unsigned char *value,
2109                                         uint16_t *status)
2110 {
2111         GList *list = NULL;
2112         char *str;
2113         int i;
2114
2115         if (!value)
2116                 return NULL;
2117
2118         switch (code) {
2119         case G_DHCPV6_DNS_SERVERS:      /* RFC 3646, chapter 3 */
2120         case G_DHCPV6_SNTP_SERVERS:     /* RFC 4075, chapter 4 */
2121                 if (len % 16) {
2122                         debug(dhcp_client,
2123                                 "%s server list length (%d) is invalid",
2124                                 code == G_DHCPV6_DNS_SERVERS ? "DNS" : "SNTP",
2125                                 len);
2126                         return NULL;
2127                 }
2128                 for (i = 0; i < len; i += 16) {
2129
2130                         str = g_try_malloc0(INET6_ADDRSTRLEN+1);
2131                         if (!str)
2132                                 return list;
2133
2134                         if (!inet_ntop(AF_INET6, &value[i], str,
2135                                         INET6_ADDRSTRLEN))
2136                                 g_free(str);
2137                         else
2138                                 list = g_list_append(list, str);
2139                 }
2140                 break;
2141
2142         case G_DHCPV6_IA_NA:            /* RFC 3315, chapter 22.4 */
2143         case G_DHCPV6_IA_TA:            /* RFC 3315, chapter 22.5 */
2144         case G_DHCPV6_IA_PD:            /* RFC 3633, chapter 9 */
2145                 list = get_addresses(dhcp_client, code, len, value, status);
2146                 break;
2147
2148         case G_DHCPV6_DOMAIN_LIST:
2149                 list = get_domains(len, value);
2150                 break;
2151
2152         default:
2153                 break;
2154         }
2155
2156         return list;
2157 }
2158
2159 static void get_dhcpv6_request(GDHCPClient *dhcp_client,
2160                                 struct dhcpv6_packet *packet,
2161                                 uint16_t pkt_len, uint16_t *status)
2162 {
2163         GList *list, *value_list;
2164         uint8_t *option;
2165         uint16_t code;
2166         uint16_t option_len;
2167
2168         for (list = dhcp_client->request_list; list; list = list->next) {
2169                 code = (uint16_t) GPOINTER_TO_INT(list->data);
2170
2171                 option = dhcpv6_get_option(packet, pkt_len, code, &option_len,
2172                                                 NULL);
2173                 if (!option) {
2174                         g_hash_table_remove(dhcp_client->code_value_hash,
2175                                                 GINT_TO_POINTER((int) code));
2176                         continue;
2177                 }
2178
2179                 value_list = get_dhcpv6_option_value_list(dhcp_client, code,
2180                                                 option_len, option, status);
2181
2182                 debug(dhcp_client, "code %d %p len %d list %p", code, option,
2183                         option_len, value_list);
2184
2185                 if (!value_list)
2186                         g_hash_table_remove(dhcp_client->code_value_hash,
2187                                                 GINT_TO_POINTER((int) code));
2188                 else
2189                         g_hash_table_insert(dhcp_client->code_value_hash,
2190                                 GINT_TO_POINTER((int) code), value_list);
2191         }
2192 }
2193
2194 static void get_request(GDHCPClient *dhcp_client, struct dhcp_packet *packet)
2195 {
2196         GDHCPOptionType type;
2197         GList *list, *value_list;
2198         char *option_value;
2199         uint8_t *option;
2200         uint8_t code;
2201
2202         for (list = dhcp_client->request_list; list; list = list->next) {
2203                 code = (uint8_t) GPOINTER_TO_INT(list->data);
2204
2205                 option = dhcp_get_option(packet, code);
2206                 if (!option) {
2207                         g_hash_table_remove(dhcp_client->code_value_hash,
2208                                                 GINT_TO_POINTER((int) code));
2209                         continue;
2210                 }
2211
2212                 type =  dhcp_get_code_type(code);
2213
2214                 option_value = malloc_option_value_string(option, type);
2215                 if (!option_value)
2216                         g_hash_table_remove(dhcp_client->code_value_hash,
2217                                                 GINT_TO_POINTER((int) code));
2218
2219                 value_list = get_option_value_list(option_value, type);
2220
2221                 g_free(option_value);
2222
2223                 if (!value_list)
2224                         g_hash_table_remove(dhcp_client->code_value_hash,
2225                                                 GINT_TO_POINTER((int) code));
2226                 else
2227                         g_hash_table_insert(dhcp_client->code_value_hash,
2228                                 GINT_TO_POINTER((int) code), value_list);
2229         }
2230 }
2231
2232 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
2233                                                         gpointer user_data)
2234 {
2235         GDHCPClient *dhcp_client = user_data;
2236         struct sockaddr_in dst_addr = { 0 };
2237         struct dhcp_packet packet;
2238         struct dhcpv6_packet *packet6 = NULL;
2239         uint8_t *message_type = NULL, *client_id = NULL, *option,
2240                 *server_id = NULL;
2241         uint16_t option_len = 0, status = 0;
2242         uint32_t xid = 0;
2243         gpointer pkt;
2244         unsigned char buf[MAX_DHCPV6_PKT_SIZE];
2245         uint16_t pkt_len = 0;
2246         int count;
2247         int re;
2248
2249         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
2250                 dhcp_client->listener_watch = 0;
2251                 return FALSE;
2252         }
2253
2254         if (dhcp_client->listen_mode == L_NONE)
2255                 return FALSE;
2256
2257         pkt = &packet;
2258
2259         dhcp_client->status_code = 0;
2260
2261         if (dhcp_client->listen_mode == L2) {
2262                 re = dhcp_recv_l2_packet(&packet,
2263                                         dhcp_client->listener_sockfd,
2264                                         &dst_addr);
2265                 xid = packet.xid;
2266         } else if (dhcp_client->listen_mode == L3) {
2267                 if (dhcp_client->type == G_DHCP_IPV6) {
2268                         re = dhcpv6_recv_l3_packet(&packet6, buf, sizeof(buf),
2269                                                 dhcp_client->listener_sockfd);
2270                         pkt_len = re;
2271                         pkt = packet6;
2272                         xid = packet6->transaction_id[0] << 16 |
2273                                 packet6->transaction_id[1] << 8 |
2274                                 packet6->transaction_id[2];
2275                 } else {
2276                         re = dhcp_recv_l3_packet(&packet,
2277                                                 dhcp_client->listener_sockfd);
2278                         xid = packet.xid;
2279                 }
2280         } else if (dhcp_client->listen_mode == L_ARP) {
2281                 ipv4ll_recv_arp_packet(dhcp_client);
2282                 return TRUE;
2283         } else
2284                 re = -EIO;
2285
2286         if (re < 0)
2287                 return TRUE;
2288
2289         if (!check_package_owner(dhcp_client, pkt))
2290                 return TRUE;
2291
2292         if (dhcp_client->type == G_DHCP_IPV6) {
2293                 if (!packet6)
2294                         return TRUE;
2295
2296                 count = 0;
2297                 client_id = dhcpv6_get_option(packet6, pkt_len,
2298                                 G_DHCPV6_CLIENTID, &option_len, &count);
2299
2300                 if (!client_id || count == 0 || option_len == 0 ||
2301                                 memcmp(dhcp_client->duid, client_id,
2302                                         dhcp_client->duid_len) != 0) {
2303                         debug(dhcp_client,
2304                                 "client duid error, discarding msg %p/%d/%d",
2305                                 client_id, option_len, count);
2306                         return TRUE;
2307                 }
2308
2309                 option = dhcpv6_get_option(packet6, pkt_len,
2310                                 G_DHCPV6_STATUS_CODE, &option_len, NULL);
2311                 if (option != 0 && option_len > 0) {
2312                         status = option[0]<<8 | option[1];
2313                         if (status != 0) {
2314                                 debug(dhcp_client, "error code %d", status);
2315                                 if (option_len > 2) {
2316                                         gchar *txt = g_strndup(
2317                                                 (gchar *)&option[2],
2318                                                 option_len - 2);
2319                                         debug(dhcp_client, "error text: %s",
2320                                                 txt);
2321                                         g_free(txt);
2322                                 }
2323                         }
2324                         dhcp_client->status_code = status;
2325                 }
2326         } else {
2327                 message_type = dhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
2328                 if (!message_type)
2329                         return TRUE;
2330         }
2331
2332         if (!message_type && !client_id)
2333                 /* No message type / client id option, ignore package */
2334                 return TRUE;
2335
2336         debug(dhcp_client, "received DHCP packet xid 0x%04x "
2337                 "(current state %d)", ntohl(xid), dhcp_client->state);
2338
2339         switch (dhcp_client->state) {
2340         case INIT_SELECTING:
2341                 if (*message_type != DHCPOFFER)
2342                         return TRUE;
2343
2344                 remove_timeouts(dhcp_client);
2345                 dhcp_client->timeout = 0;
2346                 dhcp_client->retry_times = 0;
2347
2348                 option = dhcp_get_option(&packet, DHCP_SERVER_ID);
2349                 dhcp_client->server_ip = get_be32(option);
2350                 dhcp_client->requested_ip = ntohl(packet.yiaddr);
2351
2352                 dhcp_client->state = REQUESTING;
2353
2354                 if (dst_addr.sin_addr.s_addr == INADDR_BROADCAST)
2355                         dhcp_client->request_bcast = true;
2356                 else
2357                         dhcp_client->request_bcast = false;
2358
2359                 debug(dhcp_client, "init ip %s -> %sadding broadcast flag",
2360                         inet_ntoa(dst_addr.sin_addr),
2361                         dhcp_client->request_bcast ? "" : "not ");
2362
2363                 start_request(dhcp_client);
2364
2365                 return TRUE;
2366         case REBOOTING:
2367                 if (dst_addr.sin_addr.s_addr == INADDR_BROADCAST)
2368                         dhcp_client->request_bcast = true;
2369                 else
2370                         dhcp_client->request_bcast = false;
2371
2372                 debug(dhcp_client, "ip %s -> %sadding broadcast flag",
2373                         inet_ntoa(dst_addr.sin_addr),
2374                         dhcp_client->request_bcast ? "" : "not ");
2375                 /* fall through */
2376         case REQUESTING:
2377         case RENEWING:
2378         case REBINDING:
2379                 if (*message_type == DHCPACK) {
2380                         dhcp_client->retry_times = 0;
2381
2382                         remove_timeouts(dhcp_client);
2383
2384                         dhcp_client->lease_seconds = get_lease(&packet);
2385
2386                         get_request(dhcp_client, &packet);
2387
2388                         switch_listening_mode(dhcp_client, L_NONE);
2389
2390                         g_free(dhcp_client->assigned_ip);
2391                         dhcp_client->assigned_ip = get_ip(packet.yiaddr);
2392
2393                         if (dhcp_client->state == REBOOTING) {
2394                                 option = dhcp_get_option(&packet,
2395                                                         DHCP_SERVER_ID);
2396                                 dhcp_client->server_ip = get_be32(option);
2397                         }
2398
2399                         /* Address should be set up here */
2400                         if (dhcp_client->lease_available_cb)
2401                                 dhcp_client->lease_available_cb(dhcp_client,
2402                                         dhcp_client->lease_available_data);
2403
2404                         start_bound(dhcp_client);
2405                 } else if (*message_type == DHCPNAK) {
2406                         dhcp_client->retry_times = 0;
2407
2408                         remove_timeouts(dhcp_client);
2409
2410 #if defined TIZEN_EXT
2411                         if (dhcp_client->init_reboot) {
2412                                 g_dhcp_client_set_address_known(dhcp_client, FALSE);
2413                                 dhcp_client->timeout = g_idle_add_full(
2414                                                                 G_PRIORITY_HIGH,
2415                                                                 restart_dhcp_timeout,
2416                                                                 dhcp_client,
2417                                                                 NULL);
2418
2419                                 break;
2420                         }
2421 #endif
2422                         dhcp_client->timeout = g_timeout_add_seconds_full(
2423                                                         G_PRIORITY_HIGH, 3,
2424                                                         restart_dhcp_timeout,
2425                                                         dhcp_client,
2426                                                         NULL);
2427                 }
2428
2429                 break;
2430         case SOLICITATION:
2431                 if (dhcp_client->type != G_DHCP_IPV6)
2432                         return TRUE;
2433
2434                 if (packet6->message != DHCPV6_REPLY &&
2435                                 packet6->message != DHCPV6_ADVERTISE)
2436                         return TRUE;
2437
2438                 count = 0;
2439                 server_id = dhcpv6_get_option(packet6, pkt_len,
2440                                 G_DHCPV6_SERVERID, &option_len, &count);
2441                 if (!server_id || count != 1 || option_len == 0) {
2442                         /* RFC 3315, 15.10 */
2443                         debug(dhcp_client,
2444                                 "server duid error, discarding msg %p/%d/%d",
2445                                 server_id, option_len, count);
2446                         return TRUE;
2447                 }
2448                 dhcp_client->server_duid = g_try_malloc(option_len);
2449                 if (!dhcp_client->server_duid)
2450                         return TRUE;
2451                 memcpy(dhcp_client->server_duid, server_id, option_len);
2452                 dhcp_client->server_duid_len = option_len;
2453
2454                 if (packet6->message == DHCPV6_REPLY) {
2455                         uint8_t *rapid_commit;
2456                         count = 0;
2457                         option_len = 0;
2458                         rapid_commit = dhcpv6_get_option(packet6, pkt_len,
2459                                                         G_DHCPV6_RAPID_COMMIT,
2460                                                         &option_len, &count);
2461                         if (!rapid_commit || option_len != 0 ||
2462                                                                 count != 1)
2463                                 /* RFC 3315, 17.1.4 */
2464                                 return TRUE;
2465                 }
2466
2467                 switch_listening_mode(dhcp_client, L_NONE);
2468
2469                 if (dhcp_client->status_code == 0)
2470                         get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2471                                         &dhcp_client->status_code);
2472
2473                 if (packet6->message == DHCPV6_ADVERTISE) {
2474                         if (dhcp_client->advertise_cb)
2475                                 dhcp_client->advertise_cb(dhcp_client,
2476                                                 dhcp_client->advertise_data);
2477                         return TRUE;
2478                 }
2479
2480                 if (dhcp_client->solicitation_cb) {
2481                         /*
2482                          * The dhcp_client might not be valid after the
2483                          * callback call so just return immediately.
2484                          */
2485                         dhcp_client->solicitation_cb(dhcp_client,
2486                                         dhcp_client->solicitation_data);
2487                         return TRUE;
2488                 }
2489                 break;
2490         case REBIND:
2491                 if (dhcp_client->type != G_DHCP_IPV6)
2492                         return TRUE;
2493
2494                 server_id = dhcpv6_get_option(packet6, pkt_len,
2495                                 G_DHCPV6_SERVERID, &option_len, &count);
2496                 if (!dhcp_client->server_duid && server_id &&
2497                                                                 count == 1) {
2498                         /*
2499                          * If we do not have server duid yet, then get it now.
2500                          * Prefix delegation renew support needs it.
2501                          */
2502                         dhcp_client->server_duid = g_try_malloc(option_len);
2503                         if (!dhcp_client->server_duid)
2504                                 return TRUE;
2505                         memcpy(dhcp_client->server_duid, server_id, option_len);
2506                         dhcp_client->server_duid_len = option_len;
2507                 }
2508                 /* fall through */
2509         case INFORMATION_REQ:
2510         case REQUEST:
2511         case RENEW:
2512         case RELEASE:
2513         case CONFIRM:
2514         case DECLINE:
2515                 if (dhcp_client->type != G_DHCP_IPV6)
2516                         return TRUE;
2517
2518                 if (packet6->message != DHCPV6_REPLY)
2519                         return TRUE;
2520
2521                 count = 0;
2522                 option_len = 0;
2523                 server_id = dhcpv6_get_option(packet6, pkt_len,
2524                                 G_DHCPV6_SERVERID, &option_len, &count);
2525                 if (!server_id || count != 1 || option_len == 0 ||
2526                                 (dhcp_client->server_duid_len > 0 &&
2527                                 memcmp(dhcp_client->server_duid, server_id,
2528                                         dhcp_client->server_duid_len) != 0)) {
2529                         /* RFC 3315, 15.10 */
2530                         debug(dhcp_client,
2531                                 "server duid error, discarding msg %p/%d/%d",
2532                                 server_id, option_len, count);
2533                         return TRUE;
2534                 }
2535
2536                 switch_listening_mode(dhcp_client, L_NONE);
2537
2538                 get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2539                                                 &dhcp_client->status_code);
2540
2541                 if (dhcp_client->information_req_cb) {
2542                         /*
2543                          * The dhcp_client might not be valid after the
2544                          * callback call so just return immediately.
2545                          */
2546                         dhcp_client->information_req_cb(dhcp_client,
2547                                         dhcp_client->information_req_data);
2548                         return TRUE;
2549                 }
2550                 if (dhcp_client->request_cb) {
2551                         dhcp_client->request_cb(dhcp_client,
2552                                         dhcp_client->request_data);
2553                         return TRUE;
2554                 }
2555                 if (dhcp_client->renew_cb) {
2556                         dhcp_client->renew_cb(dhcp_client,
2557                                         dhcp_client->renew_data);
2558                         return TRUE;
2559                 }
2560                 if (dhcp_client->rebind_cb) {
2561                         dhcp_client->rebind_cb(dhcp_client,
2562                                         dhcp_client->rebind_data);
2563                         return TRUE;
2564                 }
2565                 if (dhcp_client->release_cb) {
2566                         dhcp_client->release_cb(dhcp_client,
2567                                         dhcp_client->release_data);
2568                         return TRUE;
2569                 }
2570                 if (dhcp_client->decline_cb) {
2571                         dhcp_client->decline_cb(dhcp_client,
2572                                         dhcp_client->decline_data);
2573                         return TRUE;
2574                 }
2575                 if (dhcp_client->confirm_cb) {
2576                         count = 0;
2577                         server_id = dhcpv6_get_option(packet6, pkt_len,
2578                                                 G_DHCPV6_SERVERID, &option_len,
2579                                                 &count);
2580                         if (!server_id || count != 1 ||
2581                                                         option_len == 0) {
2582                                 /* RFC 3315, 15.10 */
2583                                 debug(dhcp_client,
2584                                         "confirm server duid error, "
2585                                         "discarding msg %p/%d/%d",
2586                                         server_id, option_len, count);
2587                                 return TRUE;
2588                         }
2589                         dhcp_client->server_duid = g_try_malloc(option_len);
2590                         if (!dhcp_client->server_duid)
2591                                 return TRUE;
2592                         memcpy(dhcp_client->server_duid, server_id, option_len);
2593                         dhcp_client->server_duid_len = option_len;
2594
2595                         dhcp_client->confirm_cb(dhcp_client,
2596                                                 dhcp_client->confirm_data);
2597                         return TRUE;
2598                 }
2599                 break;
2600         default:
2601                 break;
2602         }
2603
2604         debug(dhcp_client, "processed DHCP packet (new state %d)",
2605                                                         dhcp_client->state);
2606
2607         return TRUE;
2608 }
2609
2610 static gboolean discover_timeout(gpointer user_data)
2611 {
2612         GDHCPClient *dhcp_client = user_data;
2613
2614         dhcp_client->retry_times++;
2615
2616         /*
2617          * We do not send the REQUESTED IP option if we are retrying because
2618          * if the server is non-authoritative it will ignore the request if the
2619          * option is present.
2620          */
2621         g_dhcp_client_start(dhcp_client, NULL);
2622
2623         return FALSE;
2624 }
2625
2626 static gboolean reboot_timeout(gpointer user_data)
2627 {
2628         GDHCPClient *dhcp_client = user_data;
2629         dhcp_client->retry_times = 0;
2630         dhcp_client->requested_ip = 0;
2631         dhcp_client->state = INIT_SELECTING;
2632         /*
2633          * We do not send the REQUESTED IP option because the server didn't
2634          * respond when we send DHCPREQUEST with the REQUESTED IP option in
2635          * init-reboot state
2636          */
2637         g_dhcp_client_start(dhcp_client, NULL);
2638
2639         return FALSE;
2640 }
2641
2642 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
2643 {
2644         GDHCPClient *dhcp_client = dhcp_data;
2645
2646         debug(dhcp_client, "back to MONITOR mode");
2647
2648         dhcp_client->conflicts = 0;
2649         dhcp_client->state = IPV4LL_MONITOR;
2650
2651         return FALSE;
2652 }
2653
2654 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
2655 {
2656         GDHCPClient *dhcp_client = dhcp_data;
2657         uint32_t ip;
2658
2659 #if defined TIZEN_EXT
2660         if (!dhcp_client)
2661                 return FALSE;
2662 #endif
2663
2664         debug(dhcp_client, "request timeout (retries %d)",
2665                dhcp_client->retry_times);
2666
2667         if (dhcp_client->retry_times != ANNOUNCE_NUM) {
2668                 dhcp_client->retry_times++;
2669                 send_announce_packet(dhcp_client);
2670                 return FALSE;
2671         }
2672
2673         ip = htonl(dhcp_client->requested_ip);
2674         debug(dhcp_client, "switching to monitor mode");
2675         dhcp_client->state = IPV4LL_MONITOR;
2676         dhcp_client->assigned_ip = get_ip(ip);
2677
2678         if (dhcp_client->ipv4ll_available_cb)
2679                 dhcp_client->ipv4ll_available_cb(dhcp_client,
2680                                         dhcp_client->ipv4ll_available_data);
2681         dhcp_client->conflicts = 0;
2682         dhcp_client->timeout = 0;
2683
2684         return FALSE;
2685 }
2686
2687 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
2688 {
2689
2690         GDHCPClient *dhcp_client = dhcp_data;
2691
2692         debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
2693                dhcp_client->retry_times);
2694
2695         if (dhcp_client->retry_times == PROBE_NUM) {
2696                 dhcp_client->state = IPV4LL_ANNOUNCE;
2697                 dhcp_client->retry_times = 0;
2698
2699                 dhcp_client->retry_times++;
2700                 send_announce_packet(dhcp_client);
2701                 return FALSE;
2702         }
2703         dhcp_client->retry_times++;
2704         send_probe_packet(dhcp_client);
2705
2706         return FALSE;
2707 }
2708
2709 int g_dhcp_client_start(GDHCPClient *dhcp_client, const char *last_address)
2710 {
2711         int re;
2712         uint32_t addr;
2713         uint64_t rand;
2714
2715 #if defined TIZEN_EXT
2716         int discover_retry = 0;
2717         int timeout = 0;
2718 #endif
2719
2720         remove_timeouts(dhcp_client);
2721
2722         if (dhcp_client->type == G_DHCP_IPV6) {
2723                 if (dhcp_client->information_req_cb) {
2724                         dhcp_client->state = INFORMATION_REQ;
2725                         re = switch_listening_mode(dhcp_client, L3);
2726                         if (re != 0) {
2727                                 switch_listening_mode(dhcp_client, L_NONE);
2728                                 dhcp_client->state = 0;
2729                                 return re;
2730                         }
2731                         send_information_req(dhcp_client);
2732
2733                 } else if (dhcp_client->solicitation_cb) {
2734                         dhcp_client->state = SOLICITATION;
2735                         re = switch_listening_mode(dhcp_client, L3);
2736                         if (re != 0) {
2737                                 switch_listening_mode(dhcp_client, L_NONE);
2738                                 dhcp_client->state = 0;
2739                                 return re;
2740                         }
2741                         send_solicitation(dhcp_client);
2742
2743                 } else if (dhcp_client->request_cb) {
2744                         dhcp_client->state = REQUEST;
2745                         re = switch_listening_mode(dhcp_client, L3);
2746                         if (re != 0) {
2747                                 switch_listening_mode(dhcp_client, L_NONE);
2748                                 dhcp_client->state = 0;
2749                                 return re;
2750                         }
2751                         send_dhcpv6_request(dhcp_client);
2752
2753                 } else if (dhcp_client->confirm_cb) {
2754                         dhcp_client->state = CONFIRM;
2755                         re = switch_listening_mode(dhcp_client, L3);
2756                         if (re != 0) {
2757                                 switch_listening_mode(dhcp_client, L_NONE);
2758                                 dhcp_client->state = 0;
2759                                 return re;
2760                         }
2761                         send_dhcpv6_confirm(dhcp_client);
2762
2763                 } else if (dhcp_client->renew_cb) {
2764                         dhcp_client->state = RENEW;
2765                         re = switch_listening_mode(dhcp_client, L3);
2766                         if (re != 0) {
2767                                 switch_listening_mode(dhcp_client, L_NONE);
2768                                 dhcp_client->state = 0;
2769                                 return re;
2770                         }
2771                         send_dhcpv6_renew(dhcp_client);
2772
2773                 } else if (dhcp_client->rebind_cb) {
2774                         dhcp_client->state = REBIND;
2775                         re = switch_listening_mode(dhcp_client, L3);
2776                         if (re != 0) {
2777                                 switch_listening_mode(dhcp_client, L_NONE);
2778                                 dhcp_client->state = 0;
2779                                 return re;
2780                         }
2781                         send_dhcpv6_rebind(dhcp_client);
2782
2783                 } else if (dhcp_client->release_cb) {
2784                         dhcp_client->state = RENEW;
2785                         re = switch_listening_mode(dhcp_client, L3);
2786                         if (re != 0) {
2787                                 switch_listening_mode(dhcp_client, L_NONE);
2788                                 dhcp_client->state = 0;
2789                                 return re;
2790                         }
2791                         send_dhcpv6_release(dhcp_client);
2792                 } else if (dhcp_client->decline_cb) {
2793                         dhcp_client->state = DECLINE;
2794                         re = switch_listening_mode(dhcp_client, L3);
2795                         if (re != 0) {
2796                                 switch_listening_mode(dhcp_client, L_NONE);
2797                                 dhcp_client->state = 0;
2798                                 return re;
2799                         }
2800                         send_dhcpv6_decline(dhcp_client);
2801                 }
2802
2803                 return 0;
2804         }
2805
2806 #if defined TIZEN_EXT
2807         if (g_ascii_strncasecmp(dhcp_client->interface, "wlan", 4)
2808                         == 0) {
2809                 discover_retry = DISCOVER_RETRIES_WIFI;
2810                 timeout = DISCOVER_TIMEOUT_WIFI;
2811         } else {
2812                 discover_retry = DISCOVER_RETRIES;
2813                 timeout = DISCOVER_TIMEOUT;
2814         }
2815
2816         debug(dhcp_client, "[DHCPC] Discover retry/total : [%d]/[%d] timeout [%d]",
2817                         dhcp_client->retry_times, discover_retry, timeout);
2818 #endif
2819
2820
2821         if (dhcp_client->type == G_DHCP_IPV4LL) {
2822                 dhcp_client->state = INIT_SELECTING;
2823                 ipv4ll_start(dhcp_client);
2824                 return 0;
2825         }
2826
2827 #if defined TIZEN_EXT
2828                 if (dhcp_client->retry_times == discover_retry) {
2829 #else
2830                 if (dhcp_client->retry_times == DISCOVER_RETRIES) {
2831 #endif
2832                 if (dhcp_client->no_lease_cb)
2833                         dhcp_client->no_lease_cb(dhcp_client,
2834                                                 dhcp_client->no_lease_data);
2835                 dhcp_client->retry_times = 0;
2836                 return 0;
2837         }
2838
2839         if (dhcp_client->retry_times == 0) {
2840                 g_free(dhcp_client->assigned_ip);
2841                 dhcp_client->assigned_ip = NULL;
2842
2843                 dhcp_client->state = INIT_SELECTING;
2844                 re = switch_listening_mode(dhcp_client, L2);
2845                 if (re != 0)
2846                         return re;
2847
2848                 dhcp_get_random(&rand);
2849                 dhcp_client->xid = rand;
2850                 dhcp_client->start = time(NULL);
2851         }
2852
2853         if (!last_address) {
2854                 addr = 0;
2855         } else {
2856                 addr = ntohl(inet_addr(last_address));
2857                 if (addr == 0xFFFFFFFF || ((addr & LINKLOCAL_ADDR) ==
2858                                         LINKLOCAL_ADDR)) {
2859                         addr = 0;
2860                 } else if (dhcp_client->last_address != last_address) {
2861                         g_free(dhcp_client->last_address);
2862                         dhcp_client->last_address = g_strdup(last_address);
2863                 }
2864         }
2865
2866         if ((addr != 0) && (dhcp_client->type != G_DHCP_IPV4LL)) {
2867                 debug(dhcp_client, "DHCP client start with state init_reboot");
2868                 dhcp_client->requested_ip = addr;
2869                 dhcp_client->state = REBOOTING;
2870                 send_request(dhcp_client);
2871
2872                 dhcp_client->timeout = g_timeout_add_seconds_full(
2873                                                                 G_PRIORITY_HIGH,
2874 #if defined TIZEN_EXT
2875                                                                 timeout,
2876 #else
2877                                                                 REQUEST_TIMEOUT,
2878 #endif
2879                                                                 reboot_timeout,
2880                                                                 dhcp_client,
2881                                                                 NULL);
2882                 return 0;
2883         }
2884         send_discover(dhcp_client, addr);
2885
2886         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
2887 #if defined TIZEN_EXT
2888                                                         timeout,
2889 #else
2890                                                         DISCOVER_TIMEOUT,
2891 #endif
2892                                                         discover_timeout,
2893                                                         dhcp_client,
2894                                                         NULL);
2895         return 0;
2896 }
2897
2898 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
2899 {
2900         switch_listening_mode(dhcp_client, L_NONE);
2901
2902         if (dhcp_client->state == BOUND ||
2903                         dhcp_client->state == RENEWING ||
2904                                 dhcp_client->state == REBINDING)
2905                 send_release(dhcp_client, dhcp_client->server_ip,
2906                                         dhcp_client->requested_ip);
2907
2908         remove_timeouts(dhcp_client);
2909
2910         if (dhcp_client->listener_watch > 0) {
2911                 g_source_remove(dhcp_client->listener_watch);
2912                 dhcp_client->listener_watch = 0;
2913         }
2914
2915         dhcp_client->retry_times = 0;
2916         dhcp_client->ack_retry_times = 0;
2917
2918         dhcp_client->requested_ip = 0;
2919         dhcp_client->state = RELEASED;
2920         dhcp_client->lease_seconds = 0;
2921         dhcp_client->request_bcast = false;
2922 }
2923
2924 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
2925                                         unsigned char option_code)
2926 {
2927         return g_hash_table_lookup(dhcp_client->code_value_hash,
2928                                         GINT_TO_POINTER((int) option_code));
2929 }
2930
2931 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
2932                                         GDHCPClientEvent event,
2933                                         GDHCPClientEventFunc func,
2934                                                         gpointer data)
2935 {
2936         switch (event) {
2937         case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
2938                 dhcp_client->lease_available_cb = func;
2939                 dhcp_client->lease_available_data = data;
2940                 return;
2941         case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
2942                 if (dhcp_client->type == G_DHCP_IPV6)
2943                         return;
2944                 dhcp_client->ipv4ll_available_cb = func;
2945                 dhcp_client->ipv4ll_available_data = data;
2946                 return;
2947         case G_DHCP_CLIENT_EVENT_NO_LEASE:
2948                 dhcp_client->no_lease_cb = func;
2949                 dhcp_client->no_lease_data = data;
2950                 return;
2951         case G_DHCP_CLIENT_EVENT_LEASE_LOST:
2952                 dhcp_client->lease_lost_cb = func;
2953                 dhcp_client->lease_lost_data = data;
2954                 return;
2955         case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
2956                 if (dhcp_client->type == G_DHCP_IPV6)
2957                         return;
2958                 dhcp_client->ipv4ll_lost_cb = func;
2959                 dhcp_client->ipv4ll_lost_data = data;
2960                 return;
2961         case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
2962                 dhcp_client->address_conflict_cb = func;
2963                 dhcp_client->address_conflict_data = data;
2964                 return;
2965         case G_DHCP_CLIENT_EVENT_INFORMATION_REQ:
2966                 if (dhcp_client->type != G_DHCP_IPV6)
2967                         return;
2968                 dhcp_client->information_req_cb = func;
2969                 dhcp_client->information_req_data = data;
2970                 return;
2971         case G_DHCP_CLIENT_EVENT_SOLICITATION:
2972                 if (dhcp_client->type != G_DHCP_IPV6)
2973                         return;
2974                 dhcp_client->solicitation_cb = func;
2975                 dhcp_client->solicitation_data = data;
2976                 return;
2977         case G_DHCP_CLIENT_EVENT_ADVERTISE:
2978                 if (dhcp_client->type != G_DHCP_IPV6)
2979                         return;
2980                 dhcp_client->advertise_cb = func;
2981                 dhcp_client->advertise_data = data;
2982                 return;
2983         case G_DHCP_CLIENT_EVENT_REQUEST:
2984                 if (dhcp_client->type != G_DHCP_IPV6)
2985                         return;
2986                 dhcp_client->request_cb = func;
2987                 dhcp_client->request_data = data;
2988                 return;
2989         case G_DHCP_CLIENT_EVENT_RENEW:
2990                 if (dhcp_client->type != G_DHCP_IPV6)
2991                         return;
2992                 dhcp_client->renew_cb = func;
2993                 dhcp_client->renew_data = data;
2994                 return;
2995         case G_DHCP_CLIENT_EVENT_REBIND:
2996                 if (dhcp_client->type != G_DHCP_IPV6)
2997                         return;
2998                 dhcp_client->rebind_cb = func;
2999                 dhcp_client->rebind_data = data;
3000                 return;
3001         case G_DHCP_CLIENT_EVENT_RELEASE:
3002                 if (dhcp_client->type != G_DHCP_IPV6)
3003                         return;
3004                 dhcp_client->release_cb = func;
3005                 dhcp_client->release_data = data;
3006                 return;
3007         case G_DHCP_CLIENT_EVENT_CONFIRM:
3008                 if (dhcp_client->type != G_DHCP_IPV6)
3009                         return;
3010                 dhcp_client->confirm_cb = func;
3011                 dhcp_client->confirm_data = data;
3012                 return;
3013         case G_DHCP_CLIENT_EVENT_DECLINE:
3014                 if (dhcp_client->type != G_DHCP_IPV6)
3015                         return;
3016                 dhcp_client->decline_cb = func;
3017                 dhcp_client->decline_data = data;
3018                 return;
3019         }
3020 }
3021
3022 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
3023 {
3024         return dhcp_client->ifindex;
3025 }
3026
3027 char *g_dhcp_client_get_server_address(GDHCPClient *dhcp_client)
3028 {
3029         if (!dhcp_client)
3030                 return NULL;
3031
3032         return get_ip(dhcp_client->server_ip);
3033 }
3034
3035 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
3036 {
3037         return g_strdup(dhcp_client->assigned_ip);
3038 }
3039
3040 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
3041 {
3042         GList *option = NULL;
3043
3044         if (dhcp_client->type == G_DHCP_IPV6)
3045                 return NULL;
3046
3047         switch (dhcp_client->state) {
3048         case IPV4LL_DEFEND:
3049         case IPV4LL_MONITOR:
3050                 return g_strdup("255.255.0.0");
3051         case BOUND:
3052         case RENEWING:
3053         case REBINDING:
3054                 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
3055                 if (option)
3056                         return g_strdup(option->data);
3057         case INIT_SELECTING:
3058         case REBOOTING:
3059         case REQUESTING:
3060         case RELEASED:
3061         case IPV4LL_PROBE:
3062         case IPV4LL_ANNOUNCE:
3063         case INFORMATION_REQ:
3064         case SOLICITATION:
3065         case REQUEST:
3066         case CONFIRM:
3067         case RENEW:
3068         case REBIND:
3069         case RELEASE:
3070         case DECLINE:
3071                 break;
3072         }
3073         return NULL;
3074 }
3075
3076 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
3077                                                 unsigned int option_code)
3078 {
3079         if (!g_list_find(dhcp_client->request_list,
3080                                 GINT_TO_POINTER((int)option_code)))
3081                 dhcp_client->request_list = g_list_prepend(
3082                                         dhcp_client->request_list,
3083                                         (GINT_TO_POINTER((int) option_code)));
3084
3085         return G_DHCP_CLIENT_ERROR_NONE;
3086 }
3087
3088 void g_dhcp_client_clear_requests(GDHCPClient *dhcp_client)
3089 {
3090         g_list_free(dhcp_client->request_list);
3091         dhcp_client->request_list = NULL;
3092 }
3093
3094 void g_dhcp_client_clear_values(GDHCPClient *dhcp_client)
3095 {
3096         g_hash_table_remove_all(dhcp_client->send_value_hash);
3097 }
3098
3099 static uint8_t *alloc_dhcp_option(int code, const uint8_t *data, unsigned size)
3100 {
3101         uint8_t *storage;
3102
3103         storage = g_try_malloc(size + OPT_DATA);
3104         if (!storage)
3105                 return NULL;
3106
3107         storage[OPT_CODE] = code;
3108         storage[OPT_LEN] = size;
3109         memcpy(&storage[OPT_DATA], data, size);
3110
3111         return storage;
3112 }
3113
3114 static uint8_t *alloc_dhcp_data_option(int code, const uint8_t *data,
3115                                         unsigned size)
3116 {
3117         return alloc_dhcp_option(code, data, MIN(size, 255));
3118 }
3119
3120 static uint8_t *alloc_dhcp_string_option(int code, const char *str)
3121 {
3122         return alloc_dhcp_data_option(code, (const uint8_t *)str, strlen(str));
3123 }
3124
3125 GDHCPClientError g_dhcp_client_set_id(GDHCPClient *dhcp_client)
3126 {
3127         const unsigned maclen = 6;
3128         const unsigned idlen = maclen + 1;
3129         const uint8_t option_code = G_DHCP_CLIENT_ID;
3130         uint8_t idbuf[idlen];
3131         uint8_t *data_option;
3132
3133         idbuf[0] = ARPHRD_ETHER;
3134
3135         memcpy(&idbuf[1], dhcp_client->mac_address, maclen);
3136
3137         data_option = alloc_dhcp_data_option(option_code, idbuf, idlen);
3138         if (!data_option)
3139                 return G_DHCP_CLIENT_ERROR_NOMEM;
3140
3141         g_hash_table_insert(dhcp_client->send_value_hash,
3142                 GINT_TO_POINTER((int) option_code), data_option);
3143
3144         return G_DHCP_CLIENT_ERROR_NONE;
3145 }
3146
3147 /* Now only support send hostname */
3148 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
3149                 unsigned char option_code, const char *option_value)
3150 {
3151         uint8_t *binary_option;
3152
3153         if (option_code == G_DHCP_HOST_NAME && option_value) {
3154                 binary_option = alloc_dhcp_string_option(option_code,
3155                                                         option_value);
3156                 if (!binary_option)
3157                         return G_DHCP_CLIENT_ERROR_NOMEM;
3158
3159                 g_hash_table_insert(dhcp_client->send_value_hash,
3160                         GINT_TO_POINTER((int) option_code), binary_option);
3161         }
3162
3163         return G_DHCP_CLIENT_ERROR_NONE;
3164 }
3165
3166 static uint8_t *alloc_dhcpv6_option(uint16_t code, uint8_t *option,
3167                                 uint16_t len)
3168 {
3169         uint8_t *storage;
3170
3171         storage = g_malloc(2 + 2 + len);
3172         if (!storage)
3173                 return NULL;
3174
3175         storage[0] = code >> 8;
3176         storage[1] = code & 0xff;
3177         storage[2] = len >> 8;
3178         storage[3] = len & 0xff;
3179         memcpy(storage + 2 + 2, option, len);
3180
3181         return storage;
3182 }
3183
3184 gboolean g_dhcpv6_client_clear_send(GDHCPClient *dhcp_client, uint16_t code)
3185 {
3186         return g_hash_table_remove(dhcp_client->send_value_hash,
3187                                 GINT_TO_POINTER((int)code));
3188 }
3189
3190 void g_dhcpv6_client_set_send(GDHCPClient *dhcp_client,
3191                                         uint16_t option_code,
3192                                         uint8_t *option_value,
3193                                         uint16_t option_len)
3194 {
3195         if (option_value) {
3196                 uint8_t *binary_option;
3197
3198                 debug(dhcp_client, "setting option %d to %p len %d",
3199                         option_code, option_value, option_len);
3200
3201                 binary_option = alloc_dhcpv6_option(option_code, option_value,
3202                                                 option_len);
3203                 if (binary_option)
3204                         g_hash_table_insert(dhcp_client->send_value_hash,
3205                                         GINT_TO_POINTER((int) option_code),
3206                                         binary_option);
3207         }
3208 }
3209
3210 void g_dhcpv6_client_reset_request(GDHCPClient *dhcp_client)
3211 {
3212         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
3213                 return;
3214
3215         dhcp_client->last_request = time(NULL);
3216 }
3217
3218 uint16_t g_dhcpv6_client_get_status(GDHCPClient *dhcp_client)
3219 {
3220         if (!dhcp_client || dhcp_client->type != G_DHCP_IPV6)
3221                 return 0;
3222
3223         return dhcp_client->status_code;
3224 }
3225
3226 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
3227 {
3228         if (!dhcp_client)
3229                 return NULL;
3230
3231         __sync_fetch_and_add(&dhcp_client->ref_count, 1);
3232
3233         return dhcp_client;
3234 }
3235
3236 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
3237 {
3238         if (!dhcp_client)
3239                 return;
3240
3241         if (__sync_fetch_and_sub(&dhcp_client->ref_count, 1) != 1)
3242                 return;
3243
3244         g_dhcp_client_stop(dhcp_client);
3245
3246         g_free(dhcp_client->interface);
3247         g_free(dhcp_client->assigned_ip);
3248         g_free(dhcp_client->last_address);
3249         g_free(dhcp_client->duid);
3250         g_free(dhcp_client->server_duid);
3251
3252         g_list_free(dhcp_client->request_list);
3253         g_list_free(dhcp_client->require_list);
3254
3255         g_hash_table_destroy(dhcp_client->code_value_hash);
3256         g_hash_table_destroy(dhcp_client->send_value_hash);
3257
3258         g_free(dhcp_client);
3259 #if defined TIZEN_EXT
3260         dhcp_client = NULL;
3261 #endif
3262 }
3263
3264 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
3265                                 GDHCPDebugFunc func, gpointer user_data)
3266 {
3267         if (!dhcp_client)
3268                 return;
3269
3270         dhcp_client->debug_func = func;
3271         dhcp_client->debug_data = user_data;
3272 }
3273
3274 static GDHCPIAPrefix *copy_prefix(gpointer data)
3275 {
3276         GDHCPIAPrefix *copy, *prefix = data;
3277
3278         copy = g_try_new(GDHCPIAPrefix, 1);
3279         if (!copy)
3280                 return NULL;
3281
3282         memcpy(copy, prefix, sizeof(GDHCPIAPrefix));
3283
3284         return copy;
3285 }
3286
3287 GSList *g_dhcpv6_copy_prefixes(GSList *prefixes)
3288 {
3289         GSList *copy = NULL;
3290         GSList *list;
3291
3292         for (list = prefixes; list; list = list->next)
3293                 copy = g_slist_prepend(copy, copy_prefix(list->data));
3294
3295         return copy;
3296 }
3297
3298 #if defined TIZEN_EXT
3299 void g_dhcp_client_set_address_known(GDHCPClient *dhcp_client, gboolean known)
3300 {
3301         /* DHCPREQUEST during INIT-REBOOT state (rfc2131)
3302          * 4.4.3 Initialization with known network address
3303          * 4.3.2 DHCPREQUEST generated during INIT-REBOOT state
3304          */
3305         debug(dhcp_client, "known network address (%d)", known);
3306
3307         if (dhcp_client->init_reboot == known)
3308                 return;
3309
3310         dhcp_client->init_reboot = known;
3311 }
3312 #endif