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