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