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