Linux Audio

Check our new training course

Linux BSP upgrade and security maintenance

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