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