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