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