1/*
2 * Copyright (c) 2002 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#include <sys/systm.h>
26#include <sys/kpi_mbuf.h>
27#include <sys/socket.h>
28#include <sys/socketvar.h>
29#include <sys/malloc.h>
30#include <sys/syslog.h>
31#include <sys/domain.h>
32#include <kern/locks.h>
33
34#include "../../../Family/if_ppplink.h"
35#include "../../../Family/ppp_domain.h"
36#include "l2tp.h"
37#include "l2tp_rfc.h"
38#include "l2tp_udp.h"
39#include "l2tpk.h"
40
41
42/* -----------------------------------------------------------------------------
43Definitions
44----------------------------------------------------------------------------- */
45/* Wcast-align fix - cast away alignment warning when buffer is aligned */
46#define ALIGNED_CAST(type)	(type)(void *)
47
48
49#define L2TP_STATE_SESSION_EST	0x00000001	/* session is established - data can be transfered */
50#define L2TP_STATE_NEW_SEQUENCE	0x00000002	/* we have a seq number to acknowledge */
51#define L2TP_STATE_FREEING	0x00000004	/* rfc has been freed. structure is kept for 31 seconds */
52#define L2TP_STATE_RELIABILITY_OFF	0x00000008	/* reliability layer is currently off */
53
54
55/*
56 * l2tp sequence numbers are 16 bit integers operated
57 * on with modular arithmetic.  These macros can be
58 * used to compare such integers.
59 */
60#define SEQ_LT(a,b)     ((int16_t)(((int16_t)(a))-((int16_t)(b))) < 0)
61#define SEQ_LEQ(a,b)    ((int16_t)(((int16_t)(a))-((int16_t)(b))) <= 0)
62#define SEQ_GT(a,b)     ((int16_t)(((int16_t)(a))-((int16_t)(b))) > 0)
63#define SEQ_GEQ(a,b)    ((int16_t)(((int16_t)(a))-((int16_t)(b))) >= 0)
64
65#define ROUND16DIFF(a, b)  	((a >= b) ? (a - b) : (0xFFFF - b + a + 1))
66#define ABS(a) 			(a >= 0 ? a : -a)
67
68struct l2tp_elem {
69    TAILQ_ENTRY(l2tp_elem)	next;
70    mbuf_t 		packet;
71    u_int16_t			seqno;
72    u_int8_t			addr[INET6_ADDRSTRLEN]; /* use the largest address between v4 and v6 */
73};
74
75
76struct l2tp_rfc {
77
78    // administrative info
79    TAILQ_ENTRY(l2tp_rfc) 	next;
80    void 			*host; 			/* pointer back to the hosting structure */
81    l2tp_rfc_input_callback 	inputcb;		/* callback function when data are present */
82    l2tp_rfc_event_callback 	eventcb;		/* callback function for events */
83    socket_t        socket;		/* socket used for udp packets */
84    int             thread;             /* thread number to use */
85	int             delegate_pid;       /* used to set delegated process for traffic accounting */
86
87    // l2tp info
88    u_int32_t  		state;				/* state information */
89    u_int32_t  		flags;				/* miscellaneous flags */
90    u_int32_t		baudrate;				/* baudrate of the underlying transport */
91    struct sockaddr_storage*	peer_address;			/* ip address we are connected to */
92    struct sockaddr_storage*	our_address;			/* our side of the tunnel */
93    u_int16_t		our_tunnel_id;			/* our tunnel id */
94    u_int16_t		peer_tunnel_id;			/* peer's tunnel id */
95    u_int16_t		our_session_id;			/* our session id */
96    u_int16_t		peer_session_id;		/* peer's session id */
97    u_int16_t		our_window;			/* our recv window */
98    u_int16_t		peer_window;			/* peer's recv window */
99    u_int16_t		free_time_remain;		/* time until rfc is freed - seconds/2 */
100    u_int16_t		initial_timeout;		/* initial timeout value - seconds/2 */
101    u_int16_t		timeout_cap;			/* maximum timeout cap - seconds/2 */
102    u_int16_t		max_retries;			/* maximum retries allowed */
103    u_int16_t		retry_count;			/* current retry count */
104    u_int16_t		retrans_time_remain;		/* time until next retransmission - seconds/2 */
105    u_int16_t		our_ns;				/* last seq number we sent */
106    u_int16_t		our_nr;				/* last seq number we acked */
107    u_int16_t		peer_nr;			/* last seq number peer acked */
108    u_int16_t		our_last_data_seq;		/* last data seq number we sent */
109    u_int16_t		peer_last_data_seq;		/* last data seq number we received */
110    TAILQ_HEAD(, l2tp_elem) send_queue;		/* control message send queue */
111    TAILQ_HEAD(, l2tp_elem) recv_queue;		/* control or sequenced data message recv queue */
112
113};
114
115#define LOGIT(rfc, str, args...)	\
116    if (rfc->flags & L2TP_FLAG_DEBUG)   \
117        IOLog(str, args)
118
119
120
121/* -----------------------------------------------------------------------------
122Globals
123----------------------------------------------------------------------------- */
124
125static u_int16_t unique_tunnel_id = 0;
126extern lck_mtx_t	*ppp_domain_mutex;
127
128#define L2TP_RFC_MAX_HASH 256
129static TAILQ_HEAD(, l2tp_rfc) l2tp_rfc_hash[L2TP_RFC_MAX_HASH];
130
131
132/* -----------------------------------------------------------------------------
133Forward declarations
134----------------------------------------------------------------------------- */
135
136u_int16_t l2tp_rfc_output_control(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *to);
137u_int16_t l2tp_rfc_output_data(struct l2tp_rfc *rfc, mbuf_t m);
138int l2tp_rfc_output_queued(struct l2tp_rfc *rfc, struct l2tp_elem *elem);
139int l2tp_rfc_compare_address(struct sockaddr* addr1, struct sockaddr* addr2);
140void l2tp_rfc_handle_ack(struct l2tp_rfc *rfc, u_int16_t nr);
141u_int16_t l2tp_handle_data(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *from,
142    u_int16_t flags, u_int16_t len, u_int16_t tunnel_id, u_int16_t session_id);
143u_int16_t l2tp_handle_control(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *from,
144    u_int16_t flags, u_int16_t len, u_int16_t tunnel_id, u_int16_t session_id);
145void l2tp_rfc_free_now(struct l2tp_rfc *rfc);
146void l2tp_rfc_accept(struct l2tp_rfc* rfc);
147
148/* -----------------------------------------------------------------------------
149intialize L2TP protocol
150----------------------------------------------------------------------------- */
151u_int16_t l2tp_rfc_init()
152{
153	int i;
154
155    l2tp_udp_init();
156	for (i = 0; i < L2TP_RFC_MAX_HASH; i++)
157		TAILQ_INIT(&l2tp_rfc_hash[i]);
158    return 0;
159}
160
161/* -----------------------------------------------------------------------------
162dispose of a L2TP protocol
163----------------------------------------------------------------------------- */
164u_int16_t l2tp_rfc_dispose()
165{
166	int i;
167
168	lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
169
170	for (i = 0; i < L2TP_RFC_MAX_HASH; i++) {
171		if (TAILQ_FIRST(&l2tp_rfc_hash[i]))
172			return 1;
173	}
174
175    if (l2tp_udp_dispose())
176        return 1;
177    return 0;
178}
179
180/* -----------------------------------------------------------------------------
181intialize a new L2TP structure
182----------------------------------------------------------------------------- */
183u_int16_t l2tp_rfc_new_client(void *host, void **data,
184                         l2tp_rfc_input_callback input,
185                         l2tp_rfc_event_callback event)
186{
187    struct l2tp_rfc 	*rfc;
188
189	lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
190
191    if (input == 0 || event == 0)
192        return EINVAL;
193
194    rfc = (struct l2tp_rfc *)_MALLOC(sizeof (struct l2tp_rfc), M_TEMP, M_WAITOK);
195    if (rfc == 0)
196        return 1;
197
198    //IOLog("L2TP new_client rfc = %p\n", rfc);
199
200    bzero(rfc, sizeof(struct l2tp_rfc));
201
202    rfc->host = host;
203    rfc->inputcb = input;
204    rfc->eventcb = event;
205    rfc->timeout_cap = L2TP_DEFAULT_TIMEOUT_CAP * 2;
206    rfc->initial_timeout = L2TP_DEFAULT_INITIAL_TIMEOUT * 2;
207    rfc->max_retries = L2TP_DEFAULT_RETRY_COUNT;
208    rfc->flags = L2TP_FLAG_ADAPT_TIMER;
209
210    // let's use some default values
211    rfc->peer_window = L2TP_DEFAULT_WINDOW_SIZE;
212    rfc->our_window = L2TP_DEFAULT_WINDOW_SIZE;
213
214    TAILQ_INIT(&rfc->send_queue);
215    TAILQ_INIT(&rfc->recv_queue);
216
217    *data = rfc;
218
219	// insert tail
220    TAILQ_INSERT_TAIL(&l2tp_rfc_hash[0], rfc, next);
221
222    return 0;
223}
224
225/* -----------------------------------------------------------------------------
226prepare for dispose of a L2TP structure
227----------------------------------------------------------------------------- */
228void l2tp_rfc_free_client(void *data)
229{
230    struct l2tp_rfc 		*rfc = (struct l2tp_rfc *)data;
231
232	lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
233
234
235	LOGIT(rfc, "L2TP prepare for freeing (%p)\n", rfc);
236
237	rfc->host = 0;
238	rfc->inputcb = 0;
239	rfc->eventcb = 0;
240	rfc->state |= L2TP_STATE_FREEING;
241
242    if (rfc->flags & L2TP_FLAG_CONTROL
243        && rfc->our_tunnel_id && rfc->peer_tunnel_id) {
244        /* keep control connections around for a full retransmission cycle */
245        rfc->free_time_remain = 62; // give 31 seconds
246    }
247    else {
248        /* immediatly dispose of data connections */
249        rfc->free_time_remain = 1; // free it a.s.a.p
250    }
251}
252
253/* -----------------------------------------------------------------------------
254dispose of a L2TP structure
255----------------------------------------------------------------------------- */
256void l2tp_rfc_free_now(struct l2tp_rfc *rfc)
257{
258    struct l2tp_elem 	*send_elem;
259    struct l2tp_elem	*recv_elem;
260    struct l2tp_rfc 	*rfc1;
261	int					i;
262
263	lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
264
265    LOGIT(rfc, "L2TP free (%p)\n", rfc);
266
267    if (rfc->socket) {
268        /* the control connection own socket */
269        if (rfc->flags & L2TP_FLAG_CONTROL){
270            // find an rfc with same socket
271			for (i = 0; i < L2TP_RFC_MAX_HASH; i++) {
272				TAILQ_FOREACH(rfc1, &l2tp_rfc_hash[i], next)
273					if (rfc1 != rfc
274						&& (rfc1->flags & L2TP_FLAG_CONTROL)
275						&& (rfc1->socket == rfc->socket))
276						break;
277				// check if found
278				if (rfc1)
279					break;
280			}
281			// nothing other rfc found, detach socket
282            if (rfc1 == 0)
283                l2tp_udp_detach(rfc->socket, rfc->thread);
284        }
285        rfc->socket = 0;
286    }
287
288    if (rfc->peer_address)
289        _FREE(rfc->peer_address, M_SONAME);
290
291    while((send_elem = TAILQ_FIRST(&rfc->send_queue))) {
292        TAILQ_REMOVE(&rfc->send_queue, send_elem, next);
293        mbuf_freem(send_elem->packet);
294        _FREE(send_elem, M_TEMP);
295    }
296    while((recv_elem = TAILQ_FIRST(&rfc->recv_queue))) {
297        TAILQ_REMOVE(&rfc->recv_queue, recv_elem, next);
298        mbuf_freem(recv_elem->packet);
299        _FREE(recv_elem, M_TEMP);
300    }
301
302    TAILQ_REMOVE(&l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], rfc, next);
303    _FREE(rfc, M_TEMP);
304}
305
306/* -----------------------------------------------------------------------------
307----------------------------------------------------------------------------- */
308u_int16_t l2tp_rfc_command(void *data, u_int32_t cmd, void *cmddata)
309{
310    struct l2tp_rfc 	*rfc1, *rfc = (struct l2tp_rfc *)data;
311    u_int16_t		error = 0;
312    int			len, i, had_peer_addr;
313    u_char 		*p;
314    u_int16_t   aligned_short;
315
316	lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
317
318    switch (cmd) {
319
320        case L2TP_CMD_SETFLAGS:
321            LOGIT(rfc, "L2TP command (%p): set flags = 0x%x\n", rfc, *(u_int32_t *)cmddata);
322            rfc->flags = *(u_int32_t *)cmddata;
323           break;
324
325        case L2TP_CMD_GETFLAGS:
326            LOGIT(rfc, "L2TP command (%p): get flags = 0x%x\n", rfc, rfc->flags);
327            *(u_int32_t *)cmddata = rfc->flags;
328            break;
329
330        case L2TP_CMD_SETWINDOW:
331            LOGIT(rfc, "L2TP command (%p): set window = %d\n", rfc, *(u_int16_t *)cmddata);
332            rfc->our_window = *(u_int16_t *)cmddata;
333            break;
334
335        case L2TP_CMD_SETPEERWINDOW:
336            LOGIT(rfc, "L2TP command (%p): set peer window = %d\n", rfc, *(u_int16_t *)cmddata);
337            rfc->peer_window = *(u_int16_t *)cmddata;
338            break;
339
340        case L2TP_CMD_GETNEWTUNNELID:
341            /* make up a unique tunnel id */
342            do {
343                unique_tunnel_id++;
344                if (unique_tunnel_id == 0)
345                    unique_tunnel_id++;
346				TAILQ_FOREACH(rfc1, &l2tp_rfc_hash[unique_tunnel_id % L2TP_RFC_MAX_HASH], next)
347                    if (rfc1->our_tunnel_id == unique_tunnel_id)
348                        break;
349            } while (rfc1);
350            TAILQ_REMOVE(&l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], rfc, next);	/* remove the rfc struct from the hash table */
351            *(u_int16_t *)cmddata = rfc->our_tunnel_id = unique_tunnel_id;
352			TAILQ_INSERT_TAIL(&l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], rfc, next); /* and reinsert it at the right place */
353            LOGIT(rfc, "L2TP command (%p): get new tunnel id = 0x%x\n", rfc, *(u_int16_t *)cmddata);
354            break;
355
356        case L2TP_CMD_SETTUNNELID:
357            LOGIT(rfc, "L2TP command (%p): set tunnel id = 0x%x\n", rfc, *(u_int16_t *)cmddata);
358            TAILQ_REMOVE(&l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], rfc, next);	/* remove the rfc struct from the hash table */
359            rfc->our_tunnel_id = *(u_int16_t *)cmddata;
360			TAILQ_INSERT_TAIL(&l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], rfc, next); /* and reinsert it at the right place */
361
362            if (!(rfc->flags & L2TP_FLAG_CONTROL)) {
363                /* for data connection, join the existing socket of the associated control connection */
364                rfc->socket = 0;
365                TAILQ_FOREACH(rfc1, &l2tp_rfc_hash[rfc->our_tunnel_id % L2TP_RFC_MAX_HASH], next)
366                    if ((rfc1->flags & L2TP_FLAG_CONTROL)
367                        && (rfc->our_tunnel_id == rfc1->our_tunnel_id)) {
368                        rfc->socket = rfc1->socket;
369                        rfc->thread = rfc1->thread;
370                        break;
371                    }
372            }
373            break;
374
375        case L2TP_CMD_GETTUNNELID:
376            LOGIT(rfc, "L2TP command (%p): get tunnel id = 0x%x\n", rfc, rfc->our_tunnel_id);
377            *(u_int16_t *)cmddata =  rfc->our_tunnel_id;
378            break;
379
380        case L2TP_CMD_SETPEERTUNNELID:
381            LOGIT(rfc, "L2TP command (%p): set peer tunnel id = 0x%x\n", rfc, *(u_int16_t *)cmddata);
382            rfc->peer_tunnel_id = *(u_int16_t *)cmddata;
383            break;
384
385        case L2TP_CMD_SETSESSIONID:
386            LOGIT(rfc, "L2TP command (%p): set session id = 0x%x\n", rfc, *(u_int16_t *)cmddata);
387            if (!(rfc->flags & L2TP_FLAG_CONTROL))
388                rfc->our_session_id = *(u_int16_t *)cmddata;
389            break;
390
391        case L2TP_CMD_GETSESSIONID:
392            LOGIT(rfc, "L2TP command (%p): get session id = 0x%x\n", rfc, rfc->our_session_id);
393            *(u_int16_t *)cmddata =  rfc->our_session_id;
394            break;
395
396        case L2TP_CMD_SETPEERSESSIONID:
397            LOGIT(rfc, "L2TP command (%p): set peer session id = 0x%x\n", rfc, *(u_int16_t *)cmddata);
398            /* session id only used for data */
399            if (!(rfc->flags & L2TP_FLAG_CONTROL))
400                rfc->peer_session_id = *(u_int16_t *)cmddata;
401            break;
402
403        case L2TP_CMD_SETBAUDRATE:
404            LOGIT(rfc, "L2TP command (%p): set baudrate of the tunnel = %d\n", rfc, *(u_int32_t *)cmddata);
405			rfc->baudrate = *(u_int32_t *)cmddata;
406            break;
407
408        case L2TP_CMD_GETBAUDRATE:
409            LOGIT(rfc, "L2TP command (%p): get baudrate of the tunnel = %d\n", rfc, rfc->baudrate);
410            *(u_int32_t *)cmddata = rfc->baudrate;
411            break;
412
413        case L2TP_CMD_SETTIMEOUT:
414            LOGIT(rfc, "L2TP command (%p): set initial timeout = %d (seconds)\n", rfc, *(u_int16_t *)cmddata);
415            rfc->initial_timeout = *(u_int16_t *)cmddata * 2;
416            break;
417
418        case L2TP_CMD_SETTIMEOUTCAP:
419            LOGIT(rfc, "L2TP command (%p): set timeout cap = %d (seconds)\n", rfc, *(u_int16_t *)cmddata);
420            rfc->timeout_cap = *(u_int16_t *)cmddata * 2;
421            break;
422
423        case L2TP_CMD_SETMAXRETRIES:
424            LOGIT(rfc, "L2TP command (%p): set max retries = %d\n", rfc, *(u_int16_t *)cmddata);
425            rfc->max_retries = *(u_int16_t *)cmddata;
426            break;
427
428        case L2TP_CMD_ACCEPT:
429            LOGIT(rfc, "L2TP command (%p): accept\n", rfc);
430            l2tp_rfc_accept(rfc);
431            break;
432
433        case L2TP_CMD_SETPEERADDR:
434			had_peer_addr = rfc->peer_address != NULL;
435            if (rfc->peer_address) {
436                _FREE(rfc->peer_address, M_SONAME);
437                rfc->peer_address = 0;
438            }
439            p = (u_int8_t*)cmddata;
440            len = *((u_int8_t*)cmddata);
441            if (len == 0) {
442                LOGIT(rfc, "L2TP command (%p): set peer IP address = no address\n", rfc);
443                break;
444            }
445            memcpy(&aligned_short, p+2, sizeof(u_int16_t));     // Wcast-align fix - use memcpy for unaligned access
446            LOGIT(rfc, "L2TP command (%p): set peer IP address = %d.%d.%d.%d, port %d\n", rfc, p[4], p[5], p[6], p[7], aligned_short);
447            /* copy the address - this can handle IPv6 addresses */
448            if (len > INET6_ADDRSTRLEN) {
449                error = EINVAL;
450                break;
451            }
452            rfc->peer_address = _MALLOC(len, M_SONAME, M_WAITOK);
453            if (rfc->peer_address == 0)
454                error = ENOMEM;
455            else {
456                bcopy((u_int8_t*)cmddata, rfc->peer_address, len);
457                if (rfc->flags & L2TP_FLAG_CONTROL) {
458                    /* for control connections, set the other end of the socket */
459                    error = l2tp_udp_setpeer(rfc->socket, (struct sockaddr *)rfc->peer_address);
460					if (had_peer_addr) {
461						// XXX clear the INP_INADDR_ANY flag
462						// Radar 5452036 & 5448998
463						l2tp_udp_clear_INP_INADDR_ANY(rfc->socket);
464					}
465
466                    if (error == EADDRINUSE) {
467                        // find the rfc with same src/dst pair
468						for (i = 0; i < L2TP_RFC_MAX_HASH; i++) {
469							TAILQ_FOREACH(rfc1, &l2tp_rfc_hash[i], next)
470								if (rfc1 != rfc
471									&& (rfc1->flags & L2TP_FLAG_CONTROL)
472									&& rfc1->our_address
473									&& rfc1->peer_address
474									&& !l2tp_rfc_compare_address((struct sockaddr *)rfc1->our_address, (struct sockaddr *)rfc->our_address)
475									&& !l2tp_rfc_compare_address((struct sockaddr *)rfc1->peer_address, (struct sockaddr *)rfc->peer_address)) {
476									// use socket from other rfc
477									l2tp_udp_detach(rfc->socket, rfc->thread);
478									rfc->socket = rfc1->socket;
479									rfc->thread = rfc1->thread;
480									error = 0;
481									break;
482								}
483							// check if found
484							if (rfc1)
485								break;
486						}
487					}
488                }
489            }
490            break;
491
492        case L2TP_CMD_GETPEERADDR:
493            p = (u_int8_t*)cmddata;
494            len = *((u_int8_t*)cmddata);
495            bzero(p, len);
496            if (rfc->peer_address)
497                bcopy((u_int8_t*)rfc->peer_address, p, MIN(len, rfc->peer_address->ss_len));
498            memcpy(&aligned_short, p+2, sizeof(u_int16_t));     // Wcast-align fix - use memcpy for unaligned access
499            LOGIT(rfc, "L2TP command (%p): get peer IP address = %d.%d.%d.%d, port %d\n", rfc, p[4], p[5], p[6], p[7], aligned_short);
500            break;
501
502        case L2TP_CMD_SETOURADDR:
503            if (rfc->our_address) {
504                _FREE(rfc->our_address, M_SONAME);
505                rfc->our_address = 0;
506            }
507            if (rfc->socket) {
508                if (rfc->flags & L2TP_FLAG_CONTROL) {
509                    // find an rfc with same socket
510					for (i = 0; i < L2TP_RFC_MAX_HASH; i++) {
511						TAILQ_FOREACH(rfc1, &l2tp_rfc_hash[i], next)
512							if (rfc1 != rfc
513								&& (rfc1->flags & L2TP_FLAG_CONTROL)
514								&& (rfc1->socket == rfc->socket))
515								break;
516						// check if found
517						if (rfc1)
518							break;
519					}
520                    if (rfc1 == 0)
521                        l2tp_udp_detach(rfc->socket, rfc->thread);
522                }
523                rfc->socket = 0;
524            }
525            p = (u_int8_t*)cmddata;
526            len = *((u_int8_t*)cmddata);
527            if (len == 0) {
528                LOGIT(rfc, "L2TP command (%p): set our IP address = no address\n", rfc);
529                break;
530            }
531            memcpy(&aligned_short, p+2, sizeof(u_int16_t));     // Wcast-align fix - use memcpy for unaligned access
532            LOGIT(rfc, "L2TP command (%p): set our IP address = %d.%d.%d.%d, port %d\n", rfc, p[4], p[5], p[6], p[7], aligned_short);
533            /* copy the address - this can handle IPv6 addresses */
534            if (len > INET6_ADDRSTRLEN) {
535                error = EINVAL;
536                break;
537            }
538            rfc->our_address = _MALLOC(len, M_SONAME, M_WAITOK);
539            if (rfc->our_address == 0)
540                error = ENOMEM;
541            else {
542                bcopy((u_int8_t*)cmddata, rfc->our_address, len);
543                if (rfc->flags & L2TP_FLAG_CONTROL)
544                    /* for control connections, create a socket and bind */
545                    error = l2tp_udp_attach(&rfc->socket, (struct sockaddr *)rfc->our_address, &rfc->thread, rfc->flags & L2TP_FLAG_IPSEC, rfc->delegate_pid);
546            }
547            break;
548
549        case L2TP_CMD_GETOURADDR:
550            p = (u_int8_t*)cmddata;
551            len = *((u_int8_t*)cmddata);
552            bzero(p, len);
553            if (rfc->our_address)
554                bcopy((u_int8_t*)rfc->our_address, p, MIN(len, rfc->our_address->ss_len));
555            memcpy(&aligned_short, p+2, sizeof(u_int16_t));     // Wcast-align fix - use memcpy for unaligned access
556            LOGIT(rfc, "L2TP command (%p): get our IP address = %d.%d.%d.%d, port %d\n", rfc, p[4], p[5], p[6], p[7], aligned_short);
557            break;
558
559        case L2TP_CMD_SETRELIABILITY:
560            LOGIT(rfc, "L2TP command (%p): set reliability layer %s\n", rfc, *(u_int16_t *)cmddata ? "on" : "off");
561            if (*(u_int16_t *)cmddata) {
562				rfc->state &= ~L2TP_STATE_RELIABILITY_OFF;
563				rfc->retry_count = 0;
564				rfc->retrans_time_remain = rfc->initial_timeout;
565			}
566			else
567				rfc->state |= L2TP_STATE_RELIABILITY_OFF;
568            break;
569
570        case L2TP_CMD_SETDELEGATEDPID:
571            LOGIT(rfc, "L2TP command (%p): set delegated pid = %d\n", rfc, *(u_int32_t *)cmddata);
572            if (rfc->flags & L2TP_FLAG_CONTROL)
573                rfc->delegate_pid = *(int *)cmddata;
574            break;
575
576        default:
577            LOGIT(rfc, "L2TP command (%p): unknown command = %d\n", rfc, cmd);
578    }
579
580    return error;
581}
582
583
584/* -----------------------------------------------------------------------------
585 main body of function used to be l2tp_rfc_fasttimer... called by protocol family when fast timer expired:
586 now it's called when slow timer expired because of <rdar://problem/7617885>
587 ----------------------------------------------------------------------------- */
588static void l2tp_rfc_delayed_ack(struct l2tp_rfc *rfc)
589{
590    mbuf_t				m;
591    struct l2tp_header 	*hdr, hdr_data;
592
593	if ((rfc->state & L2TP_STATE_NEW_SEQUENCE) && rfc->peer_tunnel_id) {
594
595		if (mbuf_gethdr(MBUF_DONTWAIT, MBUF_TYPE_DATA, &m) != 0)
596			return;
597
598		mbuf_setlen(m, L2TP_CNTL_HDR_SIZE);
599		mbuf_pkthdr_setlen(m, L2TP_CNTL_HDR_SIZE);
600		hdr = &hdr_data;
601		memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
602		bzero(hdr, L2TP_CNTL_HDR_SIZE);
603
604		hdr->flags_vers = htons(L2TP_FLAGS_L | L2TP_FLAGS_T | L2TP_FLAGS_S | L2TP_HDR_VERSION);
605		hdr->len = htons(L2TP_CNTL_HDR_SIZE);
606
607		hdr->ns = htons(rfc->our_ns);
608		hdr->nr = htons(rfc->our_nr);
609		hdr->tunnel_id = htons(rfc->peer_tunnel_id);
610		hdr->session_id = 0;
611		rfc->state &= ~L2TP_STATE_NEW_SEQUENCE;
612
613		memcpy(mbuf_data(m), hdr, sizeof(hdr_data));
614
615		l2tp_udp_output(rfc->socket, rfc->thread, m, (struct sockaddr *)rfc->peer_address);
616	}
617}
618
619/* -----------------------------------------------------------------------------
620called by protocol family when slow timer expires
621
622    Decrements retrans_time_remain and checks if time to re-send the message
623    at the beginning of the transmit queue.  If retry count is exhasted,
624    time to break the connection.
625----------------------------------------------------------------------------- */
626void l2tp_rfc_slowtimer()
627{
628    struct l2tp_rfc  	*rfc1, *rfc;
629	int					i;
630
631	for (i = 0; i < L2TP_RFC_MAX_HASH; i++) {
632
633		rfc = TAILQ_FIRST(&l2tp_rfc_hash[i]);
634
635		while (rfc) {
636
637			if (rfc->state & L2TP_STATE_FREEING
638				&& --rfc->free_time_remain == 0) {
639
640				rfc1 = TAILQ_NEXT(rfc, next);
641				l2tp_rfc_free_now(rfc);
642				rfc = rfc1;
643				continue;
644			}
645
646			if (!(rfc->state & L2TP_STATE_RELIABILITY_OFF)
647				&& !TAILQ_EMPTY(&rfc->send_queue)) {
648				if (--rfc->retrans_time_remain == 0) {
649					rfc->retry_count++;
650					if (rfc->retry_count >= rfc->max_retries) {
651						/* send event to client */
652						if (!(rfc->state & L2TP_STATE_FREEING))
653							(*rfc->eventcb)(rfc->host, L2TP_EVT_RELIABLE_FAILED, 0);
654					}
655					else {
656						l2tp_rfc_output_queued(rfc, TAILQ_FIRST(&rfc->send_queue));
657						if (rfc->flags & L2TP_FLAG_ADAPT_TIMER)
658							rfc->retrans_time_remain = rfc->initial_timeout << rfc->retry_count;
659						else
660							rfc->retrans_time_remain = rfc->initial_timeout;
661						if (rfc->retrans_time_remain > rfc->timeout_cap)
662							rfc->retrans_time_remain = rfc->timeout_cap;
663					}
664				}
665			}
666
667			// do the delayed ack last to take advantage of any data transmits in above code
668			l2tp_rfc_delayed_ack(rfc);
669
670			rfc = TAILQ_NEXT(rfc, next);
671		}
672	}
673}
674
675/* -----------------------------------------------------------------------------
676take the packet present in the recv queue of the first rfc with tunnel id 0
677and transfer it to the given rfc.
678This is useful to listen for incoming connection on a generic tunnel 0 rfc, and
679accepting it on an other created rfc.
680----------------------------------------------------------------------------- */
681void l2tp_rfc_accept(struct l2tp_rfc* rfc)
682{
683    struct l2tp_rfc 		*call_rfc;
684    struct l2tp_elem	*elem;
685
686    TAILQ_FOREACH(call_rfc, &l2tp_rfc_hash[0], next) {
687        if ((call_rfc->flags & L2TP_FLAG_CONTROL)
688            && call_rfc->our_tunnel_id == 0
689            && !TAILQ_EMPTY(&call_rfc->recv_queue)) {
690
691            /* transfer packet to new rfc */
692            elem = TAILQ_FIRST(&call_rfc->recv_queue);
693            TAILQ_REMOVE(&call_rfc->recv_queue, elem, next);	/* remove the packet from the call socket */
694
695            rfc->our_nr = 1;							/* set nr to the correct value */
696            rfc->state |= L2TP_STATE_NEW_SEQUENCE;				/* setup to send ack */
697            if ((*rfc->inputcb)(rfc->host, elem->packet, (struct sockaddr *)elem->addr, 1)) {	/* up to the socket */
698				/* mbuf has been freed by upcall */
699			}
700            _FREE(elem, M_TEMP);
701
702            return;
703        }
704    }
705}
706
707/* -----------------------------------------------------------------------------
708----------------------------------------------------------------------------- */
709u_int16_t l2tp_rfc_output(void *data, mbuf_t m, struct sockaddr *to)
710{
711    struct l2tp_rfc 	*rfc = (struct l2tp_rfc *)data;
712
713    if (rfc->state & L2TP_STATE_FREEING) {
714        mbuf_freem(m);
715        return ENXIO;
716    }
717
718    /* control packet are received from pppd with an incomplete l2tp header in front,
719        and an ip address to send to */
720    if (rfc->flags & L2TP_FLAG_CONTROL)
721        return l2tp_rfc_output_control(rfc, m, to);
722
723    /* data packet are received from ppp stack without a l2tp header and without address
724        and an ip address to send to */
725    return l2tp_rfc_output_data(data, m);
726}
727
728/* -----------------------------------------------------------------------------
729----------------------------------------------------------------------------- */
730u_int16_t l2tp_rfc_output_control(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *to)
731{
732    struct l2tp_elem 	*elem;
733    struct l2tp_header	*hdr, hdr_data;
734    mbuf_t				m0;
735    u_int16_t 			len;
736
737    len = 0;
738    for (m0 = m; m0 != 0; m0 = mbuf_next(m0))
739        len += mbuf_len(m0);
740
741    hdr = &hdr_data;
742    memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
743
744    /* flags, version and length should have been filled already by pppd */
745    hdr->flags_vers = htons(L2TP_FLAGS_L | L2TP_HDR_VERSION | L2TP_FLAGS_T | L2TP_FLAGS_S);
746    hdr->len = htons(len);
747
748    /* session id MUST be filled by the L2TP plugin */
749    /* hdr->session_id = htons(rfc->peer_session_id); */
750
751    hdr->tunnel_id = htons(rfc->peer_tunnel_id);
752
753    /* we fill the tunnel id and the sequence information */
754    hdr->ns = htons(rfc->our_ns);
755    hdr->nr = htons(rfc->our_nr);
756    memcpy(mbuf_data(m), hdr, sizeof(hdr_data));
757
758    /* if the address is too large then we have a problem... */
759    if (to->sa_len > sizeof(elem->addr)
760        || (to->sa_family == 0 && rfc->peer_address == 0)) {
761        mbuf_freem(m);
762        return EINVAL;
763    }
764
765	if (rfc->state & L2TP_STATE_RELIABILITY_OFF) {
766		//IOLog("l2tp_rfc_output_control send once rfc = %p\n", rfc);
767		return l2tp_udp_output(rfc->socket, rfc->thread , m, to->sa_family ? to : (struct sockaddr *)rfc->peer_address);
768	}
769
770	rfc->our_ns++;
771
772    elem = (struct l2tp_elem *)_MALLOC(sizeof (struct l2tp_elem), M_TEMP, M_NOWAIT);
773    if (elem == 0) {
774        mbuf_freem(m);
775        return ENOMEM;
776    }
777
778    elem->seqno = ntohs(hdr->ns);
779    elem->packet = m;
780    if (to->sa_family)
781        bcopy(to, elem->addr, to->sa_len);
782    else
783        bcopy(rfc->peer_address, elem->addr, rfc->peer_address->ss_len);
784
785    if (TAILQ_EMPTY(&rfc->send_queue)) {			/* first on queue ? */
786        rfc->retry_count = 0;
787        rfc->retrans_time_remain = rfc->initial_timeout;
788    }
789    TAILQ_INSERT_TAIL(&rfc->send_queue, elem, next);
790    if (SEQ_LT(elem->seqno, rfc->peer_nr + rfc->peer_window)) {	/* within window ?  - send it */
791        rfc->state &= ~L2TP_STATE_NEW_SEQUENCE;			/* disable sending of ack - piggybacked on this packet */
792        return l2tp_rfc_output_queued(rfc, elem);
793    }
794
795    return 0;
796}
797
798/* -----------------------------------------------------------------------------
799----------------------------------------------------------------------------- */
800u_int16_t l2tp_rfc_output_data(struct l2tp_rfc *rfc, mbuf_t m)
801{
802    struct l2tp_header	*hdr, hdr_data;
803    mbuf_t				m0;
804    u_int16_t 			len, hdr_length, flags, i;
805
806    len = 0;
807	i = 0;
808    for (m0 = m; m0 != 0; m0 = mbuf_next(m0)) {
809        len += mbuf_len(m0);
810		i++;
811
812		if (i > 32) {
813			struct socket 	*so = (struct socket *)rfc->host;
814			struct ppp_link *link = ALIGNED_CAST(struct ppp_link *)so->so_tpcb;     // Wcast-align fix - we malloc so->so_tpcb
815
816			IOLog("L2TP output packet contains too many mbufs, circular route suspected for %s%d\n", ifnet_name(link->lk_ifnet), ifnet_unit(link->lk_ifnet));
817
818			mbuf_freem(m);
819			return ENETUNREACH;
820		};
821	}
822
823    hdr_length = L2TP_DATA_HDR_SIZE + (rfc->flags & L2TP_FLAG_PEER_SEQ_REQ ? 4 : 0);
824
825    if (mbuf_prepend(&m, hdr_length, MBUF_WAITOK) != 0)
826        return ENOBUFS;
827    hdr = &hdr_data;
828    memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
829    bzero(hdr, hdr_length);
830
831    flags = L2TP_FLAGS_L | L2TP_HDR_VERSION;
832    hdr->len = htons(len + hdr_length);
833    hdr->tunnel_id = htons(rfc->peer_tunnel_id);
834    hdr->session_id = htons(rfc->peer_session_id);
835
836    if (rfc->flags & L2TP_FLAG_PEER_SEQ_REQ) {
837        flags |= L2TP_FLAGS_S;
838        hdr->ns = htons(rfc->our_last_data_seq++);
839        hdr->nr = htons(0);
840    }
841
842    hdr->flags_vers = htons(flags);
843
844    memcpy(mbuf_data(m), hdr, sizeof(hdr_data));
845    return l2tp_udp_output(rfc->socket, rfc->thread, m, (struct sockaddr *)rfc->peer_address);
846}
847
848/* -----------------------------------------------------------------------------
849    send a queued control message
850----------------------------------------------------------------------------- */
851int l2tp_rfc_output_queued(struct l2tp_rfc *rfc, struct l2tp_elem *elem)
852{
853    mbuf_t				dup;
854    struct l2tp_header	*hdr, hdr_data;
855
856    if (mbuf_copym(elem->packet, 0, MBUF_COPYALL, MBUF_DONTWAIT, &dup) != 0)
857        return ENOBUFS;
858
859    hdr = &hdr_data;
860    memcpy(hdr, mbuf_data(dup), sizeof(hdr_data));
861    hdr->nr = htons(rfc->our_nr);
862    memcpy(mbuf_data(dup), hdr, sizeof(hdr_data));
863
864    return l2tp_udp_output(rfc->socket, rfc->thread, dup, (struct sockaddr *)elem->addr);
865}
866
867/* -----------------------------------------------------------------------------
868----------------------------------------------------------------------------- */
869u_int16_t l2tp_handle_data(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *from,
870    u_int16_t flags, u_int16_t len, u_int16_t tunnel_id, u_int16_t session_id)
871{
872    struct l2tp_header 		*hdr, hdr_data;
873    u_int16_t 			*p, ns, hdr_length;
874
875    hdr = &hdr_data;
876    memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
877
878    //IOLog("handle_data, rfc = %p, from 0x%x, peer address = 0x%x, our tunnel id = %d, tunnel id = %d, our session id = %d, session id = %d\n", rfc, from, rfc->peer_address, rfc->our_tunnel_id, tunnel_id, rfc->our_session_id, session_id);
879
880    // check the tunnel ID and session ID as well as the peer address
881    // to determine which client the packet belongs to
882    if (rfc->our_tunnel_id == tunnel_id
883        && rfc->our_session_id == session_id
884        && rfc->peer_address
885        && !l2tp_rfc_compare_address((struct sockaddr *)rfc->peer_address, from)) {
886
887        if (flags & L2TP_FLAGS_L) {			/* len field present */
888            p = &hdr->ns;
889            hdr_length = L2TP_DATA_HDR_SIZE;
890        }
891        else {
892            p = &hdr->session_id;
893            hdr_length = L2TP_DATA_HDR_SIZE - 2;
894        }
895
896        if (flags & L2TP_FLAGS_S) {			/* packet has sequence numbers */
897            ns = ntohs(*p);
898            p += 2;					/* skip sequence fields */
899            hdr_length += 4;
900            if (SEQ_GT(ns, rfc->peer_last_data_seq)) {
901				rfc->peer_last_data_seq++;
902                if (rfc->peer_last_data_seq != ns) {
903                    if (rfc->eventcb)
904						(*rfc->eventcb)(rfc->host, L2TP_EVT_INPUTERROR, 0);
905					rfc->peer_last_data_seq = ns;
906				}
907            }
908            else
909                goto dropit;
910        }
911
912        if (flags & L2TP_FLAGS_O) 			/* payload is at offset in the packet */
913            hdr_length += (2 + ntohs(*p));
914
915        /* data packet are given up without header */
916        mbuf_adj(m, hdr_length);				/* remove the header and send it up to PPP */
917		if (rfc->state & L2TP_STATE_FREEING)
918			mbuf_freem(m);
919		else
920			(*rfc->inputcb)(rfc->host, m, 0, 0);
921
922        return 1;
923    }
924
925    return 0;
926
927dropit:
928    mbuf_freem(m);
929    return 1;
930}
931
932/* -----------------------------------------------------------------------------
933----------------------------------------------------------------------------- */
934u_int16_t l2tp_handle_control(struct l2tp_rfc *rfc, mbuf_t m, struct sockaddr *from,
935    u_int16_t flags, u_int16_t len, u_int16_t tunnel_id, u_int16_t session_id)
936{
937    struct l2tp_header 		*hdr, hdr_data;
938    struct l2tp_elem 	*elem, *new_elem;
939    u_int16_t			buf_full;
940
941    hdr = &hdr_data;
942    memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
943
944    //IOLog("handle_control, rfc = %p, from 0x%x, peer address = 0x%x, our tunnel id = %d, tunnel id = %d, our session id = %d, session id = %d\n", rfc, from, rfc->peer_address, rfc->our_tunnel_id, tunnel_id, rfc->our_session_id, session_id);
945
946    // check tunnel ID as well as the peer address
947    // to determine which client the packet belongs to
948    if (rfc->our_tunnel_id == tunnel_id) {
949            if (rfc->peer_address) {
950                if (l2tp_rfc_compare_address((struct sockaddr *)rfc->peer_address, from))
951                    goto dropit;
952            }
953
954            if (((flags & L2TP_FLAGS_S) == 0)			/* check for valid flags */
955                || ((flags & L2TP_FLAGS_L) == 0)
956                || ((flags & L2TP_FLAGS_O) != 0))
957                    goto dropit;
958
959            if (mbuf_pkthdr_len(m) < len)					/* check the length */
960                goto dropit;
961            if (mbuf_len(m) > len)							/* remove padding - plugin uses datagram len */
962				mbuf_setlen(m, len);
963            mbuf_pkthdr_setlen(m, len);
964
965            if (tunnel_id == 0) {
966                /* receive a packet on a generic listening connection and queue it */
967                if (ntohs(hdr->ns) != 0)	/* first control packet for a connection ? */
968                    goto dropit;
969
970				/* search if an identical packet is already in the queue. it would be a retransmission, and we haven't
971				   had time to treat the original packet yet.
972				   should compare entire packet, but source address is good enough in real life */
973				TAILQ_FOREACH(elem, &rfc->recv_queue, next) {
974					if (!bcmp(from, elem->addr, from->sa_len)) {
975						goto dropit;
976					}
977				}
978
979                new_elem = (struct l2tp_elem *)_MALLOC(sizeof (struct l2tp_elem), M_TEMP, M_NOWAIT);
980                if (new_elem == 0)
981                    goto dropit;
982
983                if (mbuf_copym(m, 0, MBUF_COPYALL, MBUF_DONTWAIT, &new_elem->packet) != 0) {
984                    _FREE(new_elem, M_TEMP);
985                    goto dropit;
986                }
987                new_elem->seqno = 0;
988                bcopy(from, new_elem->addr, from->sa_len);
989                TAILQ_INSERT_TAIL(&rfc->recv_queue, new_elem, next);	/* queue copy */
990
991                if ((*rfc->inputcb)(rfc->host, m, (struct sockaddr *)from, 0)) {		/* send up to call socket */
992                    TAILQ_REMOVE(&rfc->recv_queue, new_elem, next);	/* remove the packet from the queue */
993                    mbuf_freem(new_elem->packet);
994                    _FREE(new_elem, M_TEMP);
995					/* mbuf has been freed by upcall */
996					return 1;
997                }
998
999                return 1;
1000            }
1001
1002            /*
1003             * the following code is only exececuted when tunnel ID is not zero
1004             * i.e. not a call socket
1005             */
1006
1007            /* clear packets being ack'd by peer */
1008            if (SEQ_GT(ntohs(hdr->nr), rfc->peer_nr))
1009                l2tp_rfc_handle_ack(rfc, (int16_t)(ntohs(hdr->nr)));
1010
1011            if (len == L2TP_CNTL_HDR_SIZE)				/* ZLB ACK */
1012                goto dropit;
1013
1014            if (SEQ_GT(ntohs(hdr->ns), rfc->our_nr)) {			/* out of order - need to queue it */
1015                //IOLog("L2TP out of order message reveived seq#=%d\n", ntohs(hdr->ns));
1016               TAILQ_FOREACH(elem, &rfc->recv_queue, next) {
1017                    if (ntohs(hdr->ns) == elem->seqno)
1018                        goto dropit;					/* already queued - drop it */
1019                    if (SEQ_GT(ntohs(hdr->ns), elem->seqno))
1020                        break;
1021                }
1022                //IOLog("L2TP queing out of order message\n");
1023                new_elem = (struct l2tp_elem *)_MALLOC(sizeof (struct l2tp_elem), M_TEMP, M_NOWAIT);
1024                if (new_elem == 0)
1025                    goto dropit;
1026                new_elem->packet = m;
1027                new_elem->seqno = ntohs(hdr->ns);
1028                bcopy(from, new_elem->addr, from->sa_len);
1029                if (elem)
1030                    TAILQ_INSERT_AFTER(&rfc->recv_queue, elem, new_elem, next);
1031                else
1032                    TAILQ_INSERT_HEAD(&rfc->recv_queue, new_elem, next);
1033            } else if (SEQ_LT(ntohs(hdr->ns), rfc->our_nr)) {
1034                //IOLog("L2TP dropping message already received seq#=%d\n", ntohs(hdr->ns));
1035                rfc->state |= L2TP_STATE_NEW_SEQUENCE;		/* its a dup thats already been ack'd - drop it and ack */
1036                goto dropit;
1037            } else {						/* packet we are waiting for */
1038
1039                /* control packets are given up with l2tp header */
1040
1041                if (rfc->state & L2TP_STATE_FREEING)
1042                    mbuf_freem(m);
1043                else if ((*rfc->inputcb)(rfc->host, m, (struct sockaddr *)from, 1))
1044					/* mbuf has been freed by upcall */
1045					return 1;
1046
1047                rfc->our_nr++;
1048                rfc->state |= L2TP_STATE_NEW_SEQUENCE;		/* sent up - ack it */
1049
1050                /*
1051                    * now check for other packets on the queue that can be sent up.
1052                    * if the host queue is full and input fails
1053                    * only the packets sent up are ack'd and the remaining are dropped
1054                    * from the queue
1055                    */
1056                buf_full = 0;
1057                while ((elem = TAILQ_FIRST(&rfc->recv_queue))) {
1058                    if (buf_full) {						/* host buffer is full - empty the queue */
1059                        mbuf_freem(elem->packet);
1060                        TAILQ_REMOVE(&rfc->recv_queue, elem, next);
1061                        _FREE(elem, M_TEMP);
1062                    } else if (elem->seqno == rfc->our_nr) {		/* another packet to send up */
1063
1064                        if (rfc->state & L2TP_STATE_FREEING) {
1065                            mbuf_freem(elem->packet);
1066                            rfc->our_nr++;
1067                        }
1068                        else if ((*rfc->inputcb)(rfc->host, elem->packet, (struct sockaddr *)elem->addr, 1)) {
1069							/* mbuf has been freed by upcall */
1070                            buf_full = 1;
1071                        }
1072                        else
1073                            rfc->our_nr++;
1074                        TAILQ_REMOVE(&rfc->recv_queue, elem, next);
1075                        _FREE(elem, M_TEMP);
1076                    } else
1077                        break;
1078                }
1079
1080                /* nothing more */
1081                if (!(rfc->state & L2TP_STATE_FREEING))
1082                    (*rfc->inputcb)(rfc->host, 0, 0, 0);
1083
1084            }
1085
1086            return 1;
1087        }
1088
1089        /* packet not for this rfc */
1090        return 0;
1091
1092dropit:
1093        mbuf_freem(m);
1094        return 1;
1095}
1096
1097
1098/* -----------------------------------------------------------------------------
1099    compare UDP addresses
1100----------------------------------------------------------------------------- */
1101int l2tp_rfc_compare_address(struct sockaddr* addr1, struct sockaddr* addr2)
1102{
1103
1104    // Wcast-align fix - bcmp for unaligned compare
1105    if (addr1->sa_family != addr2->sa_family)
1106        return 1;
1107
1108    switch (addr1->sa_family) {
1109        case AF_INET:
1110            if (bcmp(&((struct sockaddr_in*)(void*)addr1)->sin_port, &((struct sockaddr_in*)(void*)addr2)->sin_port, sizeof(u_int16_t)))
1111                return 1;
1112            if (bcmp(&((struct sockaddr_in*)(void*)addr1)->sin_addr.s_addr, &((struct sockaddr_in*)(void*)addr2)->sin_addr.s_addr, sizeof(struct in_addr)))
1113                return 1;
1114            return 0;
1115        default:
1116            return 1;
1117    }
1118}
1119
1120/* -----------------------------------------------------------------------------
1121    handle incomming ack - remove ack'd packets from the control message
1122    send queue and send any packets that were outside the window.
1123----------------------------------------------------------------------------- */
1124void l2tp_rfc_handle_ack(struct l2tp_rfc *rfc, u_int16_t nr)
1125{
1126    struct l2tp_elem 	*elem;
1127    u_int16_t			old_nr = rfc->peer_nr;
1128
1129    rfc->peer_nr = nr;
1130    while((elem = TAILQ_FIRST(&rfc->send_queue)))
1131        if (SEQ_GT(nr, elem->seqno)) {
1132            rfc->retrans_time_remain = rfc->initial_timeout;	/* setup timeout and count */
1133            rfc->retry_count = 0;
1134            TAILQ_REMOVE(&rfc->send_queue, elem, next);
1135            mbuf_freem(elem->packet);
1136            _FREE(elem, M_TEMP);
1137        } else
1138            break;
1139
1140
1141    if (!TAILQ_EMPTY(&rfc->send_queue)) {
1142         /* check for packets that were outside the window that should now be sent */
1143        TAILQ_FOREACH(elem, &rfc->send_queue, next) {
1144            if (SEQ_GT(elem->seqno, nr + rfc->peer_window - 1))	/* outside current window ? */
1145                break;
1146            if (SEQ_GT(elem->seqno, old_nr + rfc->peer_window - 1))	/* outside previous window ? */
1147                l2tp_rfc_output_queued(rfc, elem);
1148        }
1149    }
1150}
1151
1152
1153/* -----------------------------------------------------------------------------
1154called from l2tp_ip when l2tp data are present
1155----------------------------------------------------------------------------- */
1156int l2tp_rfc_lower_input(socket_t so, mbuf_t m, struct sockaddr *from)
1157{
1158    struct l2tp_rfc  	*rfc;
1159    struct l2tp_header 	*hdr, hdr_data;
1160    u_int16_t 		*p;
1161    u_int16_t		flags, len, tunnel_id, session_id, pulllen;
1162
1163
1164    hdr = &hdr_data;
1165    memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
1166
1167    lck_mtx_assert(ppp_domain_mutex, LCK_MTX_ASSERT_OWNED);
1168
1169    //IOLog("L2TP inputdata\n");
1170
1171    flags = ntohs(hdr->flags_vers);
1172
1173    if ((flags & L2TP_VERSION_MASK) != L2TP_VERSION)
1174        goto dropit;
1175
1176	pulllen = (flags & L2TP_FLAGS_T) ? L2TP_CNTL_HDR_SIZE : L2TP_DATA_HDR_SIZE;
1177	if (mbuf_len(m) < pulllen &&
1178		mbuf_pullup(&m, pulllen)) {
1179			if (m) {
1180				mbuf_freem(m);
1181				m = NULL;
1182			}
1183			IOLog("l2tp_rfc_lower_input: cannot pullup l2tp header (len %d)\n", pulllen);
1184			return 0;
1185	}
1186
1187	memcpy(hdr, mbuf_data(m), sizeof(hdr_data));
1188
1189    if (flags & L2TP_FLAGS_L) {		/* len field present ? */
1190        len = ntohs(hdr->len);
1191        p = &hdr->tunnel_id;
1192    }
1193    else {
1194        len = 0;
1195        p = &hdr->len;
1196    }
1197
1198    tunnel_id = ntohs(*p++);
1199    session_id = ntohs(*p);
1200
1201    if (flags & L2TP_FLAGS_T) {
1202        /* control packet */
1203		TAILQ_FOREACH(rfc, &l2tp_rfc_hash[tunnel_id % L2TP_RFC_MAX_HASH], next)
1204			if ((rfc->flags & L2TP_FLAG_CONTROL)
1205				&& l2tp_handle_control(rfc, m, from, flags, len, tunnel_id, session_id))
1206					return 1;
1207    }
1208    else {
1209        /* data packet */
1210		TAILQ_FOREACH(rfc, &l2tp_rfc_hash[tunnel_id % L2TP_RFC_MAX_HASH], next)
1211			if ((rfc->flags & L2TP_FLAG_CONTROL) == 0
1212				&& l2tp_handle_data(rfc, m, from, flags, len, tunnel_id, session_id))
1213					return 1;
1214    }
1215
1216    //IOLog(">>>>>>> L2TP - no matching client found for packet\n");
1217    // need to drop the packet
1218
1219dropit:
1220    mbuf_freem(m);
1221    return 0;
1222}
1223