1/*
2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/* -----------------------------------------------------------------------------
25 *
26 *  Theory of operation :
27 *
28 *  plugin to add L2TP client support to pppd.
29 *
30----------------------------------------------------------------------------- */
31
32
33/* -----------------------------------------------------------------------------
34  Includes
35----------------------------------------------------------------------------- */
36
37#include <stdio.h>
38#include <ctype.h>
39#include <stdlib.h>
40#include <string.h>
41#include <unistd.h>
42#include <signal.h>
43#include <errno.h>
44#include <fcntl.h>
45#include <syslog.h>
46#include <netdb.h>
47#include <pwd.h>
48#include <setjmp.h>
49#include <sys/param.h>
50#include <sys/types.h>
51#include <sys/wait.h>
52#include <sys/time.h>
53#include <sys/resource.h>
54#include <sys/socket.h>
55#include <sys/stat.h>
56#include <sys/socket.h>
57#include <netinet/in.h>
58#include <arpa/inet.h>
59#include <syslog.h>
60#include <ifaddrs.h>
61#include <sys/ioctl.h>
62#include <net/if.h>
63#include <net/if_media.h>
64#include <net/if_dl.h>
65#include <net/route.h>
66#include <net/pfkeyv2.h>
67#include <pthread.h>
68#include <sys/kern_event.h>
69#include <netinet/in_var.h>
70#include <CoreFoundation/CFNumber.h>
71#include <CoreFoundation/CFBundle.h>
72#include <SystemConfiguration/SystemConfiguration.h>
73#include <sys/un.h>
74
75
76#include "../../../Controller/ppp_msg.h"
77#include "../../../Family/ppp_defs.h"
78#include "../../../Family/if_ppp.h"
79#include "../../../Family/ppp_domain.h"
80#include "../L2TP-extension/l2tpk.h"
81#include "../../../Helpers/pppd/pppd.h"
82#include "../../../Helpers/pppd/fsm.h"
83#include "../../../Helpers/pppd/lcp.h"
84#include "../../../Helpers/vpnd/RASSchemaDefinitions.h"
85#include "../../../Helpers/vpnd/cf_utils.h"
86#include "l2tp.h"
87#include "../../../Helpers/vpnd/ipsec_utils.h"
88#include "vpn_control.h"
89
90#if TARGET_OS_EMBEDDED
91#include <CoreTelephony/CTServerConnectionPriv.h>
92#endif
93
94/* -----------------------------------------------------------------------------
95 Definitions
96----------------------------------------------------------------------------- */
97
98#define MODE_CONNECT	"connect"
99#define MODE_LISTEN	"listen"
100#define MODE_ANSWER	"answer"
101
102
103#define L2TP_DEFAULT_RECV_TIMEOUT      20 /* seconds */
104
105#define L2TP_MIN_HDR_SIZE 220		/* IPSec + Nat Traversal + L2TP/UDP + PPP */
106
107#define	L2TP_RETRY_CONNECT_CODE			1
108
109#define L2TP_DEFAULT_WAIT_IF_TIMEOUT      20 /* seconds */
110
111#define MAX_CONNECT_RETRIES 10
112
113/*
114	Private IPv4 addresses
115	10.0.0.0 - 10.255.255.255
116	172.16.0.0 - 172.31.255.255
117	192.168.0.0 - 192.168.255.255
118*/
119
120#define IN_PRIVATE_CLASSA_NETNUM	(u_int32_t)0xA000000 /* 10.0.0.0 */
121#define IN_PRIVATE_CLASSA(i)		(((u_int32_t)(i) & IN_CLASSA_NET) == IN_PRIVATE_CLASSA_NETNUM)
122
123#define IN_PRIVATE_CLASSB_NETNUM	(u_int32_t)0xAC100000 /* 172.16.0.0 - 172.31.0.0 */
124#define IN_PRIVATE_CLASSB(i)		(((u_int32_t)(i) & 0xFFF00000) == IN_PRIVATE_CLASSB_NETNUM)
125
126#define IN_PRIVATE_CLASSC_NETNUM	(u_int32_t)0xC0A80000 /* 192.168.0.0 */
127#define IN_PRIVATE_CLASSC(i)		(((u_int32_t)(i) & 0xFFFF0000) == IN_PRIVATE_CLASSC_NETNUM)
128
129#undef IN_PRIVATE
130#define IN_PRIVATE(i)				(IN_PRIVATE_CLASSA(i) || IN_PRIVATE_CLASSB(i) || IN_PRIVATE_CLASSC(i))
131
132
133/* -----------------------------------------------------------------------------
134 PPP globals
135----------------------------------------------------------------------------- */
136
137extern u_int8_t		control_buf[];
138
139static int 	ctrlsockfd = -1;		/* control socket (UDP) file descriptor */
140static int 	datasockfd = -1;		/* data socket (UDP) file descriptor */
141static int 	eventsockfd = -1;		/* event socket to detect interface change */
142static CFBundleRef 	bundle = 0;		/* our bundle ref */
143
144/* option variables */
145static char 	*opt_mode = MODE_CONNECT;		/* connect mode by default */
146static bool 	opt_noload = 0;				/* don't load the kernel extension */
147static bool 	opt_noipsec = 0;			/* don't use IPSec */
148static int 	opt_udpport = 0;
149static int	opt_connect_timeout = L2TP_DEFAULT_CONNECT_TIMEOUT;
150static int	opt_connect_retrycount = L2TP_DEFAULT_CONNECT_RETRY_COUNT;
151static int	opt_timeout = L2TP_DEFAULT_INITIAL_TIMEOUT;
152static int	opt_timeoutcap = L2TP_DEFAULT_TIMEOUT_CAP;
153static int	opt_retrycount = L2TP_DEFAULT_RETRY_COUNT;
154static int	opt_windowsize = L2TP_DEFAULT_WINDOW_SIZE;
155static int	opt_hello_timeout = 0;			/* default - only send for network change event */
156static int     	opt_recv_timeout = L2TP_DEFAULT_RECV_TIMEOUT;
157static char	opt_ipsecsharedsecret[MAXSECRETLEN] = { 0 };	/* IPSec Shared Secret */
158static char     *opt_ipsecsharedsecrettype = "use";	 /* use, key, keychain */
159static char	opt_ipseclocalidentifier[MAXNAMELEN] = { 0 };	/* IPSec Local Identifier */
160static char     *opt_ipseclocalidentifiertype = "keyid";	 /* keyid, fqdn, user_fqdn, asn1dn, address */
161static int	opt_wait_if_timeout = L2TP_DEFAULT_WAIT_IF_TIMEOUT;
162static int  scaled_wait_if_timeout = L2TP_DEFAULT_WAIT_IF_TIMEOUT;
163
164struct	l2tp_parameters our_params;
165struct 	l2tp_parameters peer_params;
166
167int     interface_media = 0;
168
169int racoon_ctrlsockfd = -1;
170/*
171Fast echo request procedure is run when a networking change is detected
172Echos are sent every 5 seconds for 30 seconds, or until a reply is received
173If the network is detected dead, the the tunnel is disconnected.
174Echos are not sent during normal operation.
175*/
176
177static int	hello_timer_running = 0;
178
179static struct sockaddr_in our_address;		/* our side IP address */
180static struct sockaddr_in peer_address;		/* the other side IP address */
181static int                num_alt_peer_address = 0;
182static struct sockaddr_in alt_peer_address[MAX_CONNECT_RETRIES];		/* the other side IP address */
183static struct in_addr ip_zeros;
184static u_int8_t routeraddress[16] = { 0 };
185static u_int8_t interface[17] = { 0 };
186static pthread_t resolverthread = 0;
187static int 	resolverfds[2] = { -1, -1 };
188#if TARGET_OS_EMBEDDED
189static pthread_t edgethread = 0;
190static int 	edgefds[2] = { -1, -1 };
191#endif
192static int 	peer_route_set = 0;		/* has a route to the peer been set ? */
193//static int	echo_timer_running = 0;
194static int	transport_up = 1;
195static int	wait_interface_timer_running = 0;
196
197static CFMutableDictionaryRef	ipsec_dict = NULL;
198
199extern int 		kill_link;
200extern CFStringRef	serviceidRef;		/* from pppd/sys_MacOSX.c */
201extern SCDynamicStoreRef cfgCache;		/* from pppd/sys_MacOSX.c */
202
203extern CFPropertyListRef 		userOptions;	/* from pppd/sys_MacOSX.c */
204extern CFPropertyListRef 		systemOptions;	/* from pppd/sys_MacOSX.c */
205
206/* option descriptors */
207option_t l2tp_options[] = {
208    { "l2tpnoload", o_bool, &opt_noload,
209      "Don't try to load the L2TP kernel extension", 1 },
210    { "l2tpnoipsec", o_bool, &opt_noipsec,
211      "Don't use IPSec", 1 },
212    { "l2tpipsecsharedsecret", o_string, opt_ipsecsharedsecret,
213      "IPSec Shared Secret",
214      OPT_PRIO | OPT_STATIC | OPT_HIDE, NULL, MAXSECRETLEN },
215    { "l2tpipsecsharedsecrettype", o_string, &opt_ipsecsharedsecrettype,
216      "IPSec Shared Secret Type [use, key, keychain]" },
217    { "l2tpipseclocalidentifier", o_string, opt_ipseclocalidentifier,
218      "IPSec Local Identifier",
219      OPT_PRIO | OPT_STATIC, NULL, MAXNAMELEN },
220    { "l2tpipseclocalidentifiertype", o_string, &opt_ipseclocalidentifiertype,
221      "IPSec Local Identifier Type [keyid, fqdn, user_fqdn, asn1dn, address]" },
222    { "l2tpudpport", o_int, &opt_udpport,
223      "UDP port for connect"},
224    { "l2tpmode", o_string, &opt_mode,
225      "Configure configuration mode [connect, listen, answer]" },
226    { "l2tpretrytimeout", o_int, &opt_timeout,
227      "Set control message initial retry timeout (seconds)" },
228    { "l2tptimeoutcap", o_int, &opt_timeoutcap,
229      "Set control message retry timeout cap (seconds)" },
230    { "l2tpretries", o_int, &opt_retrycount,
231      "Set control message max retries" },
232    { "l2tpconnecttimeout", o_int, &opt_connect_timeout,
233      "Set connection control message retry timeout (seconds)" },
234    { "l2tpconnectretries", o_int, &opt_connect_retrycount,
235      "Set connection control message max retries" },
236    { "l2tpwindow", o_int, &opt_windowsize,
237      "Set control message window size" },
238    { "l2tprecvtimeout", o_int, &opt_recv_timeout,
239      "Set plugin receive timeout" },
240    { "l2tphellotimeout", o_int, &opt_hello_timeout,
241      "Set timeout for hello messages: zero = send only for network change events" },
242    { "l2tpwaitiftimeout", o_int, &opt_wait_if_timeout,
243      "How long do we wait for our transport interface to come back after interface events" },
244    { NULL }
245};
246
247
248/* -----------------------------------------------------------------------------
249    Function Prototypes
250----------------------------------------------------------------------------- */
251
252void l2tp_process_extra_options();
253void l2tp_check_options();
254int  l2tp_pre_start_link_check();
255int l2tp_connect(int *errorcode);
256void l2tp_disconnect();
257void l2tp_close_fds();
258void l2tp_cleanup();
259int l2tp_establish_ppp(int);
260void l2tp_wait_input();
261void l2tp_disestablish_ppp(int);
262
263static void l2tp_hello_timeout(void *arg);
264static void closeall(void);
265static u_long load_kext(char*, int byBundleID);
266static void l2tp_link_failure();
267static boolean_t l2tp_set_host_gateway(int cmd, struct in_addr host, struct in_addr gateway, char *ifname, int isnet);
268static int l2tp_set_peer_route();
269static int l2tp_clean_peer_route();
270static void l2tp_ip_up(void *arg, uintptr_t p);
271static void l2tp_start_wait_interface ();
272static void l2tp_stop_wait_interface ();
273static void l2tp_wait_interface_timeout (void *arg);
274static void l2tp_assert_ipsec();
275
276void l2tp_init_session __P((char *, u_int32_t, struct in_addr *, link_failure_func));
277
278static ppp_session_t  l2tp_session = PPP_SESSION_INITIALIZER();
279
280/* -----------------------------------------------------------------------------
281plugin entry point, called by pppd
282----------------------------------------------------------------------------- */
283int start(CFBundleRef ref)
284{
285
286    bundle = ref;
287    CFRetain(bundle);
288
289    // hookup our socket handlers
290    bzero(the_channel, sizeof(struct channel));
291    the_channel->options = l2tp_options;
292    the_channel->process_extra_options = l2tp_process_extra_options;
293    the_channel->wait_input = l2tp_wait_input;
294    the_channel->check_options = l2tp_check_options;
295    the_channel->pre_start_link_check = l2tp_pre_start_link_check;
296    the_channel->connect = l2tp_connect;
297    the_channel->disconnect = l2tp_disconnect;
298    the_channel->cleanup = l2tp_cleanup;
299    the_channel->close = l2tp_close_fds;
300    the_channel->establish_ppp = l2tp_establish_ppp;
301    the_channel->disestablish_ppp = l2tp_disestablish_ppp;
302    // use the default config functions
303    the_channel->send_config = generic_send_config;
304    the_channel->recv_config = generic_recv_config;
305
306    add_notifier(&ip_up_notify, l2tp_ip_up, 0);
307
308    return 0;
309}
310
311/* -----------------------------------------------------------------------------
312do consistency checks on the options we were given
313----------------------------------------------------------------------------- */
314void l2tp_check_options()
315{
316    if (strcmp(opt_mode, MODE_CONNECT)
317        && strcmp(opt_mode, MODE_LISTEN)
318        && strcmp(opt_mode, MODE_ANSWER)) {
319        error("L2TP incorrect mode : '%s'", opt_mode ? opt_mode : "");
320        opt_mode = MODE_CONNECT;
321    }
322
323    if (opt_timeout < 1 || opt_timeout > 8) {
324        error("L2TP incorrect timeout - must be between 1 and 8");
325        opt_timeout = L2TP_DEFAULT_INITIAL_TIMEOUT;
326    }
327
328    if (opt_timeoutcap < 4) {
329        error("L2TP incorrect timeout cap - cannot be less than 4");
330        opt_timeoutcap = L2TP_DEFAULT_TIMEOUT_CAP;
331    }
332
333	/*
334		reuse pppd redial functionality to retry connection
335		retry every 3 seconds for the duration of the extra time
336		do not report busy state
337	 */
338	if (extraconnecttime) {
339		busycode = L2TP_RETRY_CONNECT_CODE;
340		redialtimer = 3 ;
341		redialcount = extraconnecttime / redialtimer;
342		hasbusystate = 0;
343	}
344
345}
346
347/* -----------------------------------------------------------------------------
348----------------------------------------------------------------------------- */
349void l2tp_process_extra_options()
350{
351    if (!strcmp(opt_mode, MODE_ANSWER)) {
352        // make sure we get a file descriptor > 2 so that pppd can detach and close 0,1,2
353        ctrlsockfd = dup(0);
354    }
355}
356
357/* -----------------------------------------------------------------------------
358----------------------------------------------------------------------------- */
359static void l2tp_start_wait_interface ()
360{
361    int timeout_scale_factor = 0;
362
363    if (!wait_underlying_interface_up && lcp_echo_interval) {
364        wait_underlying_interface_up = 1;
365    }
366    // the interface timer takes priority over the mapping timer
367    ppp_block_public_nat_port_mapping_timer();
368
369    if (wait_interface_timer_running != 0)
370        return;
371
372#if !TARGET_OS_EMBEDDED
373    // increase the timeout if we're waiting for a wireless interface
374    if (IFM_TYPE(interface_media) == IFM_IEEE80211) {
375        timeout_scale_factor = 2;
376    }
377#endif /* !iPhone */
378    scaled_wait_if_timeout = (opt_wait_if_timeout << timeout_scale_factor);
379    notice("starting wait-interface timer for l2tp: %d secs", scaled_wait_if_timeout);
380    TIMEOUT (l2tp_wait_interface_timeout, 0, scaled_wait_if_timeout);
381    wait_interface_timer_running = 1;
382}
383
384/* -----------------------------------------------------------------------------
385----------------------------------------------------------------------------- */
386static void l2tp_stop_wait_interface ()
387{
388    ppp_variable_echo_start();
389
390    if (wait_interface_timer_running) {
391        UNTIMEOUT (l2tp_wait_interface_timeout, 0);
392        wait_interface_timer_running = 0;
393    }
394    ppp_unblock_public_nat_port_mapping_timer();
395}
396
397/* -----------------------------------------------------------------------------
398----------------------------------------------------------------------------- */
399static void l2tp_wait_interface_timeout (void *arg)
400{
401    if (wait_interface_timer_running != 0) {
402        wait_interface_timer_running = 0;
403		log_vpn_interface_address_event(__FUNCTION__, NULL, scaled_wait_if_timeout, interface, &our_address.sin_addr);
404		// our transport interface didn't come back, take down the connection
405		l2tp_link_failure();
406    }
407}
408
409/* -----------------------------------------------------------------------------
410called back everytime we go out of select, and data needs to be read
411the hook is called and has a chance to get data out of its file descriptor
412in the case of L2TP, we get control data on the socket
413or get awaken when connection is closed
414----------------------------------------------------------------------------- */
415void l2tp_wait_input()
416{
417    int err, found;
418    struct ifaddrs *ifap = NULL;
419
420    if (eventsockfd != -1 && is_ready_fd(eventsockfd)) {
421
422		char                 	buf[256] __attribute__ ((aligned(4)));		// Wcast-align fix - force alignment
423        char ev_if[32];
424        struct kern_event_msg	*ev_msg;
425        struct kev_in_data     	*inetdata;
426
427        if (recv(eventsockfd, &buf, sizeof(buf), 0) != -1) {
428            ev_msg = ALIGNED_CAST(struct kern_event_msg *)&buf;
429            inetdata = (struct kev_in_data *) &ev_msg->event_data[0];
430			log_vpn_interface_address_event(__FUNCTION__, ev_msg, opt_wait_if_timeout, interface, &our_address.sin_addr);
431            switch (ev_msg->event_code) {
432                case KEV_INET_NEW_ADDR:
433                case KEV_INET_CHANGED_ADDR:
434                case KEV_INET_ADDR_DELETED:
435                    snprintf(ev_if, sizeof(ev_if), "%s%d", inetdata->link_data.if_name, inetdata->link_data.if_unit);
436                    // check if changes occured on the interface we are using
437                    if (!strncmp(ev_if, (char*)interface, sizeof(interface))) {
438                        if (inetdata->link_data.if_family == APPLE_IF_FAM_PPP) {
439                            // disconnect immediatly
440                            l2tp_link_failure();
441                        }
442                        else {
443
444                            /* check if address still exist */
445                            found = 0;
446                            if (getifaddrs(&ifap) == 0) {
447                                struct ifaddrs *ifa;
448                                for (ifa = ifap; ifa && !found ; ifa = ifa->ifa_next) {
449                                    found = (ifa->ifa_name
450                                            && ifa->ifa_addr
451                                            && !strncmp(ifa->ifa_name, (char*)interface, sizeof(interface))
452                                            && ifa->ifa_addr->sa_family == AF_INET
453                                            && (ALIGNED_CAST(struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr == our_address.sin_addr.s_addr);
454                                }
455                                freeifaddrs(ifap);
456                            }
457
458							if (found) {
459
460								// no meaningful change, or address came back. Cancel timer if it was on.
461								if (transport_up == 0) {
462
463									/*
464										Our transport interface comes back with the same address.
465										Stop waiting for interface.
466										A smarter algorithm should be implemented here.
467									*/
468									transport_up = 1;
469									if (phase == PHASE_WAITING)
470										new_phase(PHASE_RUNNING);
471									l2tp_stop_wait_interface();
472
473									/* since there could be a NAT inbetween, let's flush security association to force renegotiation and
474									  reacquisition of the correct port */
475									if (!opt_noipsec) {
476										l2tp_assert_ipsec();
477									} else {
478										/* reassert the tunnel by sending hello request */
479										if (l2tp_send_hello(ctrlsockfd, &our_params)) {
480											error("L2TP error on control channel sending Hello message after network change\n");
481											/* ???? */
482										}
483									}
484								}
485							}
486							else {
487								// quick exit if there has been an unrecoverable change in interface/service
488								if (check_vpn_interface_or_service_unrecoverable(cfgCache,
489														 __FUNCTION__,
490														 ev_msg,
491														 (char*)interface)) {
492									error("L2TP: the underlying interface/service has changed unrecoverably\n");
493									transport_up = 0;
494									l2tp_link_failure();
495									break;
496								}
497
498								if (transport_up == 1) {
499									transport_up = 0;
500									if (phase == PHASE_RUNNING)
501										new_phase(PHASE_WAITING);
502									l2tp_start_wait_interface();
503								} else {
504								        // transport is still down: check if there was a valid address change
505								        if (check_vpn_interface_address_change(wait_interface_timer_running /* && !transport_up */,
506													       ev_msg,
507													       (char*)interface,
508														   interface_media,
509													       &our_address.sin_addr)) {
510									        error("L2TP: the underlying interface %s address changed\n",
511										      interface);
512										// disconnect immediately
513										l2tp_link_failure();
514									}
515								}
516                            }
517
518                        }
519                    } else {
520		            /* if transport is still down: ignore deletes, and check if this alternative interface has a valid address */
521		            if (check_vpn_interface_alternate((!transport_up && wait_interface_timer_running),
522							      ev_msg,
523							      (char*)interface)) {
524			            error("L2TP: an alternative interface %s was detected while the underlying interface %s was down\n",
525					  ev_if, interface);
526				    // disconnect immediatly
527				    l2tp_link_failure();
528			    }
529                    }
530                    break;
531            }
532        }
533    }
534
535    if (ctrlsockfd != -1 && is_ready_fd(ctrlsockfd)) {
536
537       err = l2tp_data_in(ctrlsockfd);
538       if (err < 0) {
539            // looks like we have been disconnected...
540            // it's OK to get a hangup during terminate phase
541            if (phase != PHASE_TERMINATE) {
542                notice("L2TP hangup");
543                status = EXIT_HANGUP;
544            }
545            remove_fd(ctrlsockfd);
546            remove_fd(eventsockfd);
547            hungup = 1;
548            lcp_lowerdown(0);	/* L2TP link is no longer available */
549            link_terminated(0);
550            ppp_auxiliary_probe_stop();
551            l2tp_clear_nat_port_mapping();
552            ppp_session_clear(&l2tp_session);
553            session = NULL;
554	   }
555    }
556
557	ppp_process_nat_port_mapping_events();
558	ppp_process_auxiliary_probe_input();
559}
560
561/* -----------------------------------------------------------------------------
562----------------------------------------------------------------------------- */
563void *l2tp_resolver_thread(void *arg)
564{
565    struct hostent 	*host;
566    char		result = -1;
567	int			count, fd;
568	u_int8_t	rd8;
569
570    if (pthread_detach(pthread_self()) == 0) {
571
572        // try to resolve the name
573        if ((host = gethostbyname(remoteaddress))) {
574
575			for (count = 0; host->h_addr_list[count]; count++);
576
577			rd8 = 0;
578			fd = open("/dev/random", O_RDONLY);
579			if (fd) {
580				read(fd, &rd8, sizeof(rd8));
581				close(fd);
582			}
583
584			bzero(&peer_address.sin_addr, sizeof(peer_address.sin_addr));
585			if ( count )
586                memcpy(&peer_address.sin_addr, host->h_addr_list[rd8 % count], sizeof(struct in_addr));    // Wcast-align fix - using memcpy for unknown alignment
587            bzero(alt_peer_address, sizeof(alt_peer_address));
588            num_alt_peer_address = 0;
589            if (count > 1) {
590                while (num_alt_peer_address < (count - 1) &&
591                       num_alt_peer_address < MAX_CONNECT_RETRIES) {
592                    alt_peer_address[num_alt_peer_address].sin_len = sizeof(alt_peer_address[num_alt_peer_address]);
593                    alt_peer_address[num_alt_peer_address].sin_family = AF_INET;
594                    alt_peer_address[num_alt_peer_address].sin_port = htons(L2TP_UDP_PORT);
595
596                    // Wcast-align fix - using memcpy for unknown alignment
597                    memcpy(&alt_peer_address[num_alt_peer_address].sin_addr, host->h_addr_list[(rd8 + num_alt_peer_address + 1)% count], sizeof(struct in_addr));
598                    num_alt_peer_address++;
599                }
600            }
601            result = 0;
602        }
603    }
604
605    write(resolverfds[1], &result, 1);
606    return 0;
607}
608
609#if TARGET_OS_EMBEDDED
610static
611void callbackEDGE(CTServerConnectionRef connection, CFStringRef notification, CFDictionaryRef notificationInfo, void* info) {
612
613	/* not used */
614}
615
616/* -----------------------------------------------------------------------------
617 ----------------------------------------------------------------------------- */
618void *l2tp_edge_thread(void *arg)
619{
620    char		result = -1;
621	int			count;
622	CTServerConnectionRef	edgeConnection;
623	_CTServerConnectionContext ctxt = { 0, NULL, NULL, NULL, NULL };
624	Boolean active = FALSE;
625	CTError cterror = { kCTErrorDomainNoError, 0 };
626
627    if (pthread_detach(pthread_self()) == 0) {
628
629		edgeConnection = _CTServerConnectionCreate(kCFAllocatorDefault, callbackEDGE, &ctxt);
630		if (edgeConnection) {
631			_CTServerConnectionSetPacketContextActiveByServiceType(edgeConnection, kCTDataConnectionServiceTypeInternet, TRUE);
632
633			count = PPPD_WWAN_INTERFACE_TIMEOUT;
634			cterror = _CTServerConnectionGetPacketContextActive(edgeConnection, 0, &active);
635			while (!cterror.error && !active && count--) {
636				sleep(1);
637				cterror = _CTServerConnectionGetPacketContextActive(edgeConnection, 0, &active);
638			}
639			CFRelease(edgeConnection);
640
641			if (active) {
642				sleep(2); // additionnal 2 seconds for DNS information to be installed
643				result = 0;
644			}
645		}
646	}
647
648
649    write(edgefds[1], &result, 1);
650    return 0;
651}
652#endif
653
654/* -----------------------------------------------------------------------------
655get the ipsec string corresponding to the ike error
656----------------------------------------------------------------------------- */
657char *ipsec_error_to_str(int ike_code)
658{
659	switch (ike_code) {
660		case VPNCTL_NTYPE_INVALID_PAYLOAD_TYPE: return "Invalid payload type";
661		case VPNCTL_NTYPE_DOI_NOT_SUPPORTED: return "DOI not supported";
662		case VPNCTL_NTYPE_SITUATION_NOT_SUPPORTED: return "Situation not supported";
663		case VPNCTL_NTYPE_INVALID_COOKIE: return "Invalid cookie";
664		case VPNCTL_NTYPE_INVALID_MAJOR_VERSION: return "Invalid major version";
665		case VPNCTL_NTYPE_INVALID_MINOR_VERSION: return "Invalid minor version";
666		case VPNCTL_NTYPE_INVALID_EXCHANGE_TYPE: return "Invalid exchange type";
667		case VPNCTL_NTYPE_INVALID_FLAGS: return "Invalid flags";
668		case VPNCTL_NTYPE_INVALID_MESSAGE_ID: return "Invalid message id";
669		case VPNCTL_NTYPE_INVALID_PROTOCOL_ID: return "Invalid protocol id";
670		case VPNCTL_NTYPE_INVALID_SPI: return "Invalid SPI";
671		case VPNCTL_NTYPE_INVALID_TRANSFORM_ID: return "Invalid transform id";
672		case VPNCTL_NTYPE_ATTRIBUTES_NOT_SUPPORTED: return "Attributes not supported";
673		case VPNCTL_NTYPE_NO_PROPOSAL_CHOSEN: return "No proposal chosen";
674		case VPNCTL_NTYPE_BAD_PROPOSAL_SYNTAX: return "Bad proposal syntax";
675		case VPNCTL_NTYPE_PAYLOAD_MALFORMED: return "Payload malformed";
676		case VPNCTL_NTYPE_INVALID_KEY_INFORMATION: return "Invalid key information";
677		case VPNCTL_NTYPE_INVALID_ID_INFORMATION: return "Invalid id information";
678		case VPNCTL_NTYPE_INVALID_CERT_ENCODING: return "Invalid cert encoding";
679		case VPNCTL_NTYPE_INVALID_CERTIFICATE: return "Invalid certificate";
680		case VPNCTL_NTYPE_BAD_CERT_REQUEST_SYNTAX: return "Bad cert request syntax";
681		case VPNCTL_NTYPE_INVALID_CERT_AUTHORITY: return "Invalid cert authority";
682		case VPNCTL_NTYPE_INVALID_HASH_INFORMATION: return "Invalid hash information";
683		case VPNCTL_NTYPE_AUTHENTICATION_FAILED: return "Authentication Failed";
684		case VPNCTL_NTYPE_INVALID_SIGNATURE: return "Invalid signature";
685		case VPNCTL_NTYPE_ADDRESS_NOTIFICATION: return "Address notification";
686		case VPNCTL_NTYPE_NOTIFY_SA_LIFETIME: return "Notify SA lifetime";
687		case VPNCTL_NTYPE_CERTIFICATE_UNAVAILABLE: return "Certificate unavailable";
688		case VPNCTL_NTYPE_UNSUPPORTED_EXCHANGE_TYPE: return "Unsupported exchange type";
689		case VPNCTL_NTYPE_UNEQUAL_PAYLOAD_LENGTHS: return "Unequal payload lengths";
690		case VPNCTL_NTYPE_LOAD_BALANCE: return "Load balance";
691		case VPNCTL_NTYPE_INTERNAL_ERROR: return "Internal error";
692	}
693	return "Unknown error";
694}
695
696enum {
697    RACOON_BINDING = 1,		// we send a bind command to racoon
698    RACOON_TRIGGERED,		// we send a packet to triggerd racoon
699    RACOON_STARTED,			// racoon received our request and started IKE
700    RACOON_NEGOTIATING,		// the server replied, negotiation in progress
701    RACOON_DONE				// racoon is done
702};
703
704/* -----------------------------------------------------------------------------
705trigger an IKE exchange
706----------------------------------------------------------------------------- */
707int l2tp_trigger_ipsec(int listenmode,
708                       int *ipsec_status)
709{
710	int					size=0, state = 0, timeo, err = -1;
711	struct sockaddr_un	sun;
712    struct sockaddr		from;
713	u_int16_t			reliable;
714	struct sockaddr_in	redirect_addr;
715	u_int8_t					data[256] __attribute__ ((aligned(4))); 		// Wcast-align fix - force alignment
716	struct vpnctl_hdr			*hdr = ALIGNED_CAST(struct vpnctl_hdr *)data;
717	struct vpnctl_cmd_bind		*cmd_bind = ALIGNED_CAST(struct vpnctl_cmd_bind *)data;
718	struct vpnctl_status_failed *failed_status = ALIGNED_CAST(struct vpnctl_status_failed *)data;
719	int                          num_ipsec_triggers = 0;
720
721	/* open and connect to the racoon control socket */
722	if (racoon_ctrlsockfd < 0) {
723		racoon_ctrlsockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
724		if (racoon_ctrlsockfd < 0) {
725			error("L2TP: cannot create racoon control socket: %m\n");
726			goto fail;
727		}
728
729		bzero(&sun, sizeof(sun));
730		sun.sun_family = AF_LOCAL;
731		strncpy(sun.sun_path, "/var/run/vpncontrol.sock", sizeof(sun.sun_path));
732
733		if (connect(racoon_ctrlsockfd,  (struct sockaddr *)&sun, sizeof(sun)) < 0) {
734			error("L2TP: cannot connect racoon control socket: %m\n");
735			goto fail;
736		}
737	}
738
739	if ( listenmode ){
740		close(racoon_ctrlsockfd);		/* connect to vpncontrol socket to start up racoon only */
741		racoon_ctrlsockfd = -1;
742		return 0;
743	}
744
745	//sleep(2);
746start:
747
748	// bind racoon control socket to the peer address to receive only pertinent messages
749	bzero(cmd_bind, sizeof(struct vpnctl_cmd_bind));
750	cmd_bind->hdr.len = htons(sizeof(struct vpnctl_cmd_bind) - sizeof(struct vpnctl_hdr));
751	cmd_bind->hdr.msg_type = htons(VPNCTL_CMD_BIND);
752	cmd_bind->address = peer_address.sin_addr.s_addr;
753	write(racoon_ctrlsockfd, cmd_bind, sizeof(struct vpnctl_cmd_bind));
754
755	notice("IPSec connection started\n");
756	state = RACOON_BINDING;
757
758	while (state != RACOON_DONE) {
759
760		switch (state) {
761			case RACOON_BINDING:  timeo = 5; break;
762			case RACOON_TRIGGERED:  timeo = 1; break;
763			case RACOON_STARTED:	timeo = 10; break;
764			default:				timeo = 30; break;
765		}
766
767		from.sa_len = sizeof(from);
768		err = l2tp_recv(racoon_ctrlsockfd, data, sizeof(struct vpnctl_hdr), &size, &from, timeo, "from racoon control socket");
769		if (err || size == 0) {	// no reply
770		        // RACOON_TRIGGERED's timeout is actually 5 x 1 second increments.
771		        if (err == -1 &&
772			    state == RACOON_TRIGGERED &&
773			    num_ipsec_triggers < 5) {
774			        // trigger racoon again
775			        l2tp_send_hello_trigger(ctrlsockfd, (struct sockaddr *)&peer_address);
776				num_ipsec_triggers++;
777				continue;
778			}
779			if (err != -2) // cancel
780				notice("IPSec connection failed\n");
781			goto fail;
782		}
783
784		/* read end of packet */
785		if (ntohs(hdr->len)) {
786			from.sa_len = sizeof(from);
787			err = l2tp_recv(racoon_ctrlsockfd, data + sizeof(struct vpnctl_hdr), ntohs(hdr->len), &size, &from, timeo, "from racoon control socket");
788			if (err || size == 0) {	// no reply
789				if (err != -2) // cancel
790					notice("IPSec connection failed\n");
791				goto fail;
792			}
793		}
794
795		if (debug > 1) {
796			dbglog("L2TP received racoon message <type 0x%x> <flags 0x%x> <cookie 0x%x> <result %d> <reserved 0x%x> <len %d>",
797				ntohs(hdr->msg_type), ntohs(hdr->flags), ntohl(hdr->cookie), ntohl(hdr->reserved), ntohs(hdr->result), ntohs(hdr->len));
798		}
799
800		switch (ntohs(hdr->msg_type)) {
801
802			case VPNCTL_STATUS_IKE_FAILED:
803
804				switch (ntohs(failed_status->ike_code)) {
805
806					case VPNCTL_NTYPE_LOAD_BALANCE:
807
808						redirect_addr = peer_address;
809						redirect_addr.sin_addr.s_addr = *ALIGNED_CAST(u_int32_t*)failed_status->data;
810						notice("IPSec connection redirected to server '%s'...\n", inet_ntoa(redirect_addr.sin_addr));
811
812						err = l2tp_change_peeraddress(ctrlsockfd, (struct sockaddr *)&redirect_addr);
813						if (err)
814							goto fail;
815
816						goto start; // restart the connection to an other server
817						break;
818
819					default:
820						notice("IPSec connection failed <IKE Error %d (0x%x) %s>\n", ntohs(failed_status->ike_code), ntohs(failed_status->ike_code), ipsec_error_to_str(ntohs(failed_status->ike_code)));
821						err = -1;
822						goto fail;
823						break;
824				}
825				break;
826
827			case VPNCTL_STATUS_PH1_START_US:
828				dbglog("IPSec phase 1 client started\n");
829				state = RACOON_STARTED;
830				reliable = 1;
831				setsockopt(ctrlsockfd, PPPPROTO_L2TP, L2TP_OPT_RELIABILITY, &reliable, 2);
832				break;
833
834			case VPNCTL_STATUS_PH1_START_PEER:
835				dbglog("IPSec phase 1 server replied\n");
836				state = RACOON_NEGOTIATING;
837				break;
838
839			case VPNCTL_STATUS_PH1_ESTABLISHED:
840				dbglog("IPSec phase 1 established\n");
841				state = RACOON_NEGOTIATING;
842				break;
843
844			case VPNCTL_STATUS_PH2_START:
845				dbglog("IPSec phase 2 started\n");
846				state = RACOON_NEGOTIATING;
847				break;
848
849			case VPNCTL_STATUS_PH2_ESTABLISHED:
850				state = RACOON_DONE;
851				dbglog("IPSec phase 2 established\n");
852				notice("IPSec connection established\n");
853				break;
854
855			default:
856				/* ignore other messages */
857				if (state == RACOON_BINDING) {
858
859					/* send L2TP packets to trigger IPSec connection */
860					reliable = 0;
861					setsockopt(ctrlsockfd, PPPPROTO_L2TP, L2TP_OPT_RELIABILITY, &reliable, 2);
862					l2tp_send_hello_trigger(ctrlsockfd, (struct sockaddr *)&peer_address);
863					num_ipsec_triggers = 1;
864					state = RACOON_TRIGGERED;
865				}
866				break;
867
868		}
869	}
870
871	err = 0;
872
873fail:
874    *ipsec_status = state;
875	if (err == -1 || err == -2)
876        return EXIT_L2TP_NOANSWER;
877	else
878        return err;
879}
880
881/* -----------------------------------------------------------------------------
882 assert the ipsec transport after an address change or slee-wake
883 ----------------------------------------------------------------------------- */
884static void l2tp_assert_ipsec()
885{
886	if (!strcmp(opt_mode, MODE_CONNECT)){
887		struct sockaddr_un       sun;
888		struct vpnctl_cmd_assert msg;
889
890		/* open and connect to the racoon control socket */
891		if (racoon_ctrlsockfd < 0) {
892			racoon_ctrlsockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
893			if (racoon_ctrlsockfd < 0) {
894				error("L2TP: cannot create racoon control socket: %m\n");
895				goto remove_sa; // fallback to removal of SAs
896			}
897
898			bzero(&sun, sizeof(sun));
899			sun.sun_family = AF_LOCAL;
900			strncpy(sun.sun_path, "/var/run/vpncontrol.sock", sizeof(sun.sun_path));
901
902			if (connect(racoon_ctrlsockfd,  (struct sockaddr *)&sun, sizeof(sun)) < 0) {
903				error("L2TP: cannot connect racoon control socket: %m\n");
904				close(racoon_ctrlsockfd);
905				racoon_ctrlsockfd = -1;
906				goto remove_sa; // fallback to removal of SAs
907			}
908		}
909
910		bzero(&msg, sizeof(msg));
911		msg.hdr.msg_type = htons(VPNCTL_CMD_ASSERT);
912		msg.src_address = our_address.sin_addr.s_addr;
913		msg.dst_address = peer_address.sin_addr.s_addr;
914		msg.hdr.len = htons(sizeof(msg) - sizeof(msg.hdr));;
915		write(racoon_ctrlsockfd, &msg, sizeof(msg));
916		goto done;
917	}
918
919remove_sa:
920	IPSecRemoveSecurityAssociations((struct sockaddr *)&our_address, (struct sockaddr *)&peer_address);
921done:
922	// wait 3 seconds before trying to trigger tunnel
923	sleep(3);
924	return;
925}
926
927int l2tp_pre_start_link_check()
928{
929    int                      reachable = FALSE;
930    SCNetworkReachabilityRef ref;
931    SCNetworkConnectionFlags flags;
932
933    ref = SCNetworkReachabilityCreateWithName(NULL, remoteaddress);
934    if (ref) {
935        if (SCNetworkReachabilityGetFlags(ref, &flags)) {
936            if (REACHABLE_NOW || REACHABLE_AUTOMATICALLY_WITHOUT_USER) {
937                reachable = TRUE;
938            }
939        }
940        CFRelease(ref);
941    }
942
943    if (reachable) {
944        return 0;
945    }
946    return -1;
947}
948
949static CFStringRef l2tp_copy_str_at_index(CFStringRef key, int index)
950{
951    CFArrayRef	components;
952    CFStringRef foundstr = NULL;
953
954    components = CFStringCreateArrayBySeparatingStrings(NULL, key, CFSTR("/"));
955    if (index < CFArrayGetCount(components)) {
956        if ((foundstr = CFArrayGetValueAtIndex(components, index))){
957            CFRetain(foundstr);
958        }
959    }
960    CFRelease(components);
961    return foundstr;
962}
963
964static void l2tp_get_router_address(CFStringRef serviceID)
965{
966    CFStringRef		routerAddress = NULL;
967    CFStringRef     ipv4Key = NULL;
968    CFDictionaryRef ipv4Dict = NULL;
969
970    if (serviceID == NULL) {
971        goto done;
972    }
973
974    ipv4Key = SCDynamicStoreKeyCreateNetworkServiceEntity(kCFAllocatorDefault,
975                                                          kSCDynamicStoreDomainState,
976                                                          serviceID,
977                                                          kSCEntNetIPv4);
978    if (ipv4Key == NULL) {
979        goto done;
980    }
981
982    ipv4Dict = SCDynamicStoreCopyValue(NULL, ipv4Key);
983    if (ipv4Dict == NULL) {
984        goto done;
985    }
986
987    routerAddress = CFDictionaryGetValue(ipv4Dict, kSCPropNetIPv4Router);
988    if (routerAddress) {
989        CFStringGetCString(routerAddress, (char*)routeraddress, sizeof(routeraddress), kCFStringEncodingUTF8);
990    }
991
992done:
993    if (ipv4Key) {
994        CFRelease(ipv4Key);
995    }
996    if (ipv4Dict) {
997        CFRelease(ipv4Dict);
998    }
999}
1000
1001static void l2tp_get_router_address_for_interface(void)
1002{
1003    CFDictionaryRef     dict = NULL;
1004    CFStringRef         pattern = NULL;
1005    CFMutableArrayRef   patterns = NULL;
1006    CFStringRef         *keys = NULL;
1007    CFDictionaryRef     *values = NULL;
1008    CFIndex             count = 0;
1009    CFIndex             i = 0;
1010    CFStringRef         serviceID = NULL;
1011
1012    if (interface == NULL || interface[0] == 0) {
1013        goto done;
1014    }
1015
1016    patterns = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
1017    pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(kCFAllocatorDefault,
1018                                                          kSCDynamicStoreDomainState,
1019                                                          kSCCompAnyRegex,
1020                                                          kSCEntNetIPv4);
1021
1022    if (patterns == NULL || pattern == NULL)
1023        goto done;
1024    CFArrayAppendValue(patterns, pattern);
1025
1026	dict = SCDynamicStoreCopyMultiple(NULL, NULL, patterns);
1027    if (dict == NULL)
1028	    goto done;
1029
1030    count = CFDictionaryGetCount(dict);
1031
1032    keys = calloc(count, sizeof(CFStringRef));
1033    values = calloc(count, sizeof(CFDictionaryRef));
1034    if (keys == NULL || values == NULL)
1035        goto done;
1036    CFDictionaryGetKeysAndValues(dict, (const void**)keys, (const void**)values);
1037
1038    for (i=0; i < count; i++) {
1039        CFDictionaryRef ipv4Dict = NULL;
1040        CFStringRef     ipv4Key = NULL;
1041
1042        ipv4Key  = keys[i];
1043        ipv4Dict = values[i];
1044
1045        if (ipv4Key == NULL || ipv4Dict == NULL) {
1046            continue;
1047        }
1048
1049        /* Match interface name here */
1050        CFStringRef ifnameRef = CFDictionaryGetValue(ipv4Dict, kSCPropInterfaceName);
1051        if (ifnameRef) {
1052            char ifname[IFNAMSIZ] = { 0 };
1053            CFStringGetCString(ifnameRef, ifname, sizeof(ifname), kCFStringEncodingASCII);
1054            if (!strcmp(ifname, interface)) {
1055                if ((CFStringHasPrefix(ipv4Key, kSCDynamicStoreDomainState)) && (CFStringHasSuffix(ipv4Key, kSCEntNetIPv4))) {
1056                    // Fetch the serviceID, then the router address
1057                    serviceID = l2tp_copy_str_at_index(ipv4Key, 3);
1058                    l2tp_get_router_address(serviceID);
1059                    break;
1060                }
1061            }
1062        }
1063    }
1064
1065done:
1066    if (serviceID) {
1067        CFRelease(serviceID);
1068    }
1069    if (pattern) {
1070        CFRelease(pattern);
1071    }
1072    if (patterns) {
1073        CFRelease(patterns);
1074    }
1075    if (dict) {
1076        CFRelease(dict);
1077    }
1078    if (keys) {
1079        free(keys);
1080    }
1081    if (values) {
1082        free(values);
1083    }
1084}
1085
1086/* -----------------------------------------------------------------------------
1087get the socket ready to start doing PPP.
1088That is, open the socket and start the L2TP dialog
1089----------------------------------------------------------------------------- */
1090int l2tp_connect(int *errorcode)
1091{
1092    char 		dev[32], name[MAXPATHLEN], c;
1093    int 		err = 0, rcvlen;
1094	socklen_t	optlen;
1095    CFURLRef		url;
1096    CFDictionaryRef	dict;
1097    CFStringRef		string, key;
1098    struct kev_request	kev_req;
1099    struct sockaddr_in	from;
1100    struct sockaddr_in 	any_address;
1101	u_int32_t baudrate;
1102	char				*errstr;
1103	int					host_name_specified;
1104    int                 ipsec_status = 0;
1105    int                 num_connect_retries = 0;
1106
1107	*errorcode = 0;
1108
1109    if (cfgCache == NULL || serviceidRef == NULL) {
1110        goto fail;
1111    }
1112
1113    snprintf(dev, sizeof(dev), "socket[%d:%d]", PF_PPP, PPPPROTO_L2TP);
1114    strlcpy(ppp_devnam, dev, sizeof(ppp_devnam));
1115
1116    hungup = 0;
1117    kill_link = 0;
1118
1119    routeraddress[0] = 0;
1120    interface[0] = 0;
1121	host_name_specified = 0;
1122
1123    /* unknown src and dst addresses */
1124    bzero(&any_address, sizeof(any_address));
1125    any_address.sin_len = sizeof(any_address);
1126    any_address.sin_family = AF_INET;
1127    any_address.sin_port = htons(0);
1128    any_address.sin_addr.s_addr = htonl(INADDR_ANY);
1129
1130    our_address = any_address;
1131    peer_address = any_address;
1132
1133    /* init params */
1134    bzero(&our_params, sizeof(our_params));
1135    bzero(&peer_params, sizeof(peer_params));
1136
1137    our_params.tunnel_id = 0;					/* our tunnel ID - will be assigned later */
1138    our_params.session_id = getpid();			/* our session ID - use pid as unique number */
1139    our_params.window_size = opt_windowsize;	/* our receive window size */
1140    our_params.seq_required = 0;				/* sequencing required - not used for now */
1141    our_params.call_serial_num = 1; 				/* our call serial number - always 1 for now */
1142    our_params.framing_caps = L2TP_SYNC_FRAMING|L2TP_ASYNC_FRAMING;
1143    our_params.framing_type = L2TP_SYNC_FRAMING|L2TP_ASYNC_FRAMING;
1144    our_params.tx_connect_speed = 1000000;
1145    if (gethostname((char*)our_params.host_name, sizeof(our_params.host_name)) != 0) {
1146        our_params.host_name[0] = 0;
1147    }
1148    our_params.protocol_vers = L2TP_PROTOCOL_VERSION;
1149
1150    if (ifscope && ifscope[0]) {
1151        strcpy(interface, ifscope);
1152        l2tp_get_router_address_for_interface();
1153    } else {
1154        key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4);
1155        if (key) {
1156            dict = SCDynamicStoreCopyValue(cfgCache, key);
1157        CFRelease(key);
1158            if (dict) {
1159                if ((string  = CFDictionaryGetValue(dict, kSCPropNetIPv4Router)))
1160                    CFStringGetCString(string, (char*)routeraddress, sizeof(routeraddress), kCFStringEncodingUTF8);
1161                if ((string  = CFDictionaryGetValue(dict, kSCDynamicStorePropNetPrimaryInterface)))
1162                    CFStringGetCString(string, (char*)interface, sizeof(interface), kCFStringEncodingUTF8);
1163                CFRelease(dict);
1164            }
1165        }
1166    }
1167
1168	/* now that we know our interface, adjust the MTU if necessary */
1169	if (interface[0]) {
1170		int min_mtu = get_if_mtu((char*)interface) - L2TP_MIN_HDR_SIZE;
1171		if (lcp_allowoptions[0].mru > min_mtu)	/* defines out mtu */
1172			lcp_allowoptions[0].mru = min_mtu;
1173
1174		/* Don't adjust MRU, radar 3974763 */
1175#if 0
1176		if (lcp_wantoptions[0].mru > min_mtu)	/* defines out mru */
1177			lcp_wantoptions[0].mru = min_mtu;
1178		if (lcp_wantoptions[0].neg_mru > min_mtu)	/* defines our mru */
1179			lcp_wantoptions[0].neg_mru = min_mtu;
1180#endif
1181	}
1182
1183#if !TARGET_OS_EMBEDDED
1184    interface_media = get_if_media((char*)interface);
1185#endif /* !iPhone */
1186
1187	/* let's say our underlying transport is up */
1188	transport_up = 1;
1189	wait_interface_timer_running = 0;
1190	wait_underlying_interface_up = 0;
1191	ppp_session_clear(&l2tp_session);
1192	session = NULL;
1193
1194    eventsockfd = socket(PF_SYSTEM, SOCK_RAW, SYSPROTO_EVENT);
1195    if (eventsockfd != -1) {
1196        // L2TP can survive without event socket anyway
1197        kev_req.vendor_code = KEV_VENDOR_APPLE;
1198        kev_req.kev_class = KEV_NETWORK_CLASS;
1199        kev_req.kev_subclass = KEV_INET_SUBCLASS;
1200        ioctl(eventsockfd, SIOCSKEVFILT, &kev_req);
1201    }
1202
1203    if (strcmp(opt_mode, MODE_ANSWER)) {		/* not for answer mode */
1204        /* open the L2TP socket control socket */
1205        ctrlsockfd = socket(PF_PPP, SOCK_DGRAM, PPPPROTO_L2TP);
1206        if (ctrlsockfd < 0) {
1207            if (!opt_noload) {
1208                if ((url = CFBundleCopyBundleURL(bundle))) {
1209                    name[0] = 0;
1210                    CFURLGetFileSystemRepresentation(url, 0, (UInt8 *)name, MAXPATHLEN - 1);
1211                    CFRelease(url);
1212                    strlcat(name, "/", sizeof(name));
1213                    if ((url = CFBundleCopyBuiltInPlugInsURL(bundle))) {
1214                        CFURLGetFileSystemRepresentation(url, 0, (UInt8 *)(name + strlen(name)),
1215                                MAXPATHLEN - strlen(name) - strlen(L2TP_NKE) - 1);
1216                        CFRelease(url);
1217                        strlcat(name, "/", sizeof(name));
1218                        strlcat(name, L2TP_NKE, sizeof(name));
1219#if !TARGET_OS_EMBEDDED
1220                        if (!load_kext(name, 0))
1221#else
1222                        if (!load_kext(L2TP_NKE_ID, 1))
1223#endif
1224                            ctrlsockfd = socket(PF_PPP, SOCK_DGRAM, PPPPROTO_L2TP);
1225                    }
1226                }
1227            }
1228            if (ctrlsockfd < 0) {
1229                    error("Failed to open L2TP control socket: %m");
1230                    goto fail;
1231            }
1232        }
1233    }
1234
1235    l2tp_set_flag(ctrlsockfd, kdebugflag & 1, L2TP_FLAG_DEBUG);
1236    l2tp_set_flag(ctrlsockfd, 1, L2TP_FLAG_CONTROL);
1237    l2tp_set_flag(ctrlsockfd, our_params.seq_required, L2TP_FLAG_SEQ_REQ);
1238    l2tp_set_flag(ctrlsockfd, !opt_noipsec, L2TP_FLAG_IPSEC);
1239    l2tp_set_delegated_process(ctrlsockfd, getpid());  // must be set before calling l2tp_set_ouraddress
1240
1241    /* ask the kernel extension to make and assign a new tunnel id to the tunnel */
1242    optlen = 2;
1243    getsockopt(ctrlsockfd, PPPPROTO_L2TP, L2TP_OPT_NEW_TUNNEL_ID, &our_params.tunnel_id, &optlen);
1244
1245    l2tp_set_ourparams(ctrlsockfd,  &our_params);
1246    l2tp_reset_timers(ctrlsockfd, 0);
1247
1248    if (kill_link)
1249        goto fail1;
1250
1251    if (!strcmp(opt_mode, MODE_CONNECT)) {
1252        //-------------------------------------------------
1253        //	connect mode
1254        //-------------------------------------------------
1255
1256        struct sockaddr_in orig_our_address, orig_peer_address;
1257
1258        if (remoteaddress == 0) {
1259            error("L2TP: No remote address supplied...\n");
1260            devstatus = EXIT_L2TP_NOSERVER;
1261            goto fail;
1262        }
1263
1264		set_network_signature("VPN.RemoteAddress", remoteaddress, 0, 0);
1265
1266#if TARGET_OS_EMBEDDED
1267		{
1268			/* first, bring up EDGE */
1269			int need_edge = FALSE;
1270			SCNetworkReachabilityRef ref = NULL;
1271			SCNetworkConnectionFlags	flags;
1272
1273			ref = SCNetworkReachabilityCreateWithName(NULL, remoteaddress);
1274			if (ref) {
1275
1276				if (SCNetworkReachabilityGetFlags(ref, &flags)) {
1277					if ((flags & kSCNetworkReachabilityFlagsReachable) &&
1278						(flags & kSCNetworkReachabilityFlagsConnectionRequired) &&
1279						(flags & kSCNetworkReachabilityFlagsIsWWAN)) {
1280						need_edge = TRUE;
1281					}
1282				}
1283				CFRelease(ref);
1284			}
1285
1286			if (need_edge) {
1287
1288				if (pipe(edgefds) < 0) {
1289					error("L2TP: failed to create pipe for starting edge...\n");
1290					goto fail;
1291				}
1292
1293				if (pthread_create(&edgethread, NULL, l2tp_edge_thread, NULL)) {
1294					error("L2TP: failed to create thread for starting edge...\n");
1295					close(edgefds[0]);
1296					close(edgefds[1]);
1297					goto fail;
1298				}
1299
1300				while (read(edgefds[0], &c, 1) != 1) {
1301					if (kill_link) {
1302						pthread_cancel(edgethread);
1303						break;
1304					}
1305				}
1306
1307				close(edgefds[0]);
1308				close(edgefds[1]);
1309
1310				if (kill_link)
1311					goto fail1;
1312
1313				if (c) {
1314					error("L2TP: Cannot start EDGE connection...\n");
1315					*errorcode = L2TP_RETRY_CONNECT_CODE; /* wait and retry if necessary */
1316					devstatus = EXIT_L2TP_NOEDGE;
1317					goto fail;
1318				}
1319
1320			}
1321
1322		}
1323#endif
1324
1325        /* build the peer address */
1326        peer_address.sin_len = sizeof(peer_address);
1327        peer_address.sin_family = AF_INET;
1328        peer_address.sin_port = htons(L2TP_UDP_PORT);
1329        if (inet_aton(remoteaddress, &peer_address.sin_addr) == 0) {
1330
1331            if (pipe(resolverfds) < 0) {
1332                error("L2TP: failed to create pipe for gethostbyname...\n");
1333                goto fail;
1334            }
1335
1336            if (pthread_create(&resolverthread, NULL, l2tp_resolver_thread, NULL)) {
1337                error("L2TP: failed to create thread for gethostbyname...\n");
1338                close(resolverfds[0]);
1339                close(resolverfds[1]);
1340                goto fail;
1341            }
1342
1343            while (read(resolverfds[0], &c, 1) != 1) {
1344                if (kill_link) {
1345                    pthread_cancel(resolverthread);
1346                    break;
1347                }
1348            }
1349
1350            close(resolverfds[0]);
1351            close(resolverfds[1]);
1352
1353            if (kill_link)
1354                goto fail1;
1355
1356            if (c) {
1357                error("L2TP: Host '%s' not found...\n", remoteaddress);
1358				*errorcode = L2TP_RETRY_CONNECT_CODE; /* wait and retry if necessary */
1359                devstatus = EXIT_L2TP_NOSERVER;
1360                goto fail;
1361            }
1362			host_name_specified = 1;
1363        }
1364
1365        notice("L2TP connecting to server '%s' (%s)...\n", remoteaddress, inet_ntoa(peer_address.sin_addr));
1366
1367        set_server_peer(peer_address.sin_addr);
1368
1369        /* get the source address that will be used to reach the peer */
1370        if (get_src_address((struct sockaddr *)&our_address, (struct sockaddr *)&peer_address, ifscope, NULL)) {
1371            error("L2TP: cannot get our local address...\n");
1372			*errorcode = L2TP_RETRY_CONNECT_CODE; /* wait and retry if necessary */
1373            goto fail;
1374        }
1375
1376        /* bind the socket in the kernel with take an ephemeral port */
1377        /* on return, it ouraddress will contain actual port selected */
1378        our_address.sin_port = htons(opt_udpport);
1379        l2tp_set_ouraddress(ctrlsockfd, (struct sockaddr *)&our_address);
1380
1381        /* set our peer address */
1382        l2tp_set_peeraddress(ctrlsockfd, (struct sockaddr *)&peer_address);
1383
1384        /* remember the original source and dest addresses */
1385        orig_our_address = our_address;
1386        orig_peer_address = peer_address;
1387
1388        err = 0;
1389
1390        /* install IPSec filters for our address and peer address */
1391        if (!opt_noipsec) {
1392
1393			CFStringRef				secret_string = NULL;
1394			CFStringRef				secret_encryption_string = NULL;
1395			CFStringRef				localidentifier_string = NULL;
1396			CFStringRef				localidentifiertype_string = NULL;
1397			CFStringRef				auth_method = NULL;
1398			CFStringRef				verify_id = NULL;
1399			CFDataRef				certificate = NULL;
1400			CFDictionaryRef			useripsec_dict = NULL;
1401			int useripsec_dict_fromsystem = 0;
1402
1403            struct sockaddr_in addr = orig_peer_address;
1404            addr.sin_port = htons(0);	// allow port to change
1405
1406			auth_method = kRASValIPSecAuthenticationMethodSharedSecret;
1407
1408			if (userOptions)
1409				useripsec_dict = CFDictionaryGetValue(userOptions, kSCEntNetIPSec);
1410			if (!useripsec_dict && systemOptions) {
1411				useripsec_dict = CFDictionaryGetValue(systemOptions, kSCEntNetIPSec);
1412				useripsec_dict_fromsystem = 1;
1413			}
1414
1415			if (!useripsec_dict && !opt_ipsecsharedsecret[0]) {
1416				error("L2TP: no user shared secret found.\n");
1417				devstatus = EXIT_L2TP_NOSHAREDSECRET;
1418				goto fail;
1419			}
1420
1421			if (useripsec_dict) {
1422				/* XXX as a simplification, the authentication method is set in the main dictionary
1423					instead of having an array of proposals with one proposal with the
1424					requested authentication method
1425				  */
1426				auth_method = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecAuthenticationMethod);
1427				if (!isString(auth_method) || CFEqual(auth_method, kRASValIPSecAuthenticationMethodSharedSecret)) {
1428					auth_method = kRASValIPSecAuthenticationMethodSharedSecret;
1429					secret_string = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecSharedSecret);
1430					if (!isString(secret_string) &&
1431						!(isData(secret_string) && ((CFDataGetLength((CFDataRef)secret_string) % sizeof(UniChar)) == 0))) {
1432						error("L2TP: incorrect user shared secret found.\n");
1433						devstatus = EXIT_L2TP_NOSHAREDSECRET;
1434						goto fail;
1435					}
1436					if (useripsec_dict_fromsystem) {
1437						secret_encryption_string = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecSharedSecretEncryption);
1438						if (secret_encryption_string && !isString(secret_encryption_string)) {
1439							error("L2TP: incorrect secret encyption found.\n");
1440							goto fail;
1441						}
1442					}
1443
1444				}
1445				else if (CFEqual(auth_method, kRASValIPSecAuthenticationMethodCertificate)) {
1446					certificate = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecLocalCertificate);
1447					if (!isData(certificate)) {
1448						devstatus = EXIT_L2TP_NOCERTIFICATE;
1449						error("L2TP: no user certificate  found.\n");
1450						goto fail;
1451					}
1452				}
1453				else {
1454					error("L2TP: incorrect authentication method.\n");
1455					goto fail;
1456				}
1457
1458				localidentifier_string = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecLocalIdentifier);
1459				if (localidentifier_string && !isString(localidentifier_string)) {
1460					error("L2TP: incorrect local identifier found.\n");
1461					goto fail;
1462				}
1463
1464					verify_id = CFDictionaryGetValue(useripsec_dict, kRASPropIPSecIdentifierVerification);
1465					if (verify_id && !isString(verify_id)) {
1466						error("L2TP: incorrect identifier verification found.\n");
1467						goto fail;
1468					}
1469
1470
1471			}
1472
1473			if (ipsec_dict) {
1474				CFRelease(ipsec_dict);
1475				ipsec_dict = NULL;
1476			}
1477
1478			ipsec_dict = IPSecCreateL2TPDefaultConfiguration(&our_address, &peer_address,
1479				(host_name_specified ? remoteaddress : NULL),
1480				auth_method, 1, 0, verify_id);
1481
1482			if (!ipsec_dict) {
1483				error("L2TP: cannot create L2TP configuration.\n");
1484				goto fail;
1485			}
1486
1487			if (secret_string) {
1488				if (isString(secret_string))
1489					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, secret_string);
1490				else {
1491					CFStringEncoding	encoding;
1492					CFDataRef			secret_data	= (CFDataRef)secret_string;
1493
1494#if     __BIG_ENDIAN__
1495					encoding = (*(CFDataGetBytePtr(secret_data) + 1) == 0x00) ? kCFStringEncodingUTF16LE : kCFStringEncodingUTF16BE;
1496#else   // __LITTLE_ENDIAN__
1497					encoding = (*(CFDataGetBytePtr(secret_data)    ) == 0x00) ? kCFStringEncodingUTF16BE : kCFStringEncodingUTF16LE;
1498#endif
1499					secret_string = CFStringCreateWithBytes(NULL, (const UInt8 *)CFDataGetBytePtr(secret_data), CFDataGetLength(secret_data), encoding, FALSE);
1500					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, secret_string);
1501					CFRelease(secret_string);
1502				}
1503				if (secret_encryption_string) {
1504					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, secret_encryption_string);
1505				}
1506			}
1507			else if (certificate) {
1508				CFDictionarySetValue(ipsec_dict, kRASPropIPSecLocalCertificate, certificate);
1509			}
1510			else {
1511				/* set the authentication information */
1512				secret_string = CFStringCreateWithCString(0, opt_ipsecsharedsecret, kCFStringEncodingUTF8);
1513				CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, secret_string);
1514				if (!strcmp(opt_ipsecsharedsecrettype, "key"))
1515					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, kRASValIPSecSharedSecretEncryptionKey);
1516				else if (!strcmp(opt_ipsecsharedsecrettype, "keychain"))
1517					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, kRASValIPSecSharedSecretEncryptionKeychain);
1518				CFRelease(secret_string);
1519			}
1520
1521			if (localidentifier_string) {
1522				CFDictionarySetValue(ipsec_dict, kRASPropIPSecLocalIdentifier, localidentifier_string);
1523			}
1524			else if (opt_ipseclocalidentifier[0]) {
1525				/* set the local identifier information */
1526				localidentifier_string = CFStringCreateWithCString(0, opt_ipseclocalidentifier, kCFStringEncodingUTF8);
1527				CFDictionarySetValue(ipsec_dict, kRASPropIPSecLocalIdentifier, localidentifier_string);
1528				CFRelease(localidentifier_string);
1529				localidentifier_string = NULL;
1530			}
1531
1532			if (localidentifiertype_string) {
1533				CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), localidentifiertype_string);
1534			}
1535			else if (opt_ipseclocalidentifiertype) {
1536				/* set the local identifier type information */
1537				if (!strcmp(opt_ipseclocalidentifiertype, "keyid"))
1538					CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), CFSTR("KeyID"));
1539				else if (!strcmp(opt_ipseclocalidentifiertype, "fqdn"))
1540					CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), CFSTR("FQDN"));
1541				else if (!strcmp(opt_ipseclocalidentifiertype, "user_fqdn"))
1542					CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), CFSTR("UserFQDN"));
1543				else if (!strcmp(opt_ipseclocalidentifiertype, "asn1dn"))
1544					CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), CFSTR("ASN1DN"));
1545				else if (!strcmp(opt_ipseclocalidentifiertype, "address"))
1546					CFDictionarySetValue(ipsec_dict, CFSTR("LocalIdentifierType"), CFSTR("Address"));
1547			}
1548			if (debug) {
1549				// enable IPSec 'VerboseLogging' if ppp's is also enabled
1550				IPSecConfigureVerboseLogging(ipsec_dict, debug);
1551			}
1552
1553
1554			if (IPSecApplyConfiguration(ipsec_dict, &errstr)
1555				|| IPSecInstallPolicies(ipsec_dict, -1, &errstr)) {
1556				error("L2TP: cannot configure secure transport (%s).\n", errstr);
1557				goto fail;
1558			}
1559
1560			/* now trigger IKE */
1561            while ((err = l2tp_trigger_ipsec(0, &ipsec_status)) &&
1562                   ipsec_status == RACOON_STARTED &&
1563                   num_connect_retries < num_alt_peer_address) {
1564                ipsec_status = 0;
1565
1566                /* get the source address that will be used to reach the peer */
1567                if ((err = l2tp_change_peeraddress(ctrlsockfd, (struct sockaddr *)&alt_peer_address[num_connect_retries++]))) {
1568                    error("L2TP: cannot try alternate server...\n");
1569                    goto fail;
1570                }
1571
1572                notice("L2TP connecting to alternate server '%s' (%s)...\n", remoteaddress, inet_ntoa(peer_address.sin_addr));
1573            }
1574        }
1575
1576		if (err == 0) {
1577			err = l2tp_outgoing_call(ctrlsockfd, (struct sockaddr *)&peer_address, &our_params, &peer_params, opt_recv_timeout);
1578
1579			/* setup the specific route */
1580			l2tp_set_peer_route();
1581		}
1582
1583    } else {
1584
1585        //-------------------------------------------------
1586        //	listen or answer mode
1587        //-------------------------------------------------
1588
1589        int 	listenfd = -1;
1590
1591        if (!strcmp(opt_mode, MODE_LISTEN)) {
1592            //-------------------------------------------------
1593            //	listen mode
1594            //		setup listen socket and listen for calls
1595            //-------------------------------------------------
1596            struct sockaddr_in listen_address;
1597
1598            notice("L2TP listening...\n");
1599
1600            listenfd = socket(PF_PPP, SOCK_DGRAM, PPPPROTO_L2TP);
1601            if (listenfd < 0) {
1602                    error("Failed to open L2TP listening control socket: %m");
1603                    goto fail;
1604            }
1605
1606            l2tp_set_flag(listenfd, kdebugflag & 1, L2TP_FLAG_DEBUG);
1607            l2tp_set_flag(listenfd, 1, L2TP_FLAG_CONTROL);
1608			l2tp_set_flag(listenfd, !opt_noipsec, L2TP_FLAG_IPSEC);
1609            l2tp_set_delegated_process(listenfd, getpid());  // must be set before calling l2tp_set_ouraddress
1610
1611
1612            /* bind the socket in the kernel with L2TP port */
1613            listen_address.sin_len = sizeof(peer_address);
1614            listen_address.sin_family = AF_INET;
1615            listen_address.sin_port = htons(L2TP_UDP_PORT);
1616            listen_address.sin_addr.s_addr = INADDR_ANY;
1617            l2tp_set_ouraddress(listenfd, (struct sockaddr *)&listen_address);
1618
1619            our_address = listen_address;
1620
1621            /* add security policies */
1622            if (!opt_noipsec) {
1623
1624				CFStringRef				secret_string;
1625
1626				if (ipsec_dict)
1627					CFRelease(ipsec_dict);
1628
1629				ipsec_dict = IPSecCreateL2TPDefaultConfiguration(&our_address, &peer_address,
1630					(host_name_specified ? remoteaddress : NULL),
1631					kRASValIPSecAuthenticationMethodSharedSecret, 0, 0, 0);
1632
1633				/* set the authentication information */
1634				secret_string = CFStringCreateWithCString(0, opt_ipsecsharedsecret, kCFStringEncodingUTF8);
1635				CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, secret_string);
1636				if (!strcmp(opt_ipsecsharedsecrettype, "key"))
1637					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, kRASValIPSecSharedSecretEncryptionKey);
1638				else if (!strcmp(opt_ipsecsharedsecrettype, "keychain"))
1639					CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, kRASValIPSecSharedSecretEncryptionKeychain);
1640				CFRelease(secret_string);
1641
1642				if (debug) {
1643					// enable IPSec 'VerboseLogging' if ppp's is also enabled
1644					IPSecConfigureVerboseLogging(ipsec_dict, debug);
1645				}
1646
1647				if (IPSecApplyConfiguration(ipsec_dict, &errstr)
1648					|| IPSecInstallPolicies(ipsec_dict, -1, &errstr)) {
1649					error("L2TP: cannot configure secure transport (%s).\n", errstr);
1650					goto fail;
1651				}
1652			}
1653			err = l2tp_trigger_ipsec(1, &ipsec_status);
1654            /* wait indefinitely and read the duplicated SCCRQ from the listen socket and ignore for now */
1655            if ((err = l2tp_recv(listenfd, control_buf, MAX_CNTL_BUFFER_SIZE, &rcvlen, (struct sockaddr*)&from, -1, "SCCRQ"))){
1656            	if (err == 0) {
1657                	setsockopt(ctrlsockfd, PPPPROTO_L2TP, L2TP_OPT_ACCEPT, 0, 0);
1658            	}
1659			}
1660
1661            close(listenfd);
1662        }
1663
1664		//-------------------------------------------------
1665        //	listen or answer mode
1666        //		process incoming connection
1667        //-------------------------------------------------
1668        if (err == 0) {
1669
1670			// log incoming call from l2tp_change_peeraddress() because that's when we know the peer address
1671
1672           err = l2tp_incoming_call(ctrlsockfd, &our_params, &peer_params, opt_recv_timeout);
1673        }
1674
1675		//remoteaddress = inet_ntoa(peer_address.sin_addr);
1676
1677    }
1678
1679    //-------------------------------------------------
1680    //	all modes
1681    //-------------------------------------------------
1682    if (err) {
1683        if (err != -2) {
1684            if (err != -1)
1685                devstatus = err;
1686            goto fail;
1687        }
1688        goto fail1;
1689    }
1690
1691    notice("L2TP connection established.");
1692
1693    /* start hello timer */
1694    if (opt_hello_timeout) {
1695        hello_timer_running = 1;
1696        TIMEOUT(l2tp_hello_timeout, 0, opt_hello_timeout);
1697    }
1698
1699    /* open the data socket */
1700    datasockfd = socket(PF_PPP, SOCK_DGRAM, PPPPROTO_L2TP);
1701    if (datasockfd < 0) {
1702        error("Failed to open L2TP data socket: %m");
1703        goto fail;
1704    }
1705
1706    l2tp_set_flag(datasockfd, 0, L2TP_FLAG_CONTROL);
1707    l2tp_set_flag(datasockfd, kdebugflag & 1, L2TP_FLAG_DEBUG);
1708    l2tp_set_flag(datasockfd, peer_params.seq_required, L2TP_FLAG_SEQ_REQ);
1709	l2tp_set_flag(datasockfd, !opt_noipsec, L2TP_FLAG_IPSEC);
1710
1711    l2tp_set_ouraddress(datasockfd, (struct sockaddr *)&our_address);
1712    /* set the peer address of the data socket */
1713    /* on a data socket, this will find the socket of the corresponding control connection */
1714    l2tp_set_peeraddress(datasockfd, (struct sockaddr *)&peer_address);
1715
1716    l2tp_set_ourparams(datasockfd, &our_params);
1717    l2tp_set_peerparams(datasockfd, &peer_params);
1718    l2tp_reset_timers(datasockfd, 0);
1719
1720	baudrate = get_if_baudrate((char*)interface);
1721	l2tp_set_baudrate(datasockfd, baudrate);
1722
1723    if (!strcmp(opt_mode, MODE_CONNECT)) {
1724        l2tp_init_session((char *)interface, sizeof(interface), &our_address.sin_addr, ppp_variable_echo_start);
1725        l2tp_set_nat_port_mapping();
1726    }
1727
1728    return datasockfd;
1729
1730fail:
1731
1732    status = EXIT_CONNECT_FAILED;
1733fail1:
1734    l2tp_close_fds();
1735    return -1;
1736}
1737
1738/* -----------------------------------------------------------------------------
1739run the disconnector
1740----------------------------------------------------------------------------- */
1741void l2tp_disconnect()
1742{
1743    notice("L2TP disconnecting...\n");
1744
1745    if (hello_timer_running) {
1746        UNTIMEOUT(l2tp_hello_timeout, 0);
1747        hello_timer_running = 0;
1748    }
1749
1750    if (ctrlsockfd != -1) {
1751
1752        /* send CDN and StopCCN only if this is a local disconnection
1753           don't send them if the peer requested the disconnection */
1754        if (status) {
1755            /* send CDN message */
1756            our_params.result_code = L2TP_CALLRESULT_ADMIN;
1757            our_params.cause_code = 0;
1758            if (l2tp_send_CDN(ctrlsockfd, &our_params, &peer_params) == 0) {
1759                /* send StopCCN message */
1760                our_params.result_code = L2TP_CCNRESULT_GENERAL;
1761                our_params.cause_code = 0;
1762                l2tp_send_StopCCN(ctrlsockfd, &our_params);
1763            }
1764        }
1765    }
1766
1767    l2tp_close_fds();
1768
1769    ppp_auxiliary_probe_stop();
1770    l2tp_clear_nat_port_mapping();
1771    ppp_session_clear(&l2tp_session);
1772    session = NULL;
1773
1774    notice("L2TP disconnected\n");
1775}
1776
1777/* -----------------------------------------------------------------------------
1778----------------------------------------------------------------------------- */
1779int l2tp_set_baudrate(int fd, u_int32_t baudrate)
1780{
1781	setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_BAUDRATE, &baudrate, 4);
1782    return 0;
1783}
1784
1785/* -----------------------------------------------------------------------------
1786 ----------------------------------------------------------------------------- */
1787int l2tp_set_delegated_process(int fd, int pid)
1788{
1789    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_SETDELEGATEDPID, &pid, sizeof(pid));
1790    return 0;
1791}
1792
1793/* -----------------------------------------------------------------------------
1794----------------------------------------------------------------------------- */
1795int l2tp_set_ouraddress(int fd, struct sockaddr *addr)
1796{
1797    socklen_t optlen;
1798
1799    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_OURADDRESS, addr, sizeof(*addr));
1800    /* get the address to retrieve the actual port used */
1801    optlen = sizeof(*addr);
1802    getsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_OURADDRESS, addr, &optlen);
1803    return 0;
1804}
1805
1806/* -----------------------------------------------------------------------------
1807----------------------------------------------------------------------------- */
1808int l2tp_set_peeraddress(int fd, struct sockaddr *addr)
1809{
1810
1811    if (setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_PEERADDRESS, addr, sizeof(*addr))) {
1812        error("L2TP can't set L2TP server address...\n");
1813        return -1;
1814    }
1815    return 0;
1816}
1817
1818/* -----------------------------------------------------------------------------
1819----------------------------------------------------------------------------- */
1820int l2tp_new_tunnelid(int fd, u_int16_t *tunnelid)
1821{
1822    socklen_t optlen = 2;
1823
1824    getsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_NEW_TUNNEL_ID, &tunnelid, &optlen);
1825    return 0;
1826}
1827
1828/* -----------------------------------------------------------------------------
1829----------------------------------------------------------------------------- */
1830int l2tp_set_ourparams(int fd, struct l2tp_parameters *our_params)
1831{
1832    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_TUNNEL_ID, &our_params->tunnel_id, 2);
1833    /* session id is ignored for control connections */
1834    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_SESSION_ID, &our_params->session_id, 2);
1835    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_WINDOW, &our_params->window_size, 2);
1836    return 0;
1837}
1838
1839/* -----------------------------------------------------------------------------
1840----------------------------------------------------------------------------- */
1841int l2tp_set_peerparams(int fd, struct l2tp_parameters *peer_params)
1842{
1843    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_PEER_TUNNEL_ID, &peer_params->tunnel_id, 2);
1844    /* session id is ignored for control connections */
1845    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_PEER_SESSION_ID, &peer_params->session_id, 2);
1846    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_PEER_WINDOW, &peer_params->window_size, 2);
1847    return 0;
1848}
1849
1850/* -----------------------------------------------------------------------------
1851----------------------------------------------------------------------------- */
1852int l2tp_change_peeraddress(int fd, struct sockaddr *peer)
1853{
1854    struct sockaddr_in src;
1855    int err = 0;
1856	char *errstr;
1857
1858    if (peer->sa_len != peer_address.sin_len) {
1859        error("L2TP received an invalid server address...\n");
1860        return -1;
1861    }
1862
1863    if (bcmp(&peer_address, peer, peer->sa_len)) {
1864
1865        /* reset IPSec filters */
1866        if (!opt_noipsec) {
1867            if (!strcmp(opt_mode, MODE_CONNECT)) {
1868                IPSecRemoveConfiguration(ipsec_dict, &errstr);
1869                // security associations are base on IP addresses only
1870                // Wcast-align fix - use memcmp for unaligned compare
1871                if (memcmp(&((struct sockaddr_in *)(void*)peer)->sin_addr.s_addr, &((struct sockaddr_in *)(void*)&peer_address)->sin_addr.s_addr, sizeof(struct in_addr)))
1872                    IPSecRemoveSecurityAssociations((struct sockaddr *)&our_address, (struct sockaddr *)&peer_address);
1873                IPSecRemovePolicies(ipsec_dict, -1, &errstr);
1874            }
1875        }
1876
1877        if (get_src_address((struct sockaddr *)&src, peer, ifscope, NULL)) {
1878            error("L2TP: cannot get our local address...\n");
1879            return -1;
1880        }
1881
1882        /* the path to the peer has changed (beacuse it was unknown or because we use a different server) */
1883        if (src.sin_addr.s_addr != our_address.sin_addr.s_addr) {
1884            our_address = src;
1885            /* outgoing call use ephemeral ports, incoming call reuse L2TP_UDP_PORT */
1886            if (!strcmp(opt_mode, MODE_CONNECT))
1887                our_address.sin_port = htons(0);
1888            else
1889                our_address.sin_port = htons(L2TP_UDP_PORT);
1890            l2tp_set_ouraddress(fd, (struct sockaddr *)&our_address);
1891        }
1892
1893        bcopy(peer, &peer_address, peer->sa_len);
1894
1895        err = l2tp_set_peeraddress(fd, peer);
1896
1897		if (!strncmp(opt_mode, MODE_ANSWER, strlen(opt_mode))
1898			|| !strncmp(opt_mode, MODE_LISTEN, strlen(opt_mode))) {
1899
1900			remoteaddress = inet_ntoa(peer_address.sin_addr);
1901			notice("L2TP incoming call in progress from '%s'...", remoteaddress ? remoteaddress : "");
1902		}
1903
1904        /* install new IPSec filters */
1905        if (!opt_noipsec) {
1906            if (!strcmp(opt_mode, MODE_CONNECT)) {
1907
1908				CFStringRef				dst_string;
1909				CFMutableDictionaryRef	policy0;
1910				CFMutableArrayRef		policy_array;
1911				CFNumberRef				dst_port_num;
1912				int						val;
1913
1914				dst_string = CFStringCreateWithCString(0, addr2ascii(AF_INET, &peer_address.sin_addr, sizeof(peer_address.sin_addr), 0), kCFStringEncodingASCII);
1915				val = ntohs(peer_address.sin_port); /* because there is no uint16 type */
1916				dst_port_num = CFNumberCreate(0, kCFNumberIntType, &val);
1917
1918				CFDictionarySetValue(ipsec_dict, kRASPropIPSecRemoteAddress, dst_string);
1919
1920				/* create the policies */
1921				policy_array = (CFMutableArrayRef)CFDictionaryGetValue(ipsec_dict, kRASPropIPSecPolicies);
1922				if (CFArrayGetCount(policy_array) > 1)
1923					CFArrayRemoveValueAtIndex(policy_array, 1);
1924
1925				policy0 = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(policy_array, 0);
1926				CFDictionarySetValue(policy0, kRASPropIPSecPolicyRemotePort, dst_port_num);
1927				CFArraySetValueAtIndex(policy_array, 0, policy0);
1928
1929				CFDictionarySetValue(ipsec_dict, kRASPropIPSecPolicies, policy_array);
1930
1931				CFRelease(dst_string);
1932				CFRelease(dst_port_num);
1933
1934				if (IPSecApplyConfiguration(ipsec_dict, &errstr)
1935					|| IPSecInstallPolicies(ipsec_dict, -1, &errstr)) {
1936					error("L2TP: cannot reconfigure secure transport (%s).\n", errstr);
1937					return -1;
1938				}
1939			}
1940        }
1941    }
1942
1943    return err;
1944}
1945
1946/* -----------------------------------------------------------------------------
1947----------------------------------------------------------------------------- */
1948int l2tp_set_peer_route()
1949{
1950    SCNetworkReachabilityRef	ref;
1951    SCNetworkConnectionFlags	flags;
1952    bool 			is_peer_local;
1953    struct in_addr		gateway;
1954
1955    if (peer_address.sin_addr.s_addr == 0)
1956        return -1;
1957
1958    /* check if is peer on our local subnet */
1959    ref = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&peer_address);
1960    is_peer_local = SCNetworkReachabilityGetFlags(ref, &flags) && (flags & kSCNetworkFlagsIsDirect);
1961    CFRelease(ref);
1962
1963    l2tp_set_host_gateway(RTM_DELETE, peer_address.sin_addr, ip_zeros, 0, 0);
1964
1965    if (is_peer_local
1966        || routeraddress[0] == 0
1967        || inet_aton((char*)routeraddress, &gateway) != 1) {
1968
1969        if (interface[0]) {
1970            bzero(&gateway, sizeof(gateway));
1971            /* subnet route */
1972            l2tp_set_host_gateway(RTM_ADD, peer_address.sin_addr, gateway, (char*)interface, 1);
1973            peer_route_set = 2;
1974        }
1975    }
1976    else {
1977        /* host route */
1978        l2tp_set_host_gateway(RTM_ADD, peer_address.sin_addr, gateway, 0, 0);
1979        peer_route_set = 1;
1980    }
1981
1982    return 0;
1983}
1984
1985/* -----------------------------------------------------------------------------
1986----------------------------------------------------------------------------- */
1987int l2tp_clean_peer_route()
1988{
1989
1990    if (peer_address.sin_addr.s_addr == 0)
1991        return -1;
1992
1993    if (peer_route_set) {
1994	l2tp_set_host_gateway(RTM_DELETE, peer_address.sin_addr, ip_zeros, 0, peer_route_set == 1 ? 0 : 1);
1995        peer_route_set = 0;
1996    }
1997
1998    return 0;
1999}
2000
2001/* -----------------------------------------------------------------------------
2002----------------------------------------------------------------------------- */
2003void l2tp_ip_up(void *arg, uintptr_t p)
2004{
2005
2006    if (peer_route_set == 2) {
2007        /* in the link local case, delete the route to the server,
2008            in case it conflicts with the one from the ppp interface */
2009	l2tp_set_host_gateway(RTM_DELETE, peer_address.sin_addr, ip_zeros, 0, 0);
2010    }
2011}
2012
2013/* -----------------------------------------------------------------------------
2014close the socket descriptors
2015----------------------------------------------------------------------------- */
2016void l2tp_close_fds()
2017{
2018
2019    if (hello_timer_running) {
2020        UNTIMEOUT(l2tp_hello_timeout, 0);
2021        hello_timer_running = 0;
2022    }
2023    if (eventsockfd != -1) {
2024        close(eventsockfd);
2025        eventsockfd = -1;
2026    }
2027    if (datasockfd != -1) {
2028        close(datasockfd);
2029        datasockfd = -1;
2030    }
2031    if (ctrlsockfd >= 0) {
2032        close(ctrlsockfd);
2033        ctrlsockfd = -1;
2034    }
2035    if (racoon_ctrlsockfd >= 0) {
2036        close(racoon_ctrlsockfd);
2037        racoon_ctrlsockfd = -1;
2038    }
2039
2040}
2041
2042/* -----------------------------------------------------------------------------
2043clean up before quitting
2044----------------------------------------------------------------------------- */
2045void l2tp_cleanup()
2046{
2047	char *errstr;
2048
2049    l2tp_close_fds();
2050    if (!opt_noipsec) {
2051
2052		if (ipsec_dict) {
2053			IPSecRemoveConfiguration(ipsec_dict, &errstr);
2054			IPSecRemovePolicies(ipsec_dict, -1, &errstr);
2055			CFRelease(ipsec_dict);
2056			ipsec_dict = NULL;
2057		}
2058        if (strcmp(opt_mode, MODE_ANSWER)) {
2059            IPSecRemoveSecurityAssociations((struct sockaddr *)&our_address, (struct sockaddr *)&peer_address);
2060        }
2061    }
2062    l2tp_clean_peer_route();
2063}
2064
2065/* -----------------------------------------------------------------------------
2066establish the socket as a ppp link
2067----------------------------------------------------------------------------- */
2068int l2tp_establish_ppp(int fd)
2069{
2070    int x, new_fd;
2071
2072    if (ioctl(fd, PPPIOCATTACH, &x) < 0) {
2073        error("Couldn't attach socket to the link layer: %m");
2074        return -1;
2075    }
2076
2077    new_fd = generic_establish_ppp(fd, interface);
2078    if (new_fd == -1)
2079        return -1;
2080
2081    // add just the control socket
2082    // the data socket is just for moving data in the kernel
2083    add_fd(ctrlsockfd);
2084    add_fd(eventsockfd);
2085    return new_fd;
2086}
2087
2088/* -----------------------------------------------------------------------------
2089dis-establish the socket as a ppp link
2090----------------------------------------------------------------------------- */
2091void l2tp_disestablish_ppp(int fd)
2092{
2093    int 	x;
2094
2095    remove_fd(ctrlsockfd);
2096    remove_fd(eventsockfd);
2097
2098    if (ioctl(fd, PPPIOCDETACH, &x) < 0)
2099        error("Couldn't detach socket from link layer: %m");
2100
2101    generic_disestablish_ppp(fd);
2102}
2103
2104/* -----------------------------------------------------------------------------
2105----------------------------------------------------------------------------- */
2106void closeall()
2107{
2108    int i;
2109
2110    for (i = getdtablesize() - 1; i >= 0; i--) close(i);
2111    open("/dev/null", O_RDWR, 0);
2112    dup(0);
2113    dup(0);
2114    return;
2115}
2116
2117
2118/* -----------------------------------------------------------------------------
2119----------------------------------------------------------------------------- */
2120u_long load_kext(char *kext, int byBundleID)
2121{
2122    int pid;
2123
2124    if ((pid = fork()) < 0)
2125        return 1;
2126
2127    if (pid == 0) {
2128        closeall();
2129        // PPP kernel extension not loaded, try load it...
2130		if (byBundleID)
2131			execle("/sbin/kextload", "kextload", "-b", kext, (char *)0, (char *)0);
2132		else
2133			execle("/sbin/kextload", "kextload", kext, (char *)0, (char *)0);
2134        exit(1);
2135    }
2136
2137    while (waitpid(pid, 0, 0) < 0) {
2138        if (errno == EINTR)
2139            continue;
2140       return 1;
2141    }
2142    return 0;
2143}
2144
2145/* -----------------------------------------------------------------------------
2146    hello timeout
2147----------------------------------------------------------------------------- */
2148static void l2tp_hello_timeout(void *arg)
2149{
2150
2151    if (l2tp_send_hello(ctrlsockfd, &our_params)) {
2152        error("L2TP error on control channel sending Hello message\n");
2153        /* ???? */
2154    }
2155
2156    TIMEOUT(l2tp_hello_timeout, 0, opt_hello_timeout);
2157}
2158
2159/* -----------------------------------------------------------------------------
2160add/remove a host route
2161----------------------------------------------------------------------------- */
2162static boolean_t
2163l2tp_set_host_gateway(int cmd, struct in_addr host, struct in_addr gateway, char *ifname, int isnet)
2164{
2165    int 			len;
2166    int 			rtm_seq = 0;
2167    struct {
2168	struct rt_msghdr	hdr;
2169	struct sockaddr_in	dst;
2170	struct sockaddr_in	gway;
2171	struct sockaddr_in	mask;
2172	struct sockaddr_dl	link;
2173    } 				rtmsg;
2174    int 			sockfd = -1;
2175
2176    if ((sockfd = socket(PF_ROUTE, SOCK_RAW, PF_ROUTE)) < 0) {
2177	syslog(LOG_INFO, "host_gateway: open routing socket failed, %s",
2178	       strerror(errno));
2179	return (FALSE);
2180    }
2181
2182    memset(&rtmsg, 0, sizeof(rtmsg));
2183    rtmsg.hdr.rtm_type = cmd;
2184    rtmsg.hdr.rtm_flags = RTF_UP | RTF_STATIC;
2185    if (isnet)
2186        rtmsg.hdr.rtm_flags |= RTF_CLONING;
2187    else
2188        rtmsg.hdr.rtm_flags |= RTF_HOST;
2189    if (gateway.s_addr)
2190        rtmsg.hdr.rtm_flags |= RTF_GATEWAY;
2191    rtmsg.hdr.rtm_version = RTM_VERSION;
2192    rtmsg.hdr.rtm_seq = ++rtm_seq;
2193    rtmsg.hdr.rtm_addrs = RTA_DST | RTA_NETMASK;
2194    rtmsg.dst.sin_len = sizeof(rtmsg.dst);
2195    rtmsg.dst.sin_family = AF_INET;
2196    rtmsg.dst.sin_addr = host;
2197    rtmsg.hdr.rtm_addrs |= RTA_GATEWAY;
2198    rtmsg.gway.sin_len = sizeof(rtmsg.gway);
2199    rtmsg.gway.sin_family = AF_INET;
2200    rtmsg.gway.sin_addr = gateway;
2201    rtmsg.mask.sin_len = sizeof(rtmsg.mask);
2202    rtmsg.mask.sin_family = AF_INET;
2203    rtmsg.mask.sin_addr.s_addr = 0xFFFFFFFF;
2204
2205    len = sizeof(rtmsg);
2206    if (ifname) {
2207	rtmsg.link.sdl_len = sizeof(rtmsg.link);
2208	rtmsg.link.sdl_family = AF_LINK;
2209	rtmsg.link.sdl_nlen = MIN(strlen(ifname), sizeof(rtmsg.link.sdl_data));
2210	rtmsg.hdr.rtm_addrs |= RTA_IFP;
2211	bcopy(ifname, rtmsg.link.sdl_data, rtmsg.link.sdl_nlen);
2212    }
2213    else {
2214	/* no link information */
2215	len -= sizeof(rtmsg.link);
2216    }
2217    rtmsg.hdr.rtm_msglen = len;
2218    if (write(sockfd, &rtmsg, len) < 0) {
2219	syslog(LOG_DEBUG, "host_gateway: write routing socket failed, %s",
2220	       strerror(errno));
2221	close(sockfd);
2222	return (FALSE);
2223    }
2224
2225    close(sockfd);
2226    return (TRUE);
2227}
2228
2229
2230/* -----------------------------------------------------------------------------
2231set or clear a flag
2232----------------------------------------------------------------------------- */
2233int l2tp_set_flag(int fd, int set, u_int32_t flag)
2234{
2235    int			error;
2236	socklen_t	optlen;
2237    u_int32_t	flags;
2238
2239    optlen = 4;
2240    error = getsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_FLAGS, &flags, &optlen);
2241    if (error == 0) {
2242        flags = set ? flags | flag : flags & ~flag;
2243        error = setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_FLAGS, &flags, 4);
2244    }
2245    return error;
2246}
2247
2248
2249/* -----------------------------------------------------------------------------
2250----------------------------------------------------------------------------- */
2251void l2tp_reset_timers (int fd, int connect_mode)
2252{
2253    u_int16_t		timeout, timeoutcap, retries;
2254
2255    /* use non adaptative time for initial packet */
2256    l2tp_set_flag(fd, !connect_mode, L2TP_FLAG_ADAPT_TIMER);
2257
2258    if (connect_mode) {
2259        timeout = opt_connect_timeout;
2260        timeoutcap = opt_connect_timeout;
2261        retries = opt_connect_retrycount;
2262    }
2263    else {
2264        timeout = opt_timeout;
2265        timeoutcap = opt_timeoutcap;
2266        retries = opt_retrycount;
2267    }
2268
2269    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_INITIAL_TIMEOUT, &timeout, 2);
2270    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_TIMEOUT_CAP, &timeoutcap, 2);
2271    setsockopt(fd, PPPPROTO_L2TP, L2TP_OPT_MAX_RETRIES, &retries, 2);
2272}
2273
2274/* -----------------------------------------------------------------------------
2275----------------------------------------------------------------------------- */
2276static void l2tp_link_failure ()
2277{
2278    // major change happen on the interface we are using.
2279    // disconnect L2TP
2280    // Enhancement : should check if link is still usable
2281    notice("L2TP has detected change in the network and lost connection with the server.");
2282    devstatus = EXIT_L2TP_NETWORKCHANGED;
2283    status = EXIT_HANGUP;
2284    remove_fd(ctrlsockfd);
2285    remove_fd(eventsockfd);
2286    hungup = 1;
2287    lcp_lowerdown(0);	/* L2TP link is no longer available */
2288    link_terminated(0);
2289    ppp_auxiliary_probe_stop();
2290    l2tp_clear_nat_port_mapping();
2291    ppp_session_clear(&l2tp_session);
2292    session = NULL;
2293}
2294
2295
2296/* -----------------------------------------------------------------------------
2297 ----------------------------------------------------------------------------- */
2298int
2299l2tp_ip_probe_init (struct sockaddr_in *probe_addrs,
2300					int                *probe_fds,
2301					int                 num)
2302{
2303	int scope;
2304
2305	if (!probe_addrs || !probe_fds || num < 3) {
2306		return -1;
2307	}
2308
2309	scope = if_nametoindex((char *)interface);
2310
2311	bzero(probe_addrs, (sizeof(*probe_addrs) * num));
2312	probe_addrs[GOOG_DNS_PROBE].sin_len = sizeof(struct in_addr);
2313	probe_addrs[GOOG_DNS_PROBE].sin_family = AF_INET;
2314	probe_addrs[GOOG_DNS_PROBE].sin_port = 0;
2315	probe_addrs[GOOG_DNS_PROBE].sin_addr.s_addr = GOOG_DNS_PROBE_ADDR_A; // google-public-dns-a.google.com
2316	if (peer_address.sin_family == AF_INET &&
2317		peer_address.sin_addr.s_addr) {
2318		bcopy(&peer_address, &probe_addrs[PEER_ADDR_PROBE], sizeof(probe_addrs[PEER_ADDR_PROBE]));
2319		if (num_alt_peer_address) {
2320			bcopy(&alt_peer_address[(arc4random() % num_alt_peer_address)], &probe_addrs[ALT_PEER_ADDR_PROBE], sizeof(probe_addrs[ALT_PEER_ADDR_PROBE]));
2321		}
2322	}
2323	probe_fds[GOOG_DNS_PROBE] = -1;
2324	probe_fds[PEER_ADDR_PROBE] = -1;
2325	probe_fds[ALT_PEER_ADDR_PROBE] = -1;
2326	return 0;
2327}
2328
2329static char *l2tp_sd_name = "L2TP";
2330void
2331l2tp_init_session (char              *interface_name,
2332				   u_int32_t          interface_name_siz,
2333				   struct in_addr    *addr,
2334				   link_failure_func  func)
2335{
2336	ppp_session_clear(&l2tp_session);
2337	l2tp_session.sd_name = l2tp_sd_name;
2338	l2tp_session.interface_name = interface_name;
2339	l2tp_session.interface_name_siz = interface_name_siz;
2340	l2tp_session.interface_address.s_addr = addr->s_addr;
2341	l2tp_session.failure_func = func;
2342	//sess->probe_timer_running = 0;
2343	l2tp_ip_probe_init(l2tp_session.probe_addrs, l2tp_session.probe_fds, MAX_PROBE_ADDRS);
2344	l2tp_session.opt_noipsec = opt_noipsec;
2345	l2tp_session.valid = 1;
2346	session = &l2tp_session;
2347}
2348