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