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