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