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