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