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