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