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