Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / netgraph / l2tp / ng_l2tp.c
1
2 /*
3  * Copyright (c) 2001-2002 Packet Design, LLC.
4  * All rights reserved.
5  * 
6  * Subject to the following obligations and disclaimer of warranty,
7  * use and redistribution of this software, in source or object code
8  * forms, with or without modifications are expressly permitted by
9  * Packet Design; provided, however, that:
10  * 
11  *    (i)  Any and all reproductions of the source or object code
12  *         must include the copyright notice above and the following
13  *         disclaimer of warranties; and
14  *    (ii) No rights are granted, in any manner or form, to use
15  *         Packet Design trademarks, including the mark "PACKET DESIGN"
16  *         on advertising, endorsements, or otherwise except as such
17  *         appears in the above copyright notice or in the software.
18  * 
19  * THIS SOFTWARE IS BEING PROVIDED BY PACKET DESIGN "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, PACKET DESIGN MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING
22  * THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED
23  * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
24  * OR NON-INFRINGEMENT.  PACKET DESIGN DOES NOT WARRANT, GUARANTEE,
25  * OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS
26  * OF THE USE OF THIS SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY,
27  * RELIABILITY OR OTHERWISE.  IN NO EVENT SHALL PACKET DESIGN BE
28  * LIABLE FOR ANY DAMAGES RESULTING FROM OR ARISING OUT OF ANY USE
29  * OF THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY DIRECT,
30  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL
31  * DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF
32  * USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
35  * THE USE OF THIS SOFTWARE, EVEN IF PACKET DESIGN IS ADVISED OF
36  * THE POSSIBILITY OF SUCH DAMAGE.
37  * 
38  * Author: Archie Cobbs <archie@freebsd.org>
39  *
40  * $FreeBSD: src/sys/netgraph/ng_l2tp.c,v 1.1.2.1 2002/08/20 23:48:15 archie Exp $
41  */
42
43 /*
44  * L2TP netgraph node type.
45  *
46  * This node type implements the lower layer of the
47  * L2TP protocol as specified in RFC 2661.
48  */
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/time.h>
54 #include <sys/conf.h>
55 #include <sys/mbuf.h>
56 #include <sys/malloc.h>
57 #include <sys/errno.h>
58
59 #include <netgraph/ng_message.h>
60 #include <netgraph/netgraph.h>
61 #include <netgraph/ng_parse.h>
62 #include <netgraph/ng_l2tp.h>
63
64 #ifdef NG_SEPARATE_MALLOC
65 MALLOC_DEFINE(M_NETGRAPH_L2TP, "netgraph_l2tp", "netgraph l2tp node");
66 #else
67 #define M_NETGRAPH_L2TP M_NETGRAPH
68 #endif
69
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 */
78
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 */
84
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 */
89
90 /* Some hard coded values */
91 #define L2TP_MAX_XWIN           16                      /* 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 */
95
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 # */
99
100 /* Compare sequence numbers using circular math */
101 #define L2TP_SEQ_DIFF(x, y)     ((int)((int16_t)(x) - (int16_t)(y)))
102
103 /*
104  * Sequence number state
105  *
106  * Invariants:
107  *    - If cwnd < ssth, we're doing slow start, otherwise congestion avoidance
108  *    - The number of unacknowledged xmit packets is (ns - rack) <= seq->wmax
109  *    - The first (ns - rack) mbuf's in xwin[] array are copies of these
110  *      unacknowledged packets; the remainder of xwin[] consists first of
111  *      zero or more further untransmitted packets in the transmit queue
112  *    - We try to keep the peer's receive window as full as possible.
113  *      Therefore, (i < cwnd && xwin[i] != NULL) implies (ns - rack) > i.
114  *    - rack_timer is running iff (ns - rack) > 0 (unack'd xmit'd pkts)
115  *    - If xack != nr, there are unacknowledged recv packet(s) (delayed ack)
116  *    - xack_timer is running iff xack != nr (unack'd rec'd pkts)
117  */
118 struct l2tp_seq {
119         u_int16_t               ns;             /* next xmit seq we send */
120         u_int16_t               nr;             /* next recv seq we expect */
121         u_int16_t               rack;           /* last 'nr' we rec'd */
122         u_int16_t               xack;           /* last 'nr' we sent */
123         u_int16_t               wmax;           /* peer's max recv window */
124         u_int16_t               cwnd;           /* current congestion window */
125         u_int16_t               ssth;           /* slow start threshold */
126         u_int16_t               acks;           /* # consecutive acks rec'd */
127         u_int16_t               rexmits;        /* # retransmits sent */
128         u_int16_t               max_rexmits;    /* max # retransmits sent */
129         u_int16_t               max_rexmit_to;  /* max retransmit timeout */
130         struct callout          rack_timer;     /* retransmit timer */
131         struct callout          xack_timer;     /* delayed ack timer */
132         u_char                  rack_timer_running;     /* xmit timer running */
133         u_char                  xack_timer_running;     /* ack timer running */
134         struct mbuf             *xwin[L2TP_MAX_XWIN];   /* transmit window */
135 };
136
137 /* Node private data */
138 struct ng_l2tp_private {
139         node_p                  node;           /* back pointer to node */
140         hook_p                  ctrl;           /* hook to upper layers */
141         hook_p                  lower;          /* hook to lower layers */
142         struct ng_l2tp_config   conf;           /* node configuration */
143         struct ng_l2tp_stats    stats;          /* node statistics */
144         struct l2tp_seq         seq;            /* ctrl sequence number state */
145         char                    *ftarget;       /* failure message target */
146 };
147 typedef struct ng_l2tp_private *priv_p;
148
149 /* Hook private data (data session hooks only) */
150 struct ng_l2tp_hook_private {
151         struct ng_l2tp_sess_config      conf;   /* hook/session config */
152         u_int16_t                       ns;     /* data ns sequence number */
153         u_int16_t                       nr;     /* data nr sequence number */
154 };
155 typedef struct ng_l2tp_hook_private *hookpriv_p;
156
157 /* Netgraph node methods */
158 static ng_constructor_t ng_l2tp_constructor;
159 static ng_rcvmsg_t      ng_l2tp_rcvmsg;
160 static ng_shutdown_t    ng_l2tp_shutdown;
161 static ng_newhook_t     ng_l2tp_newhook;
162 static ng_rcvdata_t     ng_l2tp_rcvdata;
163 static ng_disconnect_t  ng_l2tp_disconnect;
164
165 /* Internal functions */
166 static int      ng_l2tp_recv_lower(node_p node, struct mbuf *m, meta_p meta);
167 static int      ng_l2tp_recv_ctrl(node_p node, struct mbuf *m, meta_p meta);
168 static int      ng_l2tp_recv_data(node_p node,
169                         struct mbuf *m, meta_p meta, hookpriv_p hpriv);
170
171 static int      ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns);
172
173 static void     ng_l2tp_seq_init(priv_p priv);
174 static int      ng_l2tp_seq_adjust(priv_p priv,
175                         const struct ng_l2tp_config *conf);
176 static void     ng_l2tp_seq_reset(priv_p priv);
177 static void     ng_l2tp_seq_failure(priv_p priv);
178 static void     ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr);
179 static int      ng_l2tp_seq_recv_ns(priv_p priv, u_int16_t ns);
180 static void     ng_l2tp_seq_xack_timeout(void *arg);
181 static void     ng_l2tp_seq_rack_timeout(void *arg);
182
183 #ifdef INVARIANTS
184 static void     ng_l2tp_seq_check(struct l2tp_seq *seq);
185 #endif
186
187 /* Parse type for struct ng_l2tp_config */
188 static const struct ng_parse_struct_field
189         ng_l2tp_config_type_fields[] = NG_L2TP_CONFIG_TYPE_INFO;
190 static const struct ng_parse_type ng_l2tp_config_type = {
191         &ng_parse_struct_type,
192         &ng_l2tp_config_type_fields,
193 };
194
195 /* Parse type for struct ng_l2tp_sess_config */
196 static const struct ng_parse_struct_field
197         ng_l2tp_sess_config_type_fields[] = NG_L2TP_SESS_CONFIG_TYPE_INFO;
198 static const struct ng_parse_type ng_l2tp_sess_config_type = {
199         &ng_parse_struct_type,
200         &ng_l2tp_sess_config_type_fields,
201 };
202
203 /* Parse type for struct ng_l2tp_stats */
204 static const struct ng_parse_struct_field
205         ng_l2tp_stats_type_fields[] = NG_L2TP_STATS_TYPE_INFO;
206 static const struct ng_parse_type ng_pptp_stats_type = {
207         &ng_parse_struct_type,
208         &ng_l2tp_stats_type_fields
209 };
210
211 /* List of commands and how to convert arguments to/from ASCII */
212 static const struct ng_cmdlist ng_l2tp_cmdlist[] = {
213         {
214           NGM_L2TP_COOKIE,
215           NGM_L2TP_SET_CONFIG,
216           "setconfig",
217           &ng_l2tp_config_type,
218           NULL
219         },
220         {
221           NGM_L2TP_COOKIE,
222           NGM_L2TP_GET_CONFIG,
223           "getconfig",
224           NULL,
225           &ng_l2tp_config_type
226         },
227         {
228           NGM_L2TP_COOKIE,
229           NGM_L2TP_SET_SESS_CONFIG,
230           "setsessconfig",
231           &ng_l2tp_sess_config_type,
232           NULL
233         },
234         {
235           NGM_L2TP_COOKIE,
236           NGM_L2TP_GET_SESS_CONFIG,
237           "getsessconfig",
238           &ng_parse_hint16_type,
239           &ng_l2tp_sess_config_type
240         },
241         {
242           NGM_L2TP_COOKIE,
243           NGM_L2TP_GET_STATS,
244           "getstats",
245           NULL,
246           &ng_pptp_stats_type
247         },
248         {
249           NGM_L2TP_COOKIE,
250           NGM_L2TP_CLR_STATS,
251           "clrstats",
252           NULL,
253           NULL
254         },
255         {
256           NGM_L2TP_COOKIE,
257           NGM_L2TP_GETCLR_STATS,
258           "getclrstats",
259           NULL,
260           &ng_pptp_stats_type
261         },
262         {
263           NGM_L2TP_COOKIE,
264           NGM_L2TP_ACK_FAILURE,
265           "ackfailure",
266           NULL,
267           NULL
268         },
269         { 0 }
270 };
271
272 /* Node type descriptor */
273 static struct ng_type ng_l2tp_typestruct = {
274         NG_VERSION,
275         NG_L2TP_NODE_TYPE,
276         NULL,
277         ng_l2tp_constructor,
278         ng_l2tp_rcvmsg,
279         ng_l2tp_shutdown,
280         ng_l2tp_newhook,
281         NULL,
282         NULL,
283         ng_l2tp_rcvdata,
284         ng_l2tp_rcvdata,
285         ng_l2tp_disconnect,
286         ng_l2tp_cmdlist
287 };
288 NETGRAPH_INIT(l2tp, &ng_l2tp_typestruct);
289
290 /* Sequence number state sanity checking */
291 #ifdef INVARIANTS
292 #define L2TP_SEQ_CHECK(seq)     ng_l2tp_seq_check(seq)
293 #else
294 #define L2TP_SEQ_CHECK(x)       do { } while (0)
295 #endif
296
297 /* mem*() macros */
298 #define memmove(d, s, l)        ovbcopy(s, d, l)
299 #define memset(d, z, l)         bzero(d, l)             /* XXX */
300
301 /* Whether to use m_copypacket() or m_dup() */
302 #define L2TP_COPY_MBUF          m_copypacket
303
304 /************************************************************************
305                         NETGRAPH NODE STUFF
306 ************************************************************************/
307
308 /*
309  * Node type constructor
310  */
311 static int
312 ng_l2tp_constructor(node_p *nodep)
313 {
314         priv_p priv;
315         int error;
316
317         /* Allocate private structure */
318         MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_L2TP, M_NOWAIT | M_ZERO);
319         if (priv == NULL)
320                 return (ENOMEM);
321
322         /* Apply a semi-reasonable default configuration */
323         priv->conf.peer_win = 1;
324         priv->conf.rexmit_max = L2TP_MAX_REXMIT;
325         priv->conf.rexmit_max_to = L2TP_MAX_REXMIT_TO;
326
327         /* Initialize sequence number state */
328         ng_l2tp_seq_init(priv);
329
330         /* Call generic node constructor */
331         if ((error = ng_make_node_common(&ng_l2tp_typestruct, nodep))) {
332                 FREE(priv, M_NETGRAPH_L2TP);
333                 return (error);
334         }
335         NG_NODE_SET_PRIVATE(*nodep, priv);
336         priv->node = *nodep;
337
338         /* Done */
339         return (0);
340 }
341
342 /*
343  * Give our OK for a hook to be added.
344  */
345 static int
346 ng_l2tp_newhook(node_p node, hook_p hook, const char *name)
347 {
348         const priv_p priv = NG_NODE_PRIVATE(node);
349
350         /* Check hook name */
351         if (strcmp(name, NG_L2TP_HOOK_CTRL) == 0) {
352                 if (priv->ctrl != NULL)
353                         return (EISCONN);
354                 priv->ctrl = hook;
355         } else if (strcmp(name, NG_L2TP_HOOK_LOWER) == 0) {
356                 if (priv->lower != NULL)
357                         return (EISCONN);
358                 priv->lower = hook;
359         } else {
360                 static const char hexdig[16] = "0123456789abcdef";
361                 u_int16_t session_id;
362                 hookpriv_p hpriv;
363                 const char *hex;
364                 int i;
365                 int j;
366
367                 /* Parse hook name to get session ID */
368                 if (strncmp(name, NG_L2TP_HOOK_SESSION_P,
369                     sizeof(NG_L2TP_HOOK_SESSION_P) - 1) != 0)
370                         return (EINVAL);
371                 hex = name + sizeof(NG_L2TP_HOOK_SESSION_P) - 1;
372                 for (session_id = i = 0; i < 4; i++) {
373                         for (j = 0; j < 16 && hex[i] != hexdig[j]; j++);
374                         if (j == 16)
375                                 return (EINVAL);
376                         session_id = (session_id << 4) | j;
377                 }
378                 if (hex[i] != '\0')
379                         return (EINVAL);
380
381                 /* Create hook private structure */
382                 MALLOC(hpriv, hookpriv_p,
383                     sizeof(*hpriv), M_NETGRAPH_L2TP, M_NOWAIT | M_ZERO);
384                 if (hpriv == NULL)
385                         return (ENOMEM);
386                 hpriv->conf.session_id = htons(session_id);
387                 hpriv->conf.control_dseq = L2TP_CONTROL_DSEQ;
388                 hpriv->conf.enable_dseq = L2TP_ENABLE_DSEQ;
389                 NG_HOOK_SET_PRIVATE(hook, hpriv);
390         }
391
392         /* Done */
393         return (0);
394 }
395
396 /*
397  * Receive a control message.
398  */
399 static int
400 ng_l2tp_rcvmsg(node_p node, struct ng_mesg *msg,
401         const char *raddr, struct ng_mesg **rptr)
402 {
403         const priv_p priv = NG_NODE_PRIVATE(node);
404         struct ng_mesg *resp = NULL;
405         int error = 0;
406
407         switch (msg->header.typecookie) {
408         case NGM_L2TP_COOKIE:
409                 switch (msg->header.cmd) {
410                 case NGM_L2TP_SET_CONFIG:
411                     {
412                         struct ng_l2tp_config *const conf =
413                                 (struct ng_l2tp_config *)msg->data;
414
415                         /* Check for invalid or illegal config */
416                         if (msg->header.arglen != sizeof(*conf)) {
417                                 error = EINVAL;
418                                 break;
419                         }
420                         conf->enabled = !!conf->enabled;
421                         conf->match_id = !!conf->match_id;
422                         conf->tunnel_id = htons(conf->tunnel_id);
423                         conf->peer_id = htons(conf->peer_id);
424                         if (priv->conf.enabled
425                             && ((priv->conf.tunnel_id != 0
426                                && conf->tunnel_id != priv->conf.tunnel_id)
427                               || ((priv->conf.peer_id != 0
428                                && conf->peer_id != priv->conf.peer_id)))) {
429                                 error = EBUSY;
430                                 break;
431                         }
432
433                         /* Save calling node as failure target */
434                         if (priv->ftarget != NULL)
435                                 FREE(priv->ftarget, M_NETGRAPH_L2TP);
436                         MALLOC(priv->ftarget, char *,
437                             strlen(raddr) + 1, M_NETGRAPH_L2TP, M_NOWAIT);
438                         if (priv->ftarget == NULL) {
439                                 error = ENOMEM;
440                                 break;
441                         }
442                         strcpy(priv->ftarget, raddr);
443
444                         /* Adjust sequence number state */
445                         if ((error = ng_l2tp_seq_adjust(priv, conf)) != 0)
446                                 break;
447
448                         /* Update node's config */
449                         priv->conf = *conf;
450                         break;
451                     }
452                 case NGM_L2TP_GET_CONFIG:
453                     {
454                         struct ng_l2tp_config *conf;
455
456                         NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
457                         if (resp == NULL) {
458                                 error = ENOMEM;
459                                 break;
460                         }
461                         conf = (struct ng_l2tp_config *)resp->data;
462                         *conf = priv->conf;
463
464                         /* Put ID's in host order */
465                         conf->tunnel_id = ntohs(conf->tunnel_id);
466                         conf->peer_id = ntohs(conf->peer_id);
467                         break;
468                     }
469                 case NGM_L2TP_SET_SESS_CONFIG:
470                     {
471                         struct ng_l2tp_sess_config *const conf =
472                             (struct ng_l2tp_sess_config *)msg->data;
473                         hookpriv_p hpriv = NULL;
474                         hook_p hook;
475
476                         /* Check for invalid or illegal config */
477                         if (msg->header.arglen != sizeof(*conf)) {
478                                 error = EINVAL;
479                                 break;
480                         }
481
482                         /* Put ID's in network order */
483                         conf->session_id = htons(conf->session_id);
484                         conf->peer_id = htons(conf->peer_id);
485
486                         /* Find matching hook */
487                         LIST_FOREACH(hook, &node->hooks, hooks) {
488                                 if ((hpriv = NG_HOOK_PRIVATE(hook)) == NULL)
489                                         continue;
490                                 if (hpriv->conf.session_id == conf->session_id)
491                                         break;
492                         }
493                         if (hook == NULL) {
494                                 error = ENOENT;
495                                 break;
496                         }
497
498                         /* Update hook's config */
499                         hpriv->conf = *conf;
500                         break;
501                     }
502                 case NGM_L2TP_GET_SESS_CONFIG:
503                     {
504                         struct ng_l2tp_sess_config *conf;
505                         hookpriv_p hpriv = NULL;
506                         u_int16_t session_id;
507                         hook_p hook;
508
509                         /* Get session ID */
510                         if (msg->header.arglen != sizeof(session_id)) {
511                                 error = EINVAL;
512                                 break;
513                         }
514                         memcpy(&session_id, msg->data, 2);
515                         session_id = htons(session_id);
516
517                         /* Find matching hook */
518                         LIST_FOREACH(hook, &node->hooks, hooks) {
519                                 if ((hpriv = NG_HOOK_PRIVATE(hook)) == NULL)
520                                         continue;
521                                 if (hpriv->conf.session_id == session_id)
522                                         break;
523                         }
524                         if (hook == NULL) {
525                                 error = ENOENT;
526                                 break;
527                         }
528
529                         /* Send response */
530                         NG_MKRESPONSE(resp, msg, sizeof(hpriv->conf), M_NOWAIT);
531                         if (resp == NULL) {
532                                 error = ENOMEM;
533                                 break;
534                         }
535                         conf = (struct ng_l2tp_sess_config *)resp->data;
536                         *conf = hpriv->conf;
537
538                         /* Put ID's in host order */
539                         conf->session_id = ntohs(conf->session_id);
540                         conf->peer_id = ntohs(conf->peer_id);
541                         break;
542                     }
543                 case NGM_L2TP_GET_STATS:
544                 case NGM_L2TP_CLR_STATS:
545                 case NGM_L2TP_GETCLR_STATS:
546                     {
547                         if (msg->header.cmd != NGM_L2TP_CLR_STATS) {
548                                 NG_MKRESPONSE(resp, msg,
549                                     sizeof(priv->stats), M_NOWAIT);
550                                 if (resp == NULL) {
551                                         error = ENOMEM;
552                                         break;
553                                 }
554                                 memcpy(resp->data,
555                                     &priv->stats, sizeof(priv->stats));
556                         }
557                         if (msg->header.cmd != NGM_L2TP_GET_STATS)
558                                 memset(&priv->stats, 0, sizeof(priv->stats));
559                         break;
560                     }
561                 default:
562                         error = EINVAL;
563                         break;
564                 }
565                 break;
566         default:
567                 error = EINVAL;
568                 break;
569         }
570         if (rptr)
571                 *rptr = resp;
572         else if (resp)
573                 FREE(resp, M_NETGRAPH);
574         FREE(msg, M_NETGRAPH);
575         return (error);
576 }
577
578 /*
579  * Receive incoming data on a hook.
580  */
581 static int
582 ng_l2tp_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
583 {
584         const node_p node = NG_HOOK_NODE(hook);
585         const priv_p priv = NG_NODE_PRIVATE(node);
586         int error;
587
588         /* Sanity check */
589         L2TP_SEQ_CHECK(&priv->seq);
590
591         /* If not configured, reject */
592         if (!priv->conf.enabled) {
593                 NG_FREE_DATA(m, meta);
594                 return (ENXIO);
595         }
596
597         /* Handle incoming frame from below */
598         if (hook == priv->lower) {
599                 error = ng_l2tp_recv_lower(node, m, meta);
600                 goto done;
601         }
602
603         /* Handle outgoing control frame */
604         if (hook == priv->ctrl) {
605                 error = ng_l2tp_recv_ctrl(node, m, meta);
606                 goto done;
607         }
608
609         /* Handle outgoing data frame */
610         error = ng_l2tp_recv_data(node, m, meta, NG_HOOK_PRIVATE(hook));
611
612 done:
613         /* Done */
614         L2TP_SEQ_CHECK(&priv->seq);
615         return (error);
616 }
617
618 /*
619  * Destroy node
620  */
621 static int
622 ng_l2tp_shutdown(node_p node)
623 {
624         const priv_p priv = NG_NODE_PRIVATE(node);
625         struct l2tp_seq *const seq = &priv->seq;
626
627         /* Sanity check */
628         L2TP_SEQ_CHECK(seq);
629
630         /* Reset sequence number state */
631         node->flags |= NG_INVALID;
632         ng_l2tp_seq_reset(priv);
633         ng_cutlinks(node);
634         ng_unname(node);
635
636         /* Free private data if neither timer is running */
637         if (!seq->rack_timer_running && !seq->xack_timer_running) {
638                 if (priv->ftarget != NULL)
639                         FREE(priv->ftarget, M_NETGRAPH_L2TP);
640                 FREE(priv, M_NETGRAPH_L2TP);
641                 NG_NODE_SET_PRIVATE(node, NULL);
642         }
643
644         /* Unref node */
645         NG_NODE_UNREF(node);
646         return (0);
647 }
648
649 /*
650  * Hook disconnection
651  */
652 static int
653 ng_l2tp_disconnect(hook_p hook)
654 {
655         const node_p node = NG_HOOK_NODE(hook);
656         const priv_p priv = NG_NODE_PRIVATE(node);
657
658         /* Zero out hook pointer */
659         if (hook == priv->ctrl)
660                 priv->ctrl = NULL;
661         else if (hook == priv->lower)
662                 priv->lower = NULL;
663         else {
664                 FREE(NG_HOOK_PRIVATE(hook), M_NETGRAPH_L2TP);
665                 NG_HOOK_SET_PRIVATE(hook, NULL);
666         }
667
668         /* Go away if no longer connected to anything */
669         if (node->numhooks == 0)
670                 ng_rmnode(node);
671         return (0);
672 }
673
674 /*************************************************************************
675                         INTERNAL FUNCTIONS
676 *************************************************************************/
677
678 /*
679  * Handle an incoming frame from below.
680  */
681 static int
682 ng_l2tp_recv_lower(node_p node, struct mbuf *m, meta_p meta)
683 {
684         static const u_int16_t req_bits[2][2] = {
685                 { L2TP_DATA_0BITS, L2TP_DATA_1BITS },
686                 { L2TP_CTRL_0BITS, L2TP_CTRL_1BITS },
687         };
688         const priv_p priv = NG_NODE_PRIVATE(node);
689         hookpriv_p hpriv = NULL;
690         hook_p hook = NULL;
691         u_int16_t ids[2];
692         u_int16_t hdr;
693         u_int16_t ns;
694         u_int16_t nr;
695         int is_ctrl;
696         int error;
697         int len;
698
699         /* Update stats */
700         priv->stats.recvPackets++;
701         priv->stats.recvOctets += m->m_pkthdr.len;
702
703         /* Get initial header */
704         if (m->m_pkthdr.len < 6) {
705                 priv->stats.recvRunts++;
706                 NG_FREE_DATA(m, meta);
707                 return (EINVAL);
708         }
709         if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
710                 priv->stats.memoryFailures++;
711                 NG_FREE_META(meta);
712                 return (EINVAL);
713         }
714         hdr = ntohs(*mtod(m, u_int16_t *));
715         m_adj(m, 2);
716
717         /* Check required header bits and minimum length */
718         is_ctrl = (hdr & L2TP_HDR_CTRL) != 0;
719         if ((hdr & req_bits[is_ctrl][0]) != 0
720             || (~hdr & req_bits[is_ctrl][1]) != 0) {
721                 priv->stats.recvInvalid++;
722                 NG_FREE_DATA(m, meta);
723                 return (EINVAL);
724         }
725         if (m->m_pkthdr.len < 4                         /* tunnel, session id */
726             + (2 * ((hdr & L2TP_HDR_LEN) != 0))         /* length field */
727             + (4 * ((hdr & L2TP_HDR_SEQ) != 0))         /* seq # fields */
728             + (2 * ((hdr & L2TP_HDR_OFF) != 0))) {      /* offset field */
729                 priv->stats.recvRunts++;
730                 NG_FREE_DATA(m, meta);
731                 return (EINVAL);
732         }
733
734         /* Get and validate length field if present */
735         if ((hdr & L2TP_HDR_LEN) != 0) {
736                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
737                         priv->stats.memoryFailures++;
738                         NG_FREE_META(meta);
739                         return (EINVAL);
740                 }
741                 len = (u_int16_t)ntohs(*mtod(m, u_int16_t *)) - 4;
742                 m_adj(m, 2);
743                 if (len < 0 || len > m->m_pkthdr.len) {
744                         priv->stats.recvInvalid++;
745                         NG_FREE_DATA(m, meta);
746                         return (EINVAL);
747                 }
748                 if (len < m->m_pkthdr.len)              /* trim extra bytes */
749                         m_adj(m, -(m->m_pkthdr.len - len));
750         }
751
752         /* Get tunnel ID and session ID */
753         if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
754                 priv->stats.memoryFailures++;
755                 NG_FREE_META(meta);
756                 return (EINVAL);
757         }
758         memcpy(ids, mtod(m, u_int16_t *), 4);
759         m_adj(m, 4);
760
761         /* Check tunnel ID */
762         if (ids[0] != priv->conf.tunnel_id
763             && (priv->conf.match_id || ids[0] != 0)) {
764                 priv->stats.recvWrongTunnel++;
765                 NG_FREE_DATA(m, meta);
766                 return (EADDRNOTAVAIL);
767         }
768
769         /* Check session ID (for data packets only) */
770         if ((hdr & L2TP_HDR_CTRL) == 0) {
771                 LIST_FOREACH(hook, &node->hooks, hooks) {
772                         if ((hpriv = NG_HOOK_PRIVATE(hook)) == NULL)
773                                 continue;
774                         if (hpriv->conf.session_id == ids[1])
775                                 break;
776                 }
777                 if (hook == NULL) {
778                         priv->stats.recvUnknownSID++;
779                         NG_FREE_DATA(m, meta);
780                         return (ENOTCONN);
781                 }
782                 hpriv = NG_HOOK_PRIVATE(hook);
783         }
784
785         /* Get Ns, Nr fields if present */
786         if ((hdr & L2TP_HDR_SEQ) != 0) {
787                 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
788                         priv->stats.memoryFailures++;
789                         NG_FREE_META(meta);
790                         return (EINVAL);
791                 }
792                 memcpy(&ns, &mtod(m, u_int16_t *)[0], 2);
793                 ns = ntohs(ns);
794                 memcpy(&nr, &mtod(m, u_int16_t *)[1], 2);
795                 nr = ntohs(nr);
796                 m_adj(m, 4);
797         }
798
799         /* Strip offset padding if present */
800         if ((hdr & L2TP_HDR_OFF) != 0) {
801                 u_int16_t offset;
802
803                 /* Get length of offset padding */
804                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
805                         priv->stats.memoryFailures++;
806                         NG_FREE_META(meta);
807                         return (EINVAL);
808                 }
809                 memcpy(&offset, mtod(m, u_int16_t *), 2);
810                 offset = ntohs(offset);
811
812                 /* Trim offset padding */
813                 if (offset <= 2 || offset > m->m_pkthdr.len) {
814                         priv->stats.recvInvalid++;
815                         NG_FREE_DATA(m, meta);
816                         return (EINVAL);
817                 }
818                 m_adj(m, offset);
819         }
820
821         /* Handle control packets */
822         if ((hdr & L2TP_HDR_CTRL) != 0) {
823
824                 /* Handle receive ack sequence number Nr */
825                 ng_l2tp_seq_recv_nr(priv, nr);
826
827                 /* Discard ZLB packets */
828                 if (m->m_pkthdr.len == 0) {
829                         priv->stats.recvZLBs++;
830                         NG_FREE_DATA(m, meta);
831                         return (0);
832                 }
833
834                 /*
835                  * Prepend session ID to packet here: we don't want to accept
836                  * the send sequence number Ns if we have to drop the packet
837                  * later because of a memory error, because then the upper
838                  * layer would never get the packet.
839                  */
840                 M_PREPEND(m, 2, M_DONTWAIT);
841                 if (m == NULL) {
842                         priv->stats.memoryFailures++;
843                         NG_FREE_META(meta);
844                         return (ENOBUFS);
845                 }
846                 memcpy(mtod(m, u_int16_t *), &ids[1], 2);
847
848                 /* Now handle send sequence number */
849                 if (ng_l2tp_seq_recv_ns(priv, ns) == -1) {
850                         NG_FREE_DATA(m, meta);
851                         return (0);
852                 }
853
854                 /* Deliver packet to upper layers */
855                 NG_SEND_DATA(error, priv->ctrl, m, meta);
856                 return (error);
857         }
858
859         /* Follow peer's lead in data sequencing, if configured to do so */
860         if (!hpriv->conf.control_dseq)
861                 hpriv->conf.enable_dseq = ((hdr & L2TP_HDR_SEQ) != 0);
862
863         /* Handle data sequence numbers if present and enabled */
864         if ((hdr & L2TP_HDR_SEQ) != 0) {
865                 if (hpriv->conf.enable_dseq
866                     && L2TP_SEQ_DIFF(ns, hpriv->nr) < 0) {
867                         NG_FREE_DATA(m, meta);  /* duplicate or out of order */
868                         priv->stats.recvDataDrops++;
869                         return (0);
870                 }
871                 hpriv->nr = ns + 1;
872         }
873
874         /* Drop empty data packets */
875         if (m->m_pkthdr.len == 0) {
876                 NG_FREE_DATA(m, meta);
877                 return (0);
878         }
879
880         /* Deliver data */
881         NG_SEND_DATA(error, hook, m, meta);
882         return (error);
883 }
884
885 /*
886  * Handle an outgoing control frame.
887  */
888 static int
889 ng_l2tp_recv_ctrl(node_p node, struct mbuf *m, meta_p meta)
890 {
891         const priv_p priv = NG_NODE_PRIVATE(node);
892         struct l2tp_seq *const seq = &priv->seq;
893         int i;
894
895         /* Discard meta XXX should queue meta's along with packet */
896         NG_FREE_META(meta);
897
898         /* Packet should have session ID prepended */
899         if (m->m_pkthdr.len < 2) {
900                 priv->stats.xmitInvalid++;
901                 m_freem(m);
902                 return (EINVAL);
903         }
904
905         /* Check max length */
906         if (m->m_pkthdr.len >= 0x10000 - 14) {
907                 priv->stats.xmitTooBig++;
908                 m_freem(m);
909                 return (EOVERFLOW);
910         }
911
912         /* Find next empty slot in transmit queue */
913         for (i = 0; i < L2TP_MAX_XWIN && seq->xwin[i] != NULL; i++);
914         if (i == L2TP_MAX_XWIN) {
915                 priv->stats.xmitDrops++;
916                 m_freem(m);
917                 return (ENOBUFS);
918         }
919         seq->xwin[i] = m;
920
921         /* Sanity check receive ack timer state */
922         KASSERT((i == 0) ^ seq->rack_timer_running,
923             ("%s: xwin %d full but rack timer %srunning",
924             __FUNCTION__, i, seq->rack_timer_running ? "" : "not "));
925
926         /* If peer's receive window is already full, nothing else to do */
927         if (i >= seq->cwnd)
928                 return (0);
929
930         /* Start retransmit timer if not already running */
931         if (!seq->rack_timer_running) {
932                 callout_reset(&seq->rack_timer,
933                     hz, ng_l2tp_seq_rack_timeout, node);
934                 seq->rack_timer_running = 1;
935                 NG_NODE_REF(node);
936         }
937
938         /* Copy packet */
939         if ((m = L2TP_COPY_MBUF(seq->xwin[i], M_NOWAIT)) == NULL) {
940                 priv->stats.memoryFailures++;
941                 return (ENOBUFS);
942         }
943
944         /* Send packet and increment xmit sequence number */
945         return (ng_l2tp_xmit_ctrl(priv, m, seq->ns++));
946 }
947
948 /*
949  * Handle an outgoing data frame.
950  */
951 static int
952 ng_l2tp_recv_data(node_p node, struct mbuf *m, meta_p meta, hookpriv_p hpriv)
953 {
954         const priv_p priv = NG_NODE_PRIVATE(node);
955         u_int16_t hdr;
956         int error;
957         int i = 1;
958
959         /* Check max length */
960         if (m->m_pkthdr.len >= 0x10000 - 12) {
961                 priv->stats.xmitDataTooBig++;
962                 NG_FREE_META(meta);
963                 m_freem(m);
964                 return (EOVERFLOW);
965         }
966
967         /* Prepend L2TP header */
968         M_PREPEND(m, 6
969             + (2 * (hpriv->conf.include_length != 0))
970             + (4 * (hpriv->conf.enable_dseq != 0)),
971             M_DONTWAIT);
972         if (m == NULL) {
973                 priv->stats.memoryFailures++;
974                 NG_FREE_META(meta);
975                 return (ENOBUFS);
976         }
977         hdr = L2TP_DATA_HDR;
978         if (hpriv->conf.include_length) {
979                 hdr |= L2TP_HDR_LEN;
980                 mtod(m, u_int16_t *)[i++] = htons(m->m_pkthdr.len);
981         }
982         mtod(m, u_int16_t *)[i++] = priv->conf.peer_id;
983         mtod(m, u_int16_t *)[i++] = hpriv->conf.peer_id;
984         if (hpriv->conf.enable_dseq) {
985                 hdr |= L2TP_HDR_SEQ;
986                 mtod(m, u_int16_t *)[i++] = htons(hpriv->ns);
987                 mtod(m, u_int16_t *)[i++] = htons(hpriv->nr);
988                 hpriv->ns++;
989         }
990         mtod(m, u_int16_t *)[0] = htons(hdr);
991
992         /* Send packet */
993         NG_SEND_DATA(error, priv->lower, m, meta);
994         return (error);
995 }
996
997 /*
998  * Send a message to our controlling node that we've failed.
999  */
1000 static void
1001 ng_l2tp_seq_failure(priv_p priv)
1002 {
1003         struct ng_mesg *msg;
1004
1005         NG_MKMESSAGE(msg, NGM_L2TP_COOKIE, NGM_L2TP_ACK_FAILURE, 0, M_NOWAIT);
1006         if (msg == NULL)
1007                 return;
1008         (void)ng_send_msg(priv->node, msg, priv->ftarget, NULL);
1009 }
1010
1011 /************************************************************************
1012                         SEQUENCE NUMBER HANDLING
1013 ************************************************************************/
1014
1015 /*
1016  * Initialize sequence number state.
1017  */
1018 static void
1019 ng_l2tp_seq_init(priv_p priv)
1020 {
1021         struct l2tp_seq *const seq = &priv->seq;
1022
1023         KASSERT(priv->conf.peer_win >= 1,
1024             ("%s: peer_win is zero", __FUNCTION__));
1025         memset(seq, 0, sizeof(*seq));
1026         seq->cwnd = 1;
1027         seq->wmax = priv->conf.peer_win;
1028         if (seq->wmax > L2TP_MAX_XWIN)
1029                 seq->wmax = L2TP_MAX_XWIN;
1030         seq->ssth = seq->wmax;
1031         seq->max_rexmits = priv->conf.rexmit_max;
1032         seq->max_rexmit_to = priv->conf.rexmit_max_to;
1033         callout_init(&seq->rack_timer);
1034         callout_init(&seq->xack_timer);
1035         L2TP_SEQ_CHECK(seq);
1036 }
1037
1038 /*
1039  * Adjust sequence number state accordingly after reconfiguration.
1040  */
1041 static int
1042 ng_l2tp_seq_adjust(priv_p priv, const struct ng_l2tp_config *conf)
1043 {
1044         struct l2tp_seq *const seq = &priv->seq;
1045         u_int16_t new_wmax;
1046
1047         /* If disabling node, reset state sequence number */
1048         if (!conf->enabled) {
1049                 ng_l2tp_seq_reset(priv);
1050                 return (0);
1051         }
1052
1053         /* Adjust peer's max recv window; it can only increase */
1054         new_wmax = conf->peer_win;
1055         if (new_wmax > L2TP_MAX_XWIN)
1056                 new_wmax = L2TP_MAX_XWIN;
1057         if (new_wmax == 0)
1058                 return (EINVAL);
1059         if (new_wmax < seq->wmax)
1060                 return (EBUSY);
1061         seq->wmax = new_wmax;
1062
1063         /* Update retransmit parameters */
1064         seq->max_rexmits = conf->rexmit_max;
1065         seq->max_rexmit_to = conf->rexmit_max_to;
1066
1067         /* Done */
1068         return (0);
1069 }
1070
1071 /*
1072  * Reset sequence number state.
1073  */
1074 static void
1075 ng_l2tp_seq_reset(priv_p priv)
1076 {
1077         struct l2tp_seq *const seq = &priv->seq;
1078         hookpriv_p hpriv = NULL;
1079         hook_p hook;
1080         int i;
1081
1082         /* Sanity check */
1083         L2TP_SEQ_CHECK(seq);
1084
1085         /* Stop timers */
1086         if (seq->rack_timer_running && callout_stop(&seq->rack_timer) == 1) {
1087                 seq->rack_timer_running = 0;
1088                 NG_NODE_UNREF(priv->node);
1089         }
1090         if (seq->xack_timer_running && callout_stop(&seq->xack_timer) == 1) {
1091                 seq->xack_timer_running = 0;
1092                 NG_NODE_UNREF(priv->node);
1093         }
1094
1095         /* Free retransmit queue */
1096         for (i = 0; i < L2TP_MAX_XWIN; i++) {
1097                 if (seq->xwin[i] == NULL)
1098                         break;
1099                 m_freem(seq->xwin[i]);
1100         }
1101
1102         /* Reset session hooks' sequence number states */
1103         LIST_FOREACH(hook, &priv->node->hooks, hooks) {
1104                 if ((hpriv = NG_HOOK_PRIVATE(hook)) == NULL)
1105                         continue;
1106                 hpriv->conf.control_dseq = 0;
1107                 hpriv->conf.enable_dseq = 0;
1108                 hpriv->nr = 0;
1109                 hpriv->ns = 0;
1110         }
1111
1112         /* Reset node's sequence number state */
1113         memset(seq, 0, sizeof(*seq));
1114         seq->cwnd = 1;
1115         seq->wmax = L2TP_MAX_XWIN;
1116         seq->ssth = seq->wmax;
1117
1118         /* Done */
1119         L2TP_SEQ_CHECK(seq);
1120 }
1121
1122 /*
1123  * Handle receipt of an acknowledgement value (Nr) from peer.
1124  */
1125 static void
1126 ng_l2tp_seq_recv_nr(priv_p priv, u_int16_t nr)
1127 {
1128         struct l2tp_seq *const seq = &priv->seq;
1129         struct mbuf *m;
1130         int nack;
1131         int i;
1132
1133         /* Verify peer's ACK is in range */
1134         if ((nack = L2TP_SEQ_DIFF(nr, seq->rack)) <= 0)
1135                 return;                         /* duplicate ack */
1136         if (L2TP_SEQ_DIFF(nr, seq->ns) > 0) {
1137                 priv->stats.recvBadAcks++;      /* ack for packet not sent */
1138                 return;
1139         }
1140         KASSERT(nack <= L2TP_MAX_XWIN,
1141             ("%s: nack=%d > %d", __FUNCTION__, nack, L2TP_MAX_XWIN));
1142
1143         /* Update receive ack stats */
1144         seq->rack = nr;
1145         seq->rexmits = 0;
1146
1147         /* Free acknowledged packets and shift up packets in the xmit queue */
1148         for (i = 0; i < nack; i++)
1149                 m_freem(seq->xwin[i]);
1150         memmove(seq->xwin, seq->xwin + nack,
1151             (L2TP_MAX_XWIN - nack) * sizeof(*seq->xwin));
1152         memset(seq->xwin + (L2TP_MAX_XWIN - nack), 0,
1153             nack * sizeof(*seq->xwin));
1154
1155         /*
1156          * Do slow-start/congestion avoidance windowing algorithm described
1157          * in RFC 2661, Appendix A. Here we handle a multiple ACK as if each
1158          * ACK had arrived separately.
1159          */
1160         if (seq->cwnd < seq->wmax) {
1161
1162                 /* Handle slow start phase */
1163                 if (seq->cwnd < seq->ssth) {
1164                         seq->cwnd += nack;
1165                         nack = 0;
1166                         if (seq->cwnd > seq->ssth) {    /* into cg.av. phase */
1167                                 nack = seq->cwnd - seq->ssth;
1168                                 seq->cwnd = seq->ssth;
1169                         }
1170                 }
1171
1172                 /* Handle congestion avoidance phase */
1173                 if (seq->cwnd >= seq->ssth) {
1174                         seq->acks += nack;
1175                         while (seq->acks >= seq->cwnd) {
1176                                 seq->acks -= seq->cwnd;
1177                                 if (seq->cwnd < seq->wmax)
1178                                         seq->cwnd++;
1179                         }
1180                 }
1181         }
1182
1183         /* Stop xmit timer */
1184         if (seq->rack_timer_running && callout_stop(&seq->rack_timer) == 1) {
1185                 seq->rack_timer_running = 0;
1186                 NG_NODE_UNREF(priv->node);
1187         }
1188
1189         /* If transmit queue is empty, we're done for now */
1190         if (seq->xwin[0] == NULL)
1191                 return;
1192
1193         /* Start restransmit timer again */
1194         callout_reset(&seq->rack_timer,
1195             hz, ng_l2tp_seq_rack_timeout, priv->node);
1196         seq->rack_timer_running = 1;
1197         NG_NODE_REF(priv->node);
1198
1199         /*
1200          * Send more packets, trying to keep peer's receive window full.
1201          * If there is a memory error, pretend packet was sent, as it
1202          * will get retransmitted later anyway.
1203          */
1204         while ((i = L2TP_SEQ_DIFF(seq->ns, seq->rack)) < seq->cwnd
1205             && seq->xwin[i] != NULL) {
1206                 if ((m = L2TP_COPY_MBUF(seq->xwin[i], M_NOWAIT)) == NULL)
1207                         priv->stats.memoryFailures++;
1208                 else
1209                         ng_l2tp_xmit_ctrl(priv, m, seq->ns);
1210                 seq->ns++;
1211         }
1212 }
1213
1214 /*
1215  * Handle receipt of a sequence number value (Ns) from peer.
1216  * We make no attempt to re-order out of order packets.
1217  *
1218  * This function should only be called for non-ZLB packets.
1219  *
1220  * Returns:
1221  *       0      Accept packet
1222  *      -1      Drop packet
1223  */
1224 static int
1225 ng_l2tp_seq_recv_ns(priv_p priv, u_int16_t ns)
1226 {
1227         struct l2tp_seq *const seq = &priv->seq;
1228
1229         /* If not what we expect, drop packet and send an immediate ZLB ack */
1230         if (ns != seq->nr) {
1231                 if (L2TP_SEQ_DIFF(ns, seq->nr) < 0)
1232                         priv->stats.recvDuplicates++;
1233                 else
1234                         priv->stats.recvOutOfOrder++;
1235                 ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
1236                 return (-1);
1237         }
1238
1239         /* Update recv sequence number */
1240         seq->nr++;
1241
1242         /* Start receive ack timer, if not already running */
1243         if (!seq->xack_timer_running) {
1244                 callout_reset(&seq->xack_timer,
1245                     L2TP_DELAYED_ACK, ng_l2tp_seq_xack_timeout, priv->node);
1246                 seq->xack_timer_running = 1;
1247                 NG_NODE_REF(priv->node);
1248         }
1249
1250         /* Accept packet */
1251         return (0);
1252 }
1253
1254 /*
1255  * Handle an ack timeout. We have an outstanding ack that we
1256  * were hoping to piggy-back, but haven't, so send a ZLB.
1257  */
1258 static void
1259 ng_l2tp_seq_xack_timeout(void *arg)
1260 {
1261         const node_p node = arg;
1262         const priv_p priv = NG_NODE_PRIVATE(node);
1263         struct l2tp_seq *const seq = &priv->seq;
1264         int s;
1265
1266         /* Check if node is going away */
1267         s = splnet();
1268         if (NG_NODE_NOT_VALID(node)) {
1269                 seq->xack_timer_running = 0;
1270                 if (!seq->rack_timer_running) {
1271                         if (priv->ftarget != NULL)
1272                                 FREE(priv->ftarget, M_NETGRAPH_L2TP);
1273                         FREE(priv, M_NETGRAPH_L2TP);
1274                         NG_NODE_SET_PRIVATE(node, NULL);
1275                 }
1276                 NG_NODE_UNREF(node);
1277                 splx(s);
1278                 return;
1279         }
1280
1281         /* Sanity check */
1282         L2TP_SEQ_CHECK(seq);
1283
1284         /* If ack is still outstanding, send a ZLB */
1285         if (seq->xack != seq->nr)
1286                 ng_l2tp_xmit_ctrl(priv, NULL, seq->ns);
1287
1288         /* Done */
1289         seq->xack_timer_running = 0;
1290         NG_NODE_UNREF(node);
1291         L2TP_SEQ_CHECK(seq);
1292         splx(s);
1293 }
1294
1295 /* 
1296  * Handle a transmit timeout. The peer has failed to respond
1297  * with an ack for our packet, so retransmit it.
1298  */
1299 static void
1300 ng_l2tp_seq_rack_timeout(void *arg)
1301 {
1302         const node_p node = arg;
1303         const priv_p priv = NG_NODE_PRIVATE(node);
1304         struct l2tp_seq *const seq = &priv->seq;
1305         struct mbuf *m;
1306         u_int delay;
1307         int s;
1308
1309         /* Check if node is going away */
1310         s = splnet();
1311         if (NG_NODE_NOT_VALID(node)) {
1312                 seq->rack_timer_running = 0;
1313                 if (!seq->xack_timer_running) {
1314                         if (priv->ftarget != NULL)
1315                                 FREE(priv->ftarget, M_NETGRAPH_L2TP);
1316                         FREE(priv, M_NETGRAPH_L2TP);
1317                         NG_NODE_SET_PRIVATE(node, NULL);
1318                 }
1319                 NG_NODE_UNREF(node);
1320                 splx(s);
1321                 return;
1322         }
1323
1324         /* Sanity check */
1325         L2TP_SEQ_CHECK(seq);
1326
1327         /* Make sure peer's ack is still outstanding before doing anything */
1328         if (seq->rack == seq->ns) {
1329                 seq->rack_timer_running = 0;
1330                 NG_NODE_UNREF(node);
1331                 goto done;
1332         }
1333         priv->stats.xmitRetransmits++;
1334
1335         /* Have we reached the retransmit limit? If so, notify owner. */
1336         if (seq->rexmits++ >= seq->max_rexmits)
1337                 ng_l2tp_seq_failure(priv);
1338
1339         /* Restart timer, this time with an increased delay */
1340         delay = (seq->rexmits > 12) ? (1 << 12) : (1 << seq->rexmits);
1341         if (delay > seq->max_rexmit_to)
1342                 delay = seq->max_rexmit_to;
1343         callout_reset(&seq->rack_timer,
1344             hz * delay, ng_l2tp_seq_rack_timeout, node);
1345
1346         /* Do slow-start/congestion algorithm windowing algorithm */
1347         seq->ssth = (seq->cwnd + 1) / 2;
1348         seq->cwnd = 1;
1349         seq->acks = 0;
1350
1351         /* Retransmit oldest unack'd packet */
1352         if ((m = L2TP_COPY_MBUF(seq->xwin[0], M_NOWAIT)) == NULL)
1353                 priv->stats.memoryFailures++;
1354         else
1355                 ng_l2tp_xmit_ctrl(priv, m, seq->rack);
1356
1357 done:
1358         /* Done */
1359         L2TP_SEQ_CHECK(seq);
1360         splx(s);
1361 }
1362
1363 /*
1364  * Transmit a control stream packet, payload optional.
1365  * The transmit sequence number is not incremented.
1366  */
1367 static int
1368 ng_l2tp_xmit_ctrl(priv_p priv, struct mbuf *m, u_int16_t ns)
1369 {
1370         struct l2tp_seq *const seq = &priv->seq;
1371         u_int16_t session_id = 0;
1372         meta_p meta = NULL;
1373         int error;
1374
1375         /* If no mbuf passed, send an empty packet (ZLB) */
1376         if (m == NULL) {
1377
1378                 /* Create a new mbuf for ZLB packet */
1379                 MGETHDR(m, M_DONTWAIT, MT_DATA);
1380                 if (m == NULL) {
1381                         priv->stats.memoryFailures++;
1382                         return (ENOBUFS);
1383                 }
1384                 m->m_len = m->m_pkthdr.len = 12;
1385                 m->m_pkthdr.rcvif = NULL;
1386                 priv->stats.xmitZLBs++;
1387         } else {
1388
1389                 /* Strip off session ID */
1390                 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
1391                         priv->stats.memoryFailures++;
1392                         return (ENOBUFS);
1393                 }
1394                 memcpy(&session_id, mtod(m, u_int16_t *), 2);
1395                 m_adj(m, 2);
1396
1397                 /* Make room for L2TP header */
1398                 M_PREPEND(m, 12, M_DONTWAIT);
1399                 if (m == NULL) {
1400                         priv->stats.memoryFailures++;
1401                         return (ENOBUFS);
1402                 }
1403         }
1404
1405         /* Fill in L2TP header */
1406         mtod(m, u_int16_t *)[0] = htons(L2TP_CTRL_HDR);
1407         mtod(m, u_int16_t *)[1] = htons(m->m_pkthdr.len);
1408         mtod(m, u_int16_t *)[2] = priv->conf.peer_id;
1409         mtod(m, u_int16_t *)[3] = session_id;
1410         mtod(m, u_int16_t *)[4] = htons(ns);
1411         mtod(m, u_int16_t *)[5] = htons(seq->nr);
1412
1413         /* Update sequence number info and stats */
1414         priv->stats.xmitPackets++;
1415         priv->stats.xmitOctets += m->m_pkthdr.len;
1416
1417         /* Stop ack timer: we're sending an ack with this packet */
1418         if (seq->xack_timer_running && callout_stop(&seq->xack_timer) == 1) {
1419                 seq->xack_timer_running = 0;
1420                 NG_NODE_UNREF(priv->node);
1421         }
1422         seq->xack = seq->nr;
1423
1424         /* Send packet */
1425         NG_SEND_DATA(error, priv->lower, m, meta);
1426         return (error);
1427 }
1428
1429 #ifdef INVARIANTS
1430 /*
1431  * Sanity check sequence number state.
1432  */
1433 static void
1434 ng_l2tp_seq_check(struct l2tp_seq *seq)
1435 {
1436         const int self_unack = L2TP_SEQ_DIFF(seq->nr, seq->xack);
1437         const int peer_unack = L2TP_SEQ_DIFF(seq->ns, seq->rack);
1438         int i;
1439
1440 #define CHECK(p)        KASSERT((p), ("%s: not: %s", __FUNCTION__, #p))
1441
1442         CHECK(seq->wmax <= L2TP_MAX_XWIN);
1443         CHECK(seq->cwnd >= 1);
1444         CHECK(seq->cwnd <= seq->wmax);
1445         CHECK(seq->ssth >= 1);
1446         CHECK(seq->ssth <= seq->wmax);
1447         if (seq->cwnd < seq->ssth)
1448                 CHECK(seq->acks == 0);
1449         else
1450                 CHECK(seq->acks <= seq->cwnd);
1451         CHECK(self_unack >= 0);
1452         CHECK(peer_unack >= 0);
1453         CHECK(peer_unack <= seq->wmax);
1454         CHECK((self_unack == 0) ^ seq->xack_timer_running);
1455         CHECK((peer_unack == 0) ^ seq->rack_timer_running);
1456         CHECK(seq->rack_timer_running || !callout_pending(&seq->rack_timer));
1457         CHECK(seq->xack_timer_running || !callout_pending(&seq->xack_timer));
1458         for (i = 0; i < peer_unack; i++)
1459                 CHECK(seq->xwin[i] != NULL);
1460         for ( ; i < seq->cwnd; i++)         /* verify peer's recv window full */
1461                 CHECK(seq->xwin[i] == NULL);
1462
1463 #undef CHECK
1464 }
1465 #endif  /* INVARIANTS */
1466
1467