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