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