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