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