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