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