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