2 * Copyright (c) 2001-2002 Packet Design, LLC.
5 * Subject to the following obligations and disclaimer of warranty,
6 * use and redistribution of this software, in source or object code
7 * forms, with or without modifications are expressly permitted by
8 * Packet Design; provided, however, that:
10 * (i) Any and all reproductions of the source or object code
11 * must include the copyright notice above and the following
12 * disclaimer of warranties; and
13 * (ii) No rights are granted, in any manner or form, to use
14 * Packet Design trademarks, including the mark "PACKET DESIGN"
15 * on advertising, endorsements, or otherwise except as such
16 * appears in the above copyright notice or in the software.
18 * THIS SOFTWARE IS BEING PROVIDED BY PACKET DESIGN "AS IS", AND
19 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, PACKET DESIGN MAKES NO
20 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING
21 * THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED
22 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
23 * OR NON-INFRINGEMENT. PACKET DESIGN DOES NOT WARRANT, GUARANTEE,
24 * OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS
25 * OF THE USE OF THIS SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY,
26 * RELIABILITY OR OTHERWISE. IN NO EVENT SHALL PACKET DESIGN BE
27 * LIABLE FOR ANY DAMAGES RESULTING FROM OR ARISING OUT OF ANY USE
28 * OF THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY DIRECT,
29 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL
30 * DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF
31 * USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
34 * THE USE OF THIS SOFTWARE, EVEN IF PACKET DESIGN IS ADVISED OF
35 * THE POSSIBILITY OF SUCH DAMAGE.
37 * Author: Archie Cobbs <archie@freebsd.org>
43 * L2TP netgraph node type.
45 * This node type implements the lower layer of the
46 * L2TP protocol as specified in RFC 2661.
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/kernel.h>
55 #include <sys/malloc.h>
56 #include <sys/errno.h>
57 #include <sys/libkern.h>
59 #include <netgraph/ng_message.h>
60 #include <netgraph/netgraph.h>
61 #include <netgraph/ng_parse.h>
62 #include <netgraph/ng_l2tp.h>
64 #ifdef NG_SEPARATE_MALLOC
65 static MALLOC_DEFINE(M_NETGRAPH_L2TP, "netgraph_l2tp", "netgraph l2tp node");
67 #define M_NETGRAPH_L2TP M_NETGRAPH
70 /* L2TP header format (first 2 bytes only) */
71 #define L2TP_HDR_CTRL 0x8000 /* control packet */
72 #define L2TP_HDR_LEN 0x4000 /* has length field */
73 #define L2TP_HDR_SEQ 0x0800 /* has ns, nr fields */
74 #define L2TP_HDR_OFF 0x0200 /* has offset field */
75 #define L2TP_HDR_PRIO 0x0100 /* give priority */
76 #define L2TP_HDR_VERS_MASK 0x000f /* version field mask */
77 #define L2TP_HDR_VERSION 0x0002 /* version field */
79 /* Bits that must be zero or one in first two bytes of header */
80 #define L2TP_CTRL_0BITS 0x030d /* ctrl: must be 0 */
81 #define L2TP_CTRL_1BITS 0xc802 /* ctrl: must be 1 */
82 #define L2TP_DATA_0BITS 0x800d /* data: must be 0 */
83 #define L2TP_DATA_1BITS 0x0002 /* data: must be 1 */
85 /* Standard xmit ctrl and data header bits */
86 #define L2TP_CTRL_HDR (L2TP_HDR_CTRL | L2TP_HDR_LEN \
87 | L2TP_HDR_SEQ | L2TP_HDR_VERSION)
88 #define L2TP_DATA_HDR (L2TP_HDR_VERSION) /* optional: len, seq */
90 /* Some hard coded values */
91 #define L2TP_MAX_XWIN 128 /* my max xmit window */
92 #define L2TP_MAX_REXMIT 5 /* default max rexmit */
93 #define L2TP_MAX_REXMIT_TO 30 /* default rexmit to */
94 #define L2TP_DELAYED_ACK ((hz + 19) / 20) /* delayed ack: 50 ms */
96 /* Default data sequence number configuration for new sessions */
97 #define L2TP_CONTROL_DSEQ 1 /* we are the lns */
98 #define L2TP_ENABLE_DSEQ 1 /* enable data seq # */
100 /* Compare sequence numbers using circular math */
101 #define L2TP_SEQ_DIFF(x, y) ((int16_t)((x) - (y)))
103 #define SESSHASHSIZE 0x0020
104 #define SESSHASH(x) (((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
106 /* Hook private data (data session hooks only) */
107 struct ng_l2tp_hook_private {
108 struct ng_l2tp_sess_config conf; /* hook/session config */
109 struct ng_l2tp_session_stats stats; /* per sessions statistics */
110 hook_p hook; /* hook reference */
111 u_int16_t ns; /* data ns sequence number */
112 u_int16_t nr; /* data nr sequence number */
113 LIST_ENTRY(ng_l2tp_hook_private) sessions;
115 typedef struct ng_l2tp_hook_private *hookpriv_p;
118 * Sequence number state
121 * - If cwnd < ssth, we're doing slow start, otherwise congestion avoidance
122 * - The number of unacknowledged xmit packets is (ns - rack) <= seq->wmax
123 * - The first (ns - rack) mbuf's in xwin[] array are copies of these
124 * unacknowledged packets; the remainder of xwin[] consists first of
125 * zero or more further untransmitted packets in the transmit queue
126 * - We try to keep the peer's receive window as full as possible.
127 * Therefore, (i < cwnd && xwin[i] != NULL) implies (ns - rack) > i.
128 * - rack_timer is running iff (ns - rack) > 0 (unack'd xmit'd pkts)
129 * - If xack != nr, there are unacknowledged recv packet(s) (delayed ack)
130 * - xack_timer is running iff xack != nr (unack'd rec'd pkts)
133 u_int16_t ns; /* next xmit seq we send */
134 u_int16_t nr; /* next recv seq we expect */
135 u_int16_t inproc; /* packet is in processing */
136 u_int16_t rack; /* last 'nr' we rec'd */
137 u_int16_t xack; /* last 'nr' we sent */
138 u_int16_t wmax; /* peer's max recv window */
139 u_int16_t cwnd; /* current congestion window */
140 u_int16_t ssth; /* slow start threshold */
141 u_int16_t acks; /* # consecutive acks rec'd */
142 u_int16_t rexmits; /* # retransmits sent */
143 struct callout rack_timer; /* retransmit timer */
144 struct callout xack_timer; /* delayed ack timer */
145 struct mbuf *xwin[L2TP_MAX_XWIN]; /* transmit window */
146 struct mtx mtx; /* seq mutex */
149 /* Node private data */
150 struct ng_l2tp_private {
151 node_p node; /* back pointer to node */
152 hook_p ctrl; /* hook to upper layers */
153 hook_p lower; /* hook to lower layers */
154 struct ng_l2tp_config conf; /* node configuration */
155 struct ng_l2tp_stats stats; /* node statistics */
156 struct l2tp_seq seq; /* ctrl sequence number state */
157 ng_ID_t ftarget; /* failure message target */
158 LIST_HEAD(, ng_l2tp_hook_private) sesshash[SESSHASHSIZE];
160 typedef struct ng_l2tp_private *priv_p;
162 /* Netgraph node methods */
163 static ng_constructor_t ng_l2tp_constructor;
164 static ng_rcvmsg_t ng_l2tp_rcvmsg;
165 static ng_shutdown_t ng_l2tp_shutdown;
166 static ng_newhook_t ng_l2tp_newhook;
167 static ng_rcvdata_t ng_l2tp_rcvdata;
168 static ng_rcvdata_t ng_l2tp_rcvdata_lower;
169 static ng_rcvdata_t ng_l2tp_rcvdata_ctrl;
170 static ng_disconnect_t ng_l2tp_disconnect;
172 /* Internal functions */
173 static int ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns);
175 static void ng_l2tp_seq_init(priv_p priv);
176 static int ng_l2tp_seq_set(priv_p priv,
177 const struct ng_l2tp_seq_config *conf);
178 static int ng_l2tp_seq_adjust(priv_p priv,
179 const struct ng_l2tp_config *conf);
180 static void ng_l2tp_seq_reset(priv_p priv);
181 static void ng_l2tp_seq_failure(priv_p priv);
182 static void ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr);
183 static void ng_l2tp_seq_xack_timeout(node_p node, hook_p hook,
184 void *arg1, int arg2);
185 static void ng_l2tp_seq_rack_timeout(node_p node, hook_p hook,
186 void *arg1, int arg2);
188 static hookpriv_p ng_l2tp_find_session(priv_p privp, u_int16_t sid);
189 static ng_fn_eachhook ng_l2tp_reset_session;
191 /* Parse type for struct ng_l2tp_seq_config. */
192 static const struct ng_parse_struct_field
193 ng_l2tp_seq_config_fields[] = NG_L2TP_SEQ_CONFIG_TYPE_INFO;
194 static const struct ng_parse_type ng_l2tp_seq_config_type = {
195 &ng_parse_struct_type,
196 &ng_l2tp_seq_config_fields
199 /* Parse type for struct ng_l2tp_config */
200 static const struct ng_parse_struct_field
201 ng_l2tp_config_type_fields[] = NG_L2TP_CONFIG_TYPE_INFO;
202 static const struct ng_parse_type ng_l2tp_config_type = {
203 &ng_parse_struct_type,
204 &ng_l2tp_config_type_fields,
207 /* Parse type for struct ng_l2tp_sess_config */
208 static const struct ng_parse_struct_field
209 ng_l2tp_sess_config_type_fields[] = NG_L2TP_SESS_CONFIG_TYPE_INFO;
210 static const struct ng_parse_type ng_l2tp_sess_config_type = {
211 &ng_parse_struct_type,
212 &ng_l2tp_sess_config_type_fields,
215 /* Parse type for struct ng_l2tp_stats */
216 static const struct ng_parse_struct_field
217 ng_l2tp_stats_type_fields[] = NG_L2TP_STATS_TYPE_INFO;
218 static const struct ng_parse_type ng_l2tp_stats_type = {
219 &ng_parse_struct_type,
220 &ng_l2tp_stats_type_fields
223 /* Parse type for struct ng_l2tp_session_stats. */
224 static const struct ng_parse_struct_field
225 ng_l2tp_session_stats_type_fields[] = NG_L2TP_SESSION_STATS_TYPE_INFO;
226 static const struct ng_parse_type ng_l2tp_session_stats_type = {
227 &ng_parse_struct_type,
228 &ng_l2tp_session_stats_type_fields
231 /* List of commands and how to convert arguments to/from ASCII */
232 static const struct ng_cmdlist ng_l2tp_cmdlist[] = {
237 &ng_l2tp_config_type,
249 NGM_L2TP_SET_SESS_CONFIG,
251 &ng_l2tp_sess_config_type,
256 NGM_L2TP_GET_SESS_CONFIG,
258 &ng_parse_hint16_type,
259 &ng_l2tp_sess_config_type
277 NGM_L2TP_GETCLR_STATS,
284 NGM_L2TP_GET_SESSION_STATS,
286 &ng_parse_int16_type,
287 &ng_l2tp_session_stats_type
291 NGM_L2TP_CLR_SESSION_STATS,
293 &ng_parse_int16_type,
298 NGM_L2TP_GETCLR_SESSION_STATS,
300 &ng_parse_int16_type,
301 &ng_l2tp_session_stats_type
305 NGM_L2TP_ACK_FAILURE,
314 &ng_l2tp_seq_config_type,
320 /* Node type descriptor */
321 static struct ng_type ng_l2tp_typestruct = {
322 .version = NG_ABI_VERSION,
323 .name = NG_L2TP_NODE_TYPE,
324 .constructor = ng_l2tp_constructor,
325 .rcvmsg = ng_l2tp_rcvmsg,
326 .shutdown = ng_l2tp_shutdown,
327 .newhook = ng_l2tp_newhook,
328 .rcvdata = ng_l2tp_rcvdata,
329 .disconnect = ng_l2tp_disconnect,
330 .cmdlist = ng_l2tp_cmdlist,
332 NETGRAPH_INIT(l2tp, &ng_l2tp_typestruct);
334 /* Sequence number state locking & sanity checking */
336 static void ng_l2tp_seq_check(struct l2tp_seq *seq);
337 #define SEQ_LOCK(seq) do { \
338 mtx_lock(&(seq)->mtx); \
339 ng_l2tp_seq_check(seq); \
341 #define SEQ_UNLOCK(seq) do { \
342 ng_l2tp_seq_check(seq); \
343 mtx_unlock(&(seq)->mtx); \
346 #define SEQ_LOCK(seq) mtx_lock(&(seq)->mtx)
347 #define SEQ_UNLOCK(seq) mtx_unlock(&(seq)->mtx)
349 #define SEQ_LOCK_ASSERT(seq) mtx_assert(&(seq)->mtx, MA_OWNED)
351 /* Whether to use m_copypacket() or m_dup() */
352 #define L2TP_COPY_MBUF m_copypacket
354 #define ERROUT(x) do { error = (x); goto done; } while (0)
356 /************************************************************************
358 ************************************************************************/
361 * Node type constructor
364 ng_l2tp_constructor(node_p node)
369 /* Allocate private structure */
370 priv = malloc(sizeof(*priv), M_NETGRAPH_L2TP, M_WAITOK | M_ZERO);
371 NG_NODE_SET_PRIVATE(node, priv);
374 /* Apply a semi-reasonable default configuration */
375 priv->conf.peer_win = 1;
376 priv->conf.rexmit_max = L2TP_MAX_REXMIT;
377 priv->conf.rexmit_max_to = L2TP_MAX_REXMIT_TO;
379 /* Initialize sequence number state */
380 ng_l2tp_seq_init(priv);
382 for (i = 0; i < SESSHASHSIZE; i++)
383 LIST_INIT(&priv->sesshash[i]);
390 * Give our OK for a hook to be added.
393 ng_l2tp_newhook(node_p node, hook_p hook, const char *name)
395 const priv_p priv = NG_NODE_PRIVATE(node);
397 /* Check hook name */
398 if (strcmp(name, NG_L2TP_HOOK_CTRL) == 0) {
399 if (priv->ctrl != NULL)
402 NG_HOOK_SET_RCVDATA(hook, ng_l2tp_rcvdata_ctrl);
403 } else if (strcmp(name, NG_L2TP_HOOK_LOWER) == 0) {
404 if (priv->lower != NULL)
407 NG_HOOK_SET_RCVDATA(hook, ng_l2tp_rcvdata_lower);
409 static const char hexdig[16] = "0123456789abcdef";
410 u_int16_t session_id;
417 /* Parse hook name to get session ID */
418 if (strncmp(name, NG_L2TP_HOOK_SESSION_P,
419 sizeof(NG_L2TP_HOOK_SESSION_P) - 1) != 0)
421 hex = name + sizeof(NG_L2TP_HOOK_SESSION_P) - 1;
422 for (session_id = i = 0; i < 4; i++) {
423 for (j = 0; j < 16 && hex[i] != hexdig[j]; j++);
426 session_id = (session_id << 4) | j;
431 /* Create hook private structure */
432 hpriv = malloc(sizeof(*hpriv),
433 M_NETGRAPH_L2TP, M_NOWAIT | M_ZERO);
436 hpriv->conf.session_id = session_id;
437 hpriv->conf.control_dseq = L2TP_CONTROL_DSEQ;
438 hpriv->conf.enable_dseq = L2TP_ENABLE_DSEQ;
440 NG_HOOK_SET_PRIVATE(hook, hpriv);
441 hash = SESSHASH(hpriv->conf.session_id);
442 LIST_INSERT_HEAD(&priv->sesshash[hash], hpriv, sessions);
450 * Receive a control message.
453 ng_l2tp_rcvmsg(node_p node, item_p item, hook_p lasthook)
455 const priv_p priv = NG_NODE_PRIVATE(node);
456 struct ng_mesg *resp = NULL;
460 NGI_GET_MSG(item, msg);
461 switch (msg->header.typecookie) {
462 case NGM_L2TP_COOKIE:
463 switch (msg->header.cmd) {
464 case NGM_L2TP_SET_CONFIG:
466 struct ng_l2tp_config *const conf =
467 (struct ng_l2tp_config *)msg->data;
469 /* Check for invalid or illegal config */
470 if (msg->header.arglen != sizeof(*conf)) {
474 conf->enabled = !!conf->enabled;
475 conf->match_id = !!conf->match_id;
476 if (priv->conf.enabled
477 && ((priv->conf.tunnel_id != 0
478 && conf->tunnel_id != priv->conf.tunnel_id)
479 || ((priv->conf.peer_id != 0
480 && conf->peer_id != priv->conf.peer_id)))) {
485 /* Save calling node as failure target */
486 priv->ftarget = NGI_RETADDR(item);
488 /* Adjust sequence number state */
489 if ((error = ng_l2tp_seq_adjust(priv, conf)) != 0)
492 /* Update node's config */
496 case NGM_L2TP_GET_CONFIG:
498 struct ng_l2tp_config *conf;
500 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
505 conf = (struct ng_l2tp_config *)resp->data;
509 case NGM_L2TP_SET_SESS_CONFIG:
511 struct ng_l2tp_sess_config *const conf =
512 (struct ng_l2tp_sess_config *)msg->data;
515 /* Check for invalid or illegal config. */
516 if (msg->header.arglen != sizeof(*conf)) {
521 /* Find matching hook */
522 hpriv = ng_l2tp_find_session(priv, conf->session_id);
528 /* Update hook's config */
532 case NGM_L2TP_GET_SESS_CONFIG:
534 struct ng_l2tp_sess_config *conf;
535 u_int16_t session_id;
539 if (msg->header.arglen != sizeof(session_id)) {
543 memcpy(&session_id, msg->data, 2);
545 /* Find matching hook */
546 hpriv = ng_l2tp_find_session(priv, session_id);
553 NG_MKRESPONSE(resp, msg, sizeof(hpriv->conf), M_NOWAIT);
558 conf = (struct ng_l2tp_sess_config *)resp->data;
562 case NGM_L2TP_GET_STATS:
563 case NGM_L2TP_CLR_STATS:
564 case NGM_L2TP_GETCLR_STATS:
566 if (msg->header.cmd != NGM_L2TP_CLR_STATS) {
567 NG_MKRESPONSE(resp, msg,
568 sizeof(priv->stats), M_NOWAIT);
574 &priv->stats, sizeof(priv->stats));
576 if (msg->header.cmd != NGM_L2TP_GET_STATS)
577 memset(&priv->stats, 0, sizeof(priv->stats));
580 case NGM_L2TP_GET_SESSION_STATS:
581 case NGM_L2TP_CLR_SESSION_STATS:
582 case NGM_L2TP_GETCLR_SESSION_STATS:
587 /* Get session ID. */
588 if (msg->header.arglen != sizeof(session_id)) {
592 bcopy(msg->data, &session_id, sizeof(uint16_t));
594 /* Find matching hook. */
595 hpriv = ng_l2tp_find_session(priv, session_id);
601 if (msg->header.cmd != NGM_L2TP_CLR_SESSION_STATS) {
602 NG_MKRESPONSE(resp, msg,
603 sizeof(hpriv->stats), M_NOWAIT);
608 bcopy(&hpriv->stats, resp->data,
609 sizeof(hpriv->stats));
611 if (msg->header.cmd != NGM_L2TP_GET_SESSION_STATS)
612 bzero(&hpriv->stats, sizeof(hpriv->stats));
615 case NGM_L2TP_SET_SEQ:
617 struct ng_l2tp_seq_config *const conf =
618 (struct ng_l2tp_seq_config *)msg->data;
620 /* Check for invalid or illegal seq config. */
621 if (msg->header.arglen != sizeof(*conf)) {
625 conf->ns = htons(conf->ns);
626 conf->nr = htons(conf->nr);
627 conf->rack = htons(conf->rack);
628 conf->xack = htons(conf->xack);
630 /* Set sequence numbers. */
631 error = ng_l2tp_seq_set(priv, conf);
645 NG_RESPOND_MSG(error, node, item, resp);
654 ng_l2tp_shutdown(node_p node)
656 const priv_p priv = NG_NODE_PRIVATE(node);
657 struct l2tp_seq *const seq = &priv->seq;
659 /* Reset sequence number state */
661 ng_l2tp_seq_reset(priv);
664 /* Free private data if neither timer is running */
665 ng_uncallout(&seq->rack_timer, node);
666 ng_uncallout(&seq->xack_timer, node);
668 mtx_destroy(&seq->mtx);
670 free(priv, M_NETGRAPH_L2TP);
681 ng_l2tp_disconnect(hook_p hook)
683 const node_p node = NG_HOOK_NODE(hook);
684 const priv_p priv = NG_NODE_PRIVATE(node);
686 /* Zero out hook pointer */
687 if (hook == priv->ctrl)
689 else if (hook == priv->lower)
692 const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
693 LIST_REMOVE(hpriv, sessions);
694 free(hpriv, M_NETGRAPH_L2TP);
695 NG_HOOK_SET_PRIVATE(hook, NULL);
698 /* Go away if no longer connected to anything */
699 if (NG_NODE_NUMHOOKS(node) == 0 && NG_NODE_IS_VALID(node))
700 ng_rmnode_self(node);
704 /*************************************************************************
706 *************************************************************************/
709 * Find the hook with a given session ID.
712 ng_l2tp_find_session(priv_p privp, u_int16_t sid)
714 uint16_t hash = SESSHASH(sid);
715 hookpriv_p hpriv = NULL;
717 LIST_FOREACH(hpriv, &privp->sesshash[hash], sessions) {
718 if (hpriv->conf.session_id == sid)
726 * Reset a hook's session state.
729 ng_l2tp_reset_session(hook_p hook, void *arg)
731 const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
734 hpriv->conf.control_dseq = 0;
735 hpriv->conf.enable_dseq = 0;
736 bzero(&hpriv->stats, sizeof(struct ng_l2tp_session_stats));
744 * Handle an incoming frame from below.
747 ng_l2tp_rcvdata_lower(hook_p h, item_p item)
749 static const u_int16_t req_bits[2][2] = {
750 { L2TP_DATA_0BITS, L2TP_DATA_1BITS },
751 { L2TP_CTRL_0BITS, L2TP_CTRL_1BITS },
753 const node_p node = NG_HOOK_NODE(h);
754 const priv_p priv = NG_NODE_PRIVATE(node);
755 hookpriv_p hpriv = NULL;
765 /* If not configured, reject */
766 if (!priv->conf.enabled) {
774 /* Remember full packet length; needed for per session accounting. */
775 plen = m->m_pkthdr.len;
778 priv->stats.recvPackets++;
779 priv->stats.recvOctets += plen;
781 /* Get initial header */
782 if (m->m_pkthdr.len < 6) {
783 priv->stats.recvRunts++;
788 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
789 priv->stats.memoryFailures++;
793 hdr = (mtod(m, uint8_t *)[0] << 8) + mtod(m, uint8_t *)[1];
796 /* Check required header bits and minimum length */
797 is_ctrl = (hdr & L2TP_HDR_CTRL) != 0;
798 if ((hdr & req_bits[is_ctrl][0]) != 0
799 || (~hdr & req_bits[is_ctrl][1]) != 0) {
800 priv->stats.recvInvalid++;
805 if (m->m_pkthdr.len < 4 /* tunnel, session id */
806 + (2 * ((hdr & L2TP_HDR_LEN) != 0)) /* length field */
807 + (4 * ((hdr & L2TP_HDR_SEQ) != 0)) /* seq # fields */
808 + (2 * ((hdr & L2TP_HDR_OFF) != 0))) { /* offset field */
809 priv->stats.recvRunts++;
815 /* Get and validate length field if present */
816 if ((hdr & L2TP_HDR_LEN) != 0) {
817 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
818 priv->stats.memoryFailures++;
822 len = (mtod(m, uint8_t *)[0] << 8) + mtod(m, uint8_t *)[1] - 4;
824 if (len < 0 || len > m->m_pkthdr.len) {
825 priv->stats.recvInvalid++;
830 if (len < m->m_pkthdr.len) /* trim extra bytes */
831 m_adj(m, -(m->m_pkthdr.len - len));
834 /* Get tunnel ID and session ID */
835 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
836 priv->stats.memoryFailures++;
840 tid = (mtod(m, u_int8_t *)[0] << 8) + mtod(m, u_int8_t *)[1];
841 sid = (mtod(m, u_int8_t *)[2] << 8) + mtod(m, u_int8_t *)[3];
844 /* Check tunnel ID */
845 if (tid != priv->conf.tunnel_id &&
846 (priv->conf.match_id || tid != 0)) {
847 priv->stats.recvWrongTunnel++;
850 ERROUT(EADDRNOTAVAIL);
853 /* Check session ID (for data packets only) */
854 if ((hdr & L2TP_HDR_CTRL) == 0) {
855 hpriv = ng_l2tp_find_session(priv, sid);
857 priv->stats.recvUnknownSID++;
865 /* Get Ns, Nr fields if present */
866 if ((hdr & L2TP_HDR_SEQ) != 0) {
867 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
868 priv->stats.memoryFailures++;
872 ns = (mtod(m, u_int8_t *)[0] << 8) + mtod(m, u_int8_t *)[1];
873 nr = (mtod(m, u_int8_t *)[2] << 8) + mtod(m, u_int8_t *)[3];
878 /* Strip offset padding if present */
879 if ((hdr & L2TP_HDR_OFF) != 0) {
882 /* Get length of offset padding */
883 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
884 priv->stats.memoryFailures++;
888 offset = (mtod(m, u_int8_t *)[0] << 8) + mtod(m, u_int8_t *)[1];
890 /* Trim offset padding */
891 if ((2+offset) > m->m_pkthdr.len) {
892 priv->stats.recvInvalid++;
900 /* Handle control packets */
901 if ((hdr & L2TP_HDR_CTRL) != 0) {
902 struct l2tp_seq *const seq = &priv->seq;
906 /* Handle receive ack sequence number Nr */
907 ng_l2tp_seq_recv_nr(priv, nr);
909 /* Discard ZLB packets */
910 if (m->m_pkthdr.len == 0) {
912 priv->stats.recvZLBs++;
919 * If not what we expect or we are busy, drop packet and
920 * send an immediate ZLB ack.
922 if (ns != seq->nr || seq->inproc) {
923 if (L2TP_SEQ_DIFF(ns, seq->nr) <= 0)
924 priv->stats.recvDuplicates++;
926 priv->stats.recvOutOfOrder++;
927 ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
933 /* Prepend session ID to packet. */
934 M_PREPEND(m, 2, M_NOWAIT);
937 priv->stats.memoryFailures++;
941 mtod(m, u_int8_t *)[0] = sid >> 8;
942 mtod(m, u_int8_t *)[1] = sid & 0xff;
945 * Until we deliver this packet we can't receive next one as
946 * we have no information for sending ack.
951 /* Deliver packet to upper layers */
952 NG_FWD_NEW_DATA(error, item, priv->ctrl, m);
955 /* Ready to process next packet. */
958 /* If packet was successfully delivered send ack. */
960 /* Update recv sequence number */
962 /* Start receive ack timer, if not already running */
963 if (!callout_active(&seq->xack_timer)) {
964 ng_callout(&seq->xack_timer, priv->node, NULL,
965 L2TP_DELAYED_ACK, ng_l2tp_seq_xack_timeout,
974 /* Per session packet, account it. */
975 hpriv->stats.recvPackets++;
976 hpriv->stats.recvOctets += plen;
978 /* Follow peer's lead in data sequencing, if configured to do so */
979 if (!hpriv->conf.control_dseq)
980 hpriv->conf.enable_dseq = ((hdr & L2TP_HDR_SEQ) != 0);
982 /* Handle data sequence numbers if present and enabled */
983 if ((hdr & L2TP_HDR_SEQ) != 0) {
984 if (hpriv->conf.enable_dseq
985 && L2TP_SEQ_DIFF(ns, hpriv->nr) < 0) {
986 NG_FREE_ITEM(item); /* duplicate or out of order */
988 priv->stats.recvDataDrops++;
994 /* Drop empty data packets */
995 if (m->m_pkthdr.len == 0) {
1002 NG_FWD_NEW_DATA(error, item, hook, m);
1008 * Handle an outgoing control frame.
1011 ng_l2tp_rcvdata_ctrl(hook_p hook, item_p item)
1013 const node_p node = NG_HOOK_NODE(hook);
1014 const priv_p priv = NG_NODE_PRIVATE(node);
1015 struct l2tp_seq *const seq = &priv->seq;
1021 /* If not configured, reject */
1022 if (!priv->conf.enabled) {
1027 /* Grab mbuf and discard other stuff XXX */
1031 /* Packet should have session ID prepended */
1032 if (m->m_pkthdr.len < 2) {
1033 priv->stats.xmitInvalid++;
1038 /* Check max length */
1039 if (m->m_pkthdr.len >= 0x10000 - 14) {
1040 priv->stats.xmitTooBig++;
1047 /* Find next empty slot in transmit queue */
1048 for (i = 0; i < L2TP_MAX_XWIN && seq->xwin[i] != NULL; i++);
1049 if (i == L2TP_MAX_XWIN) {
1051 priv->stats.xmitDrops++;
1057 /* If peer's receive window is already full, nothing else to do */
1058 if (i >= seq->cwnd) {
1063 /* Start retransmit timer if not already running */
1064 if (!callout_active(&seq->rack_timer))
1065 ng_callout(&seq->rack_timer, node, NULL,
1066 hz, ng_l2tp_seq_rack_timeout, NULL, 0);
1071 if ((m = L2TP_COPY_MBUF(m, M_NOWAIT)) == NULL) {
1073 priv->stats.memoryFailures++;
1077 /* Send packet and increment xmit sequence number */
1078 error = ng_l2tp_xmit_ctrl(priv, m, ns);
1084 * Handle an outgoing data frame.
1087 ng_l2tp_rcvdata(hook_p hook, item_p item)
1089 const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1090 const hookpriv_p hpriv = NG_HOOK_PRIVATE(hook);
1097 /* If not configured, reject */
1098 if (!priv->conf.enabled) {
1106 /* Check max length */
1107 if (m->m_pkthdr.len >= 0x10000 - 12) {
1108 priv->stats.xmitDataTooBig++;
1114 /* Prepend L2TP header */
1116 + (2 * (hpriv->conf.include_length != 0))
1117 + (4 * (hpriv->conf.enable_dseq != 0)),
1120 priv->stats.memoryFailures++;
1124 p = mtod(m, uint8_t *);
1125 hdr = L2TP_DATA_HDR;
1126 if (hpriv->conf.include_length) {
1127 hdr |= L2TP_HDR_LEN;
1128 p[i++] = m->m_pkthdr.len >> 8;
1129 p[i++] = m->m_pkthdr.len & 0xff;
1131 p[i++] = priv->conf.peer_id >> 8;
1132 p[i++] = priv->conf.peer_id & 0xff;
1133 p[i++] = hpriv->conf.peer_id >> 8;
1134 p[i++] = hpriv->conf.peer_id & 0xff;
1135 if (hpriv->conf.enable_dseq) {
1136 hdr |= L2TP_HDR_SEQ;
1137 p[i++] = hpriv->ns >> 8;
1138 p[i++] = hpriv->ns & 0xff;
1139 p[i++] = hpriv->nr >> 8;
1140 p[i++] = hpriv->nr & 0xff;
1146 /* Update per session stats. */
1147 hpriv->stats.xmitPackets++;
1148 hpriv->stats.xmitOctets += m->m_pkthdr.len;
1150 /* And the global one. */
1151 priv->stats.xmitPackets++;
1152 priv->stats.xmitOctets += m->m_pkthdr.len;
1155 NG_FWD_NEW_DATA(error, item, priv->lower, m);
1161 * Send a message to our controlling node that we've failed.
1164 ng_l2tp_seq_failure(priv_p priv)
1166 struct ng_mesg *msg;
1169 NG_MKMESSAGE(msg, NGM_L2TP_COOKIE, NGM_L2TP_ACK_FAILURE, 0, M_NOWAIT);
1172 NG_SEND_MSG_ID(error, priv->node, msg, priv->ftarget, 0);
1175 /************************************************************************
1176 SEQUENCE NUMBER HANDLING
1177 ************************************************************************/
1180 * Initialize sequence number state.
1183 ng_l2tp_seq_init(priv_p priv)
1185 struct l2tp_seq *const seq = &priv->seq;
1187 KASSERT(priv->conf.peer_win >= 1,
1188 ("%s: peer_win is zero", __func__));
1189 memset(seq, 0, sizeof(*seq));
1191 seq->wmax = priv->conf.peer_win;
1192 if (seq->wmax > L2TP_MAX_XWIN)
1193 seq->wmax = L2TP_MAX_XWIN;
1194 seq->ssth = seq->wmax;
1195 ng_callout_init(&seq->rack_timer);
1196 ng_callout_init(&seq->xack_timer);
1197 mtx_init(&seq->mtx, "ng_l2tp", NULL, MTX_DEF);
1201 * Set sequence number state as given from user.
1204 ng_l2tp_seq_set(priv_p priv, const struct ng_l2tp_seq_config *conf)
1206 struct l2tp_seq *const seq = &priv->seq;
1208 /* If node is enabled, deny update to sequence numbers. */
1209 if (priv->conf.enabled)
1212 /* We only can handle the simple cases. */
1213 if (conf->xack != conf->nr || conf->ns != conf->rack)
1216 /* Set ns,nr,rack,xack parameters. */
1219 seq->rack = conf->rack;
1220 seq->xack = conf->xack;
1226 * Adjust sequence number state accordingly after reconfiguration.
1229 ng_l2tp_seq_adjust(priv_p priv, const struct ng_l2tp_config *conf)
1231 struct l2tp_seq *const seq = &priv->seq;
1236 /* If disabling node, reset state sequence number */
1237 if (!conf->enabled) {
1238 ng_l2tp_seq_reset(priv);
1243 /* Adjust peer's max recv window; it can only increase */
1244 new_wmax = conf->peer_win;
1245 if (new_wmax > L2TP_MAX_XWIN)
1246 new_wmax = L2TP_MAX_XWIN;
1249 if (new_wmax < seq->wmax)
1251 seq->wmax = new_wmax;
1259 * Reset sequence number state.
1262 ng_l2tp_seq_reset(priv_p priv)
1264 struct l2tp_seq *const seq = &priv->seq;
1268 SEQ_LOCK_ASSERT(seq);
1271 ng_uncallout(&seq->rack_timer, priv->node);
1272 ng_uncallout(&seq->xack_timer, priv->node);
1274 /* Free retransmit queue */
1275 for (i = 0; i < L2TP_MAX_XWIN; i++) {
1276 if (seq->xwin[i] == NULL)
1278 m_freem(seq->xwin[i]);
1281 /* Reset session hooks' sequence number states */
1282 NG_NODE_FOREACH_HOOK(priv->node, ng_l2tp_reset_session, NULL, hook);
1284 /* Reset node's sequence number state */
1289 seq->wmax = L2TP_MAX_XWIN;
1291 seq->ssth = seq->wmax;
1294 bzero(seq->xwin, sizeof(seq->xwin));
1298 * Handle receipt of an acknowledgement value (Nr) from peer.
1301 ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr)
1303 struct l2tp_seq *const seq = &priv->seq;
1304 struct mbuf *xwin[L2TP_MAX_XWIN]; /* partial local copy */
1309 SEQ_LOCK_ASSERT(seq);
1311 /* Verify peer's ACK is in range */
1312 if ((nack = L2TP_SEQ_DIFF(nr, seq->rack)) <= 0)
1313 return; /* duplicate ack */
1314 if (L2TP_SEQ_DIFF(nr, seq->ns) > 0) {
1315 priv->stats.recvBadAcks++; /* ack for packet not sent */
1318 KASSERT(nack <= L2TP_MAX_XWIN,
1319 ("%s: nack=%d > %d", __func__, nack, L2TP_MAX_XWIN));
1321 /* Update receive ack stats */
1325 /* Free acknowledged packets and shift up packets in the xmit queue */
1326 for (i = 0; i < nack; i++)
1327 m_freem(seq->xwin[i]);
1328 memmove(seq->xwin, seq->xwin + nack,
1329 (L2TP_MAX_XWIN - nack) * sizeof(*seq->xwin));
1330 memset(seq->xwin + (L2TP_MAX_XWIN - nack), 0,
1331 nack * sizeof(*seq->xwin));
1334 * Do slow-start/congestion avoidance windowing algorithm described
1335 * in RFC 2661, Appendix A. Here we handle a multiple ACK as if each
1336 * ACK had arrived separately.
1338 if (seq->cwnd < seq->wmax) {
1339 /* Handle slow start phase */
1340 if (seq->cwnd < seq->ssth) {
1343 if (seq->cwnd > seq->ssth) { /* into cg.av. phase */
1344 nack = seq->cwnd - seq->ssth;
1345 seq->cwnd = seq->ssth;
1349 /* Handle congestion avoidance phase */
1350 if (seq->cwnd >= seq->ssth) {
1352 while (seq->acks >= seq->cwnd) {
1353 seq->acks -= seq->cwnd;
1354 if (seq->cwnd < seq->wmax)
1360 /* Stop xmit timer */
1361 if (callout_active(&seq->rack_timer))
1362 ng_uncallout(&seq->rack_timer, priv->node);
1364 /* If transmit queue is empty, we're done for now */
1365 if (seq->xwin[0] == NULL)
1368 /* Start restransmit timer again */
1369 ng_callout(&seq->rack_timer, priv->node, NULL,
1370 hz, ng_l2tp_seq_rack_timeout, NULL, 0);
1373 * Send more packets, trying to keep peer's receive window full.
1374 * Make copy of everything we need before lock release.
1378 while ((i = L2TP_SEQ_DIFF(seq->ns, seq->rack)) < seq->cwnd
1379 && seq->xwin[i] != NULL) {
1380 xwin[j++] = seq->xwin[i];
1386 * If there is a memory error, pretend packet was sent, as it
1387 * will get retransmitted later anyway.
1389 for (i = 0; i < j; i++) {
1391 if ((m = L2TP_COPY_MBUF(xwin[i], M_NOWAIT)) == NULL)
1392 priv->stats.memoryFailures++;
1394 ng_l2tp_xmit_ctrl(priv, m, ns);
1402 * Handle an ack timeout. We have an outstanding ack that we
1403 * were hoping to piggy-back, but haven't, so send a ZLB.
1406 ng_l2tp_seq_xack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1408 const priv_p priv = NG_NODE_PRIVATE(node);
1409 struct l2tp_seq *const seq = &priv->seq;
1411 /* Make sure callout is still active before doing anything */
1412 if (callout_pending(&seq->xack_timer) ||
1413 (!callout_active(&seq->xack_timer)))
1419 ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
1421 /* callout_deactivate() is not needed here
1422 as ng_uncallout() was called by ng_l2tp_xmit_ctrl() */
1426 * Handle a transmit timeout. The peer has failed to respond
1427 * with an ack for our packet, so retransmit it.
1430 ng_l2tp_seq_rack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1432 const priv_p priv = NG_NODE_PRIVATE(node);
1433 struct l2tp_seq *const seq = &priv->seq;
1439 /* Make sure callout is still active before doing anything */
1440 if (callout_pending(&seq->rack_timer) ||
1441 !callout_active(&seq->rack_timer)) {
1446 priv->stats.xmitRetransmits++;
1448 /* Have we reached the retransmit limit? If so, notify owner. */
1449 if (seq->rexmits++ >= priv->conf.rexmit_max)
1450 ng_l2tp_seq_failure(priv);
1452 /* Restart timer, this time with an increased delay */
1453 delay = (seq->rexmits > 12) ? (1 << 12) : (1 << seq->rexmits);
1454 if (delay > priv->conf.rexmit_max_to)
1455 delay = priv->conf.rexmit_max_to;
1456 ng_callout(&seq->rack_timer, node, NULL,
1457 hz * delay, ng_l2tp_seq_rack_timeout, NULL, 0);
1459 /* Do slow-start/congestion algorithm windowing algorithm */
1460 seq->ns = seq->rack;
1461 seq->ssth = (seq->cwnd + 1) / 2;
1465 /* Retransmit oldest unack'd packet */
1466 m = L2TP_COPY_MBUF(seq->xwin[0], M_NOWAIT);
1469 priv->stats.memoryFailures++;
1471 ng_l2tp_xmit_ctrl(priv, m, seq->ns++);
1473 /* callout_deactivate() is not needed here
1474 as ng_callout() is getting called each time */
1478 * Transmit a control stream packet, payload optional.
1479 * The transmit sequence number is not incremented.
1480 * Requires seq lock, returns unlocked.
1483 ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns)
1485 struct l2tp_seq *const seq = &priv->seq;
1487 uint16_t nr, session_id = 0;
1490 SEQ_LOCK_ASSERT(seq);
1492 /* Stop ack timer: we're sending an ack with this packet.
1493 Doing this before to keep state predictable after error. */
1494 if (callout_active(&seq->xack_timer))
1495 ng_uncallout(&seq->xack_timer, priv->node);
1497 nr = seq->xack = seq->nr;
1501 /* If no mbuf passed, send an empty packet (ZLB) */
1503 /* Create a new mbuf for ZLB packet */
1504 MGETHDR(m, M_NOWAIT, MT_DATA);
1506 priv->stats.memoryFailures++;
1509 m->m_len = m->m_pkthdr.len = 12;
1510 m->m_pkthdr.rcvif = NULL;
1511 priv->stats.xmitZLBs++;
1513 /* Strip off session ID */
1514 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
1515 priv->stats.memoryFailures++;
1518 session_id = (mtod(m, u_int8_t *)[0] << 8) + mtod(m, u_int8_t *)[1];
1520 /* Make room for L2TP header */
1521 M_PREPEND(m, 10, M_NOWAIT); /* - 2 + 12 = 10 */
1523 priv->stats.memoryFailures++;
1528 * The below requires 12 contiguous bytes for the L2TP header
1529 * to be written into.
1531 m = m_pullup(m, 12);
1533 priv->stats.memoryFailures++;
1538 /* Fill in L2TP header */
1539 p = mtod(m, u_int8_t *);
1540 p[0] = L2TP_CTRL_HDR >> 8;
1541 p[1] = L2TP_CTRL_HDR & 0xff;
1542 p[2] = m->m_pkthdr.len >> 8;
1543 p[3] = m->m_pkthdr.len & 0xff;
1544 p[4] = priv->conf.peer_id >> 8;
1545 p[5] = priv->conf.peer_id & 0xff;
1546 p[6] = session_id >> 8;
1547 p[7] = session_id & 0xff;
1553 /* Update sequence number info and stats */
1554 priv->stats.xmitPackets++;
1555 priv->stats.xmitOctets += m->m_pkthdr.len;
1558 NG_SEND_DATA_ONLY(error, priv->lower, m);
1564 * Sanity check sequence number state.
1567 ng_l2tp_seq_check(struct l2tp_seq *seq)
1569 int self_unack, peer_unack;
1572 #define CHECK(p) KASSERT((p), ("%s: not: %s", __func__, #p))
1574 SEQ_LOCK_ASSERT(seq);
1576 self_unack = L2TP_SEQ_DIFF(seq->nr, seq->xack);
1577 peer_unack = L2TP_SEQ_DIFF(seq->ns, seq->rack);
1578 CHECK(seq->wmax <= L2TP_MAX_XWIN);
1579 CHECK(seq->cwnd >= 1);
1580 CHECK(seq->cwnd <= seq->wmax);
1581 CHECK(seq->ssth >= 1);
1582 CHECK(seq->ssth <= seq->wmax);
1583 if (seq->cwnd < seq->ssth)
1584 CHECK(seq->acks == 0);
1586 CHECK(seq->acks <= seq->cwnd);
1587 CHECK(self_unack >= 0);
1588 CHECK(peer_unack >= 0);
1589 CHECK(peer_unack <= seq->wmax);
1590 CHECK((self_unack == 0) ^ callout_active(&seq->xack_timer));
1591 CHECK((peer_unack == 0) ^ callout_active(&seq->rack_timer));
1592 for (i = 0; i < peer_unack; i++)
1593 CHECK(seq->xwin[i] != NULL);
1594 for ( ; i < seq->cwnd; i++) /* verify peer's recv window full */
1595 CHECK(seq->xwin[i] == NULL);
1599 #endif /* INVARIANTS */