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