iptables: Merge clear_tables_flags() and reset_xtables()
[platform/upstream/connman.git] / gdhcp / client.c
1 /*
2  *
3  *  DHCP client library with GLib integration
4  *
5  *  Copyright (C) 2009-2012  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <stdio.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <arpa/inet.h>
34
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_option_uint32(&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_option_uint16(&packet, DHCP_MAX_SIZE, 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_option_uint32(&packet, DHCP_REQUESTED_IP,
393                                                 dhcp_client->requested_ip);
394         dhcp_add_option_uint32(&packet, DHCP_SERVER_ID,
395                                                 dhcp_client->server_ip);
396
397         add_request_options(dhcp_client, &packet);
398
399         add_send_options(dhcp_client, &packet);
400
401         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
402                                         INADDR_BROADCAST, SERVER_PORT,
403                                         MAC_BCAST_ADDR, dhcp_client->ifindex);
404 }
405
406 static int send_renew(GDHCPClient *dhcp_client)
407 {
408         struct dhcp_packet packet;
409
410         debug(dhcp_client, "sending DHCP renew request");
411
412         init_packet(dhcp_client , &packet, DHCPREQUEST);
413         packet.xid = dhcp_client->xid;
414         packet.ciaddr = htonl(dhcp_client->requested_ip);
415
416         add_request_options(dhcp_client, &packet);
417
418         add_send_options(dhcp_client, &packet);
419
420         return dhcp_send_kernel_packet(&packet,
421                 dhcp_client->requested_ip, CLIENT_PORT,
422                 dhcp_client->server_ip, SERVER_PORT);
423 }
424
425 static int send_rebound(GDHCPClient *dhcp_client)
426 {
427         struct dhcp_packet packet;
428
429         debug(dhcp_client, "sending DHCP rebound request");
430
431         init_packet(dhcp_client , &packet, DHCPREQUEST);
432         packet.xid = dhcp_client->xid;
433         packet.ciaddr = htonl(dhcp_client->requested_ip);
434
435         add_request_options(dhcp_client, &packet);
436
437         add_send_options(dhcp_client, &packet);
438
439         return dhcp_send_raw_packet(&packet, INADDR_ANY, CLIENT_PORT,
440                                         INADDR_BROADCAST, SERVER_PORT,
441                                         MAC_BCAST_ADDR, dhcp_client->ifindex);
442 }
443
444 static int send_release(GDHCPClient *dhcp_client,
445                         uint32_t server, uint32_t ciaddr)
446 {
447         struct dhcp_packet packet;
448
449         debug(dhcp_client, "sending DHCP release request");
450
451         init_packet(dhcp_client, &packet, DHCPRELEASE);
452         packet.xid = rand();
453         packet.ciaddr = htonl(ciaddr);
454
455         dhcp_add_option_uint32(&packet, DHCP_SERVER_ID, server);
456
457         return dhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT,
458                                                 server, SERVER_PORT);
459 }
460
461 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data);
462 static int switch_listening_mode(GDHCPClient *dhcp_client,
463                                         ListenMode listen_mode);
464
465 static gboolean send_probe_packet(gpointer dhcp_data)
466 {
467         GDHCPClient *dhcp_client;
468         guint timeout;
469
470         dhcp_client = dhcp_data;
471         /* if requested_ip is not valid, pick a new address*/
472         if (dhcp_client->requested_ip == 0) {
473                 debug(dhcp_client, "pick a new random address");
474                 dhcp_client->requested_ip = ipv4ll_random_ip(0);
475         }
476
477         debug(dhcp_client, "sending IPV4LL probe request");
478
479         if (dhcp_client->retry_times == 1) {
480                 dhcp_client->state = IPV4LL_PROBE;
481                 switch_listening_mode(dhcp_client, L_ARP);
482         }
483         ipv4ll_send_arp_packet(dhcp_client->mac_address, 0,
484                         dhcp_client->requested_ip, dhcp_client->ifindex);
485
486         if (dhcp_client->retry_times < PROBE_NUM) {
487                 /*add a random timeout in range of PROBE_MIN to PROBE_MAX*/
488                 timeout = ipv4ll_random_delay_ms(PROBE_MAX-PROBE_MIN);
489                 timeout += PROBE_MIN*1000;
490         } else
491                 timeout = (ANNOUNCE_WAIT * 1000);
492
493         dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
494                                                  timeout,
495                                                  ipv4ll_probe_timeout,
496                                                  dhcp_client,
497                                                  NULL);
498         return FALSE;
499 }
500
501 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data);
502 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data);
503
504 static gboolean send_announce_packet(gpointer dhcp_data)
505 {
506         GDHCPClient *dhcp_client;
507
508         dhcp_client = dhcp_data;
509
510         debug(dhcp_client, "sending IPV4LL announce request");
511
512         ipv4ll_send_arp_packet(dhcp_client->mac_address,
513                                 dhcp_client->requested_ip,
514                                 dhcp_client->requested_ip,
515                                 dhcp_client->ifindex);
516
517         if (dhcp_client->timeout > 0)
518                 g_source_remove(dhcp_client->timeout);
519         dhcp_client->timeout = 0;
520
521         if (dhcp_client->state == IPV4LL_DEFEND) {
522                 dhcp_client->timeout =
523                         g_timeout_add_seconds_full(G_PRIORITY_HIGH,
524                                                 DEFEND_INTERVAL,
525                                                 ipv4ll_defend_timeout,
526                                                 dhcp_client,
527                                                 NULL);
528                 return TRUE;
529         } else
530                 dhcp_client->timeout =
531                         g_timeout_add_seconds_full(G_PRIORITY_HIGH,
532                                                 ANNOUNCE_INTERVAL,
533                                                 ipv4ll_announce_timeout,
534                                                 dhcp_client,
535                                                 NULL);
536         return TRUE;
537 }
538
539 static void get_interface_mac_address(int index, uint8_t *mac_address)
540 {
541         struct ifreq ifr;
542         int sk, err;
543
544         sk = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
545         if (sk < 0) {
546                 perror("Open socket error");
547                 return;
548         }
549
550         memset(&ifr, 0, sizeof(ifr));
551         ifr.ifr_ifindex = index;
552
553         err = ioctl(sk, SIOCGIFNAME, &ifr);
554         if (err < 0) {
555                 perror("Get interface name error");
556                 goto done;
557         }
558
559         err = ioctl(sk, SIOCGIFHWADDR, &ifr);
560         if (err < 0) {
561                 perror("Get mac address error");
562                 goto done;
563         }
564
565         memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
566
567 done:
568         close(sk);
569 }
570
571 int g_dhcpv6_create_duid(GDHCPDuidType duid_type, int index, int type,
572                         unsigned char **duid, int *duid_len)
573 {
574         time_t duid_time;
575
576         switch (duid_type) {
577         case G_DHCPV6_DUID_LLT:
578                 *duid_len = 2 + 2 + 4 + ETH_ALEN;
579                 *duid = g_try_malloc(*duid_len);
580                 if (*duid == NULL)
581                         return -ENOMEM;
582
583                 (*duid)[0] = 0;
584                 (*duid)[1] = 1;
585                 get_interface_mac_address(index, &(*duid)[2 + 2 + 4]);
586                 (*duid)[2] = 0;
587                 (*duid)[3] = type;
588                 duid_time = time(NULL) - DUID_TIME_EPOCH;
589                 (*duid)[4] = duid_time >> 24;
590                 (*duid)[5] = duid_time >> 16;
591                 (*duid)[6] = duid_time >> 8;
592                 (*duid)[7] = duid_time & 0xff;
593                 break;
594         case G_DHCPV6_DUID_EN:
595                 return -EINVAL;
596         case G_DHCPV6_DUID_LL:
597                 *duid_len = 2 + 2 + ETH_ALEN;
598                 *duid = g_try_malloc(*duid_len);
599                 if (*duid == NULL)
600                         return -ENOMEM;
601
602                 (*duid)[0] = 0;
603                 (*duid)[1] = 3;
604                 get_interface_mac_address(index, &(*duid)[2 + 2]);
605                 (*duid)[2] = 0;
606                 (*duid)[3] = type;
607                 break;
608         }
609
610         return 0;
611 }
612
613 int g_dhcpv6_client_set_duid(GDHCPClient *dhcp_client, unsigned char *duid,
614                         int duid_len)
615 {
616         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
617                 return -EINVAL;
618
619         g_free(dhcp_client->duid);
620
621         dhcp_client->duid = duid;
622         dhcp_client->duid_len = duid_len;
623
624         return 0;
625 }
626
627 uint32_t g_dhcpv6_client_get_iaid(GDHCPClient *dhcp_client)
628 {
629         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
630                 return 0;
631
632         return dhcp_client->iaid;
633 }
634
635 void g_dhcpv6_client_create_iaid(GDHCPClient *dhcp_client, int index,
636                                 unsigned char *iaid)
637 {
638         uint8_t buf[6];
639
640         get_interface_mac_address(index, buf);
641
642         memcpy(iaid, &buf[2], 4);
643         dhcp_client->iaid = iaid[0] << 24 |
644                         iaid[1] << 16 | iaid[2] << 8 | iaid[3];
645 }
646
647 int g_dhcpv6_client_get_timeouts(GDHCPClient *dhcp_client,
648                                 uint32_t *T1, uint32_t *T2,
649                                 time_t *last_renew, time_t *last_rebind,
650                                 time_t *expire)
651 {
652         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
653                 return -EINVAL;
654
655         if (T1 != NULL)
656                 *T1 = dhcp_client->T1;
657
658         if (T2 != NULL)
659                 *T2 = dhcp_client->T2;
660
661         if (last_renew != NULL)
662                 *last_renew = dhcp_client->last_renew;
663
664         if (last_rebind != NULL)
665                 *last_rebind = dhcp_client->last_rebind;
666
667         if (expire != NULL)
668                 *expire = dhcp_client->expire;
669
670         return 0;
671 }
672
673 static uint8_t *create_iaaddr(GDHCPClient *dhcp_client, uint8_t *buf,
674                                 uint16_t len)
675 {
676         buf[0] = 0;
677         buf[1] = G_DHCPV6_IAADDR;
678         buf[2] = 0;
679         buf[3] = len;
680         memcpy(&buf[4], &dhcp_client->ia_na, 16);
681         memset(&buf[20], 0, 4); /* preferred */
682         memset(&buf[24], 0, 4); /* valid */
683         return buf;
684 }
685
686 static void put_iaid(GDHCPClient *dhcp_client, int index, uint8_t *buf)
687 {
688         uint32_t iaid;
689
690         iaid = g_dhcpv6_client_get_iaid(dhcp_client);
691         if (iaid == 0) {
692                 g_dhcpv6_client_create_iaid(dhcp_client, index, buf);
693                 return;
694         }
695
696         buf[0] = iaid >> 24;
697         buf[1] = iaid >> 16;
698         buf[2] = iaid >> 8;
699         buf[3] = iaid;
700 }
701
702 int g_dhcpv6_client_set_ia(GDHCPClient *dhcp_client, int index,
703                         int code, uint32_t *T1, uint32_t *T2,
704                         gboolean add_iaaddr)
705 {
706         if (code == G_DHCPV6_IA_TA) {
707                 uint8_t ia_options[4];
708
709                 put_iaid(dhcp_client, index, ia_options);
710
711                 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_TA);
712                 g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_TA,
713                                         ia_options, sizeof(ia_options));
714
715         } else if (code == G_DHCPV6_IA_NA) {
716
717                 g_dhcp_client_set_request(dhcp_client, G_DHCPV6_IA_NA);
718
719                 if (add_iaaddr == TRUE) {
720 #define IAADDR_LEN (16+4+4)
721                         uint8_t ia_options[4+4+4+2+2+IAADDR_LEN];
722
723                         put_iaid(dhcp_client, index, ia_options);
724
725                         if (T1 != NULL) {
726                                 ia_options[4] = *T1 >> 24;
727                                 ia_options[5] = *T1 >> 16;
728                                 ia_options[6] = *T1 >> 8;
729                                 ia_options[7] = *T1;
730                         } else
731                                 memset(&ia_options[4], 0x00, 4);
732
733                         if (T2 != NULL) {
734                                 ia_options[8] = *T2 >> 24;
735                                 ia_options[9] = *T2 >> 16;
736                                 ia_options[10] = *T2 >> 8;
737                                 ia_options[11] = *T2;
738                         } else
739                                 memset(&ia_options[8], 0x00, 4);
740
741                         create_iaaddr(dhcp_client, &ia_options[12],
742                                         IAADDR_LEN);
743
744                         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
745                                         ia_options, sizeof(ia_options));
746                 } else {
747                         uint8_t ia_options[4+4+4];
748
749                         put_iaid(dhcp_client, index, ia_options);
750
751                         memset(&ia_options[4], 0x00, 4); /* T1 (4 bytes) */
752                         memset(&ia_options[8], 0x00, 4); /* T2 (4 bytes) */
753
754                         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_IA_NA,
755                                         ia_options, sizeof(ia_options));
756                 }
757
758         } else
759                 return -EINVAL;
760
761         return 0;
762 }
763
764 int g_dhcpv6_client_set_oro(GDHCPClient *dhcp_client, int args, ...)
765 {
766         va_list va;
767         int i, j, len = sizeof(uint16_t) * args;
768         uint8_t *values;
769
770         values = g_try_malloc(len);
771         if (values == NULL)
772                 return -ENOMEM;
773
774         va_start(va, args);
775         for (i = 0, j = 0; i < args; i++) {
776                 uint16_t value = va_arg(va, int);
777                 values[j++] = value >> 8;
778                 values[j++] = value & 0xff;
779         }
780         va_end(va);
781
782         g_dhcpv6_client_set_send(dhcp_client, G_DHCPV6_ORO, values, len);
783
784         g_free(values);
785
786         return 0;
787 }
788
789 static int send_dhcpv6_msg(GDHCPClient *dhcp_client, int type, char *msg)
790 {
791         struct dhcpv6_packet *packet;
792         uint8_t buf[MAX_DHCPV6_PKT_SIZE];
793         unsigned char *ptr;
794         int ret, max_buf;
795
796         memset(buf, 0, sizeof(buf));
797         packet = (struct dhcpv6_packet *)&buf[0];
798         ptr = buf + sizeof(struct dhcpv6_packet);
799
800         debug(dhcp_client, "sending DHCPv6 %s message", msg);
801
802         init_packet(dhcp_client, packet, type);
803
804         dhcp_client->xid = packet->transaction_id[0] << 16 |
805                         packet->transaction_id[1] << 8 |
806                         packet->transaction_id[2];
807
808         max_buf = MAX_DHCPV6_PKT_SIZE - sizeof(struct dhcpv6_packet);
809
810         add_dhcpv6_request_options(dhcp_client, packet, buf, max_buf, &ptr);
811
812         add_dhcpv6_send_options(dhcp_client, buf, max_buf, &ptr);
813
814         ret = dhcpv6_send_packet(dhcp_client->ifindex, packet, ptr - buf);
815
816         debug(dhcp_client, "sent %d pkt %p len %d", ret, packet, ptr - buf);
817         return ret;
818 }
819
820 static int send_solicitation(GDHCPClient *dhcp_client)
821 {
822         return send_dhcpv6_msg(dhcp_client, DHCPV6_SOLICIT, "solicit");
823 }
824
825 static int send_dhcpv6_request(GDHCPClient *dhcp_client)
826 {
827         return send_dhcpv6_msg(dhcp_client, DHCPV6_REQUEST, "request");
828 }
829
830 static int send_dhcpv6_renew(GDHCPClient *dhcp_client)
831 {
832         return send_dhcpv6_msg(dhcp_client, DHCPV6_RENEW, "renew");
833 }
834
835 static int send_dhcpv6_rebind(GDHCPClient *dhcp_client)
836 {
837         return send_dhcpv6_msg(dhcp_client, DHCPV6_REBIND, "rebind");
838 }
839
840 static int send_dhcpv6_release(GDHCPClient *dhcp_client)
841 {
842         return send_dhcpv6_msg(dhcp_client, DHCPV6_RELEASE, "release");
843 }
844
845 static int send_information_req(GDHCPClient *dhcp_client)
846 {
847         return send_dhcpv6_msg(dhcp_client, DHCPV6_INFORMATION_REQ,
848                                 "information-req");
849 }
850
851 static void remove_value(gpointer data, gpointer user_data)
852 {
853         char *value = data;
854         g_free(value);
855 }
856
857 static void remove_option_value(gpointer data)
858 {
859         GList *option_value = data;
860
861         g_list_foreach(option_value, remove_value, NULL);
862 }
863
864 GDHCPClient *g_dhcp_client_new(GDHCPType type,
865                         int ifindex, GDHCPClientError *error)
866 {
867         GDHCPClient *dhcp_client;
868
869         if (ifindex < 0) {
870                 *error = G_DHCP_CLIENT_ERROR_INVALID_INDEX;
871                 return NULL;
872         }
873
874         dhcp_client = g_try_new0(GDHCPClient, 1);
875         if (dhcp_client == NULL) {
876                 *error = G_DHCP_CLIENT_ERROR_NOMEM;
877                 return NULL;
878         }
879
880         dhcp_client->interface = get_interface_name(ifindex);
881         if (dhcp_client->interface == NULL) {
882                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE;
883                 goto error;
884         }
885
886         if (interface_is_up(ifindex) == FALSE) {
887                 *error = G_DHCP_CLIENT_ERROR_INTERFACE_DOWN;
888                 goto error;
889         }
890
891         get_interface_mac_address(ifindex, dhcp_client->mac_address);
892
893         dhcp_client->listener_sockfd = -1;
894         dhcp_client->listener_channel = NULL;
895         dhcp_client->listen_mode = L_NONE;
896         dhcp_client->ref_count = 1;
897         dhcp_client->type = type;
898         dhcp_client->ifindex = ifindex;
899         dhcp_client->lease_available_cb = NULL;
900         dhcp_client->ipv4ll_available_cb = NULL;
901         dhcp_client->no_lease_cb = NULL;
902         dhcp_client->lease_lost_cb = NULL;
903         dhcp_client->ipv4ll_lost_cb = NULL;
904         dhcp_client->address_conflict_cb = NULL;
905         dhcp_client->listener_watch = 0;
906         dhcp_client->retry_times = 0;
907         dhcp_client->ack_retry_times = 0;
908         dhcp_client->code_value_hash = g_hash_table_new_full(g_direct_hash,
909                                 g_direct_equal, NULL, remove_option_value);
910         dhcp_client->send_value_hash = g_hash_table_new_full(g_direct_hash,
911                                 g_direct_equal, NULL, g_free);
912         dhcp_client->request_list = NULL;
913         dhcp_client->require_list = NULL;
914         dhcp_client->duid = NULL;
915         dhcp_client->duid_len = 0;
916         dhcp_client->last_renew = dhcp_client->last_rebind = time(NULL);
917         dhcp_client->expire = 0;
918
919         *error = G_DHCP_CLIENT_ERROR_NONE;
920
921         return dhcp_client;
922
923 error:
924         g_free(dhcp_client->interface);
925         g_free(dhcp_client);
926         return NULL;
927 }
928
929 #define SERVER_AND_CLIENT_PORTS  ((67 << 16) + 68)
930
931 static int dhcp_l2_socket(int ifindex)
932 {
933         int fd;
934         struct sockaddr_ll sock;
935
936         /*
937          * Comment:
938          *
939          *      I've selected not to see LL header, so BPF doesn't see it, too.
940          *      The filter may also pass non-IP and non-ARP packets, but we do
941          *      a more complete check when receiving the message in userspace.
942          *
943          * and filter shamelessly stolen from:
944          *
945          *      http://www.flamewarmaster.de/software/dhcpclient/
946          *
947          * There are a few other interesting ideas on that page (look under
948          * "Motivation").  Use of netlink events is most interesting.  Think
949          * of various network servers listening for events and reconfiguring.
950          * That would obsolete sending HUP signals and/or make use of restarts.
951          *
952          * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
953          * License: GPL v2.
954          *
955          * TODO: make conditional?
956          */
957         static const struct sock_filter filter_instr[] = {
958                 /* check for udp */
959                 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
960                 /* L5, L1, is UDP? */
961                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 2, 0),
962                 /* ugly check for arp on ethernet-like and IPv4 */
963                 BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), /* L1: */
964                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x08000604, 3, 4),/* L3, L4 */
965                 /* skip IP header */
966                 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */
967                 /* check udp source and destination ports */
968                 BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0),
969                 /* L3, L4 */
970                 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1),
971                 /* returns */
972                 BPF_STMT(BPF_RET|BPF_K, 0x0fffffff), /* L3: pass */
973                 BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */
974         };
975
976         static const struct sock_fprog filter_prog = {
977                 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
978                 /* casting const away: */
979                 .filter = (struct sock_filter *) filter_instr,
980         };
981
982         fd = socket(PF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IP));
983         if (fd < 0)
984                 return fd;
985
986         if (SERVER_PORT == 67 && CLIENT_PORT == 68)
987                 /* Use only if standard ports are in use */
988                 setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
989                                                         sizeof(filter_prog));
990
991         memset(&sock, 0, sizeof(sock));
992         sock.sll_family = AF_PACKET;
993         sock.sll_protocol = htons(ETH_P_IP);
994         sock.sll_ifindex = ifindex;
995
996         if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) != 0) {
997                 close(fd);
998                 return -errno;
999         }
1000
1001         return fd;
1002 }
1003
1004 static gboolean sanity_check(struct ip_udp_dhcp_packet *packet, int bytes)
1005 {
1006         if (packet->ip.protocol != IPPROTO_UDP)
1007                 return FALSE;
1008
1009         if (packet->ip.version != IPVERSION)
1010                 return FALSE;
1011
1012         if (packet->ip.ihl != sizeof(packet->ip) >> 2)
1013                 return FALSE;
1014
1015         if (packet->udp.dest != htons(CLIENT_PORT))
1016                 return FALSE;
1017
1018         if (ntohs(packet->udp.len) != (uint16_t)(bytes - sizeof(packet->ip)))
1019                 return FALSE;
1020
1021         return TRUE;
1022 }
1023
1024 static int dhcp_recv_l2_packet(struct dhcp_packet *dhcp_pkt, int fd)
1025 {
1026         int bytes;
1027         struct ip_udp_dhcp_packet packet;
1028         uint16_t check;
1029
1030         memset(&packet, 0, sizeof(packet));
1031
1032         bytes = read(fd, &packet, sizeof(packet));
1033         if (bytes < 0)
1034                 return -1;
1035
1036         if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp)))
1037                 return -1;
1038
1039         if (bytes < ntohs(packet.ip.tot_len))
1040                 /* packet is bigger than sizeof(packet), we did partial read */
1041                 return -1;
1042
1043         /* ignore any extra garbage bytes */
1044         bytes = ntohs(packet.ip.tot_len);
1045
1046         if (sanity_check(&packet, bytes) == FALSE)
1047                 return -1;
1048
1049         check = packet.ip.check;
1050         packet.ip.check = 0;
1051         if (check != dhcp_checksum(&packet.ip, sizeof(packet.ip)))
1052                 return -1;
1053
1054         /* verify UDP checksum. IP header has to be modified for this */
1055         memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
1056         /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
1057         packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
1058         check = packet.udp.check;
1059         packet.udp.check = 0;
1060         if (check && check != dhcp_checksum(&packet, bytes))
1061                 return -1;
1062
1063         memcpy(dhcp_pkt, &packet.data, bytes - (sizeof(packet.ip) +
1064                                                         sizeof(packet.udp)));
1065
1066         if (dhcp_pkt->cookie != htonl(DHCP_MAGIC))
1067                 return -1;
1068
1069         return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
1070 }
1071
1072 static void ipv4ll_start(GDHCPClient *dhcp_client)
1073 {
1074         guint timeout;
1075         int seed;
1076
1077         if (dhcp_client->timeout > 0) {
1078                 g_source_remove(dhcp_client->timeout);
1079                 dhcp_client->timeout = 0;
1080         }
1081
1082         switch_listening_mode(dhcp_client, L_NONE);
1083         dhcp_client->type = G_DHCP_IPV4LL;
1084         dhcp_client->retry_times = 0;
1085         dhcp_client->requested_ip = 0;
1086
1087         /*try to start with a based mac address ip*/
1088         seed = (dhcp_client->mac_address[4] << 8 | dhcp_client->mac_address[4]);
1089         dhcp_client->requested_ip = ipv4ll_random_ip(seed);
1090
1091         /*first wait a random delay to avoid storm of arp request on boot*/
1092         timeout = ipv4ll_random_delay_ms(PROBE_WAIT);
1093
1094         dhcp_client->retry_times++;
1095         dhcp_client->timeout = g_timeout_add_full(G_PRIORITY_HIGH,
1096                                                 timeout,
1097                                                 send_probe_packet,
1098                                                 dhcp_client,
1099                                                 NULL);
1100 }
1101
1102 static void ipv4ll_stop(GDHCPClient *dhcp_client)
1103 {
1104
1105         switch_listening_mode(dhcp_client, L_NONE);
1106
1107         if (dhcp_client->timeout > 0)
1108                 g_source_remove(dhcp_client->timeout);
1109
1110         if (dhcp_client->listener_watch > 0) {
1111                 g_source_remove(dhcp_client->listener_watch);
1112                 dhcp_client->listener_watch = 0;
1113         }
1114
1115         dhcp_client->state = IPV4LL_PROBE;
1116         dhcp_client->retry_times = 0;
1117         dhcp_client->requested_ip = 0;
1118
1119         g_free(dhcp_client->assigned_ip);
1120         dhcp_client->assigned_ip = NULL;
1121 }
1122
1123 static int ipv4ll_recv_arp_packet(GDHCPClient *dhcp_client)
1124 {
1125         int bytes;
1126         struct ether_arp arp;
1127         uint32_t ip_requested;
1128         int source_conflict;
1129         int target_conflict;
1130
1131         memset(&arp, 0, sizeof(arp));
1132         bytes = read(dhcp_client->listener_sockfd, &arp, sizeof(arp));
1133         if (bytes < 0)
1134                 return bytes;
1135
1136         if (arp.arp_op != htons(ARPOP_REPLY) &&
1137                         arp.arp_op != htons(ARPOP_REQUEST))
1138                 return -EINVAL;
1139
1140         ip_requested = htonl(dhcp_client->requested_ip);
1141         source_conflict = !memcmp(arp.arp_spa, &ip_requested,
1142                                                 sizeof(ip_requested));
1143
1144         target_conflict = !memcmp(arp.arp_tpa, &ip_requested,
1145                                 sizeof(ip_requested));
1146
1147         if (!source_conflict && !target_conflict)
1148                 return 0;
1149
1150         dhcp_client->conflicts++;
1151
1152         debug(dhcp_client, "IPV4LL conflict detected");
1153
1154         if (dhcp_client->state == IPV4LL_MONITOR) {
1155                 if (!source_conflict)
1156                         return 0;
1157                 dhcp_client->state = IPV4LL_DEFEND;
1158                 debug(dhcp_client, "DEFEND mode conflicts : %d",
1159                         dhcp_client->conflicts);
1160                 /*Try to defend with a single announce*/
1161                 send_announce_packet(dhcp_client);
1162                 return 0;
1163         }
1164
1165         if (dhcp_client->state == IPV4LL_DEFEND) {
1166                 if (!source_conflict)
1167                         return 0;
1168                 else if (dhcp_client->ipv4ll_lost_cb != NULL)
1169                         dhcp_client->ipv4ll_lost_cb(dhcp_client,
1170                                                 dhcp_client->ipv4ll_lost_data);
1171         }
1172
1173         ipv4ll_stop(dhcp_client);
1174
1175         if (dhcp_client->conflicts < MAX_CONFLICTS) {
1176                 /*restart whole state machine*/
1177                 dhcp_client->retry_times++;
1178                 dhcp_client->timeout =
1179                         g_timeout_add_full(G_PRIORITY_HIGH,
1180                                         ipv4ll_random_delay_ms(PROBE_WAIT),
1181                                         send_probe_packet,
1182                                         dhcp_client,
1183                                         NULL);
1184         }
1185         /* Here we got a lot of conflicts, RFC3927 states that we have
1186          * to wait RATE_LIMIT_INTERVAL before retrying,
1187          * but we just report failure.
1188          */
1189         else if (dhcp_client->no_lease_cb != NULL)
1190                         dhcp_client->no_lease_cb(dhcp_client,
1191                                                 dhcp_client->no_lease_data);
1192
1193         return 0;
1194 }
1195
1196 static gboolean check_package_owner(GDHCPClient *dhcp_client, gpointer pkt)
1197 {
1198         if (dhcp_client->type == G_DHCP_IPV6) {
1199                 struct dhcpv6_packet *packet6 = pkt;
1200                 uint32_t xid;
1201
1202                 if (packet6 == NULL)
1203                         return FALSE;
1204
1205                 xid = packet6->transaction_id[0] << 16 |
1206                         packet6->transaction_id[1] << 8 |
1207                         packet6->transaction_id[2];
1208
1209                 if (xid != dhcp_client->xid)
1210                         return FALSE;
1211         } else {
1212                 struct dhcp_packet *packet = pkt;
1213
1214                 if (packet->xid != dhcp_client->xid)
1215                         return FALSE;
1216
1217                 if (packet->hlen != 6)
1218                         return FALSE;
1219
1220                 if (memcmp(packet->chaddr, dhcp_client->mac_address, 6))
1221                         return FALSE;
1222         }
1223
1224         return TRUE;
1225 }
1226
1227 static void start_request(GDHCPClient *dhcp_client);
1228
1229 static gboolean request_timeout(gpointer user_data)
1230 {
1231         GDHCPClient *dhcp_client = user_data;
1232
1233         debug(dhcp_client, "request timeout (retries %d)",
1234                                         dhcp_client->retry_times);
1235
1236         dhcp_client->retry_times++;
1237
1238         start_request(dhcp_client);
1239
1240         return FALSE;
1241 }
1242
1243 static gboolean listener_event(GIOChannel *channel, GIOCondition condition,
1244                                                         gpointer user_data);
1245
1246 static int switch_listening_mode(GDHCPClient *dhcp_client,
1247                                         ListenMode listen_mode)
1248 {
1249         GIOChannel *listener_channel;
1250         int listener_sockfd;
1251
1252         if (dhcp_client->listen_mode == listen_mode)
1253                 return 0;
1254
1255         debug(dhcp_client, "switch listening mode (%d ==> %d)",
1256                                 dhcp_client->listen_mode, listen_mode);
1257
1258         if (dhcp_client->listen_mode != L_NONE) {
1259                 if (dhcp_client->listener_watch > 0)
1260                         g_source_remove(dhcp_client->listener_watch);
1261                 dhcp_client->listener_channel = NULL;
1262                 dhcp_client->listen_mode = L_NONE;
1263                 dhcp_client->listener_sockfd = -1;
1264                 dhcp_client->listener_watch = 0;
1265         }
1266
1267         if (listen_mode == L_NONE)
1268                 return 0;
1269
1270         if (listen_mode == L2)
1271                 listener_sockfd = dhcp_l2_socket(dhcp_client->ifindex);
1272         else if (listen_mode == L3) {
1273                 if (dhcp_client->type == G_DHCP_IPV6)
1274                         listener_sockfd = dhcp_l3_socket(DHCPV6_CLIENT_PORT,
1275                                                         dhcp_client->interface,
1276                                                         AF_INET6);
1277                 else
1278                         listener_sockfd = dhcp_l3_socket(CLIENT_PORT,
1279                                                         dhcp_client->interface,
1280                                                         AF_INET);
1281         } else if (listen_mode == L_ARP)
1282                 listener_sockfd = ipv4ll_arp_socket(dhcp_client->ifindex);
1283         else
1284                 return -EIO;
1285
1286         if (listener_sockfd < 0)
1287                 return -EIO;
1288
1289         listener_channel = g_io_channel_unix_new(listener_sockfd);
1290         if (listener_channel == NULL) {
1291                 /* Failed to create listener channel */
1292                 close(listener_sockfd);
1293                 return -EIO;
1294         }
1295
1296         dhcp_client->listen_mode = listen_mode;
1297         dhcp_client->listener_sockfd = listener_sockfd;
1298         dhcp_client->listener_channel = listener_channel;
1299
1300         g_io_channel_set_close_on_unref(listener_channel, TRUE);
1301         dhcp_client->listener_watch =
1302                         g_io_add_watch_full(listener_channel, G_PRIORITY_HIGH,
1303                                 G_IO_IN | G_IO_NVAL | G_IO_ERR | G_IO_HUP,
1304                                                 listener_event, dhcp_client,
1305                                                                 NULL);
1306         g_io_channel_unref(dhcp_client->listener_channel);
1307
1308         return 0;
1309 }
1310
1311 static void start_request(GDHCPClient *dhcp_client)
1312 {
1313         debug(dhcp_client, "start request (retries %d)",
1314                                         dhcp_client->retry_times);
1315
1316         if (dhcp_client->retry_times == REQUEST_RETRIES) {
1317                 dhcp_client->state = INIT_SELECTING;
1318                 ipv4ll_start(dhcp_client);
1319
1320                 return;
1321         }
1322
1323         if (dhcp_client->retry_times == 0) {
1324                 dhcp_client->state = REQUESTING;
1325                 switch_listening_mode(dhcp_client, L2);
1326         }
1327
1328         send_select(dhcp_client);
1329
1330         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1331                                                         REQUEST_TIMEOUT,
1332                                                         request_timeout,
1333                                                         dhcp_client,
1334                                                         NULL);
1335 }
1336
1337 static uint32_t get_lease(struct dhcp_packet *packet)
1338 {
1339         uint8_t *option;
1340         uint32_t lease_seconds;
1341
1342         option = dhcp_get_option(packet, DHCP_LEASE_TIME);
1343         if (option == NULL)
1344                 return 3600;
1345
1346         lease_seconds = get_be32(option);
1347         /* paranoia: must not be prone to overflows */
1348         lease_seconds &= 0x0fffffff;
1349         if (lease_seconds < 10)
1350                 lease_seconds = 10;
1351
1352         return lease_seconds;
1353 }
1354
1355 static void restart_dhcp(GDHCPClient *dhcp_client, int retry_times)
1356 {
1357         debug(dhcp_client, "restart DHCP (retries %d)", retry_times);
1358
1359         if (dhcp_client->timeout > 0) {
1360                 g_source_remove(dhcp_client->timeout);
1361                 dhcp_client->timeout = 0;
1362         }
1363
1364         dhcp_client->retry_times = retry_times;
1365         dhcp_client->requested_ip = 0;
1366         dhcp_client->state = INIT_SELECTING;
1367         switch_listening_mode(dhcp_client, L2);
1368
1369         g_dhcp_client_start(dhcp_client, dhcp_client->last_address);
1370 }
1371
1372 static gboolean start_rebound_timeout(gpointer user_data)
1373 {
1374         GDHCPClient *dhcp_client = user_data;
1375
1376         debug(dhcp_client, "start rebound timeout");
1377
1378         switch_listening_mode(dhcp_client, L2);
1379
1380         dhcp_client->lease_seconds >>= 1;
1381
1382         /* We need to have enough time to receive ACK package*/
1383         if (dhcp_client->lease_seconds <= 6) {
1384
1385                 /* ip need to be cleared */
1386                 if (dhcp_client->lease_lost_cb != NULL)
1387                         dhcp_client->lease_lost_cb(dhcp_client,
1388                                         dhcp_client->lease_lost_data);
1389
1390                 restart_dhcp(dhcp_client, 0);
1391         } else {
1392                 send_rebound(dhcp_client);
1393
1394                 dhcp_client->timeout =
1395                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1396                                                 dhcp_client->lease_seconds >> 1,
1397                                                         start_rebound_timeout,
1398                                                                 dhcp_client,
1399                                                                 NULL);
1400         }
1401
1402         return FALSE;
1403 }
1404
1405 static void start_rebound(GDHCPClient *dhcp_client)
1406 {
1407         debug(dhcp_client, "start rebound");
1408
1409         dhcp_client->state = REBINDING;
1410
1411         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1412                                                 dhcp_client->lease_seconds >> 1,
1413                                                         start_rebound_timeout,
1414                                                                 dhcp_client,
1415                                                                 NULL);
1416 }
1417
1418 static gboolean start_renew_timeout(gpointer user_data)
1419 {
1420         GDHCPClient *dhcp_client = user_data;
1421
1422         debug(dhcp_client, "start renew timeout");
1423
1424         dhcp_client->state = RENEWING;
1425
1426         dhcp_client->lease_seconds >>= 1;
1427
1428         switch_listening_mode(dhcp_client, L3);
1429         if (dhcp_client->lease_seconds <= 60)
1430                 start_rebound(dhcp_client);
1431         else {
1432                 send_renew(dhcp_client);
1433
1434                 if (dhcp_client->timeout > 0)
1435                         g_source_remove(dhcp_client->timeout);
1436
1437                 dhcp_client->timeout =
1438                                 g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1439                                                 dhcp_client->lease_seconds >> 1,
1440                                                         start_renew_timeout,
1441                                                                 dhcp_client,
1442                                                                 NULL);
1443         }
1444
1445         return FALSE;
1446 }
1447
1448 static void start_bound(GDHCPClient *dhcp_client)
1449 {
1450         debug(dhcp_client, "start bound");
1451
1452         dhcp_client->state = BOUND;
1453
1454         if (dhcp_client->timeout > 0)
1455                 g_source_remove(dhcp_client->timeout);
1456
1457         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
1458                                         dhcp_client->lease_seconds >> 1,
1459                                         start_renew_timeout, dhcp_client,
1460                                                         NULL);
1461 }
1462
1463 static gboolean restart_dhcp_timeout(gpointer user_data)
1464 {
1465         GDHCPClient *dhcp_client = user_data;
1466
1467         debug(dhcp_client, "restart DHCP timeout");
1468
1469         dhcp_client->ack_retry_times++;
1470
1471         restart_dhcp(dhcp_client, dhcp_client->ack_retry_times);
1472
1473         return FALSE;
1474 }
1475
1476 static char *get_ip(uint32_t ip)
1477 {
1478         struct in_addr addr;
1479
1480         addr.s_addr = ip;
1481
1482         return g_strdup(inet_ntoa(addr));
1483 }
1484
1485 /* get a rough idea of how long an option will be */
1486 static const uint8_t len_of_option_as_string[] = {
1487         [OPTION_IP] = sizeof("255.255.255.255 "),
1488         [OPTION_STRING] = 1,
1489         [OPTION_U8] = sizeof("255 "),
1490         [OPTION_U16] = sizeof("65535 "),
1491         [OPTION_U32] = sizeof("4294967295 "),
1492 };
1493
1494 static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
1495 {
1496         return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
1497 }
1498
1499 /* Create "opt_value1 option_value2 ..." string */
1500 static char *malloc_option_value_string(uint8_t *option, GDHCPOptionType type)
1501 {
1502         unsigned upper_length;
1503         int len, optlen;
1504         char *dest, *ret;
1505
1506         len = option[OPT_LEN - OPT_DATA];
1507         type &= OPTION_TYPE_MASK;
1508         optlen = dhcp_option_lengths[type];
1509         if (optlen == 0)
1510                 return NULL;
1511         upper_length = len_of_option_as_string[type] *
1512                         ((unsigned)len / (unsigned)optlen);
1513         dest = ret = g_malloc(upper_length + 1);
1514         if (ret == NULL)
1515                 return NULL;
1516
1517         while (len >= optlen) {
1518                 switch (type) {
1519                 case OPTION_IP:
1520                         dest += sprint_nip(dest, "", option);
1521                         break;
1522                 case OPTION_U16: {
1523                         uint16_t val_u16 = get_be16(option);
1524                         dest += sprintf(dest, "%u", val_u16);
1525                         break;
1526                 }
1527                 case OPTION_U32: {
1528                         uint32_t val_u32 = get_be32(option);
1529                         dest += sprintf(dest, "%u", 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 addr_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, addr_str, INET6_ADDRSTRLEN);
1678                 debug(dhcp_client, "count %d addr %s T1 %u T2 %u",
1679                         addr_count, addr_str, T1, T2);
1680
1681                 list = g_list_append(list, g_strdup(addr_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,
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 = dhcpv6_get_option(packet6, pkt_len,
1885                                 G_DHCPV6_STATUS_CODE, &option_len, NULL);
1886                 if (option != 0 && option_len > 0) {
1887                         status = option[0]<<8 | option[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[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 = dhcp_get_option(&packet, DHCP_SERVER_ID);
1926                 dhcp_client->server_ip = get_be32(option);
1927                 dhcp_client->requested_ip = ntohl(packet.yiaddr);
1928
1929                 dhcp_client->state = REQUESTING;
1930
1931                 start_request(dhcp_client);
1932
1933                 return TRUE;
1934         case REQUESTING:
1935         case RENEWING:
1936         case REBINDING:
1937                 if (*message_type == DHCPACK) {
1938                         dhcp_client->retry_times = 0;
1939
1940                         if (dhcp_client->timeout > 0)
1941                                 g_source_remove(dhcp_client->timeout);
1942                         dhcp_client->timeout = 0;
1943
1944                         dhcp_client->lease_seconds = get_lease(&packet);
1945
1946                         get_request(dhcp_client, &packet);
1947
1948                         switch_listening_mode(dhcp_client, L_NONE);
1949
1950                         g_free(dhcp_client->assigned_ip);
1951                         dhcp_client->assigned_ip = get_ip(packet.yiaddr);
1952
1953                         /* Address should be set up here */
1954                         if (dhcp_client->lease_available_cb != NULL)
1955                                 dhcp_client->lease_available_cb(dhcp_client,
1956                                         dhcp_client->lease_available_data);
1957
1958                         start_bound(dhcp_client);
1959                 } else if (*message_type == DHCPNAK) {
1960                         dhcp_client->retry_times = 0;
1961
1962                         if (dhcp_client->timeout > 0)
1963                                 g_source_remove(dhcp_client->timeout);
1964
1965                         dhcp_client->timeout = g_timeout_add_seconds_full(
1966                                                         G_PRIORITY_HIGH, 3,
1967                                                         restart_dhcp_timeout,
1968                                                         dhcp_client,
1969                                                         NULL);
1970                 }
1971
1972                 break;
1973         case SOLICITATION:
1974                 if (dhcp_client->type != G_DHCP_IPV6)
1975                         return TRUE;
1976
1977                 if (packet6->message != DHCPV6_REPLY &&
1978                                 packet6->message != DHCPV6_ADVERTISE)
1979                         return TRUE;
1980
1981                 count = 0;
1982                 server_id = dhcpv6_get_option(packet6, pkt_len,
1983                                 G_DHCPV6_SERVERID, &option_len, &count);
1984                 if (server_id == NULL || count != 1 || option_len == 0) {
1985                         /* RFC 3315, 15.10 */
1986                         debug(dhcp_client,
1987                                 "server duid error, discarding msg %p/%d/%d",
1988                                 server_id, option_len, count);
1989                         return TRUE;
1990                 }
1991                 dhcp_client->server_duid = g_try_malloc(option_len);
1992                 if (dhcp_client->server_duid == NULL)
1993                         return TRUE;
1994                 memcpy(dhcp_client->server_duid, server_id, option_len);
1995                 dhcp_client->server_duid_len = option_len;
1996
1997                 if (packet6->message == DHCPV6_REPLY) {
1998                         uint8_t *rapid_commit;
1999                         count = 0;
2000                         option_len = 0;
2001                         rapid_commit = dhcpv6_get_option(packet6, pkt_len,
2002                                                         G_DHCPV6_RAPID_COMMIT,
2003                                                         &option_len, &count);
2004                         if (rapid_commit == NULL || option_len == 0 ||
2005                                                                 count != 1)
2006                                 /* RFC 3315, 17.1.4 */
2007                                 return TRUE;
2008                 }
2009
2010                 switch_listening_mode(dhcp_client, L_NONE);
2011
2012                 if (dhcp_client->status_code == 0)
2013                         get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2014                                         &dhcp_client->status_code);
2015
2016                 if (packet6->message == DHCPV6_ADVERTISE) {
2017                         if (dhcp_client->advertise_cb != NULL)
2018                                 dhcp_client->advertise_cb(dhcp_client,
2019                                                 dhcp_client->advertise_data);
2020                         return TRUE;
2021                 }
2022
2023                 if (dhcp_client->solicitation_cb != NULL) {
2024                         /*
2025                          * The dhcp_client might not be valid after the
2026                          * callback call so just return immediately.
2027                          */
2028                         dhcp_client->solicitation_cb(dhcp_client,
2029                                         dhcp_client->solicitation_data);
2030                         return TRUE;
2031                 }
2032                 break;
2033         case INFORMATION_REQ:
2034         case REQUEST:
2035         case RENEW:
2036         case REBIND:
2037         case RELEASE:
2038                 if (dhcp_client->type != G_DHCP_IPV6)
2039                         return TRUE;
2040
2041                 if (packet6->message != DHCPV6_REPLY)
2042                         return TRUE;
2043
2044                 count = 0;
2045                 option_len = 0;
2046                 server_id = dhcpv6_get_option(packet6, pkt_len,
2047                                 G_DHCPV6_SERVERID, &option_len, &count);
2048                 if (server_id == NULL || count != 1 || option_len == 0 ||
2049                                 (dhcp_client->server_duid_len > 0 &&
2050                                 memcmp(dhcp_client->server_duid, server_id,
2051                                         dhcp_client->server_duid_len) != 0)) {
2052                         /* RFC 3315, 15.10 */
2053                         debug(dhcp_client,
2054                                 "server duid error, discarding msg %p/%d/%d",
2055                                 server_id, option_len, count);
2056                         return TRUE;
2057                 }
2058
2059                 switch_listening_mode(dhcp_client, L_NONE);
2060
2061                 dhcp_client->status_code = 0;
2062                 get_dhcpv6_request(dhcp_client, packet6, pkt_len,
2063                                                 &dhcp_client->status_code);
2064
2065                 if (dhcp_client->information_req_cb != NULL) {
2066                         /*
2067                          * The dhcp_client might not be valid after the
2068                          * callback call so just return immediately.
2069                          */
2070                         dhcp_client->information_req_cb(dhcp_client,
2071                                         dhcp_client->information_req_data);
2072                         return TRUE;
2073                 }
2074                 if (dhcp_client->request_cb != NULL) {
2075                         dhcp_client->request_cb(dhcp_client,
2076                                         dhcp_client->request_data);
2077                         return TRUE;
2078                 }
2079                 if (dhcp_client->renew_cb != NULL) {
2080                         dhcp_client->renew_cb(dhcp_client,
2081                                         dhcp_client->renew_data);
2082                         return TRUE;
2083                 }
2084                 if (dhcp_client->rebind_cb != NULL) {
2085                         dhcp_client->rebind_cb(dhcp_client,
2086                                         dhcp_client->rebind_data);
2087                         return TRUE;
2088                 }
2089                 if (dhcp_client->release_cb != NULL) {
2090                         dhcp_client->release_cb(dhcp_client,
2091                                         dhcp_client->release_data);
2092                         return TRUE;
2093                 }
2094                 break;
2095         default:
2096                 break;
2097         }
2098
2099         debug(dhcp_client, "processed DHCP packet (new state %d)",
2100                                                         dhcp_client->state);
2101
2102         return TRUE;
2103 }
2104
2105 static gboolean discover_timeout(gpointer user_data)
2106 {
2107         GDHCPClient *dhcp_client = user_data;
2108
2109         dhcp_client->retry_times++;
2110
2111         /*
2112          * We do not send the REQUESTED IP option if we are retrying because
2113          * if the server is non-authoritative it will ignore the request if the
2114          * option is present.
2115          */
2116         g_dhcp_client_start(dhcp_client, NULL);
2117
2118         return FALSE;
2119 }
2120
2121 static gboolean ipv4ll_defend_timeout(gpointer dhcp_data)
2122 {
2123         GDHCPClient *dhcp_client = dhcp_data;
2124
2125         debug(dhcp_client, "back to MONITOR mode");
2126
2127         dhcp_client->conflicts = 0;
2128         dhcp_client->state = IPV4LL_MONITOR;
2129
2130         return FALSE;
2131 }
2132
2133 static gboolean ipv4ll_announce_timeout(gpointer dhcp_data)
2134 {
2135         GDHCPClient *dhcp_client = dhcp_data;
2136         uint32_t ip;
2137
2138         debug(dhcp_client, "request timeout (retries %d)",
2139                dhcp_client->retry_times);
2140
2141         if (dhcp_client->retry_times != ANNOUNCE_NUM){
2142                 dhcp_client->retry_times++;
2143                 send_announce_packet(dhcp_client);
2144                 return FALSE;
2145         }
2146
2147         ip = htonl(dhcp_client->requested_ip);
2148         debug(dhcp_client, "switching to monitor mode");
2149         dhcp_client->state = IPV4LL_MONITOR;
2150         dhcp_client->assigned_ip = get_ip(ip);
2151
2152         if (dhcp_client->ipv4ll_available_cb != NULL)
2153                 dhcp_client->ipv4ll_available_cb(dhcp_client,
2154                                         dhcp_client->ipv4ll_available_data);
2155         dhcp_client->conflicts = 0;
2156
2157         return FALSE;
2158 }
2159
2160 static gboolean ipv4ll_probe_timeout(gpointer dhcp_data)
2161 {
2162
2163         GDHCPClient *dhcp_client = dhcp_data;
2164
2165         debug(dhcp_client, "IPV4LL probe timeout (retries %d)",
2166                dhcp_client->retry_times);
2167
2168         if (dhcp_client->retry_times == PROBE_NUM) {
2169                 dhcp_client->state = IPV4LL_ANNOUNCE;
2170                 dhcp_client->retry_times = 0;
2171
2172                 dhcp_client->retry_times++;
2173                 send_announce_packet(dhcp_client);
2174                 return FALSE;
2175         }
2176         dhcp_client->retry_times++;
2177         send_probe_packet(dhcp_client);
2178
2179         return FALSE;
2180 }
2181
2182 int g_dhcp_client_start(GDHCPClient *dhcp_client, const char *last_address)
2183 {
2184         int re;
2185         uint32_t addr;
2186
2187         if (dhcp_client->type == G_DHCP_IPV6) {
2188                 if (dhcp_client->information_req_cb) {
2189                         dhcp_client->state = INFORMATION_REQ;
2190                         re = switch_listening_mode(dhcp_client, L3);
2191                         if (re != 0) {
2192                                 switch_listening_mode(dhcp_client, L_NONE);
2193                                 dhcp_client->state = 0;
2194                                 return re;
2195                         }
2196                         send_information_req(dhcp_client);
2197
2198                 } else if (dhcp_client->solicitation_cb) {
2199                         dhcp_client->state = SOLICITATION;
2200                         re = switch_listening_mode(dhcp_client, L3);
2201                         if (re != 0) {
2202                                 switch_listening_mode(dhcp_client, L_NONE);
2203                                 dhcp_client->state = 0;
2204                                 return re;
2205                         }
2206                         send_solicitation(dhcp_client);
2207
2208                 } else if (dhcp_client->request_cb) {
2209                         dhcp_client->state = REQUEST;
2210                         re = switch_listening_mode(dhcp_client, L3);
2211                         if (re != 0) {
2212                                 switch_listening_mode(dhcp_client, L_NONE);
2213                                 dhcp_client->state = 0;
2214                                 return re;
2215                         }
2216                         send_dhcpv6_request(dhcp_client);
2217
2218                 } else if (dhcp_client->renew_cb) {
2219                         dhcp_client->state = RENEW;
2220                         re = switch_listening_mode(dhcp_client, L3);
2221                         if (re != 0) {
2222                                 switch_listening_mode(dhcp_client, L_NONE);
2223                                 dhcp_client->state = 0;
2224                                 return re;
2225                         }
2226                         send_dhcpv6_renew(dhcp_client);
2227
2228                 } else if (dhcp_client->rebind_cb) {
2229                         dhcp_client->state = REBIND;
2230                         re = switch_listening_mode(dhcp_client, L3);
2231                         if (re != 0) {
2232                                 switch_listening_mode(dhcp_client, L_NONE);
2233                                 dhcp_client->state = 0;
2234                                 return re;
2235                         }
2236                         send_dhcpv6_rebind(dhcp_client);
2237
2238                 } else if (dhcp_client->release_cb) {
2239                         dhcp_client->state = RENEW;
2240                         re = switch_listening_mode(dhcp_client, L3);
2241                         if (re != 0) {
2242                                 switch_listening_mode(dhcp_client, L_NONE);
2243                                 dhcp_client->state = 0;
2244                                 return re;
2245                         }
2246                         send_dhcpv6_release(dhcp_client);
2247                 }
2248
2249                 return 0;
2250         }
2251
2252         if (dhcp_client->retry_times == DISCOVER_RETRIES) {
2253                 ipv4ll_start(dhcp_client);
2254                 return 0;
2255         }
2256
2257         if (dhcp_client->retry_times == 0) {
2258                 g_free(dhcp_client->assigned_ip);
2259                 dhcp_client->assigned_ip = NULL;
2260
2261                 dhcp_client->state = INIT_SELECTING;
2262                 re = switch_listening_mode(dhcp_client, L2);
2263                 if (re != 0)
2264                         return re;
2265
2266                 dhcp_client->xid = rand();
2267                 dhcp_client->start = time(NULL);
2268         }
2269
2270         if (last_address == NULL) {
2271                 addr = 0;
2272         } else {
2273                 addr = inet_addr(last_address);
2274                 if (addr == 0xFFFFFFFF) {
2275                         addr = 0;
2276                 } else {
2277                         g_free(dhcp_client->last_address);
2278                         dhcp_client->last_address = g_strdup(last_address);
2279                 }
2280         }
2281         send_discover(dhcp_client, addr);
2282
2283         dhcp_client->timeout = g_timeout_add_seconds_full(G_PRIORITY_HIGH,
2284                                                         DISCOVER_TIMEOUT,
2285                                                         discover_timeout,
2286                                                         dhcp_client,
2287                                                         NULL);
2288         return 0;
2289 }
2290
2291 void g_dhcp_client_stop(GDHCPClient *dhcp_client)
2292 {
2293         switch_listening_mode(dhcp_client, L_NONE);
2294
2295         if (dhcp_client->state == BOUND ||
2296                         dhcp_client->state == RENEWING ||
2297                                 dhcp_client->state == REBINDING)
2298                 send_release(dhcp_client, dhcp_client->server_ip,
2299                                         dhcp_client->requested_ip);
2300
2301         if (dhcp_client->timeout > 0) {
2302                 g_source_remove(dhcp_client->timeout);
2303                 dhcp_client->timeout = 0;
2304         }
2305
2306         if (dhcp_client->listener_watch > 0) {
2307                 g_source_remove(dhcp_client->listener_watch);
2308                 dhcp_client->listener_watch = 0;
2309         }
2310
2311         dhcp_client->listener_channel = NULL;
2312
2313         dhcp_client->retry_times = 0;
2314         dhcp_client->ack_retry_times = 0;
2315
2316         dhcp_client->requested_ip = 0;
2317         dhcp_client->state = RELEASED;
2318         dhcp_client->lease_seconds = 0;
2319 }
2320
2321 GList *g_dhcp_client_get_option(GDHCPClient *dhcp_client,
2322                                         unsigned char option_code)
2323 {
2324         return g_hash_table_lookup(dhcp_client->code_value_hash,
2325                                         GINT_TO_POINTER((int) option_code));
2326 }
2327
2328 void g_dhcp_client_register_event(GDHCPClient *dhcp_client,
2329                                         GDHCPClientEvent event,
2330                                         GDHCPClientEventFunc func,
2331                                                         gpointer data)
2332 {
2333         switch (event) {
2334         case G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE:
2335                 dhcp_client->lease_available_cb = func;
2336                 dhcp_client->lease_available_data = data;
2337                 return;
2338         case G_DHCP_CLIENT_EVENT_IPV4LL_AVAILABLE:
2339                 if (dhcp_client->type == G_DHCP_IPV6)
2340                         return;
2341                 dhcp_client->ipv4ll_available_cb = func;
2342                 dhcp_client->ipv4ll_available_data = data;
2343                 return;
2344         case G_DHCP_CLIENT_EVENT_NO_LEASE:
2345                 dhcp_client->no_lease_cb = func;
2346                 dhcp_client->no_lease_data = data;
2347                 return;
2348         case G_DHCP_CLIENT_EVENT_LEASE_LOST:
2349                 dhcp_client->lease_lost_cb = func;
2350                 dhcp_client->lease_lost_data = data;
2351                 return;
2352         case G_DHCP_CLIENT_EVENT_IPV4LL_LOST:
2353                 if (dhcp_client->type == G_DHCP_IPV6)
2354                         return;
2355                 dhcp_client->ipv4ll_lost_cb = func;
2356                 dhcp_client->ipv4ll_lost_data = data;
2357                 return;
2358         case G_DHCP_CLIENT_EVENT_ADDRESS_CONFLICT:
2359                 dhcp_client->address_conflict_cb = func;
2360                 dhcp_client->address_conflict_data = data;
2361                 return;
2362         case G_DHCP_CLIENT_EVENT_INFORMATION_REQ:
2363                 if (dhcp_client->type == G_DHCP_IPV4)
2364                         return;
2365                 dhcp_client->information_req_cb = func;
2366                 dhcp_client->information_req_data = data;
2367                 return;
2368         case G_DHCP_CLIENT_EVENT_SOLICITATION:
2369                 if (dhcp_client->type == G_DHCP_IPV4)
2370                         return;
2371                 dhcp_client->solicitation_cb = func;
2372                 dhcp_client->solicitation_data = data;
2373                 return;
2374         case G_DHCP_CLIENT_EVENT_ADVERTISE:
2375                 if (dhcp_client->type == G_DHCP_IPV4)
2376                         return;
2377                 dhcp_client->advertise_cb = func;
2378                 dhcp_client->advertise_data = data;
2379                 return;
2380         case G_DHCP_CLIENT_EVENT_REQUEST:
2381                 if (dhcp_client->type == G_DHCP_IPV4)
2382                         return;
2383                 dhcp_client->request_cb = func;
2384                 dhcp_client->request_data = data;
2385                 return;
2386         case G_DHCP_CLIENT_EVENT_RENEW:
2387                 if (dhcp_client->type == G_DHCP_IPV4)
2388                         return;
2389                 dhcp_client->renew_cb = func;
2390                 dhcp_client->renew_data = data;
2391                 return;
2392         case G_DHCP_CLIENT_EVENT_REBIND:
2393                 if (dhcp_client->type == G_DHCP_IPV4)
2394                         return;
2395                 dhcp_client->rebind_cb = func;
2396                 dhcp_client->rebind_data = data;
2397                 return;
2398         case G_DHCP_CLIENT_EVENT_RELEASE:
2399                 if (dhcp_client->type == G_DHCP_IPV4)
2400                         return;
2401                 dhcp_client->release_cb = func;
2402                 dhcp_client->release_data = data;
2403                 return;
2404         }
2405 }
2406
2407 int g_dhcp_client_get_index(GDHCPClient *dhcp_client)
2408 {
2409         return dhcp_client->ifindex;
2410 }
2411
2412 char *g_dhcp_client_get_address(GDHCPClient *dhcp_client)
2413 {
2414         return g_strdup(dhcp_client->assigned_ip);
2415 }
2416
2417 char *g_dhcp_client_get_netmask(GDHCPClient *dhcp_client)
2418 {
2419         GList *option = NULL;
2420
2421         if (dhcp_client->type == G_DHCP_IPV6)
2422                 return NULL;
2423
2424         switch (dhcp_client->state) {
2425         case IPV4LL_DEFEND:
2426         case IPV4LL_MONITOR:
2427                 return g_strdup("255.255.0.0");
2428         case BOUND:
2429         case RENEWING:
2430         case REBINDING:
2431                 option = g_dhcp_client_get_option(dhcp_client, G_DHCP_SUBNET);
2432                 if (option != NULL)
2433                         return g_strdup(option->data);
2434         case INIT_SELECTING:
2435         case REQUESTING:
2436         case RELEASED:
2437         case IPV4LL_PROBE:
2438         case IPV4LL_ANNOUNCE:
2439         case INFORMATION_REQ:
2440         case SOLICITATION:
2441         case REQUEST:
2442         case RENEW:
2443         case REBIND:
2444         case RELEASE:
2445                 break;
2446         }
2447         return NULL;
2448 }
2449
2450 GDHCPClientError g_dhcp_client_set_request(GDHCPClient *dhcp_client,
2451                                                 unsigned int option_code)
2452 {
2453         if (g_list_find(dhcp_client->request_list,
2454                         GINT_TO_POINTER((int) option_code)) == NULL)
2455                 dhcp_client->request_list = g_list_prepend(
2456                                         dhcp_client->request_list,
2457                                         (GINT_TO_POINTER((int) option_code)));
2458
2459         return G_DHCP_CLIENT_ERROR_NONE;
2460 }
2461
2462 void g_dhcp_client_clear_requests(GDHCPClient *dhcp_client)
2463 {
2464         g_list_free(dhcp_client->request_list);
2465         dhcp_client->request_list = NULL;
2466 }
2467
2468 void g_dhcp_client_clear_values(GDHCPClient *dhcp_client)
2469 {
2470         g_hash_table_remove_all(dhcp_client->send_value_hash);
2471 }
2472
2473 static uint8_t *alloc_dhcp_option(int code, const uint8_t *data, unsigned size)
2474 {
2475         uint8_t *storage;
2476
2477         storage = g_try_malloc(size + OPT_DATA);
2478         if (storage == NULL)
2479                 return NULL;
2480
2481         storage[OPT_CODE] = code;
2482         storage[OPT_LEN] = size;
2483         memcpy(&storage[OPT_DATA], data, size);
2484
2485         return storage;
2486 }
2487
2488 static uint8_t *alloc_dhcp_data_option(int code, const uint8_t *data, unsigned size)
2489 {
2490         return alloc_dhcp_option(code, data, MIN(size, 255));
2491 }
2492
2493 static uint8_t *alloc_dhcp_string_option(int code, const char *str)
2494 {
2495         return alloc_dhcp_data_option(code, (const uint8_t *)str, strlen(str));
2496 }
2497
2498 GDHCPClientError g_dhcp_client_set_id(GDHCPClient *dhcp_client)
2499 {
2500         const unsigned maclen = 6;
2501         const unsigned idlen = maclen + 1;
2502         const uint8_t option_code = G_DHCP_CLIENT_ID;
2503         uint8_t idbuf[idlen];
2504         uint8_t *data_option;
2505
2506         idbuf[0] = ARPHRD_ETHER;
2507
2508         memcpy(&idbuf[1], dhcp_client->mac_address, maclen);
2509
2510         data_option = alloc_dhcp_data_option(option_code, idbuf, idlen);
2511         if (data_option == NULL)
2512                 return G_DHCP_CLIENT_ERROR_NOMEM;
2513
2514         g_hash_table_insert(dhcp_client->send_value_hash,
2515                 GINT_TO_POINTER((int) option_code), data_option);
2516
2517         return G_DHCP_CLIENT_ERROR_NONE;
2518 }
2519
2520 /* Now only support send hostname */
2521 GDHCPClientError g_dhcp_client_set_send(GDHCPClient *dhcp_client,
2522                 unsigned char option_code, const char *option_value)
2523 {
2524         uint8_t *binary_option;
2525
2526         if (option_code == G_DHCP_HOST_NAME && option_value != NULL) {
2527                 binary_option = alloc_dhcp_string_option(option_code,
2528                                                         option_value);
2529                 if (binary_option == NULL)
2530                         return G_DHCP_CLIENT_ERROR_NOMEM;
2531
2532                 g_hash_table_insert(dhcp_client->send_value_hash,
2533                         GINT_TO_POINTER((int) option_code), binary_option);
2534         }
2535
2536         return G_DHCP_CLIENT_ERROR_NONE;
2537 }
2538
2539 static uint8_t *alloc_dhcpv6_option(uint16_t code, uint8_t *option,
2540                                 uint16_t len)
2541 {
2542         uint8_t *storage;
2543
2544         storage = g_malloc(2 + 2 + len);
2545         if (storage == NULL)
2546                 return NULL;
2547
2548         storage[0] = code >> 8;
2549         storage[1] = code & 0xff;
2550         storage[2] = len >> 8;
2551         storage[3] = len & 0xff;
2552         memcpy(storage + 2 + 2, option, len);
2553
2554         return storage;
2555 }
2556
2557 void g_dhcpv6_client_set_send(GDHCPClient *dhcp_client,
2558                                         uint16_t option_code,
2559                                         uint8_t *option_value,
2560                                         uint16_t option_len)
2561 {
2562         if (option_value != NULL) {
2563                 uint8_t *binary_option;
2564
2565                 debug(dhcp_client, "setting option %d to %p len %d",
2566                         option_code, option_value, option_len);
2567
2568                 binary_option = alloc_dhcpv6_option(option_code, option_value,
2569                                                 option_len);
2570                 if (binary_option != NULL)
2571                         g_hash_table_insert(dhcp_client->send_value_hash,
2572                                         GINT_TO_POINTER((int) option_code),
2573                                         binary_option);
2574         }
2575 }
2576
2577 void g_dhcpv6_client_reset_renew(GDHCPClient *dhcp_client)
2578 {
2579         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2580                 return;
2581
2582         dhcp_client->last_renew = time(NULL);
2583 }
2584
2585 void g_dhcpv6_client_reset_rebind(GDHCPClient *dhcp_client)
2586 {
2587         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2588                 return;
2589
2590         dhcp_client->last_rebind = time(NULL);
2591 }
2592
2593 void g_dhcpv6_client_set_expire(GDHCPClient *dhcp_client, uint32_t timeout)
2594 {
2595         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2596                 return;
2597
2598         dhcp_client->expire = time(NULL) + timeout;
2599 }
2600
2601 uint16_t g_dhcpv6_client_get_status(GDHCPClient *dhcp_client)
2602 {
2603         if (dhcp_client == NULL || dhcp_client->type == G_DHCP_IPV4)
2604                 return 0;
2605
2606         return dhcp_client->status_code;
2607 }
2608
2609 GDHCPClient *g_dhcp_client_ref(GDHCPClient *dhcp_client)
2610 {
2611         if (dhcp_client == NULL)
2612                 return NULL;
2613
2614         __sync_fetch_and_add(&dhcp_client->ref_count, 1);
2615
2616         return dhcp_client;
2617 }
2618
2619 void g_dhcp_client_unref(GDHCPClient *dhcp_client)
2620 {
2621         if (dhcp_client == NULL)
2622                 return;
2623
2624         if (__sync_fetch_and_sub(&dhcp_client->ref_count, 1) != 1)
2625                 return;
2626
2627         g_dhcp_client_stop(dhcp_client);
2628
2629         g_free(dhcp_client->interface);
2630         g_free(dhcp_client->assigned_ip);
2631         g_free(dhcp_client->last_address);
2632         g_free(dhcp_client->duid);
2633         g_free(dhcp_client->server_duid);
2634
2635         g_list_free(dhcp_client->request_list);
2636         g_list_free(dhcp_client->require_list);
2637
2638         g_hash_table_destroy(dhcp_client->code_value_hash);
2639         g_hash_table_destroy(dhcp_client->send_value_hash);
2640
2641         g_free(dhcp_client);
2642 }
2643
2644 void g_dhcp_client_set_debug(GDHCPClient *dhcp_client,
2645                                 GDHCPDebugFunc func, gpointer user_data)
2646 {
2647         if (dhcp_client == NULL)
2648                 return;
2649
2650         dhcp_client->debug_func = func;
2651         dhcp_client->debug_data = user_data;
2652 }