xref: /linux/net/l2tp/l2tp_core.c (revision 910bfc26d16d07df5a2bfcbc63f0aa9d1397e2ef)
1 // SPDX-License-Identifier: GPL-2.0-only
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 
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 
19 #include <linux/module.h>
20 #include <linux/string.h>
21 #include <linux/list.h>
22 #include <linux/rculist.h>
23 #include <linux/uaccess.h>
24 
25 #include <linux/kernel.h>
26 #include <linux/spinlock.h>
27 #include <linux/kthread.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
30 #include <linux/errno.h>
31 #include <linux/jiffies.h>
32 
33 #include <linux/netdevice.h>
34 #include <linux/net.h>
35 #include <linux/inetdevice.h>
36 #include <linux/skbuff.h>
37 #include <linux/init.h>
38 #include <linux/in.h>
39 #include <linux/ip.h>
40 #include <linux/udp.h>
41 #include <linux/l2tp.h>
42 #include <linux/sort.h>
43 #include <linux/file.h>
44 #include <linux/nsproxy.h>
45 #include <net/net_namespace.h>
46 #include <net/netns/generic.h>
47 #include <net/dst.h>
48 #include <net/ip.h>
49 #include <net/udp.h>
50 #include <net/udp_tunnel.h>
51 #include <net/inet_common.h>
52 #include <net/xfrm.h>
53 #include <net/protocol.h>
54 #include <net/inet6_connection_sock.h>
55 #include <net/inet_ecn.h>
56 #include <net/ip6_route.h>
57 #include <net/ip6_checksum.h>
58 
59 #include <asm/byteorder.h>
60 #include <linux/atomic.h>
61 
62 #include "l2tp_core.h"
63 
64 #define CREATE_TRACE_POINTS
65 #include "trace.h"
66 
67 #define L2TP_DRV_VERSION	"V2.0"
68 
69 /* L2TP header constants */
70 #define L2TP_HDRFLAG_T	   0x8000
71 #define L2TP_HDRFLAG_L	   0x4000
72 #define L2TP_HDRFLAG_S	   0x0800
73 #define L2TP_HDRFLAG_O	   0x0200
74 #define L2TP_HDRFLAG_P	   0x0100
75 
76 #define L2TP_HDR_VER_MASK  0x000F
77 #define L2TP_HDR_VER_2	   0x0002
78 #define L2TP_HDR_VER_3	   0x0003
79 
80 /* L2TPv3 default L2-specific sublayer */
81 #define L2TP_SLFLAG_S	   0x40000000
82 #define L2TP_SL_SEQ_MASK   0x00ffffff
83 
84 #define L2TP_HDR_SIZE_MAX		14
85 
86 /* Default trace flags */
87 #define L2TP_DEFAULT_DEBUG_FLAGS	0
88 
89 /* Private data stored for received packets in the skb.
90  */
91 struct l2tp_skb_cb {
92 	u32			ns;
93 	u16			has_seq;
94 	u16			length;
95 	unsigned long		expires;
96 };
97 
98 #define L2TP_SKB_CB(skb)	((struct l2tp_skb_cb *)&(skb)->cb[sizeof(struct inet_skb_parm)])
99 
100 static struct workqueue_struct *l2tp_wq;
101 
102 /* per-net private data for this module */
103 static unsigned int l2tp_net_id;
104 struct l2tp_net {
105 	/* Lock for write access to l2tp_tunnel_idr */
106 	spinlock_t l2tp_tunnel_idr_lock;
107 	struct idr l2tp_tunnel_idr;
108 	/* Lock for write access to l2tp_v[23]_session_idr/htable */
109 	spinlock_t l2tp_session_idr_lock;
110 	struct idr l2tp_v2_session_idr;
111 	struct idr l2tp_v3_session_idr;
112 	struct hlist_head l2tp_v3_session_htable[16];
113 };
114 
115 static inline u32 l2tp_v2_session_key(u16 tunnel_id, u16 session_id)
116 {
117 	return ((u32)tunnel_id) << 16 | session_id;
118 }
119 
120 static inline unsigned long l2tp_v3_session_hashkey(struct sock *sk, u32 session_id)
121 {
122 	return ((unsigned long)sk) + session_id;
123 }
124 
125 #if IS_ENABLED(CONFIG_IPV6)
126 static bool l2tp_sk_is_v6(struct sock *sk)
127 {
128 	return sk->sk_family == PF_INET6 &&
129 	       !ipv6_addr_v4mapped(&sk->sk_v6_daddr);
130 }
131 #endif
132 
133 static inline struct l2tp_net *l2tp_pernet(const struct net *net)
134 {
135 	return net_generic(net, l2tp_net_id);
136 }
137 
138 static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
139 {
140 	trace_free_tunnel(tunnel);
141 	sock_put(tunnel->sock);
142 	/* the tunnel is freed in the socket destructor */
143 }
144 
145 static void l2tp_session_free(struct l2tp_session *session)
146 {
147 	trace_free_session(session);
148 	if (session->tunnel)
149 		l2tp_tunnel_dec_refcount(session->tunnel);
150 	kfree(session);
151 }
152 
153 struct l2tp_tunnel *l2tp_sk_to_tunnel(struct sock *sk)
154 {
155 	struct l2tp_tunnel *tunnel = sk->sk_user_data;
156 
157 	if (tunnel)
158 		if (WARN_ON(tunnel->magic != L2TP_TUNNEL_MAGIC))
159 			return NULL;
160 
161 	return tunnel;
162 }
163 EXPORT_SYMBOL_GPL(l2tp_sk_to_tunnel);
164 
165 void l2tp_tunnel_inc_refcount(struct l2tp_tunnel *tunnel)
166 {
167 	refcount_inc(&tunnel->ref_count);
168 }
169 EXPORT_SYMBOL_GPL(l2tp_tunnel_inc_refcount);
170 
171 void l2tp_tunnel_dec_refcount(struct l2tp_tunnel *tunnel)
172 {
173 	if (refcount_dec_and_test(&tunnel->ref_count))
174 		l2tp_tunnel_free(tunnel);
175 }
176 EXPORT_SYMBOL_GPL(l2tp_tunnel_dec_refcount);
177 
178 void l2tp_session_inc_refcount(struct l2tp_session *session)
179 {
180 	refcount_inc(&session->ref_count);
181 }
182 EXPORT_SYMBOL_GPL(l2tp_session_inc_refcount);
183 
184 void l2tp_session_dec_refcount(struct l2tp_session *session)
185 {
186 	if (refcount_dec_and_test(&session->ref_count))
187 		l2tp_session_free(session);
188 }
189 EXPORT_SYMBOL_GPL(l2tp_session_dec_refcount);
190 
191 /* Lookup a tunnel. A new reference is held on the returned tunnel. */
192 struct l2tp_tunnel *l2tp_tunnel_get(const struct net *net, u32 tunnel_id)
193 {
194 	const struct l2tp_net *pn = l2tp_pernet(net);
195 	struct l2tp_tunnel *tunnel;
196 
197 	rcu_read_lock_bh();
198 	tunnel = idr_find(&pn->l2tp_tunnel_idr, tunnel_id);
199 	if (tunnel && refcount_inc_not_zero(&tunnel->ref_count)) {
200 		rcu_read_unlock_bh();
201 		return tunnel;
202 	}
203 	rcu_read_unlock_bh();
204 
205 	return NULL;
206 }
207 EXPORT_SYMBOL_GPL(l2tp_tunnel_get);
208 
209 struct l2tp_tunnel *l2tp_tunnel_get_nth(const struct net *net, int nth)
210 {
211 	struct l2tp_net *pn = l2tp_pernet(net);
212 	unsigned long tunnel_id, tmp;
213 	struct l2tp_tunnel *tunnel;
214 	int count = 0;
215 
216 	rcu_read_lock_bh();
217 	idr_for_each_entry_ul(&pn->l2tp_tunnel_idr, tunnel, tmp, tunnel_id) {
218 		if (tunnel && ++count > nth &&
219 		    refcount_inc_not_zero(&tunnel->ref_count)) {
220 			rcu_read_unlock_bh();
221 			return tunnel;
222 		}
223 	}
224 	rcu_read_unlock_bh();
225 
226 	return NULL;
227 }
228 EXPORT_SYMBOL_GPL(l2tp_tunnel_get_nth);
229 
230 struct l2tp_session *l2tp_v3_session_get(const struct net *net, struct sock *sk, u32 session_id)
231 {
232 	const struct l2tp_net *pn = l2tp_pernet(net);
233 	struct l2tp_session *session;
234 
235 	rcu_read_lock_bh();
236 	session = idr_find(&pn->l2tp_v3_session_idr, session_id);
237 	if (session && !hash_hashed(&session->hlist) &&
238 	    refcount_inc_not_zero(&session->ref_count)) {
239 		rcu_read_unlock_bh();
240 		return session;
241 	}
242 
243 	/* If we get here and session is non-NULL, the session_id
244 	 * collides with one in another tunnel. If sk is non-NULL,
245 	 * find the session matching sk.
246 	 */
247 	if (session && sk) {
248 		unsigned long key = l2tp_v3_session_hashkey(sk, session->session_id);
249 
250 		hash_for_each_possible_rcu(pn->l2tp_v3_session_htable, session,
251 					   hlist, key) {
252 			if (session->tunnel->sock == sk &&
253 			    refcount_inc_not_zero(&session->ref_count)) {
254 				rcu_read_unlock_bh();
255 				return session;
256 			}
257 		}
258 	}
259 	rcu_read_unlock_bh();
260 
261 	return NULL;
262 }
263 EXPORT_SYMBOL_GPL(l2tp_v3_session_get);
264 
265 struct l2tp_session *l2tp_v2_session_get(const struct net *net, u16 tunnel_id, u16 session_id)
266 {
267 	u32 session_key = l2tp_v2_session_key(tunnel_id, session_id);
268 	const struct l2tp_net *pn = l2tp_pernet(net);
269 	struct l2tp_session *session;
270 
271 	rcu_read_lock_bh();
272 	session = idr_find(&pn->l2tp_v2_session_idr, session_key);
273 	if (session && refcount_inc_not_zero(&session->ref_count)) {
274 		rcu_read_unlock_bh();
275 		return session;
276 	}
277 	rcu_read_unlock_bh();
278 
279 	return NULL;
280 }
281 EXPORT_SYMBOL_GPL(l2tp_v2_session_get);
282 
283 struct l2tp_session *l2tp_session_get(const struct net *net, struct sock *sk, int pver,
284 				      u32 tunnel_id, u32 session_id)
285 {
286 	if (pver == L2TP_HDR_VER_2)
287 		return l2tp_v2_session_get(net, tunnel_id, session_id);
288 	else
289 		return l2tp_v3_session_get(net, sk, session_id);
290 }
291 EXPORT_SYMBOL_GPL(l2tp_session_get);
292 
293 struct l2tp_session *l2tp_session_get_nth(struct l2tp_tunnel *tunnel, int nth)
294 {
295 	struct l2tp_session *session;
296 	int count = 0;
297 
298 	rcu_read_lock_bh();
299 	list_for_each_entry_rcu(session, &tunnel->session_list, list) {
300 		if (++count > nth) {
301 			l2tp_session_inc_refcount(session);
302 			rcu_read_unlock_bh();
303 			return session;
304 		}
305 	}
306 	rcu_read_unlock_bh();
307 
308 	return NULL;
309 }
310 EXPORT_SYMBOL_GPL(l2tp_session_get_nth);
311 
312 /* Lookup a session by interface name.
313  * This is very inefficient but is only used by management interfaces.
314  */
315 struct l2tp_session *l2tp_session_get_by_ifname(const struct net *net,
316 						const char *ifname)
317 {
318 	struct l2tp_net *pn = l2tp_pernet(net);
319 	unsigned long tunnel_id, tmp;
320 	struct l2tp_session *session;
321 	struct l2tp_tunnel *tunnel;
322 
323 	rcu_read_lock_bh();
324 	idr_for_each_entry_ul(&pn->l2tp_tunnel_idr, tunnel, tmp, tunnel_id) {
325 		if (tunnel) {
326 			list_for_each_entry_rcu(session, &tunnel->session_list, list) {
327 				if (!strcmp(session->ifname, ifname)) {
328 					l2tp_session_inc_refcount(session);
329 					rcu_read_unlock_bh();
330 
331 					return session;
332 				}
333 			}
334 		}
335 	}
336 	rcu_read_unlock_bh();
337 
338 	return NULL;
339 }
340 EXPORT_SYMBOL_GPL(l2tp_session_get_by_ifname);
341 
342 static void l2tp_session_coll_list_add(struct l2tp_session_coll_list *clist,
343 				       struct l2tp_session *session)
344 {
345 	l2tp_session_inc_refcount(session);
346 	WARN_ON_ONCE(session->coll_list);
347 	session->coll_list = clist;
348 	spin_lock(&clist->lock);
349 	list_add(&session->clist, &clist->list);
350 	spin_unlock(&clist->lock);
351 }
352 
353 static int l2tp_session_collision_add(struct l2tp_net *pn,
354 				      struct l2tp_session *session1,
355 				      struct l2tp_session *session2)
356 {
357 	struct l2tp_session_coll_list *clist;
358 
359 	lockdep_assert_held(&pn->l2tp_session_idr_lock);
360 
361 	if (!session2)
362 		return -EEXIST;
363 
364 	/* If existing session is in IP-encap tunnel, refuse new session */
365 	if (session2->tunnel->encap == L2TP_ENCAPTYPE_IP)
366 		return -EEXIST;
367 
368 	clist = session2->coll_list;
369 	if (!clist) {
370 		/* First collision. Allocate list to manage the collided sessions
371 		 * and add the existing session to the list.
372 		 */
373 		clist = kmalloc(sizeof(*clist), GFP_ATOMIC);
374 		if (!clist)
375 			return -ENOMEM;
376 
377 		spin_lock_init(&clist->lock);
378 		INIT_LIST_HEAD(&clist->list);
379 		refcount_set(&clist->ref_count, 1);
380 		l2tp_session_coll_list_add(clist, session2);
381 	}
382 
383 	/* If existing session isn't already in the session hlist, add it. */
384 	if (!hash_hashed(&session2->hlist))
385 		hash_add(pn->l2tp_v3_session_htable, &session2->hlist,
386 			 session2->hlist_key);
387 
388 	/* Add new session to the hlist and collision list */
389 	hash_add(pn->l2tp_v3_session_htable, &session1->hlist,
390 		 session1->hlist_key);
391 	refcount_inc(&clist->ref_count);
392 	l2tp_session_coll_list_add(clist, session1);
393 
394 	return 0;
395 }
396 
397 static void l2tp_session_collision_del(struct l2tp_net *pn,
398 				       struct l2tp_session *session)
399 {
400 	struct l2tp_session_coll_list *clist = session->coll_list;
401 	unsigned long session_key = session->session_id;
402 	struct l2tp_session *session2;
403 
404 	lockdep_assert_held(&pn->l2tp_session_idr_lock);
405 
406 	hash_del(&session->hlist);
407 
408 	if (clist) {
409 		/* Remove session from its collision list. If there
410 		 * are other sessions with the same ID, replace this
411 		 * session's IDR entry with that session, otherwise
412 		 * remove the IDR entry. If this is the last session,
413 		 * the collision list data is freed.
414 		 */
415 		spin_lock(&clist->lock);
416 		list_del_init(&session->clist);
417 		session2 = list_first_entry_or_null(&clist->list, struct l2tp_session, clist);
418 		if (session2) {
419 			void *old = idr_replace(&pn->l2tp_v3_session_idr, session2, session_key);
420 
421 			WARN_ON_ONCE(IS_ERR_VALUE(old));
422 		} else {
423 			void *removed = idr_remove(&pn->l2tp_v3_session_idr, session_key);
424 
425 			WARN_ON_ONCE(removed != session);
426 		}
427 		session->coll_list = NULL;
428 		spin_unlock(&clist->lock);
429 		if (refcount_dec_and_test(&clist->ref_count))
430 			kfree(clist);
431 		l2tp_session_dec_refcount(session);
432 	}
433 }
434 
435 int l2tp_session_register(struct l2tp_session *session,
436 			  struct l2tp_tunnel *tunnel)
437 {
438 	struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
439 	struct l2tp_session *other_session = NULL;
440 	u32 session_key;
441 	int err;
442 
443 	spin_lock_bh(&tunnel->list_lock);
444 	spin_lock_bh(&pn->l2tp_session_idr_lock);
445 
446 	if (!tunnel->acpt_newsess) {
447 		err = -ENODEV;
448 		goto out;
449 	}
450 
451 	if (tunnel->version == L2TP_HDR_VER_3) {
452 		session_key = session->session_id;
453 		err = idr_alloc_u32(&pn->l2tp_v3_session_idr, NULL,
454 				    &session_key, session_key, GFP_ATOMIC);
455 		/* IP encap expects session IDs to be globally unique, while
456 		 * UDP encap doesn't. This isn't per the RFC, which says that
457 		 * sessions are identified only by the session ID, but is to
458 		 * support existing userspace which depends on it.
459 		 */
460 		if (err == -ENOSPC && tunnel->encap == L2TP_ENCAPTYPE_UDP) {
461 			other_session = idr_find(&pn->l2tp_v3_session_idr,
462 						 session_key);
463 			err = l2tp_session_collision_add(pn, session,
464 							 other_session);
465 		}
466 	} else {
467 		session_key = l2tp_v2_session_key(tunnel->tunnel_id,
468 						  session->session_id);
469 		err = idr_alloc_u32(&pn->l2tp_v2_session_idr, NULL,
470 				    &session_key, session_key, GFP_ATOMIC);
471 	}
472 
473 	if (err) {
474 		if (err == -ENOSPC)
475 			err = -EEXIST;
476 		goto out;
477 	}
478 
479 	l2tp_tunnel_inc_refcount(tunnel);
480 	list_add(&session->list, &tunnel->session_list);
481 
482 	if (tunnel->version == L2TP_HDR_VER_3) {
483 		if (!other_session)
484 			idr_replace(&pn->l2tp_v3_session_idr, session, session_key);
485 	} else {
486 		idr_replace(&pn->l2tp_v2_session_idr, session, session_key);
487 	}
488 
489 out:
490 	spin_unlock_bh(&pn->l2tp_session_idr_lock);
491 	spin_unlock_bh(&tunnel->list_lock);
492 
493 	if (!err)
494 		trace_register_session(session);
495 
496 	return err;
497 }
498 EXPORT_SYMBOL_GPL(l2tp_session_register);
499 
500 /*****************************************************************************
501  * Receive data handling
502  *****************************************************************************/
503 
504 /* Queue a skb in order. We come here only if the skb has an L2TP sequence
505  * number.
506  */
507 static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
508 {
509 	struct sk_buff *skbp;
510 	struct sk_buff *tmp;
511 	u32 ns = L2TP_SKB_CB(skb)->ns;
512 
513 	spin_lock_bh(&session->reorder_q.lock);
514 	skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
515 		if (L2TP_SKB_CB(skbp)->ns > ns) {
516 			__skb_queue_before(&session->reorder_q, skbp, skb);
517 			atomic_long_inc(&session->stats.rx_oos_packets);
518 			goto out;
519 		}
520 	}
521 
522 	__skb_queue_tail(&session->reorder_q, skb);
523 
524 out:
525 	spin_unlock_bh(&session->reorder_q.lock);
526 }
527 
528 /* Dequeue a single skb.
529  */
530 static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
531 {
532 	struct l2tp_tunnel *tunnel = session->tunnel;
533 	int length = L2TP_SKB_CB(skb)->length;
534 
535 	/* We're about to requeue the skb, so return resources
536 	 * to its current owner (a socket receive buffer).
537 	 */
538 	skb_orphan(skb);
539 
540 	atomic_long_inc(&tunnel->stats.rx_packets);
541 	atomic_long_add(length, &tunnel->stats.rx_bytes);
542 	atomic_long_inc(&session->stats.rx_packets);
543 	atomic_long_add(length, &session->stats.rx_bytes);
544 
545 	if (L2TP_SKB_CB(skb)->has_seq) {
546 		/* Bump our Nr */
547 		session->nr++;
548 		session->nr &= session->nr_max;
549 		trace_session_seqnum_update(session);
550 	}
551 
552 	/* call private receive handler */
553 	if (session->recv_skb)
554 		(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
555 	else
556 		kfree_skb(skb);
557 }
558 
559 /* Dequeue skbs from the session's reorder_q, subject to packet order.
560  * Skbs that have been in the queue for too long are simply discarded.
561  */
562 static void l2tp_recv_dequeue(struct l2tp_session *session)
563 {
564 	struct sk_buff *skb;
565 	struct sk_buff *tmp;
566 
567 	/* If the pkt at the head of the queue has the nr that we
568 	 * expect to send up next, dequeue it and any other
569 	 * in-sequence packets behind it.
570 	 */
571 start:
572 	spin_lock_bh(&session->reorder_q.lock);
573 	skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
574 		struct l2tp_skb_cb *cb = L2TP_SKB_CB(skb);
575 
576 		/* If the packet has been pending on the queue for too long, discard it */
577 		if (time_after(jiffies, cb->expires)) {
578 			atomic_long_inc(&session->stats.rx_seq_discards);
579 			atomic_long_inc(&session->stats.rx_errors);
580 			trace_session_pkt_expired(session, cb->ns);
581 			session->reorder_skip = 1;
582 			__skb_unlink(skb, &session->reorder_q);
583 			kfree_skb(skb);
584 			continue;
585 		}
586 
587 		if (cb->has_seq) {
588 			if (session->reorder_skip) {
589 				session->reorder_skip = 0;
590 				session->nr = cb->ns;
591 				trace_session_seqnum_reset(session);
592 			}
593 			if (cb->ns != session->nr)
594 				goto out;
595 		}
596 		__skb_unlink(skb, &session->reorder_q);
597 
598 		/* Process the skb. We release the queue lock while we
599 		 * do so to let other contexts process the queue.
600 		 */
601 		spin_unlock_bh(&session->reorder_q.lock);
602 		l2tp_recv_dequeue_skb(session, skb);
603 		goto start;
604 	}
605 
606 out:
607 	spin_unlock_bh(&session->reorder_q.lock);
608 }
609 
610 static int l2tp_seq_check_rx_window(struct l2tp_session *session, u32 nr)
611 {
612 	u32 nws;
613 
614 	if (nr >= session->nr)
615 		nws = nr - session->nr;
616 	else
617 		nws = (session->nr_max + 1) - (session->nr - nr);
618 
619 	return nws < session->nr_window_size;
620 }
621 
622 /* If packet has sequence numbers, queue it if acceptable. Returns 0 if
623  * acceptable, else non-zero.
624  */
625 static int l2tp_recv_data_seq(struct l2tp_session *session, struct sk_buff *skb)
626 {
627 	struct l2tp_skb_cb *cb = L2TP_SKB_CB(skb);
628 
629 	if (!l2tp_seq_check_rx_window(session, cb->ns)) {
630 		/* Packet sequence number is outside allowed window.
631 		 * Discard it.
632 		 */
633 		trace_session_pkt_outside_rx_window(session, cb->ns);
634 		goto discard;
635 	}
636 
637 	if (session->reorder_timeout != 0) {
638 		/* Packet reordering enabled. Add skb to session's
639 		 * reorder queue, in order of ns.
640 		 */
641 		l2tp_recv_queue_skb(session, skb);
642 		goto out;
643 	}
644 
645 	/* Packet reordering disabled. Discard out-of-sequence packets, while
646 	 * tracking the number if in-sequence packets after the first OOS packet
647 	 * is seen. After nr_oos_count_max in-sequence packets, reset the
648 	 * sequence number to re-enable packet reception.
649 	 */
650 	if (cb->ns == session->nr) {
651 		skb_queue_tail(&session->reorder_q, skb);
652 	} else {
653 		u32 nr_oos = cb->ns;
654 		u32 nr_next = (session->nr_oos + 1) & session->nr_max;
655 
656 		if (nr_oos == nr_next)
657 			session->nr_oos_count++;
658 		else
659 			session->nr_oos_count = 0;
660 
661 		session->nr_oos = nr_oos;
662 		if (session->nr_oos_count > session->nr_oos_count_max) {
663 			session->reorder_skip = 1;
664 		}
665 		if (!session->reorder_skip) {
666 			atomic_long_inc(&session->stats.rx_seq_discards);
667 			trace_session_pkt_oos(session, cb->ns);
668 			goto discard;
669 		}
670 		skb_queue_tail(&session->reorder_q, skb);
671 	}
672 
673 out:
674 	return 0;
675 
676 discard:
677 	return 1;
678 }
679 
680 /* Do receive processing of L2TP data frames. We handle both L2TPv2
681  * and L2TPv3 data frames here.
682  *
683  * L2TPv2 Data Message Header
684  *
685  *  0                   1                   2                   3
686  *  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
687  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
688  * |T|L|x|x|S|x|O|P|x|x|x|x|  Ver  |          Length (opt)         |
689  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
690  * |           Tunnel ID           |           Session ID          |
691  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
692  * |             Ns (opt)          |             Nr (opt)          |
693  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
694  * |      Offset Size (opt)        |    Offset pad... (opt)
695  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
696  *
697  * Data frames are marked by T=0. All other fields are the same as
698  * those in L2TP control frames.
699  *
700  * L2TPv3 Data Message Header
701  *
702  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
703  * |                      L2TP Session Header                      |
704  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
705  * |                      L2-Specific Sublayer                     |
706  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
707  * |                        Tunnel Payload                      ...
708  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
709  *
710  * L2TPv3 Session Header Over IP
711  *
712  *  0                   1                   2                   3
713  *  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
714  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
715  * |                           Session ID                          |
716  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
717  * |               Cookie (optional, maximum 64 bits)...
718  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
719  *                                                                 |
720  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
721  *
722  * L2TPv3 L2-Specific Sublayer Format
723  *
724  *  0                   1                   2                   3
725  *  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
726  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
727  * |x|S|x|x|x|x|x|x|              Sequence Number                  |
728  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
729  *
730  * Cookie value and sublayer format are negotiated with the peer when
731  * the session is set up. Unlike L2TPv2, we do not need to parse the
732  * packet header to determine if optional fields are present.
733  *
734  * Caller must already have parsed the frame and determined that it is
735  * a data (not control) frame before coming here. Fields up to the
736  * session-id have already been parsed and ptr points to the data
737  * after the session-id.
738  */
739 void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
740 		      unsigned char *ptr, unsigned char *optr, u16 hdrflags,
741 		      int length)
742 {
743 	struct l2tp_tunnel *tunnel = session->tunnel;
744 	int offset;
745 
746 	/* Parse and check optional cookie */
747 	if (session->peer_cookie_len > 0) {
748 		if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
749 			pr_debug_ratelimited("%s: cookie mismatch (%u/%u). Discarding.\n",
750 					     tunnel->name, tunnel->tunnel_id,
751 					     session->session_id);
752 			atomic_long_inc(&session->stats.rx_cookie_discards);
753 			goto discard;
754 		}
755 		ptr += session->peer_cookie_len;
756 	}
757 
758 	/* Handle the optional sequence numbers. Sequence numbers are
759 	 * in different places for L2TPv2 and L2TPv3.
760 	 *
761 	 * If we are the LAC, enable/disable sequence numbers under
762 	 * the control of the LNS.  If no sequence numbers present but
763 	 * we were expecting them, discard frame.
764 	 */
765 	L2TP_SKB_CB(skb)->has_seq = 0;
766 	if (tunnel->version == L2TP_HDR_VER_2) {
767 		if (hdrflags & L2TP_HDRFLAG_S) {
768 			/* Store L2TP info in the skb */
769 			L2TP_SKB_CB(skb)->ns = ntohs(*(__be16 *)ptr);
770 			L2TP_SKB_CB(skb)->has_seq = 1;
771 			ptr += 2;
772 			/* Skip past nr in the header */
773 			ptr += 2;
774 
775 		}
776 	} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
777 		u32 l2h = ntohl(*(__be32 *)ptr);
778 
779 		if (l2h & 0x40000000) {
780 			/* Store L2TP info in the skb */
781 			L2TP_SKB_CB(skb)->ns = l2h & 0x00ffffff;
782 			L2TP_SKB_CB(skb)->has_seq = 1;
783 		}
784 		ptr += 4;
785 	}
786 
787 	if (L2TP_SKB_CB(skb)->has_seq) {
788 		/* Received a packet with sequence numbers. If we're the LAC,
789 		 * check if we sre sending sequence numbers and if not,
790 		 * configure it so.
791 		 */
792 		if (!session->lns_mode && !session->send_seq) {
793 			trace_session_seqnum_lns_enable(session);
794 			session->send_seq = 1;
795 			l2tp_session_set_header_len(session, tunnel->version);
796 		}
797 	} else {
798 		/* No sequence numbers.
799 		 * If user has configured mandatory sequence numbers, discard.
800 		 */
801 		if (session->recv_seq) {
802 			pr_debug_ratelimited("%s: recv data has no seq numbers when required. Discarding.\n",
803 					     session->name);
804 			atomic_long_inc(&session->stats.rx_seq_discards);
805 			goto discard;
806 		}
807 
808 		/* If we're the LAC and we're sending sequence numbers, the
809 		 * LNS has requested that we no longer send sequence numbers.
810 		 * If we're the LNS and we're sending sequence numbers, the
811 		 * LAC is broken. Discard the frame.
812 		 */
813 		if (!session->lns_mode && session->send_seq) {
814 			trace_session_seqnum_lns_disable(session);
815 			session->send_seq = 0;
816 			l2tp_session_set_header_len(session, tunnel->version);
817 		} else if (session->send_seq) {
818 			pr_debug_ratelimited("%s: recv data has no seq numbers when required. Discarding.\n",
819 					     session->name);
820 			atomic_long_inc(&session->stats.rx_seq_discards);
821 			goto discard;
822 		}
823 	}
824 
825 	/* Session data offset is defined only for L2TPv2 and is
826 	 * indicated by an optional 16-bit value in the header.
827 	 */
828 	if (tunnel->version == L2TP_HDR_VER_2) {
829 		/* If offset bit set, skip it. */
830 		if (hdrflags & L2TP_HDRFLAG_O) {
831 			offset = ntohs(*(__be16 *)ptr);
832 			ptr += 2 + offset;
833 		}
834 	}
835 
836 	offset = ptr - optr;
837 	if (!pskb_may_pull(skb, offset))
838 		goto discard;
839 
840 	__skb_pull(skb, offset);
841 
842 	/* Prepare skb for adding to the session's reorder_q.  Hold
843 	 * packets for max reorder_timeout or 1 second if not
844 	 * reordering.
845 	 */
846 	L2TP_SKB_CB(skb)->length = length;
847 	L2TP_SKB_CB(skb)->expires = jiffies +
848 		(session->reorder_timeout ? session->reorder_timeout : HZ);
849 
850 	/* Add packet to the session's receive queue. Reordering is done here, if
851 	 * enabled. Saved L2TP protocol info is stored in skb->sb[].
852 	 */
853 	if (L2TP_SKB_CB(skb)->has_seq) {
854 		if (l2tp_recv_data_seq(session, skb))
855 			goto discard;
856 	} else {
857 		/* No sequence numbers. Add the skb to the tail of the
858 		 * reorder queue. This ensures that it will be
859 		 * delivered after all previous sequenced skbs.
860 		 */
861 		skb_queue_tail(&session->reorder_q, skb);
862 	}
863 
864 	/* Try to dequeue as many skbs from reorder_q as we can. */
865 	l2tp_recv_dequeue(session);
866 
867 	return;
868 
869 discard:
870 	atomic_long_inc(&session->stats.rx_errors);
871 	kfree_skb(skb);
872 }
873 EXPORT_SYMBOL_GPL(l2tp_recv_common);
874 
875 /* Drop skbs from the session's reorder_q
876  */
877 static void l2tp_session_queue_purge(struct l2tp_session *session)
878 {
879 	struct sk_buff *skb = NULL;
880 
881 	while ((skb = skb_dequeue(&session->reorder_q))) {
882 		atomic_long_inc(&session->stats.rx_errors);
883 		kfree_skb(skb);
884 	}
885 }
886 
887 /* UDP encapsulation receive handler. See net/ipv4/udp.c for details. */
888 int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
889 {
890 	struct l2tp_session *session = NULL;
891 	struct l2tp_tunnel *tunnel = NULL;
892 	struct net *net = sock_net(sk);
893 	unsigned char *ptr, *optr;
894 	u16 hdrflags;
895 	u16 version;
896 	int length;
897 
898 	/* UDP has verified checksum */
899 
900 	/* UDP always verifies the packet length. */
901 	__skb_pull(skb, sizeof(struct udphdr));
902 
903 	/* Short packet? */
904 	if (!pskb_may_pull(skb, L2TP_HDR_SIZE_MAX))
905 		goto pass;
906 
907 	/* Point to L2TP header */
908 	optr = skb->data;
909 	ptr = skb->data;
910 
911 	/* Get L2TP header flags */
912 	hdrflags = ntohs(*(__be16 *)ptr);
913 
914 	/* Get protocol version */
915 	version = hdrflags & L2TP_HDR_VER_MASK;
916 
917 	/* Get length of L2TP packet */
918 	length = skb->len;
919 
920 	/* If type is control packet, it is handled by userspace. */
921 	if (hdrflags & L2TP_HDRFLAG_T)
922 		goto pass;
923 
924 	/* Skip flags */
925 	ptr += 2;
926 
927 	if (version == L2TP_HDR_VER_2) {
928 		u16 tunnel_id, session_id;
929 
930 		/* If length is present, skip it */
931 		if (hdrflags & L2TP_HDRFLAG_L)
932 			ptr += 2;
933 
934 		/* Extract tunnel and session ID */
935 		tunnel_id = ntohs(*(__be16 *)ptr);
936 		ptr += 2;
937 		session_id = ntohs(*(__be16 *)ptr);
938 		ptr += 2;
939 
940 		session = l2tp_v2_session_get(net, tunnel_id, session_id);
941 	} else {
942 		u32 session_id;
943 
944 		ptr += 2;	/* skip reserved bits */
945 		session_id = ntohl(*(__be32 *)ptr);
946 		ptr += 4;
947 
948 		session = l2tp_v3_session_get(net, sk, session_id);
949 	}
950 
951 	if (!session || !session->recv_skb) {
952 		if (session)
953 			l2tp_session_dec_refcount(session);
954 
955 		/* Not found? Pass to userspace to deal with */
956 		goto pass;
957 	}
958 
959 	tunnel = session->tunnel;
960 
961 	/* Check protocol version */
962 	if (version != tunnel->version)
963 		goto invalid;
964 
965 	if (version == L2TP_HDR_VER_3 &&
966 	    l2tp_v3_ensure_opt_in_linear(session, skb, &ptr, &optr)) {
967 		l2tp_session_dec_refcount(session);
968 		goto invalid;
969 	}
970 
971 	l2tp_recv_common(session, skb, ptr, optr, hdrflags, length);
972 	l2tp_session_dec_refcount(session);
973 
974 	return 0;
975 
976 invalid:
977 	atomic_long_inc(&tunnel->stats.rx_invalid);
978 
979 pass:
980 	/* Put UDP header back */
981 	__skb_push(skb, sizeof(struct udphdr));
982 
983 	return 1;
984 }
985 EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
986 
987 /* UDP encapsulation receive error handler. See net/ipv4/udp.c for details. */
988 static void l2tp_udp_encap_err_recv(struct sock *sk, struct sk_buff *skb, int err,
989 				    __be16 port, u32 info, u8 *payload)
990 {
991 	sk->sk_err = err;
992 	sk_error_report(sk);
993 
994 	if (ip_hdr(skb)->version == IPVERSION) {
995 		if (inet_test_bit(RECVERR, sk))
996 			return ip_icmp_error(sk, skb, err, port, info, payload);
997 #if IS_ENABLED(CONFIG_IPV6)
998 	} else {
999 		if (inet6_test_bit(RECVERR6, sk))
1000 			return ipv6_icmp_error(sk, skb, err, port, info, payload);
1001 #endif
1002 	}
1003 }
1004 
1005 /************************************************************************
1006  * Transmit handling
1007  ***********************************************************************/
1008 
1009 /* Build an L2TP header for the session into the buffer provided.
1010  */
1011 static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
1012 {
1013 	struct l2tp_tunnel *tunnel = session->tunnel;
1014 	__be16 *bufp = buf;
1015 	__be16 *optr = buf;
1016 	u16 flags = L2TP_HDR_VER_2;
1017 	u32 tunnel_id = tunnel->peer_tunnel_id;
1018 	u32 session_id = session->peer_session_id;
1019 
1020 	if (session->send_seq)
1021 		flags |= L2TP_HDRFLAG_S;
1022 
1023 	/* Setup L2TP header. */
1024 	*bufp++ = htons(flags);
1025 	*bufp++ = htons(tunnel_id);
1026 	*bufp++ = htons(session_id);
1027 	if (session->send_seq) {
1028 		*bufp++ = htons(session->ns);
1029 		*bufp++ = 0;
1030 		session->ns++;
1031 		session->ns &= 0xffff;
1032 		trace_session_seqnum_update(session);
1033 	}
1034 
1035 	return bufp - optr;
1036 }
1037 
1038 static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
1039 {
1040 	struct l2tp_tunnel *tunnel = session->tunnel;
1041 	char *bufp = buf;
1042 	char *optr = bufp;
1043 
1044 	/* Setup L2TP header. The header differs slightly for UDP and
1045 	 * IP encapsulations. For UDP, there is 4 bytes of flags.
1046 	 */
1047 	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
1048 		u16 flags = L2TP_HDR_VER_3;
1049 		*((__be16 *)bufp) = htons(flags);
1050 		bufp += 2;
1051 		*((__be16 *)bufp) = 0;
1052 		bufp += 2;
1053 	}
1054 
1055 	*((__be32 *)bufp) = htonl(session->peer_session_id);
1056 	bufp += 4;
1057 	if (session->cookie_len) {
1058 		memcpy(bufp, &session->cookie[0], session->cookie_len);
1059 		bufp += session->cookie_len;
1060 	}
1061 	if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
1062 		u32 l2h = 0;
1063 
1064 		if (session->send_seq) {
1065 			l2h = 0x40000000 | session->ns;
1066 			session->ns++;
1067 			session->ns &= 0xffffff;
1068 			trace_session_seqnum_update(session);
1069 		}
1070 
1071 		*((__be32 *)bufp) = htonl(l2h);
1072 		bufp += 4;
1073 	}
1074 
1075 	return bufp - optr;
1076 }
1077 
1078 /* Queue the packet to IP for output: tunnel socket lock must be held */
1079 static int l2tp_xmit_queue(struct l2tp_tunnel *tunnel, struct sk_buff *skb, struct flowi *fl)
1080 {
1081 	int err;
1082 
1083 	skb->ignore_df = 1;
1084 	skb_dst_drop(skb);
1085 #if IS_ENABLED(CONFIG_IPV6)
1086 	if (l2tp_sk_is_v6(tunnel->sock))
1087 		err = inet6_csk_xmit(tunnel->sock, skb, NULL);
1088 	else
1089 #endif
1090 		err = ip_queue_xmit(tunnel->sock, skb, fl);
1091 
1092 	return err >= 0 ? NET_XMIT_SUCCESS : NET_XMIT_DROP;
1093 }
1094 
1095 static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb, unsigned int *len)
1096 {
1097 	struct l2tp_tunnel *tunnel = session->tunnel;
1098 	unsigned int data_len = skb->len;
1099 	struct sock *sk = tunnel->sock;
1100 	int headroom, uhlen, udp_len;
1101 	int ret = NET_XMIT_SUCCESS;
1102 	struct inet_sock *inet;
1103 	struct udphdr *uh;
1104 
1105 	/* Check that there's enough headroom in the skb to insert IP,
1106 	 * UDP and L2TP headers. If not enough, expand it to
1107 	 * make room. Adjust truesize.
1108 	 */
1109 	uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(*uh) : 0;
1110 	headroom = NET_SKB_PAD + sizeof(struct iphdr) + uhlen + session->hdr_len;
1111 	if (skb_cow_head(skb, headroom)) {
1112 		kfree_skb(skb);
1113 		return NET_XMIT_DROP;
1114 	}
1115 
1116 	/* Setup L2TP header */
1117 	if (tunnel->version == L2TP_HDR_VER_2)
1118 		l2tp_build_l2tpv2_header(session, __skb_push(skb, session->hdr_len));
1119 	else
1120 		l2tp_build_l2tpv3_header(session, __skb_push(skb, session->hdr_len));
1121 
1122 	/* Reset skb netfilter state */
1123 	memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1124 	IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED | IPSKB_REROUTED);
1125 	nf_reset_ct(skb);
1126 
1127 	bh_lock_sock_nested(sk);
1128 	if (sock_owned_by_user(sk)) {
1129 		kfree_skb(skb);
1130 		ret = NET_XMIT_DROP;
1131 		goto out_unlock;
1132 	}
1133 
1134 	/* The user-space may change the connection status for the user-space
1135 	 * provided socket at run time: we must check it under the socket lock
1136 	 */
1137 	if (tunnel->fd >= 0 && sk->sk_state != TCP_ESTABLISHED) {
1138 		kfree_skb(skb);
1139 		ret = NET_XMIT_DROP;
1140 		goto out_unlock;
1141 	}
1142 
1143 	/* Report transmitted length before we add encap header, which keeps
1144 	 * statistics consistent for both UDP and IP encap tx/rx paths.
1145 	 */
1146 	*len = skb->len;
1147 
1148 	inet = inet_sk(sk);
1149 	switch (tunnel->encap) {
1150 	case L2TP_ENCAPTYPE_UDP:
1151 		/* Setup UDP header */
1152 		__skb_push(skb, sizeof(*uh));
1153 		skb_reset_transport_header(skb);
1154 		uh = udp_hdr(skb);
1155 		uh->source = inet->inet_sport;
1156 		uh->dest = inet->inet_dport;
1157 		udp_len = uhlen + session->hdr_len + data_len;
1158 		uh->len = htons(udp_len);
1159 
1160 		/* Calculate UDP checksum if configured to do so */
1161 #if IS_ENABLED(CONFIG_IPV6)
1162 		if (l2tp_sk_is_v6(sk))
1163 			udp6_set_csum(udp_get_no_check6_tx(sk),
1164 				      skb, &inet6_sk(sk)->saddr,
1165 				      &sk->sk_v6_daddr, udp_len);
1166 		else
1167 #endif
1168 			udp_set_csum(sk->sk_no_check_tx, skb, inet->inet_saddr,
1169 				     inet->inet_daddr, udp_len);
1170 		break;
1171 
1172 	case L2TP_ENCAPTYPE_IP:
1173 		break;
1174 	}
1175 
1176 	ret = l2tp_xmit_queue(tunnel, skb, &inet->cork.fl);
1177 
1178 out_unlock:
1179 	bh_unlock_sock(sk);
1180 
1181 	return ret;
1182 }
1183 
1184 /* If caller requires the skb to have a ppp header, the header must be
1185  * inserted in the skb data before calling this function.
1186  */
1187 int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb)
1188 {
1189 	unsigned int len = 0;
1190 	int ret;
1191 
1192 	ret = l2tp_xmit_core(session, skb, &len);
1193 	if (ret == NET_XMIT_SUCCESS) {
1194 		atomic_long_inc(&session->tunnel->stats.tx_packets);
1195 		atomic_long_add(len, &session->tunnel->stats.tx_bytes);
1196 		atomic_long_inc(&session->stats.tx_packets);
1197 		atomic_long_add(len, &session->stats.tx_bytes);
1198 	} else {
1199 		atomic_long_inc(&session->tunnel->stats.tx_errors);
1200 		atomic_long_inc(&session->stats.tx_errors);
1201 	}
1202 	return ret;
1203 }
1204 EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
1205 
1206 /*****************************************************************************
1207  * Tinnel and session create/destroy.
1208  *****************************************************************************/
1209 
1210 /* Tunnel socket destruct hook.
1211  * The tunnel context is deleted only when all session sockets have been
1212  * closed.
1213  */
1214 static void l2tp_tunnel_destruct(struct sock *sk)
1215 {
1216 	struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
1217 
1218 	if (!tunnel)
1219 		goto end;
1220 
1221 	/* Disable udp encapsulation */
1222 	switch (tunnel->encap) {
1223 	case L2TP_ENCAPTYPE_UDP:
1224 		/* No longer an encapsulation socket. See net/ipv4/udp.c */
1225 		WRITE_ONCE(udp_sk(sk)->encap_type, 0);
1226 		udp_sk(sk)->encap_rcv = NULL;
1227 		udp_sk(sk)->encap_destroy = NULL;
1228 		break;
1229 	case L2TP_ENCAPTYPE_IP:
1230 		break;
1231 	}
1232 
1233 	/* Remove hooks into tunnel socket */
1234 	write_lock_bh(&sk->sk_callback_lock);
1235 	sk->sk_destruct = tunnel->old_sk_destruct;
1236 	sk->sk_user_data = NULL;
1237 	write_unlock_bh(&sk->sk_callback_lock);
1238 
1239 	/* Call the original destructor */
1240 	if (sk->sk_destruct)
1241 		(*sk->sk_destruct)(sk);
1242 
1243 	kfree_rcu(tunnel, rcu);
1244 end:
1245 	return;
1246 }
1247 
1248 /* Remove an l2tp session from l2tp_core's lists. */
1249 static void l2tp_session_unhash(struct l2tp_session *session)
1250 {
1251 	struct l2tp_tunnel *tunnel = session->tunnel;
1252 
1253 	if (tunnel) {
1254 		struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1255 		struct l2tp_session *removed = session;
1256 
1257 		spin_lock_bh(&tunnel->list_lock);
1258 		spin_lock_bh(&pn->l2tp_session_idr_lock);
1259 
1260 		/* Remove from the per-tunnel list */
1261 		list_del_init(&session->list);
1262 
1263 		/* Remove from per-net IDR */
1264 		if (tunnel->version == L2TP_HDR_VER_3) {
1265 			if (hash_hashed(&session->hlist))
1266 				l2tp_session_collision_del(pn, session);
1267 			else
1268 				removed = idr_remove(&pn->l2tp_v3_session_idr,
1269 						     session->session_id);
1270 		} else {
1271 			u32 session_key = l2tp_v2_session_key(tunnel->tunnel_id,
1272 							      session->session_id);
1273 			removed = idr_remove(&pn->l2tp_v2_session_idr,
1274 					     session_key);
1275 		}
1276 		WARN_ON_ONCE(removed && removed != session);
1277 
1278 		spin_unlock_bh(&pn->l2tp_session_idr_lock);
1279 		spin_unlock_bh(&tunnel->list_lock);
1280 
1281 		synchronize_rcu();
1282 	}
1283 }
1284 
1285 /* When the tunnel is closed, all the attached sessions need to go too.
1286  */
1287 static void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
1288 {
1289 	struct l2tp_session *session;
1290 
1291 	spin_lock_bh(&tunnel->list_lock);
1292 	tunnel->acpt_newsess = false;
1293 	for (;;) {
1294 		session = list_first_entry_or_null(&tunnel->session_list,
1295 						   struct l2tp_session, list);
1296 		if (!session)
1297 			break;
1298 		l2tp_session_inc_refcount(session);
1299 		list_del_init(&session->list);
1300 		spin_unlock_bh(&tunnel->list_lock);
1301 		l2tp_session_delete(session);
1302 		spin_lock_bh(&tunnel->list_lock);
1303 		l2tp_session_dec_refcount(session);
1304 	}
1305 	spin_unlock_bh(&tunnel->list_lock);
1306 }
1307 
1308 /* Tunnel socket destroy hook for UDP encapsulation */
1309 static void l2tp_udp_encap_destroy(struct sock *sk)
1310 {
1311 	struct l2tp_tunnel *tunnel = l2tp_sk_to_tunnel(sk);
1312 
1313 	if (tunnel)
1314 		l2tp_tunnel_delete(tunnel);
1315 }
1316 
1317 static void l2tp_tunnel_remove(struct net *net, struct l2tp_tunnel *tunnel)
1318 {
1319 	struct l2tp_net *pn = l2tp_pernet(net);
1320 
1321 	spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
1322 	idr_remove(&pn->l2tp_tunnel_idr, tunnel->tunnel_id);
1323 	spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
1324 }
1325 
1326 /* Workqueue tunnel deletion function */
1327 static void l2tp_tunnel_del_work(struct work_struct *work)
1328 {
1329 	struct l2tp_tunnel *tunnel = container_of(work, struct l2tp_tunnel,
1330 						  del_work);
1331 	struct sock *sk = tunnel->sock;
1332 	struct socket *sock = sk->sk_socket;
1333 
1334 	l2tp_tunnel_closeall(tunnel);
1335 
1336 	/* If the tunnel socket was created within the kernel, use
1337 	 * the sk API to release it here.
1338 	 */
1339 	if (tunnel->fd < 0) {
1340 		if (sock) {
1341 			kernel_sock_shutdown(sock, SHUT_RDWR);
1342 			sock_release(sock);
1343 		}
1344 	}
1345 
1346 	l2tp_tunnel_remove(tunnel->l2tp_net, tunnel);
1347 	/* drop initial ref */
1348 	l2tp_tunnel_dec_refcount(tunnel);
1349 
1350 	/* drop workqueue ref */
1351 	l2tp_tunnel_dec_refcount(tunnel);
1352 }
1353 
1354 /* Create a socket for the tunnel, if one isn't set up by
1355  * userspace. This is used for static tunnels where there is no
1356  * managing L2TP daemon.
1357  *
1358  * Since we don't want these sockets to keep a namespace alive by
1359  * themselves, we drop the socket's namespace refcount after creation.
1360  * These sockets are freed when the namespace exits using the pernet
1361  * exit hook.
1362  */
1363 static int l2tp_tunnel_sock_create(struct net *net,
1364 				   u32 tunnel_id,
1365 				   u32 peer_tunnel_id,
1366 				   struct l2tp_tunnel_cfg *cfg,
1367 				   struct socket **sockp)
1368 {
1369 	int err = -EINVAL;
1370 	struct socket *sock = NULL;
1371 	struct udp_port_cfg udp_conf;
1372 
1373 	switch (cfg->encap) {
1374 	case L2TP_ENCAPTYPE_UDP:
1375 		memset(&udp_conf, 0, sizeof(udp_conf));
1376 
1377 #if IS_ENABLED(CONFIG_IPV6)
1378 		if (cfg->local_ip6 && cfg->peer_ip6) {
1379 			udp_conf.family = AF_INET6;
1380 			memcpy(&udp_conf.local_ip6, cfg->local_ip6,
1381 			       sizeof(udp_conf.local_ip6));
1382 			memcpy(&udp_conf.peer_ip6, cfg->peer_ip6,
1383 			       sizeof(udp_conf.peer_ip6));
1384 			udp_conf.use_udp6_tx_checksums =
1385 			  !cfg->udp6_zero_tx_checksums;
1386 			udp_conf.use_udp6_rx_checksums =
1387 			  !cfg->udp6_zero_rx_checksums;
1388 		} else
1389 #endif
1390 		{
1391 			udp_conf.family = AF_INET;
1392 			udp_conf.local_ip = cfg->local_ip;
1393 			udp_conf.peer_ip = cfg->peer_ip;
1394 			udp_conf.use_udp_checksums = cfg->use_udp_checksums;
1395 		}
1396 
1397 		udp_conf.local_udp_port = htons(cfg->local_udp_port);
1398 		udp_conf.peer_udp_port = htons(cfg->peer_udp_port);
1399 
1400 		err = udp_sock_create(net, &udp_conf, &sock);
1401 		if (err < 0)
1402 			goto out;
1403 
1404 		break;
1405 
1406 	case L2TP_ENCAPTYPE_IP:
1407 #if IS_ENABLED(CONFIG_IPV6)
1408 		if (cfg->local_ip6 && cfg->peer_ip6) {
1409 			struct sockaddr_l2tpip6 ip6_addr = {0};
1410 
1411 			err = sock_create_kern(net, AF_INET6, SOCK_DGRAM,
1412 					       IPPROTO_L2TP, &sock);
1413 			if (err < 0)
1414 				goto out;
1415 
1416 			ip6_addr.l2tp_family = AF_INET6;
1417 			memcpy(&ip6_addr.l2tp_addr, cfg->local_ip6,
1418 			       sizeof(ip6_addr.l2tp_addr));
1419 			ip6_addr.l2tp_conn_id = tunnel_id;
1420 			err = kernel_bind(sock, (struct sockaddr *)&ip6_addr,
1421 					  sizeof(ip6_addr));
1422 			if (err < 0)
1423 				goto out;
1424 
1425 			ip6_addr.l2tp_family = AF_INET6;
1426 			memcpy(&ip6_addr.l2tp_addr, cfg->peer_ip6,
1427 			       sizeof(ip6_addr.l2tp_addr));
1428 			ip6_addr.l2tp_conn_id = peer_tunnel_id;
1429 			err = kernel_connect(sock,
1430 					     (struct sockaddr *)&ip6_addr,
1431 					     sizeof(ip6_addr), 0);
1432 			if (err < 0)
1433 				goto out;
1434 		} else
1435 #endif
1436 		{
1437 			struct sockaddr_l2tpip ip_addr = {0};
1438 
1439 			err = sock_create_kern(net, AF_INET, SOCK_DGRAM,
1440 					       IPPROTO_L2TP, &sock);
1441 			if (err < 0)
1442 				goto out;
1443 
1444 			ip_addr.l2tp_family = AF_INET;
1445 			ip_addr.l2tp_addr = cfg->local_ip;
1446 			ip_addr.l2tp_conn_id = tunnel_id;
1447 			err = kernel_bind(sock, (struct sockaddr *)&ip_addr,
1448 					  sizeof(ip_addr));
1449 			if (err < 0)
1450 				goto out;
1451 
1452 			ip_addr.l2tp_family = AF_INET;
1453 			ip_addr.l2tp_addr = cfg->peer_ip;
1454 			ip_addr.l2tp_conn_id = peer_tunnel_id;
1455 			err = kernel_connect(sock, (struct sockaddr *)&ip_addr,
1456 					     sizeof(ip_addr), 0);
1457 			if (err < 0)
1458 				goto out;
1459 		}
1460 		break;
1461 
1462 	default:
1463 		goto out;
1464 	}
1465 
1466 out:
1467 	*sockp = sock;
1468 	if (err < 0 && sock) {
1469 		kernel_sock_shutdown(sock, SHUT_RDWR);
1470 		sock_release(sock);
1471 		*sockp = NULL;
1472 	}
1473 
1474 	return err;
1475 }
1476 
1477 int l2tp_tunnel_create(int fd, int version, u32 tunnel_id, u32 peer_tunnel_id,
1478 		       struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
1479 {
1480 	struct l2tp_tunnel *tunnel = NULL;
1481 	int err;
1482 	enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
1483 
1484 	if (cfg)
1485 		encap = cfg->encap;
1486 
1487 	tunnel = kzalloc(sizeof(*tunnel), GFP_KERNEL);
1488 	if (!tunnel) {
1489 		err = -ENOMEM;
1490 		goto err;
1491 	}
1492 
1493 	tunnel->version = version;
1494 	tunnel->tunnel_id = tunnel_id;
1495 	tunnel->peer_tunnel_id = peer_tunnel_id;
1496 
1497 	tunnel->magic = L2TP_TUNNEL_MAGIC;
1498 	sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
1499 	spin_lock_init(&tunnel->list_lock);
1500 	tunnel->acpt_newsess = true;
1501 	INIT_LIST_HEAD(&tunnel->session_list);
1502 
1503 	tunnel->encap = encap;
1504 
1505 	refcount_set(&tunnel->ref_count, 1);
1506 	tunnel->fd = fd;
1507 
1508 	/* Init delete workqueue struct */
1509 	INIT_WORK(&tunnel->del_work, l2tp_tunnel_del_work);
1510 
1511 	err = 0;
1512 err:
1513 	if (tunnelp)
1514 		*tunnelp = tunnel;
1515 
1516 	return err;
1517 }
1518 EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
1519 
1520 static int l2tp_validate_socket(const struct sock *sk, const struct net *net,
1521 				enum l2tp_encap_type encap)
1522 {
1523 	if (!net_eq(sock_net(sk), net))
1524 		return -EINVAL;
1525 
1526 	if (sk->sk_type != SOCK_DGRAM)
1527 		return -EPROTONOSUPPORT;
1528 
1529 	if (sk->sk_family != PF_INET && sk->sk_family != PF_INET6)
1530 		return -EPROTONOSUPPORT;
1531 
1532 	if ((encap == L2TP_ENCAPTYPE_UDP && sk->sk_protocol != IPPROTO_UDP) ||
1533 	    (encap == L2TP_ENCAPTYPE_IP && sk->sk_protocol != IPPROTO_L2TP))
1534 		return -EPROTONOSUPPORT;
1535 
1536 	if (sk->sk_user_data)
1537 		return -EBUSY;
1538 
1539 	return 0;
1540 }
1541 
1542 int l2tp_tunnel_register(struct l2tp_tunnel *tunnel, struct net *net,
1543 			 struct l2tp_tunnel_cfg *cfg)
1544 {
1545 	struct l2tp_net *pn = l2tp_pernet(net);
1546 	u32 tunnel_id = tunnel->tunnel_id;
1547 	struct socket *sock;
1548 	struct sock *sk;
1549 	int ret;
1550 
1551 	spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
1552 	ret = idr_alloc_u32(&pn->l2tp_tunnel_idr, NULL, &tunnel_id, tunnel_id,
1553 			    GFP_ATOMIC);
1554 	spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
1555 	if (ret)
1556 		return ret == -ENOSPC ? -EEXIST : ret;
1557 
1558 	if (tunnel->fd < 0) {
1559 		ret = l2tp_tunnel_sock_create(net, tunnel->tunnel_id,
1560 					      tunnel->peer_tunnel_id, cfg,
1561 					      &sock);
1562 		if (ret < 0)
1563 			goto err;
1564 	} else {
1565 		sock = sockfd_lookup(tunnel->fd, &ret);
1566 		if (!sock)
1567 			goto err;
1568 	}
1569 
1570 	sk = sock->sk;
1571 	lock_sock(sk);
1572 	write_lock_bh(&sk->sk_callback_lock);
1573 	ret = l2tp_validate_socket(sk, net, tunnel->encap);
1574 	if (ret < 0)
1575 		goto err_inval_sock;
1576 	rcu_assign_sk_user_data(sk, tunnel);
1577 	write_unlock_bh(&sk->sk_callback_lock);
1578 
1579 	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
1580 		struct udp_tunnel_sock_cfg udp_cfg = {
1581 			.sk_user_data = tunnel,
1582 			.encap_type = UDP_ENCAP_L2TPINUDP,
1583 			.encap_rcv = l2tp_udp_encap_recv,
1584 			.encap_err_rcv = l2tp_udp_encap_err_recv,
1585 			.encap_destroy = l2tp_udp_encap_destroy,
1586 		};
1587 
1588 		setup_udp_tunnel_sock(net, sock, &udp_cfg);
1589 	}
1590 
1591 	tunnel->old_sk_destruct = sk->sk_destruct;
1592 	sk->sk_destruct = &l2tp_tunnel_destruct;
1593 	sk->sk_allocation = GFP_ATOMIC;
1594 	release_sock(sk);
1595 
1596 	sock_hold(sk);
1597 	tunnel->sock = sk;
1598 	tunnel->l2tp_net = net;
1599 
1600 	spin_lock_bh(&pn->l2tp_tunnel_idr_lock);
1601 	idr_replace(&pn->l2tp_tunnel_idr, tunnel, tunnel->tunnel_id);
1602 	spin_unlock_bh(&pn->l2tp_tunnel_idr_lock);
1603 
1604 	trace_register_tunnel(tunnel);
1605 
1606 	if (tunnel->fd >= 0)
1607 		sockfd_put(sock);
1608 
1609 	return 0;
1610 
1611 err_inval_sock:
1612 	write_unlock_bh(&sk->sk_callback_lock);
1613 	release_sock(sk);
1614 
1615 	if (tunnel->fd < 0)
1616 		sock_release(sock);
1617 	else
1618 		sockfd_put(sock);
1619 err:
1620 	l2tp_tunnel_remove(net, tunnel);
1621 	return ret;
1622 }
1623 EXPORT_SYMBOL_GPL(l2tp_tunnel_register);
1624 
1625 /* This function is used by the netlink TUNNEL_DELETE command.
1626  */
1627 void l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
1628 {
1629 	if (!test_and_set_bit(0, &tunnel->dead)) {
1630 		trace_delete_tunnel(tunnel);
1631 		l2tp_tunnel_inc_refcount(tunnel);
1632 		queue_work(l2tp_wq, &tunnel->del_work);
1633 	}
1634 }
1635 EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
1636 
1637 void l2tp_session_delete(struct l2tp_session *session)
1638 {
1639 	if (test_and_set_bit(0, &session->dead))
1640 		return;
1641 
1642 	trace_delete_session(session);
1643 	l2tp_session_unhash(session);
1644 	l2tp_session_queue_purge(session);
1645 	if (session->session_close)
1646 		(*session->session_close)(session);
1647 
1648 	l2tp_session_dec_refcount(session);
1649 }
1650 EXPORT_SYMBOL_GPL(l2tp_session_delete);
1651 
1652 /* We come here whenever a session's send_seq, cookie_len or
1653  * l2specific_type parameters are set.
1654  */
1655 void l2tp_session_set_header_len(struct l2tp_session *session, int version)
1656 {
1657 	if (version == L2TP_HDR_VER_2) {
1658 		session->hdr_len = 6;
1659 		if (session->send_seq)
1660 			session->hdr_len += 4;
1661 	} else {
1662 		session->hdr_len = 4 + session->cookie_len;
1663 		session->hdr_len += l2tp_get_l2specific_len(session);
1664 		if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
1665 			session->hdr_len += 4;
1666 	}
1667 }
1668 EXPORT_SYMBOL_GPL(l2tp_session_set_header_len);
1669 
1670 struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id,
1671 					 u32 peer_session_id, struct l2tp_session_cfg *cfg)
1672 {
1673 	struct l2tp_session *session;
1674 
1675 	session = kzalloc(sizeof(*session) + priv_size, GFP_KERNEL);
1676 	if (session) {
1677 		session->magic = L2TP_SESSION_MAGIC;
1678 		session->tunnel = tunnel;
1679 
1680 		session->session_id = session_id;
1681 		session->peer_session_id = peer_session_id;
1682 		session->nr = 0;
1683 		if (tunnel->version == L2TP_HDR_VER_2)
1684 			session->nr_max = 0xffff;
1685 		else
1686 			session->nr_max = 0xffffff;
1687 		session->nr_window_size = session->nr_max / 2;
1688 		session->nr_oos_count_max = 4;
1689 
1690 		/* Use NR of first received packet */
1691 		session->reorder_skip = 1;
1692 
1693 		sprintf(&session->name[0], "sess %u/%u",
1694 			tunnel->tunnel_id, session->session_id);
1695 
1696 		skb_queue_head_init(&session->reorder_q);
1697 
1698 		session->hlist_key = l2tp_v3_session_hashkey(tunnel->sock, session->session_id);
1699 		INIT_HLIST_NODE(&session->hlist);
1700 		INIT_LIST_HEAD(&session->clist);
1701 		INIT_LIST_HEAD(&session->list);
1702 
1703 		if (cfg) {
1704 			session->pwtype = cfg->pw_type;
1705 			session->send_seq = cfg->send_seq;
1706 			session->recv_seq = cfg->recv_seq;
1707 			session->lns_mode = cfg->lns_mode;
1708 			session->reorder_timeout = cfg->reorder_timeout;
1709 			session->l2specific_type = cfg->l2specific_type;
1710 			session->cookie_len = cfg->cookie_len;
1711 			memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
1712 			session->peer_cookie_len = cfg->peer_cookie_len;
1713 			memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
1714 		}
1715 
1716 		l2tp_session_set_header_len(session, tunnel->version);
1717 
1718 		refcount_set(&session->ref_count, 1);
1719 
1720 		return session;
1721 	}
1722 
1723 	return ERR_PTR(-ENOMEM);
1724 }
1725 EXPORT_SYMBOL_GPL(l2tp_session_create);
1726 
1727 /*****************************************************************************
1728  * Init and cleanup
1729  *****************************************************************************/
1730 
1731 static __net_init int l2tp_init_net(struct net *net)
1732 {
1733 	struct l2tp_net *pn = net_generic(net, l2tp_net_id);
1734 
1735 	idr_init(&pn->l2tp_tunnel_idr);
1736 	spin_lock_init(&pn->l2tp_tunnel_idr_lock);
1737 
1738 	idr_init(&pn->l2tp_v2_session_idr);
1739 	idr_init(&pn->l2tp_v3_session_idr);
1740 	spin_lock_init(&pn->l2tp_session_idr_lock);
1741 
1742 	return 0;
1743 }
1744 
1745 static __net_exit void l2tp_exit_net(struct net *net)
1746 {
1747 	struct l2tp_net *pn = l2tp_pernet(net);
1748 	struct l2tp_tunnel *tunnel = NULL;
1749 	unsigned long tunnel_id, tmp;
1750 
1751 	rcu_read_lock_bh();
1752 	idr_for_each_entry_ul(&pn->l2tp_tunnel_idr, tunnel, tmp, tunnel_id) {
1753 		if (tunnel)
1754 			l2tp_tunnel_delete(tunnel);
1755 	}
1756 	rcu_read_unlock_bh();
1757 
1758 	if (l2tp_wq)
1759 		flush_workqueue(l2tp_wq);
1760 	rcu_barrier();
1761 
1762 	idr_destroy(&pn->l2tp_v2_session_idr);
1763 	idr_destroy(&pn->l2tp_v3_session_idr);
1764 	idr_destroy(&pn->l2tp_tunnel_idr);
1765 }
1766 
1767 static struct pernet_operations l2tp_net_ops = {
1768 	.init = l2tp_init_net,
1769 	.exit = l2tp_exit_net,
1770 	.id   = &l2tp_net_id,
1771 	.size = sizeof(struct l2tp_net),
1772 };
1773 
1774 static int __init l2tp_init(void)
1775 {
1776 	int rc = 0;
1777 
1778 	rc = register_pernet_device(&l2tp_net_ops);
1779 	if (rc)
1780 		goto out;
1781 
1782 	l2tp_wq = alloc_workqueue("l2tp", WQ_UNBOUND, 0);
1783 	if (!l2tp_wq) {
1784 		pr_err("alloc_workqueue failed\n");
1785 		unregister_pernet_device(&l2tp_net_ops);
1786 		rc = -ENOMEM;
1787 		goto out;
1788 	}
1789 
1790 	pr_info("L2TP core driver, %s\n", L2TP_DRV_VERSION);
1791 
1792 out:
1793 	return rc;
1794 }
1795 
1796 static void __exit l2tp_exit(void)
1797 {
1798 	unregister_pernet_device(&l2tp_net_ops);
1799 	if (l2tp_wq) {
1800 		destroy_workqueue(l2tp_wq);
1801 		l2tp_wq = NULL;
1802 	}
1803 }
1804 
1805 module_init(l2tp_init);
1806 module_exit(l2tp_exit);
1807 
1808 MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
1809 MODULE_DESCRIPTION("L2TP core");
1810 MODULE_LICENSE("GPL");
1811 MODULE_VERSION(L2TP_DRV_VERSION);
1812