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