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