• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/net/l2tp/
1/*
2 * L2TP core.
3 *
4 * Copyright (c) 2008,2009,2010 Katalix Systems Ltd
5 *
6 * This file contains some code of the original L2TPv2 pppol2tp
7 * driver, which has the following copyright:
8 *
9 * Authors:	Martijn van Oosterhout <kleptog@svana.org>
10 *		James Chapman (jchapman@katalix.com)
11 * Contributors:
12 *		Michal Ostrowski <mostrows@speakeasy.net>
13 *		Arnaldo Carvalho de Melo <acme@xconectiva.com.br>
14 *		David S. Miller (davem@redhat.com)
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License version 2 as
18 * published by the Free Software Foundation.
19 */
20
21#include <linux/module.h>
22#include <linux/string.h>
23#include <linux/list.h>
24#include <linux/rculist.h>
25#include <linux/uaccess.h>
26
27#include <linux/kernel.h>
28#include <linux/spinlock.h>
29#include <linux/kthread.h>
30#include <linux/sched.h>
31#include <linux/slab.h>
32#include <linux/errno.h>
33#include <linux/jiffies.h>
34
35#include <linux/netdevice.h>
36#include <linux/net.h>
37#include <linux/inetdevice.h>
38#include <linux/skbuff.h>
39#include <linux/init.h>
40#include <linux/in.h>
41#include <linux/ip.h>
42#include <linux/udp.h>
43#include <linux/l2tp.h>
44#include <linux/hash.h>
45#include <linux/sort.h>
46#include <linux/file.h>
47#include <linux/nsproxy.h>
48#include <net/net_namespace.h>
49#include <net/netns/generic.h>
50#include <net/dst.h>
51#include <net/ip.h>
52#include <net/udp.h>
53#include <net/inet_common.h>
54#include <net/xfrm.h>
55#include <net/protocol.h>
56
57#include <asm/byteorder.h>
58#include <asm/atomic.h>
59
60#include "l2tp_core.h"
61
62#ifdef CTF_L2TP
63#include <ctf/hndctf.h>
64#endif
65
66#define L2TP_DRV_VERSION	"V2.0"
67
68/* L2TP header constants */
69#define L2TP_HDRFLAG_T	   0x8000
70#define L2TP_HDRFLAG_L	   0x4000
71#define L2TP_HDRFLAG_S	   0x0800
72#define L2TP_HDRFLAG_O	   0x0200
73#define L2TP_HDRFLAG_P	   0x0100
74
75#define L2TP_HDR_VER_MASK  0x000F
76#define L2TP_HDR_VER_2	   0x0002
77#define L2TP_HDR_VER_3	   0x0003
78
79/* L2TPv3 default L2-specific sublayer */
80#define L2TP_SLFLAG_S	   0x40000000
81#define L2TP_SL_SEQ_MASK   0x00ffffff
82
83#define L2TP_HDR_SIZE_SEQ		10
84#define L2TP_HDR_SIZE_NOSEQ		6
85
86/* Default trace flags */
87#define L2TP_DEFAULT_DEBUG_FLAGS	0
88
89#define PRINTK(_mask, _type, _lvl, _fmt, args...)			\
90	do {								\
91		if ((_mask) & (_type))					\
92			printk(_lvl "L2TP: " _fmt, ##args);		\
93	} while (0)
94
95/* Private data stored for received packets in the skb.
96 */
97struct l2tp_skb_cb {
98	u32			ns;
99	u16			has_seq;
100	u16			length;
101	unsigned long		expires;
102};
103
104#define L2TP_SKB_CB(skb)	((struct l2tp_skb_cb *) &skb->cb[sizeof(struct inet_skb_parm)])
105
106static atomic_t l2tp_tunnel_count;
107static atomic_t l2tp_session_count;
108
109/* per-net private data for this module */
110static unsigned int l2tp_net_id;
111struct l2tp_net {
112	struct list_head l2tp_tunnel_list;
113	spinlock_t l2tp_tunnel_list_lock;
114	struct hlist_head l2tp_session_hlist[L2TP_HASH_SIZE_2];
115	spinlock_t l2tp_session_hlist_lock;
116};
117
118static inline struct l2tp_net *l2tp_pernet(struct net *net)
119{
120	BUG_ON(!net);
121
122	return net_generic(net, l2tp_net_id);
123}
124
125/* Session hash global list for L2TPv3.
126 * The session_id SHOULD be random according to RFC3931, but several
127 * L2TP implementations use incrementing session_ids.  So we do a real
128 * hash on the session_id, rather than a simple bitmask.
129 */
130static inline struct hlist_head *
131l2tp_session_id_hash_2(struct l2tp_net *pn, u32 session_id)
132{
133	return &pn->l2tp_session_hlist[hash_32(session_id, L2TP_HASH_BITS_2)];
134
135}
136
137/* Lookup a session by id in the global session list
138 */
139static struct l2tp_session *l2tp_session_find_2(struct net *net, u32 session_id)
140{
141	struct l2tp_net *pn = l2tp_pernet(net);
142	struct hlist_head *session_list =
143		l2tp_session_id_hash_2(pn, session_id);
144	struct l2tp_session *session;
145	struct hlist_node *walk;
146
147	rcu_read_lock_bh();
148	hlist_for_each_entry_rcu(session, walk, session_list, global_hlist) {
149		if (session->session_id == session_id) {
150			rcu_read_unlock_bh();
151			return session;
152		}
153	}
154	rcu_read_unlock_bh();
155
156	return NULL;
157}
158
159/* Session hash list.
160 * The session_id SHOULD be random according to RFC2661, but several
161 * L2TP implementations (Cisco and Microsoft) use incrementing
162 * session_ids.  So we do a real hash on the session_id, rather than a
163 * simple bitmask.
164 */
165static inline struct hlist_head *
166l2tp_session_id_hash(struct l2tp_tunnel *tunnel, u32 session_id)
167{
168	return &tunnel->session_hlist[hash_32(session_id, L2TP_HASH_BITS)];
169}
170
171/* Lookup a session by id
172 */
173struct l2tp_session *l2tp_session_find(struct net *net, struct l2tp_tunnel *tunnel, u32 session_id)
174{
175	struct hlist_head *session_list;
176	struct l2tp_session *session;
177	struct hlist_node *walk;
178
179	/* In L2TPv3, session_ids are unique over all tunnels and we
180	 * sometimes need to look them up before we know the
181	 * tunnel.
182	 */
183	if (tunnel == NULL)
184		return l2tp_session_find_2(net, session_id);
185
186	session_list = l2tp_session_id_hash(tunnel, session_id);
187	read_lock_bh(&tunnel->hlist_lock);
188	hlist_for_each_entry(session, walk, session_list, hlist) {
189		if (session->session_id == session_id) {
190			read_unlock_bh(&tunnel->hlist_lock);
191			return session;
192		}
193	}
194	read_unlock_bh(&tunnel->hlist_lock);
195
196	return NULL;
197}
198EXPORT_SYMBOL_GPL(l2tp_session_find);
199
200struct l2tp_session *l2tp_session_find_nth(struct l2tp_tunnel *tunnel, int nth)
201{
202	int hash;
203	struct hlist_node *walk;
204	struct l2tp_session *session;
205	int count = 0;
206
207	read_lock_bh(&tunnel->hlist_lock);
208	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
209		hlist_for_each_entry(session, walk, &tunnel->session_hlist[hash], hlist) {
210			if (++count > nth) {
211				read_unlock_bh(&tunnel->hlist_lock);
212				return session;
213			}
214		}
215	}
216
217	read_unlock_bh(&tunnel->hlist_lock);
218
219	return NULL;
220}
221EXPORT_SYMBOL_GPL(l2tp_session_find_nth);
222
223/* Lookup a session by interface name.
224 * This is very inefficient but is only used by management interfaces.
225 */
226struct l2tp_session *l2tp_session_find_by_ifname(struct net *net, char *ifname)
227{
228	struct l2tp_net *pn = l2tp_pernet(net);
229	int hash;
230	struct hlist_node *walk;
231	struct l2tp_session *session;
232
233	rcu_read_lock_bh();
234	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++) {
235		hlist_for_each_entry_rcu(session, walk, &pn->l2tp_session_hlist[hash], global_hlist) {
236			if (!strcmp(session->ifname, ifname)) {
237				rcu_read_unlock_bh();
238				return session;
239			}
240		}
241	}
242
243	rcu_read_unlock_bh();
244
245	return NULL;
246}
247EXPORT_SYMBOL_GPL(l2tp_session_find_by_ifname);
248
249/* Lookup a tunnel by id
250 */
251struct l2tp_tunnel *l2tp_tunnel_find(struct net *net, u32 tunnel_id)
252{
253	struct l2tp_tunnel *tunnel;
254	struct l2tp_net *pn = l2tp_pernet(net);
255
256	rcu_read_lock_bh();
257	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
258		if (tunnel->tunnel_id == tunnel_id) {
259			rcu_read_unlock_bh();
260			return tunnel;
261		}
262	}
263	rcu_read_unlock_bh();
264
265	return NULL;
266}
267EXPORT_SYMBOL_GPL(l2tp_tunnel_find);
268
269struct l2tp_tunnel *l2tp_tunnel_find_nth(struct net *net, int nth)
270{
271	struct l2tp_net *pn = l2tp_pernet(net);
272	struct l2tp_tunnel *tunnel;
273	int count = 0;
274
275	rcu_read_lock_bh();
276	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
277		if (++count > nth) {
278			rcu_read_unlock_bh();
279			return tunnel;
280		}
281	}
282
283	rcu_read_unlock_bh();
284
285	return NULL;
286}
287EXPORT_SYMBOL_GPL(l2tp_tunnel_find_nth);
288
289/*****************************************************************************
290 * Receive data handling
291 *****************************************************************************/
292
293/* Queue a skb in order. We come here only if the skb has an L2TP sequence
294 * number.
295 */
296static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
297{
298	struct sk_buff *skbp;
299	struct sk_buff *tmp;
300	u32 ns = L2TP_SKB_CB(skb)->ns;
301
302	spin_lock_bh(&session->reorder_q.lock);
303	skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
304		if (L2TP_SKB_CB(skbp)->ns > ns) {
305			__skb_queue_before(&session->reorder_q, skbp, skb);
306			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
307			       "%s: pkt %hu, inserted before %hu, reorder_q len=%d\n",
308			       session->name, ns, L2TP_SKB_CB(skbp)->ns,
309			       skb_queue_len(&session->reorder_q));
310			session->stats.rx_oos_packets++;
311			goto out;
312		}
313	}
314
315	__skb_queue_tail(&session->reorder_q, skb);
316
317out:
318	spin_unlock_bh(&session->reorder_q.lock);
319}
320
321/* Dequeue a single skb.
322 */
323static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
324{
325	struct l2tp_tunnel *tunnel = session->tunnel;
326	int length = L2TP_SKB_CB(skb)->length;
327
328	/* We're about to requeue the skb, so return resources
329	 * to its current owner (a socket receive buffer).
330	 */
331	skb_orphan(skb);
332
333	tunnel->stats.rx_packets++;
334	tunnel->stats.rx_bytes += length;
335	session->stats.rx_packets++;
336	session->stats.rx_bytes += length;
337
338	if (L2TP_SKB_CB(skb)->has_seq) {
339		/* Bump our Nr */
340		session->nr++;
341		if (tunnel->version == L2TP_HDR_VER_2)
342			session->nr &= 0xffff;
343		else
344			session->nr &= 0xffffff;
345
346		PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
347		       "%s: updated nr to %hu\n", session->name, session->nr);
348	}
349
350	/* call private receive handler */
351	if (session->recv_skb != NULL)
352		(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
353	else
354		kfree_skb(skb);
355
356	if (session->deref)
357		(*session->deref)(session);
358}
359
360/* Dequeue skbs from the session's reorder_q, subject to packet order.
361 * Skbs that have been in the queue for too long are simply discarded.
362 */
363static void l2tp_recv_dequeue(struct l2tp_session *session)
364{
365	struct sk_buff *skb;
366	struct sk_buff *tmp;
367
368	/* If the pkt at the head of the queue has the nr that we
369	 * expect to send up next, dequeue it and any other
370	 * in-sequence packets behind it.
371	 */
372	spin_lock_bh(&session->reorder_q.lock);
373	skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
374		if (time_after(jiffies, L2TP_SKB_CB(skb)->expires)) {
375			session->stats.rx_seq_discards++;
376			session->stats.rx_errors++;
377			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
378			       "%s: oos pkt %u len %d discarded (too old), "
379			       "waiting for %u, reorder_q_len=%d\n",
380			       session->name, L2TP_SKB_CB(skb)->ns,
381			       L2TP_SKB_CB(skb)->length, session->nr,
382			       skb_queue_len(&session->reorder_q));
383			__skb_unlink(skb, &session->reorder_q);
384			kfree_skb(skb);
385			if (session->deref)
386				(*session->deref)(session);
387			continue;
388		}
389
390		if (L2TP_SKB_CB(skb)->has_seq) {
391			if (L2TP_SKB_CB(skb)->ns != session->nr) {
392				PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
393				       "%s: holding oos pkt %u len %d, "
394				       "waiting for %u, reorder_q_len=%d\n",
395				       session->name, L2TP_SKB_CB(skb)->ns,
396				       L2TP_SKB_CB(skb)->length, session->nr,
397				       skb_queue_len(&session->reorder_q));
398				goto out;
399			}
400		}
401		__skb_unlink(skb, &session->reorder_q);
402
403		/* Process the skb. We release the queue lock while we
404		 * do so to let other contexts process the queue.
405		 */
406		spin_unlock_bh(&session->reorder_q.lock);
407		l2tp_recv_dequeue_skb(session, skb);
408		spin_lock_bh(&session->reorder_q.lock);
409	}
410
411out:
412	spin_unlock_bh(&session->reorder_q.lock);
413}
414
415static inline int l2tp_verify_udp_checksum(struct sock *sk,
416					   struct sk_buff *skb)
417{
418	struct udphdr *uh = udp_hdr(skb);
419	u16 ulen = ntohs(uh->len);
420	struct inet_sock *inet;
421	__wsum psum;
422
423	if (sk->sk_no_check || skb_csum_unnecessary(skb) || !uh->check)
424		return 0;
425
426	inet = inet_sk(sk);
427	psum = csum_tcpudp_nofold(inet->inet_saddr, inet->inet_daddr, ulen,
428				  IPPROTO_UDP, 0);
429
430	if ((skb->ip_summed == CHECKSUM_COMPLETE) &&
431	    !csum_fold(csum_add(psum, skb->csum)))
432		return 0;
433
434	skb->csum = psum;
435
436	return __skb_checksum_complete(skb);
437}
438
439/* Do receive processing of L2TP data frames. We handle both L2TPv2
440 * and L2TPv3 data frames here.
441 *
442 * L2TPv2 Data Message Header
443 *
444 *  0                   1                   2                   3
445 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
446 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
447 * |T|L|x|x|S|x|O|P|x|x|x|x|  Ver  |          Length (opt)         |
448 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
449 * |           Tunnel ID           |           Session ID          |
450 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
451 * |             Ns (opt)          |             Nr (opt)          |
452 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
453 * |      Offset Size (opt)        |    Offset pad... (opt)
454 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
455 *
456 * Data frames are marked by T=0. All other fields are the same as
457 * those in L2TP control frames.
458 *
459 * L2TPv3 Data Message Header
460 *
461 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
462 * |                      L2TP Session Header                      |
463 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
464 * |                      L2-Specific Sublayer                     |
465 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
466 * |                        Tunnel Payload                      ...
467 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
468 *
469 * L2TPv3 Session Header Over IP
470 *
471 *  0                   1                   2                   3
472 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
473 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
474 * |                           Session ID                          |
475 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
476 * |               Cookie (optional, maximum 64 bits)...
477 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
478 *                                                                 |
479 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
480 *
481 * L2TPv3 L2-Specific Sublayer Format
482 *
483 *  0                   1                   2                   3
484 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
485 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
486 * |x|S|x|x|x|x|x|x|              Sequence Number                  |
487 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
488 *
489 * Cookie value, sublayer format and offset (pad) are negotiated with
490 * the peer when the session is set up. Unlike L2TPv2, we do not need
491 * to parse the packet header to determine if optional fields are
492 * present.
493 *
494 * Caller must already have parsed the frame and determined that it is
495 * a data (not control) frame before coming here. Fields up to the
496 * session-id have already been parsed and ptr points to the data
497 * after the session-id.
498 */
499void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
500		      unsigned char *ptr, unsigned char *optr, u16 hdrflags,
501		      int length, int (*payload_hook)(struct sk_buff *skb))
502{
503	struct l2tp_tunnel *tunnel = session->tunnel;
504	int offset;
505	u32 ns, nr;
506
507	/* The ref count is increased since we now hold a pointer to
508	 * the session. Take care to decrement the refcnt when exiting
509	 * this function from now on...
510	 */
511	l2tp_session_inc_refcount(session);
512	if (session->ref)
513		(*session->ref)(session);
514
515	/* Parse and check optional cookie */
516	if (session->peer_cookie_len > 0) {
517		if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
518			PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
519			       "%s: cookie mismatch (%u/%u). Discarding.\n",
520			       tunnel->name, tunnel->tunnel_id, session->session_id);
521			session->stats.rx_cookie_discards++;
522			goto discard;
523		}
524		ptr += session->peer_cookie_len;
525	}
526
527	/* Handle the optional sequence numbers. Sequence numbers are
528	 * in different places for L2TPv2 and L2TPv3.
529	 *
530	 * If we are the LAC, enable/disable sequence numbers under
531	 * the control of the LNS.  If no sequence numbers present but
532	 * we were expecting them, discard frame.
533	 */
534	ns = nr = 0;
535	L2TP_SKB_CB(skb)->has_seq = 0;
536	if (tunnel->version == L2TP_HDR_VER_2) {
537		if (hdrflags & L2TP_HDRFLAG_S) {
538			ns = ntohs(*(__be16 *) ptr);
539			ptr += 2;
540			nr = ntohs(*(__be16 *) ptr);
541			ptr += 2;
542
543			/* Store L2TP info in the skb */
544			L2TP_SKB_CB(skb)->ns = ns;
545			L2TP_SKB_CB(skb)->has_seq = 1;
546
547			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
548			       "%s: recv data ns=%u, nr=%u, session nr=%u\n",
549			       session->name, ns, nr, session->nr);
550		}
551	} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
552		u32 l2h = ntohl(*(__be32 *) ptr);
553
554		if (l2h & 0x40000000) {
555			ns = l2h & 0x00ffffff;
556
557			/* Store L2TP info in the skb */
558			L2TP_SKB_CB(skb)->ns = ns;
559			L2TP_SKB_CB(skb)->has_seq = 1;
560
561			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
562			       "%s: recv data ns=%u, session nr=%u\n",
563			       session->name, ns, session->nr);
564		}
565	}
566
567	/* Advance past L2-specific header, if present */
568	ptr += session->l2specific_len;
569
570	if (L2TP_SKB_CB(skb)->has_seq) {
571		/* Received a packet with sequence numbers. If we're the LNS,
572		 * check if we sre sending sequence numbers and if not,
573		 * configure it so.
574		 */
575		if ((!session->lns_mode) && (!session->send_seq)) {
576			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_INFO,
577			       "%s: requested to enable seq numbers by LNS\n",
578			       session->name);
579			session->send_seq = -1;
580			l2tp_session_set_header_len(session, tunnel->version);
581		}
582	} else {
583		/* No sequence numbers.
584		 * If user has configured mandatory sequence numbers, discard.
585		 */
586		if (session->recv_seq) {
587			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_WARNING,
588			       "%s: recv data has no seq numbers when required. "
589			       "Discarding\n", session->name);
590			session->stats.rx_seq_discards++;
591			goto discard;
592		}
593
594		/* If we're the LAC and we're sending sequence numbers, the
595		 * LNS has requested that we no longer send sequence numbers.
596		 * If we're the LNS and we're sending sequence numbers, the
597		 * LAC is broken. Discard the frame.
598		 */
599		if ((!session->lns_mode) && (session->send_seq)) {
600			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_INFO,
601			       "%s: requested to disable seq numbers by LNS\n",
602			       session->name);
603			session->send_seq = 0;
604			l2tp_session_set_header_len(session, tunnel->version);
605		} else if (session->send_seq) {
606			PRINTK(session->debug, L2TP_MSG_SEQ, KERN_WARNING,
607			       "%s: recv data has no seq numbers when required. "
608			       "Discarding\n", session->name);
609			session->stats.rx_seq_discards++;
610			goto discard;
611		}
612	}
613
614	/* Session data offset is handled differently for L2TPv2 and
615	 * L2TPv3. For L2TPv2, there is an optional 16-bit value in
616	 * the header. For L2TPv3, the offset is negotiated using AVPs
617	 * in the session setup control protocol.
618	 */
619	if (tunnel->version == L2TP_HDR_VER_2) {
620		/* If offset bit set, skip it. */
621		if (hdrflags & L2TP_HDRFLAG_O) {
622			offset = ntohs(*(__be16 *)ptr);
623			ptr += 2 + offset;
624		}
625	} else
626		ptr += session->offset;
627
628	offset = ptr - optr;
629	if (!pskb_may_pull(skb, offset))
630		goto discard;
631
632	__skb_pull(skb, offset);
633
634	/* If caller wants to process the payload before we queue the
635	 * packet, do so now.
636	 */
637	if (payload_hook)
638		if ((*payload_hook)(skb))
639			goto discard;
640
641	/* Prepare skb for adding to the session's reorder_q.  Hold
642	 * packets for max reorder_timeout or 1 second if not
643	 * reordering.
644	 */
645	L2TP_SKB_CB(skb)->length = length;
646	L2TP_SKB_CB(skb)->expires = jiffies +
647		(session->reorder_timeout ? session->reorder_timeout : HZ);
648
649	/* Add packet to the session's receive queue. Reordering is done here, if
650	 * enabled. Saved L2TP protocol info is stored in skb->sb[].
651	 */
652	if (L2TP_SKB_CB(skb)->has_seq) {
653		if (session->reorder_timeout != 0) {
654			/* Packet reordering enabled. Add skb to session's
655			 * reorder queue, in order of ns.
656			 */
657			l2tp_recv_queue_skb(session, skb);
658		} else {
659			/* Packet reordering disabled. Discard out-of-sequence
660			 * packets
661			 */
662			if (L2TP_SKB_CB(skb)->ns != session->nr) {
663				session->stats.rx_seq_discards++;
664				PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
665				       "%s: oos pkt %u len %d discarded, "
666				       "waiting for %u, reorder_q_len=%d\n",
667				       session->name, L2TP_SKB_CB(skb)->ns,
668				       L2TP_SKB_CB(skb)->length, session->nr,
669				       skb_queue_len(&session->reorder_q));
670				goto discard;
671			}
672			skb_queue_tail(&session->reorder_q, skb);
673		}
674	} else {
675		/* No sequence numbers. Add the skb to the tail of the
676		 * reorder queue. This ensures that it will be
677		 * delivered after all previous sequenced skbs.
678		 */
679		skb_queue_tail(&session->reorder_q, skb);
680	}
681
682	/* Try to dequeue as many skbs from reorder_q as we can. */
683	l2tp_recv_dequeue(session);
684
685	l2tp_session_dec_refcount(session);
686
687	return;
688
689discard:
690	session->stats.rx_errors++;
691	kfree_skb(skb);
692
693	if (session->deref)
694		(*session->deref)(session);
695
696	l2tp_session_dec_refcount(session);
697}
698EXPORT_SYMBOL(l2tp_recv_common);
699
700/* Internal UDP receive frame. Do the real work of receiving an L2TP data frame
701 * here. The skb is not on a list when we get here.
702 * Returns 0 if the packet was a data packet and was successfully passed on.
703 * Returns 1 if the packet was not a good data packet and could not be
704 * forwarded.  All such packets are passed up to userspace to deal with.
705 */
706int l2tp_udp_recv_core(struct l2tp_tunnel *tunnel, struct sk_buff *skb,
707		       int (*payload_hook)(struct sk_buff *skb))
708{
709	struct l2tp_session *session = NULL;
710	unsigned char *ptr, *optr;
711	u16 hdrflags;
712	u32 tunnel_id, session_id;
713	int offset;
714	u16 version;
715	int length;
716
717	if (tunnel->sock && l2tp_verify_udp_checksum(tunnel->sock, skb))
718		goto discard_bad_csum;
719
720	/* UDP always verifies the packet length. */
721	__skb_pull(skb, sizeof(struct udphdr));
722
723	/* Short packet? */
724	if (!pskb_may_pull(skb, L2TP_HDR_SIZE_SEQ)) {
725		PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
726		       "%s: recv short packet (len=%d)\n", tunnel->name, skb->len);
727		goto error;
728	}
729
730	/* Point to L2TP header */
731	optr = ptr = skb->data;
732
733	/* Trace packet contents, if enabled */
734	if (tunnel->debug & L2TP_MSG_DATA) {
735		length = min(32u, skb->len);
736		if (!pskb_may_pull(skb, length))
737			goto error;
738
739		printk(KERN_DEBUG "%s: recv: ", tunnel->name);
740
741		offset = 0;
742		do {
743			printk(" %02X", ptr[offset]);
744		} while (++offset < length);
745
746		printk("\n");
747	}
748
749	/* Get L2TP header flags */
750	hdrflags = ntohs(*(__be16 *) ptr);
751
752	/* Check protocol version */
753	version = hdrflags & L2TP_HDR_VER_MASK;
754	if (version != tunnel->version) {
755		PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
756		       "%s: recv protocol version mismatch: got %d expected %d\n",
757		       tunnel->name, version, tunnel->version);
758		goto error;
759	}
760
761	/* Get length of L2TP packet */
762	length = skb->len;
763
764	/* If type is control packet, it is handled by userspace. */
765	if (hdrflags & L2TP_HDRFLAG_T) {
766		PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_DEBUG,
767		       "%s: recv control packet, len=%d\n", tunnel->name, length);
768		goto error;
769	}
770
771	/* Skip flags */
772	ptr += 2;
773
774	if (tunnel->version == L2TP_HDR_VER_2) {
775		/* If length is present, skip it */
776		if (hdrflags & L2TP_HDRFLAG_L)
777			ptr += 2;
778
779		/* Extract tunnel and session ID */
780		tunnel_id = ntohs(*(__be16 *) ptr);
781		ptr += 2;
782		session_id = ntohs(*(__be16 *) ptr);
783		ptr += 2;
784	} else {
785		ptr += 2;	/* skip reserved bits */
786		tunnel_id = tunnel->tunnel_id;
787		session_id = ntohl(*(__be32 *) ptr);
788		ptr += 4;
789	}
790
791	/* Find the session context */
792	session = l2tp_session_find(tunnel->l2tp_net, tunnel, session_id);
793	if (!session || !session->recv_skb) {
794		/* Not found? Pass to userspace to deal with */
795		PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_INFO,
796		       "%s: no session found (%u/%u). Passing up.\n",
797		       tunnel->name, tunnel_id, session_id);
798		goto error;
799	}
800
801	l2tp_recv_common(session, skb, ptr, optr, hdrflags, length, payload_hook);
802
803	return 0;
804
805discard_bad_csum:
806	LIMIT_NETDEBUG("%s: UDP: bad checksum\n", tunnel->name);
807	UDP_INC_STATS_USER(tunnel->l2tp_net, UDP_MIB_INERRORS, 0);
808	tunnel->stats.rx_errors++;
809	kfree_skb(skb);
810
811	return 0;
812
813error:
814	/* Put UDP header back */
815	__skb_push(skb, sizeof(struct udphdr));
816
817	return 1;
818}
819EXPORT_SYMBOL_GPL(l2tp_udp_recv_core);
820
821/* UDP encapsulation receive handler. See net/ipv4/udp.c.
822 * Return codes:
823 * 0 : success.
824 * <0: error
825 * >0: skb should be passed up to userspace as UDP.
826 */
827int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
828{
829	struct l2tp_tunnel *tunnel;
830
831	tunnel = l2tp_sock_to_tunnel(sk);
832	if (tunnel == NULL)
833		goto pass_up;
834
835	PRINTK(tunnel->debug, L2TP_MSG_DATA, KERN_DEBUG,
836	       "%s: received %d bytes\n", tunnel->name, skb->len);
837
838	if (l2tp_udp_recv_core(tunnel, skb, tunnel->recv_payload_hook))
839		goto pass_up_put;
840
841	sock_put(sk);
842	return 0;
843
844pass_up_put:
845	sock_put(sk);
846pass_up:
847	return 1;
848}
849EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
850
851/************************************************************************
852 * Transmit handling
853 ***********************************************************************/
854
855/* Build an L2TP header for the session into the buffer provided.
856 */
857static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
858{
859	struct l2tp_tunnel *tunnel = session->tunnel;
860	__be16 *bufp = buf;
861	__be16 *optr = buf;
862	u16 flags = L2TP_HDR_VER_2;
863	u32 tunnel_id = tunnel->peer_tunnel_id;
864	u32 session_id = session->peer_session_id;
865
866	if (session->send_seq)
867		flags |= L2TP_HDRFLAG_S;
868
869	/* Setup L2TP header. */
870	*bufp++ = htons(flags);
871	*bufp++ = htons(tunnel_id);
872	*bufp++ = htons(session_id);
873	if (session->send_seq) {
874		*bufp++ = htons(session->ns);
875		*bufp++ = 0;
876		session->ns++;
877		session->ns &= 0xffff;
878		PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
879		       "%s: updated ns to %u\n", session->name, session->ns);
880	}
881
882	return bufp - optr;
883}
884
885static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
886{
887	struct l2tp_tunnel *tunnel = session->tunnel;
888	char *bufp = buf;
889	char *optr = bufp;
890
891	/* Setup L2TP header. The header differs slightly for UDP and
892	 * IP encapsulations. For UDP, there is 4 bytes of flags.
893	 */
894	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
895		u16 flags = L2TP_HDR_VER_3;
896		*((__be16 *) bufp) = htons(flags);
897		bufp += 2;
898		*((__be16 *) bufp) = 0;
899		bufp += 2;
900	}
901
902	*((__be32 *) bufp) = htonl(session->peer_session_id);
903	bufp += 4;
904	if (session->cookie_len) {
905		memcpy(bufp, &session->cookie[0], session->cookie_len);
906		bufp += session->cookie_len;
907	}
908	if (session->l2specific_len) {
909		if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
910			u32 l2h = 0;
911			if (session->send_seq) {
912				l2h = 0x40000000 | session->ns;
913				session->ns++;
914				session->ns &= 0xffffff;
915				PRINTK(session->debug, L2TP_MSG_SEQ, KERN_DEBUG,
916				       "%s: updated ns to %u\n", session->name, session->ns);
917			}
918
919			*((__be32 *) bufp) = htonl(l2h);
920		}
921		bufp += session->l2specific_len;
922	}
923	if (session->offset)
924		bufp += session->offset;
925
926	return bufp - optr;
927}
928
929int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb, size_t data_len)
930{
931	struct l2tp_tunnel *tunnel = session->tunnel;
932	unsigned int len = skb->len;
933	int error;
934
935	/* Debug */
936	if (session->send_seq)
937		PRINTK(session->debug, L2TP_MSG_DATA, KERN_DEBUG,
938		       "%s: send %Zd bytes, ns=%u\n", session->name,
939		       data_len, session->ns - 1);
940	else
941		PRINTK(session->debug, L2TP_MSG_DATA, KERN_DEBUG,
942		       "%s: send %Zd bytes\n", session->name, data_len);
943
944	if (session->debug & L2TP_MSG_DATA) {
945		int i;
946		int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
947		unsigned char *datap = skb->data + uhlen;
948
949		printk(KERN_DEBUG "%s: xmit:", session->name);
950		for (i = 0; i < (len - uhlen); i++) {
951			printk(" %02X", *datap++);
952			if (i == 31) {
953				printk(" ...");
954				break;
955			}
956		}
957		printk("\n");
958	}
959
960	/* Queue the packet to IP for output */
961	skb->local_df = 1;
962	error = ip_queue_xmit(skb);
963
964	/* Update stats */
965	if (error >= 0) {
966		tunnel->stats.tx_packets++;
967		tunnel->stats.tx_bytes += len;
968		session->stats.tx_packets++;
969		session->stats.tx_bytes += len;
970	} else {
971		tunnel->stats.tx_errors++;
972		session->stats.tx_errors++;
973	}
974
975	return 0;
976}
977EXPORT_SYMBOL_GPL(l2tp_xmit_core);
978
979/* Automatically called when the skb is freed.
980 */
981static void l2tp_sock_wfree(struct sk_buff *skb)
982{
983	sock_put(skb->sk);
984}
985
986/* For data skbs that we transmit, we associate with the tunnel socket
987 * but don't do accounting.
988 */
989static inline void l2tp_skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
990{
991	sock_hold(sk);
992	skb->sk = sk;
993	skb->destructor = l2tp_sock_wfree;
994}
995
996/* If caller requires the skb to have a ppp header, the header must be
997 * inserted in the skb data before calling this function.
998 */
999int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb, int hdr_len)
1000{
1001	int data_len = skb->len;
1002	struct l2tp_tunnel *tunnel = session->tunnel;
1003	struct sock *sk = tunnel->sock;
1004	struct udphdr *uh;
1005	struct inet_sock *inet;
1006	__wsum csum;
1007	int old_headroom;
1008	int new_headroom;
1009	int headroom;
1010	int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
1011	int udp_len;
1012
1013	/* Check that there's enough headroom in the skb to insert IP,
1014	 * UDP and L2TP headers. If not enough, expand it to
1015	 * make room. Adjust truesize.
1016	 */
1017	headroom = NET_SKB_PAD + sizeof(struct iphdr) +
1018		uhlen + hdr_len;
1019	old_headroom = skb_headroom(skb);
1020	if (skb_cow_head(skb, headroom))
1021		goto abort;
1022
1023	new_headroom = skb_headroom(skb);
1024	skb_orphan(skb);
1025	skb->truesize += new_headroom - old_headroom;
1026
1027	/* Setup L2TP header */
1028	session->build_header(session, __skb_push(skb, hdr_len));
1029
1030	/* Reset skb netfilter state */
1031	memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1032	IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED |
1033			      IPSKB_REROUTED);
1034	nf_reset(skb);
1035
1036	/* Get routing info from the tunnel socket */
1037	skb_dst_drop(skb);
1038	skb_dst_set(skb, dst_clone(__sk_dst_get(sk)));
1039
1040	switch (tunnel->encap) {
1041	case L2TP_ENCAPTYPE_UDP:
1042		/* Setup UDP header */
1043		inet = inet_sk(sk);
1044		__skb_push(skb, sizeof(*uh));
1045		skb_reset_transport_header(skb);
1046		uh = udp_hdr(skb);
1047		uh->source = inet->inet_sport;
1048		uh->dest = inet->inet_dport;
1049		udp_len = uhlen + hdr_len + data_len;
1050		uh->len = htons(udp_len);
1051		uh->check = 0;
1052
1053		/* Calculate UDP checksum if configured to do so */
1054		if (sk->sk_no_check == UDP_CSUM_NOXMIT)
1055			skb->ip_summed = CHECKSUM_NONE;
1056		else if ((skb_dst(skb) && skb_dst(skb)->dev) &&
1057			 (!(skb_dst(skb)->dev->features & NETIF_F_V4_CSUM))) {
1058			skb->ip_summed = CHECKSUM_COMPLETE;
1059			csum = skb_checksum(skb, 0, udp_len, 0);
1060			uh->check = csum_tcpudp_magic(inet->inet_saddr,
1061						      inet->inet_daddr,
1062						      udp_len, IPPROTO_UDP, csum);
1063			if (uh->check == 0)
1064				uh->check = CSUM_MANGLED_0;
1065		} else {
1066			skb->ip_summed = CHECKSUM_PARTIAL;
1067			skb->csum_start = skb_transport_header(skb) - skb->head;
1068			skb->csum_offset = offsetof(struct udphdr, check);
1069			uh->check = ~csum_tcpudp_magic(inet->inet_saddr,
1070						       inet->inet_daddr,
1071						       udp_len, IPPROTO_UDP, 0);
1072		}
1073		break;
1074
1075	case L2TP_ENCAPTYPE_IP:
1076		break;
1077	}
1078
1079	l2tp_skb_set_owner_w(skb, sk);
1080
1081	l2tp_xmit_core(session, skb, data_len);
1082
1083abort:
1084	return 0;
1085}
1086EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
1087
1088/*****************************************************************************
1089 * Tinnel and session create/destroy.
1090 *****************************************************************************/
1091
1092/* Tunnel socket destruct hook.
1093 * The tunnel context is deleted only when all session sockets have been
1094 * closed.
1095 */
1096void l2tp_tunnel_destruct(struct sock *sk)
1097{
1098	struct l2tp_tunnel *tunnel;
1099
1100	tunnel = sk->sk_user_data;
1101	if (tunnel == NULL)
1102		goto end;
1103
1104	PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
1105	       "%s: closing...\n", tunnel->name);
1106
1107	/* Close all sessions */
1108	l2tp_tunnel_closeall(tunnel);
1109
1110	switch (tunnel->encap) {
1111	case L2TP_ENCAPTYPE_UDP:
1112		/* No longer an encapsulation socket. See net/ipv4/udp.c */
1113		(udp_sk(sk))->encap_type = 0;
1114		(udp_sk(sk))->encap_rcv = NULL;
1115		break;
1116	case L2TP_ENCAPTYPE_IP:
1117		break;
1118	}
1119
1120	/* Remove hooks into tunnel socket */
1121	tunnel->sock = NULL;
1122	sk->sk_destruct = tunnel->old_sk_destruct;
1123	sk->sk_user_data = NULL;
1124
1125	/* Call the original destructor */
1126	if (sk->sk_destruct)
1127		(*sk->sk_destruct)(sk);
1128
1129	/* We're finished with the socket */
1130	l2tp_tunnel_dec_refcount(tunnel);
1131
1132end:
1133	return;
1134}
1135EXPORT_SYMBOL(l2tp_tunnel_destruct);
1136
1137/* When the tunnel is closed, all the attached sessions need to go too.
1138 */
1139void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
1140{
1141	int hash;
1142	struct hlist_node *walk;
1143	struct hlist_node *tmp;
1144	struct l2tp_session *session;
1145
1146	BUG_ON(tunnel == NULL);
1147
1148	PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
1149	       "%s: closing all sessions...\n", tunnel->name);
1150
1151	write_lock_bh(&tunnel->hlist_lock);
1152	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
1153again:
1154		hlist_for_each_safe(walk, tmp, &tunnel->session_hlist[hash]) {
1155			session = hlist_entry(walk, struct l2tp_session, hlist);
1156
1157			PRINTK(session->debug, L2TP_MSG_CONTROL, KERN_INFO,
1158			       "%s: closing session\n", session->name);
1159
1160			hlist_del_init(&session->hlist);
1161
1162			/* Since we should hold the sock lock while
1163			 * doing any unbinding, we need to release the
1164			 * lock we're holding before taking that lock.
1165			 * Hold a reference to the sock so it doesn't
1166			 * disappear as we're jumping between locks.
1167			 */
1168			if (session->ref != NULL)
1169				(*session->ref)(session);
1170
1171			write_unlock_bh(&tunnel->hlist_lock);
1172
1173			if (tunnel->version != L2TP_HDR_VER_2) {
1174				struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1175
1176				spin_lock_bh(&pn->l2tp_session_hlist_lock);
1177				hlist_del_init_rcu(&session->global_hlist);
1178				spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1179				synchronize_rcu();
1180			}
1181
1182			if (session->session_close != NULL)
1183				(*session->session_close)(session);
1184
1185			if (session->deref != NULL)
1186				(*session->deref)(session);
1187
1188			write_lock_bh(&tunnel->hlist_lock);
1189
1190			/* Now restart from the beginning of this hash
1191			 * chain.  We always remove a session from the
1192			 * list so we are guaranteed to make forward
1193			 * progress.
1194			 */
1195			goto again;
1196		}
1197	}
1198	write_unlock_bh(&tunnel->hlist_lock);
1199}
1200EXPORT_SYMBOL_GPL(l2tp_tunnel_closeall);
1201
1202/* Really kill the tunnel.
1203 * Come here only when all sessions have been cleared from the tunnel.
1204 */
1205void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
1206{
1207	struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1208
1209	BUG_ON(atomic_read(&tunnel->ref_count) != 0);
1210	BUG_ON(tunnel->sock != NULL);
1211
1212	PRINTK(tunnel->debug, L2TP_MSG_CONTROL, KERN_INFO,
1213	       "%s: free...\n", tunnel->name);
1214
1215	/* Remove from tunnel list */
1216	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1217	list_del_rcu(&tunnel->list);
1218	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1219	synchronize_rcu();
1220
1221	atomic_dec(&l2tp_tunnel_count);
1222	kfree(tunnel);
1223
1224#if defined(CTFPOOL) && defined(CTF_L2TP)
1225	osl_ctfpool_direction(0);
1226#endif
1227}
1228EXPORT_SYMBOL_GPL(l2tp_tunnel_free);
1229
1230/* Create a socket for the tunnel, if one isn't set up by
1231 * userspace. This is used for static tunnels where there is no
1232 * managing L2TP daemon.
1233 */
1234static int l2tp_tunnel_sock_create(u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct socket **sockp)
1235{
1236	int err = -EINVAL;
1237	struct sockaddr_in udp_addr;
1238	struct sockaddr_l2tpip ip_addr;
1239	struct socket *sock = NULL;
1240
1241	switch (cfg->encap) {
1242	case L2TP_ENCAPTYPE_UDP:
1243		err = sock_create(AF_INET, SOCK_DGRAM, 0, sockp);
1244		if (err < 0)
1245			goto out;
1246
1247		sock = *sockp;
1248
1249		memset(&udp_addr, 0, sizeof(udp_addr));
1250		udp_addr.sin_family = AF_INET;
1251		udp_addr.sin_addr = cfg->local_ip;
1252		udp_addr.sin_port = htons(cfg->local_udp_port);
1253		err = kernel_bind(sock, (struct sockaddr *) &udp_addr, sizeof(udp_addr));
1254		if (err < 0)
1255			goto out;
1256
1257		udp_addr.sin_family = AF_INET;
1258		udp_addr.sin_addr = cfg->peer_ip;
1259		udp_addr.sin_port = htons(cfg->peer_udp_port);
1260		err = kernel_connect(sock, (struct sockaddr *) &udp_addr, sizeof(udp_addr), 0);
1261		if (err < 0)
1262			goto out;
1263
1264		if (!cfg->use_udp_checksums)
1265			sock->sk->sk_no_check = UDP_CSUM_NOXMIT;
1266
1267		break;
1268
1269	case L2TP_ENCAPTYPE_IP:
1270		err = sock_create(AF_INET, SOCK_DGRAM, IPPROTO_L2TP, sockp);
1271		if (err < 0)
1272			goto out;
1273
1274		sock = *sockp;
1275
1276		memset(&ip_addr, 0, sizeof(ip_addr));
1277		ip_addr.l2tp_family = AF_INET;
1278		ip_addr.l2tp_addr = cfg->local_ip;
1279		ip_addr.l2tp_conn_id = tunnel_id;
1280		err = kernel_bind(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr));
1281		if (err < 0)
1282			goto out;
1283
1284		ip_addr.l2tp_family = AF_INET;
1285		ip_addr.l2tp_addr = cfg->peer_ip;
1286		ip_addr.l2tp_conn_id = peer_tunnel_id;
1287		err = kernel_connect(sock, (struct sockaddr *) &ip_addr, sizeof(ip_addr), 0);
1288		if (err < 0)
1289			goto out;
1290
1291		break;
1292
1293	default:
1294		goto out;
1295	}
1296
1297out:
1298	if ((err < 0) && sock) {
1299		sock_release(sock);
1300		*sockp = NULL;
1301	}
1302
1303	return err;
1304}
1305
1306int l2tp_tunnel_create(struct net *net, int fd, int version, u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
1307{
1308	struct l2tp_tunnel *tunnel = NULL;
1309	int err;
1310	struct socket *sock = NULL;
1311	struct sock *sk = NULL;
1312	struct l2tp_net *pn;
1313	enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
1314
1315	/* Get the tunnel socket from the fd, which was opened by
1316	 * the userspace L2TP daemon. If not specified, create a
1317	 * kernel socket.
1318	 */
1319	if (fd < 0) {
1320		err = l2tp_tunnel_sock_create(tunnel_id, peer_tunnel_id, cfg, &sock);
1321		if (err < 0)
1322			goto err;
1323	} else {
1324		err = -EBADF;
1325		sock = sockfd_lookup(fd, &err);
1326		if (!sock) {
1327			printk(KERN_ERR "tunl %hu: sockfd_lookup(fd=%d) returned %d\n",
1328			       tunnel_id, fd, err);
1329			goto err;
1330		}
1331	}
1332
1333	sk = sock->sk;
1334
1335	if (cfg != NULL)
1336		encap = cfg->encap;
1337
1338	/* Quick sanity checks */
1339	switch (encap) {
1340	case L2TP_ENCAPTYPE_UDP:
1341		err = -EPROTONOSUPPORT;
1342		if (sk->sk_protocol != IPPROTO_UDP) {
1343			printk(KERN_ERR "tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
1344			       tunnel_id, fd, sk->sk_protocol, IPPROTO_UDP);
1345			goto err;
1346		}
1347		break;
1348	case L2TP_ENCAPTYPE_IP:
1349		err = -EPROTONOSUPPORT;
1350		if (sk->sk_protocol != IPPROTO_L2TP) {
1351			printk(KERN_ERR "tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
1352			       tunnel_id, fd, sk->sk_protocol, IPPROTO_L2TP);
1353			goto err;
1354		}
1355		break;
1356	}
1357
1358	/* Check if this socket has already been prepped */
1359	tunnel = (struct l2tp_tunnel *)sk->sk_user_data;
1360	if (tunnel != NULL) {
1361		/* This socket has already been prepped */
1362		err = -EBUSY;
1363		goto err;
1364	}
1365
1366	tunnel = kzalloc(sizeof(struct l2tp_tunnel), GFP_KERNEL);
1367	if (tunnel == NULL) {
1368		err = -ENOMEM;
1369		goto err;
1370	}
1371
1372	tunnel->version = version;
1373	tunnel->tunnel_id = tunnel_id;
1374	tunnel->peer_tunnel_id = peer_tunnel_id;
1375	tunnel->debug = L2TP_DEFAULT_DEBUG_FLAGS;
1376
1377	tunnel->magic = L2TP_TUNNEL_MAGIC;
1378	sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
1379	rwlock_init(&tunnel->hlist_lock);
1380
1381	/* The net we belong to */
1382	tunnel->l2tp_net = net;
1383	pn = l2tp_pernet(net);
1384
1385	if (cfg != NULL)
1386		tunnel->debug = cfg->debug;
1387
1388	/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
1389	tunnel->encap = encap;
1390	if (encap == L2TP_ENCAPTYPE_UDP) {
1391		/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
1392		udp_sk(sk)->encap_type = UDP_ENCAP_L2TPINUDP;
1393		udp_sk(sk)->encap_rcv = l2tp_udp_encap_recv;
1394	}
1395
1396	sk->sk_user_data = tunnel;
1397
1398	/* Hook on the tunnel socket destructor so that we can cleanup
1399	 * if the tunnel socket goes away.
1400	 */
1401	tunnel->old_sk_destruct = sk->sk_destruct;
1402	sk->sk_destruct = &l2tp_tunnel_destruct;
1403	tunnel->sock = sk;
1404	sk->sk_allocation = GFP_ATOMIC;
1405
1406	/* Add tunnel to our list */
1407	INIT_LIST_HEAD(&tunnel->list);
1408	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1409	list_add_rcu(&tunnel->list, &pn->l2tp_tunnel_list);
1410	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1411	synchronize_rcu();
1412	atomic_inc(&l2tp_tunnel_count);
1413
1414	/* Bump the reference count. The tunnel context is deleted
1415	 * only when this drops to zero.
1416	 */
1417	l2tp_tunnel_inc_refcount(tunnel);
1418
1419#if defined(CTFPOOL) && defined(CTF_L2TP)
1420	osl_ctfpool_direction(1);
1421#endif
1422
1423	err = 0;
1424err:
1425	if (tunnelp)
1426		*tunnelp = tunnel;
1427
1428	/* If tunnel's socket was created by the kernel, it doesn't
1429	 *  have a file.
1430	 */
1431	if (sock && sock->file)
1432		sockfd_put(sock);
1433
1434	return err;
1435}
1436EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
1437
1438/* This function is used by the netlink TUNNEL_DELETE command.
1439 */
1440int l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
1441{
1442	int err = 0;
1443	struct socket *sock = tunnel->sock ? tunnel->sock->sk_socket : NULL;
1444
1445	/* Force the tunnel socket to close. This will eventually
1446	 * cause the tunnel to be deleted via the normal socket close
1447	 * mechanisms when userspace closes the tunnel socket.
1448	 */
1449	if (sock != NULL) {
1450		err = inet_shutdown(sock, 2);
1451
1452		/* If the tunnel's socket was created by the kernel,
1453		 * close the socket here since the socket was not
1454		 * created by userspace.
1455		 */
1456		if (sock->file == NULL)
1457			err = inet_release(sock);
1458	}
1459
1460	return err;
1461}
1462EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
1463
1464/* Really kill the session.
1465 */
1466void l2tp_session_free(struct l2tp_session *session)
1467{
1468	struct l2tp_tunnel *tunnel;
1469
1470	BUG_ON(atomic_read(&session->ref_count) != 0);
1471
1472	tunnel = session->tunnel;
1473	if (tunnel != NULL) {
1474		BUG_ON(tunnel->magic != L2TP_TUNNEL_MAGIC);
1475
1476		/* Delete the session from the hash */
1477		write_lock_bh(&tunnel->hlist_lock);
1478		hlist_del_init(&session->hlist);
1479		write_unlock_bh(&tunnel->hlist_lock);
1480
1481		/* Unlink from the global hash if not L2TPv2 */
1482		if (tunnel->version != L2TP_HDR_VER_2) {
1483			struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1484
1485			spin_lock_bh(&pn->l2tp_session_hlist_lock);
1486			hlist_del_init_rcu(&session->global_hlist);
1487			spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1488			synchronize_rcu();
1489		}
1490
1491		if (session->session_id != 0)
1492			atomic_dec(&l2tp_session_count);
1493
1494		sock_put(tunnel->sock);
1495
1496		/* This will delete the tunnel context if this
1497		 * is the last session on the tunnel.
1498		 */
1499		session->tunnel = NULL;
1500		l2tp_tunnel_dec_refcount(tunnel);
1501	}
1502
1503	kfree(session);
1504
1505	return;
1506}
1507EXPORT_SYMBOL_GPL(l2tp_session_free);
1508
1509/* This function is used by the netlink SESSION_DELETE command and by
1510   pseudowire modules.
1511 */
1512int l2tp_session_delete(struct l2tp_session *session)
1513{
1514	if (session->session_close != NULL)
1515		(*session->session_close)(session);
1516
1517	l2tp_session_dec_refcount(session);
1518
1519	return 0;
1520}
1521EXPORT_SYMBOL_GPL(l2tp_session_delete);
1522
1523
1524/* We come here whenever a session's send_seq, cookie_len or
1525 * l2specific_len parameters are set.
1526 */
1527void l2tp_session_set_header_len(struct l2tp_session *session, int version)
1528{
1529	if (version == L2TP_HDR_VER_2) {
1530		session->hdr_len = 6;
1531		if (session->send_seq)
1532			session->hdr_len += 4;
1533	} else {
1534		session->hdr_len = 4 + session->cookie_len + session->l2specific_len + session->offset;
1535		if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
1536			session->hdr_len += 4;
1537	}
1538
1539}
1540EXPORT_SYMBOL_GPL(l2tp_session_set_header_len);
1541
1542struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
1543{
1544	struct l2tp_session *session;
1545
1546	session = kzalloc(sizeof(struct l2tp_session) + priv_size, GFP_KERNEL);
1547	if (session != NULL) {
1548		session->magic = L2TP_SESSION_MAGIC;
1549		session->tunnel = tunnel;
1550
1551		session->session_id = session_id;
1552		session->peer_session_id = peer_session_id;
1553		session->nr = 1;
1554
1555		sprintf(&session->name[0], "sess %u/%u",
1556			tunnel->tunnel_id, session->session_id);
1557
1558		skb_queue_head_init(&session->reorder_q);
1559
1560		INIT_HLIST_NODE(&session->hlist);
1561		INIT_HLIST_NODE(&session->global_hlist);
1562
1563		/* Inherit debug options from tunnel */
1564		session->debug = tunnel->debug;
1565
1566		if (cfg) {
1567			session->pwtype = cfg->pw_type;
1568			session->debug = cfg->debug;
1569			session->mtu = cfg->mtu;
1570			session->mru = cfg->mru;
1571			session->send_seq = cfg->send_seq;
1572			session->recv_seq = cfg->recv_seq;
1573			session->lns_mode = cfg->lns_mode;
1574			session->reorder_timeout = cfg->reorder_timeout;
1575			session->offset = cfg->offset;
1576			session->l2specific_type = cfg->l2specific_type;
1577			session->l2specific_len = cfg->l2specific_len;
1578			session->cookie_len = cfg->cookie_len;
1579			memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
1580			session->peer_cookie_len = cfg->peer_cookie_len;
1581			memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
1582		}
1583
1584		if (tunnel->version == L2TP_HDR_VER_2)
1585			session->build_header = l2tp_build_l2tpv2_header;
1586		else
1587			session->build_header = l2tp_build_l2tpv3_header;
1588
1589		l2tp_session_set_header_len(session, tunnel->version);
1590
1591		/* Bump the reference count. The session context is deleted
1592		 * only when this drops to zero.
1593		 */
1594		l2tp_session_inc_refcount(session);
1595		l2tp_tunnel_inc_refcount(tunnel);
1596
1597		/* Ensure tunnel socket isn't deleted */
1598		sock_hold(tunnel->sock);
1599
1600		/* Add session to the tunnel's hash list */
1601		write_lock_bh(&tunnel->hlist_lock);
1602		hlist_add_head(&session->hlist,
1603			       l2tp_session_id_hash(tunnel, session_id));
1604		write_unlock_bh(&tunnel->hlist_lock);
1605
1606		/* And to the global session list if L2TPv3 */
1607		if (tunnel->version != L2TP_HDR_VER_2) {
1608			struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1609
1610			spin_lock_bh(&pn->l2tp_session_hlist_lock);
1611			hlist_add_head_rcu(&session->global_hlist,
1612					   l2tp_session_id_hash_2(pn, session_id));
1613			spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1614			synchronize_rcu();
1615		}
1616
1617		/* Ignore management session in session count value */
1618		if (session->session_id != 0)
1619			atomic_inc(&l2tp_session_count);
1620	}
1621
1622	return session;
1623}
1624EXPORT_SYMBOL_GPL(l2tp_session_create);
1625
1626/*****************************************************************************
1627 * Init and cleanup
1628 *****************************************************************************/
1629
1630static __net_init int l2tp_init_net(struct net *net)
1631{
1632	struct l2tp_net *pn = net_generic(net, l2tp_net_id);
1633	int hash;
1634
1635	INIT_LIST_HEAD(&pn->l2tp_tunnel_list);
1636	spin_lock_init(&pn->l2tp_tunnel_list_lock);
1637
1638	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
1639		INIT_HLIST_HEAD(&pn->l2tp_session_hlist[hash]);
1640
1641	spin_lock_init(&pn->l2tp_session_hlist_lock);
1642
1643	return 0;
1644}
1645
1646static struct pernet_operations l2tp_net_ops = {
1647	.init = l2tp_init_net,
1648	.id   = &l2tp_net_id,
1649	.size = sizeof(struct l2tp_net),
1650};
1651
1652static int __init l2tp_init(void)
1653{
1654	int rc = 0;
1655
1656	rc = register_pernet_device(&l2tp_net_ops);
1657	if (rc)
1658		goto out;
1659
1660	printk(KERN_INFO "L2TP core driver, %s\n", L2TP_DRV_VERSION);
1661
1662out:
1663	return rc;
1664}
1665
1666static void __exit l2tp_exit(void)
1667{
1668	unregister_pernet_device(&l2tp_net_ops);
1669}
1670
1671module_init(l2tp_init);
1672module_exit(l2tp_exit);
1673
1674MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
1675MODULE_DESCRIPTION("L2TP core");
1676MODULE_LICENSE("GPL");
1677MODULE_VERSION(L2TP_DRV_VERSION);
1678