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