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