6 * Copyright (c) 1996-1999 Whistle Communications, Inc.
9 * Subject to the following obligations and disclaimer of warranty, use and
10 * redistribution of this software, in source or object code forms, with or
11 * without modifications are expressly permitted by Whistle Communications;
12 * provided, however, that:
13 * 1. Any and all reproductions of the source or object code must include the
14 * copyright notice above and the following disclaimer of warranties; and
15 * 2. No rights are granted, in any manner or form, to use Whistle
16 * Communications, Inc. trademarks, including the mark "WHISTLE
17 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18 * such appears in the above copyright notice or in the software.
20 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
38 * Author: Archie Cobbs <archie@freebsd.org>
41 * $Whistle: ng_pptpgre.c,v 1.7 1999/12/08 00:10:06 archie Exp $
45 * PPTP/GRE netgraph node type.
47 * This node type does the GRE encapsulation as specified for the PPTP
48 * protocol (RFC 2637, section 4). This includes sequencing and
49 * retransmission of frames, but not the actual packet delivery nor
50 * any of the TCP control stream protocol.
52 * The "upper" hook of this node is suitable for attaching to a "ppp"
53 * node link hook. The "lower" hook of this node is suitable for attaching
54 * to a "ksocket" node on hook "inet/raw/gre".
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/kernel.h>
62 #include <sys/malloc.h>
64 #include <sys/mutex.h>
65 #include <sys/endian.h>
66 #include <sys/errno.h>
67 #include <sys/sysctl.h>
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
73 #include <netgraph/ng_message.h>
74 #include <netgraph/netgraph.h>
75 #include <netgraph/ng_parse.h>
76 #include <netgraph/ng_pptpgre.h>
78 /* GRE packet format, as used by PPTP */
80 #if BYTE_ORDER == LITTLE_ENDIAN
81 u_char recursion:3; /* recursion control */
82 u_char ssr:1; /* strict source route */
83 u_char hasSeq:1; /* sequence number present */
84 u_char hasKey:1; /* key present */
85 u_char hasRoute:1; /* routing present */
86 u_char hasSum:1; /* checksum present */
87 u_char vers:3; /* version */
88 u_char flags:4; /* flags */
89 u_char hasAck:1; /* acknowlege number present */
90 #elif BYTE_ORDER == BIG_ENDIAN
91 u_char hasSum:1; /* checksum present */
92 u_char hasRoute:1; /* routing present */
93 u_char hasKey:1; /* key present */
94 u_char hasSeq:1; /* sequence number present */
95 u_char ssr:1; /* strict source route */
96 u_char recursion:3; /* recursion control */
97 u_char hasAck:1; /* acknowlege number present */
98 u_char flags:4; /* flags */
99 u_char vers:3; /* version */
101 #error BYTE_ORDER is not defined properly
103 u_int16_t proto; /* protocol (ethertype) */
104 u_int16_t length; /* payload length */
105 u_int16_t cid; /* call id */
106 u_int32_t data[0]; /* opt. seq, ack, then data */
109 /* The PPTP protocol ID used in the GRE 'proto' field */
110 #define PPTP_GRE_PROTO 0x880b
112 /* Bits that must be set a certain way in all PPTP/GRE packets */
113 #define PPTP_INIT_VALUE ((0x2001 << 16) | PPTP_GRE_PROTO)
114 #define PPTP_INIT_MASK 0xef7fffff
116 /* Min and max packet length */
117 #define PPTP_MAX_PAYLOAD (0xffff - sizeof(struct greheader) - 8)
119 /* All times are scaled by this (PPTP_TIME_SCALE time units = 1 sec.) */
120 #define PPTP_TIME_SCALE 1024 /* milliseconds */
121 typedef u_int64_t pptptime_t;
123 /* Acknowledgment timeout parameters and functions */
124 #define PPTP_XMIT_WIN 16 /* max xmit window */
125 #define PPTP_MIN_TIMEOUT (PPTP_TIME_SCALE / 83) /* 12 milliseconds */
126 #define PPTP_MAX_TIMEOUT (3 * PPTP_TIME_SCALE) /* 3 seconds */
128 #define PPTP_REORDER_TIMEOUT 1
130 /* When we receive a packet, we wait to see if there's an outgoing packet
131 we can piggy-back the ACK off of. These parameters determine the mimimum
132 and maxmimum length of time we're willing to wait in order to do that.
133 These have no effect unless "enableDelayedAck" is turned on. */
134 #define PPTP_MIN_ACK_DELAY (PPTP_TIME_SCALE / 500) /* 2 milliseconds */
135 #define PPTP_MAX_ACK_DELAY (PPTP_TIME_SCALE / 2) /* 500 milliseconds */
137 /* See RFC 2637 section 4.4 */
138 #define PPTP_ACK_ALPHA(x) (((x) + 4) >> 3) /* alpha = 0.125 */
139 #define PPTP_ACK_BETA(x) (((x) + 2) >> 2) /* beta = 0.25 */
140 #define PPTP_ACK_CHI(x) ((x) << 2) /* chi = 4 */
141 #define PPTP_ACK_DELTA(x) ((x) << 1) /* delta = 2 */
143 #define PPTP_SEQ_DIFF(x,y) ((int32_t)(x) - (int32_t)(y))
145 #define SESSHASHSIZE 0x0020
146 #define SESSHASH(x) (((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
148 SYSCTL_NODE(_net_graph, OID_AUTO, pptpgre, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
152 * Reorder queue maximum length. Zero disables reorder.
154 * The node may keep reorder_max queue entries per session
155 * if reorder is enabled, plus allocate one more for short time.
157 * Be conservative in memory consumption by default.
158 * Lots of sessions with large queues can overflow M_NETGRAPH zone.
160 static int reorder_max = 1; /* reorder up to two swapped packets in a row */
161 SYSCTL_UINT(_net_graph_pptpgre, OID_AUTO, reorder_max, CTLFLAG_RWTUN,
162 &reorder_max, 0, "Reorder queue maximum length");
164 static int reorder_timeout = PPTP_REORDER_TIMEOUT;
165 SYSCTL_UINT(_net_graph_pptpgre, OID_AUTO, reorder_timeout, CTLFLAG_RWTUN,
166 &reorder_timeout, 0, "Reorder timeout is milliseconds");
168 /* Packet reorder FIFO queue */
169 struct ng_pptpgre_roq {
170 SLIST_ENTRY(ng_pptpgre_roq) next; /* next entry of the queue */
171 item_p item; /* netgraph item */
172 u_int32_t seq; /* packet sequence number */
174 SLIST_HEAD(ng_pptpgre_roq_head, ng_pptpgre_roq);
175 typedef struct ng_pptpgre_roq_head roqh;
177 /* We keep packet retransmit and acknowlegement state in this struct */
178 struct ng_pptpgre_sess {
179 node_p node; /* this node pointer */
180 hook_p hook; /* hook to upper layers */
181 struct ng_pptpgre_conf conf; /* configuration info */
182 struct mtx mtx; /* session mutex */
183 u_int32_t recvSeq; /* last seq # we rcv'd */
184 u_int32_t xmitSeq; /* last seq # we sent */
185 u_int32_t recvAck; /* last seq # peer ack'd */
186 u_int32_t xmitAck; /* last seq # we ack'd */
187 int32_t ato; /* adaptive time-out value */
188 int32_t rtt; /* round trip time estimate */
189 int32_t dev; /* deviation estimate */
190 u_int16_t xmitWin; /* size of xmit window */
191 struct callout sackTimer; /* send ack timer */
192 struct callout rackTimer; /* recv ack timer */
193 u_int32_t winAck; /* seq when xmitWin will grow */
194 pptptime_t timeSent[PPTP_XMIT_WIN];
195 LIST_ENTRY(ng_pptpgre_sess) sessions;
196 roqh roq; /* reorder queue head */
197 u_int8_t roq_len; /* reorder queue length */
198 struct callout reorderTimer; /* reorder timeout handler */
200 typedef struct ng_pptpgre_sess *hpriv_p;
202 /* Node private data */
203 struct ng_pptpgre_private {
204 hook_p upper; /* hook to upper layers */
205 hook_p lower; /* hook to lower layers */
206 struct ng_pptpgre_sess uppersess; /* default session for compat */
207 LIST_HEAD(, ng_pptpgre_sess) sesshash[SESSHASHSIZE];
208 struct ng_pptpgre_stats stats; /* node statistics */
210 typedef struct ng_pptpgre_private *priv_p;
212 /* Netgraph node methods */
213 static ng_constructor_t ng_pptpgre_constructor;
214 static ng_rcvmsg_t ng_pptpgre_rcvmsg;
215 static ng_shutdown_t ng_pptpgre_shutdown;
216 static ng_newhook_t ng_pptpgre_newhook;
217 static ng_rcvdata_t ng_pptpgre_rcvdata;
218 static ng_rcvdata_t ng_pptpgre_rcvdata_lower;
219 static ng_disconnect_t ng_pptpgre_disconnect;
221 /* Helper functions */
222 static int ng_pptpgre_xmit(hpriv_p hpriv, item_p item);
223 static void ng_pptpgre_start_send_ack_timer(hpriv_p hpriv);
224 static void ng_pptpgre_start_recv_ack_timer(hpriv_p hpriv);
225 static void ng_pptpgre_start_reorder_timer(hpriv_p hpriv);
226 static void ng_pptpgre_recv_ack_timeout(node_p node, hook_p hook,
227 void *arg1, int arg2);
228 static void ng_pptpgre_send_ack_timeout(node_p node, hook_p hook,
229 void *arg1, int arg2);
230 static void ng_pptpgre_reorder_timeout(node_p node, hook_p hook,
231 void *arg1, int arg2);
232 static hpriv_p ng_pptpgre_find_session(priv_p privp, u_int16_t cid);
233 static void ng_pptpgre_reset(hpriv_p hpriv);
234 static pptptime_t ng_pptpgre_time(void);
235 static void ng_pptpgre_ack(const hpriv_p hpriv);
236 static int ng_pptpgre_sendq(const hpriv_p hpriv, roqh *q,
237 const struct ng_pptpgre_roq *st);
239 /* Parse type for struct ng_pptpgre_conf */
240 static const struct ng_parse_struct_field ng_pptpgre_conf_type_fields[]
241 = NG_PPTPGRE_CONF_TYPE_INFO;
242 static const struct ng_parse_type ng_pptpgre_conf_type = {
243 &ng_parse_struct_type,
244 &ng_pptpgre_conf_type_fields,
247 /* Parse type for struct ng_pptpgre_stats */
248 static const struct ng_parse_struct_field ng_pptpgre_stats_type_fields[]
249 = NG_PPTPGRE_STATS_TYPE_INFO;
250 static const struct ng_parse_type ng_pptp_stats_type = {
251 &ng_parse_struct_type,
252 &ng_pptpgre_stats_type_fields
255 /* List of commands and how to convert arguments to/from ASCII */
256 static const struct ng_cmdlist ng_pptpgre_cmdlist[] = {
259 NGM_PPTPGRE_SET_CONFIG,
261 &ng_pptpgre_conf_type,
266 NGM_PPTPGRE_GET_CONFIG,
268 &ng_parse_hint16_type,
269 &ng_pptpgre_conf_type
273 NGM_PPTPGRE_GET_STATS,
280 NGM_PPTPGRE_CLR_STATS,
287 NGM_PPTPGRE_GETCLR_STATS,
295 /* Node type descriptor */
296 static struct ng_type ng_pptpgre_typestruct = {
297 .version = NG_ABI_VERSION,
298 .name = NG_PPTPGRE_NODE_TYPE,
299 .constructor = ng_pptpgre_constructor,
300 .rcvmsg = ng_pptpgre_rcvmsg,
301 .shutdown = ng_pptpgre_shutdown,
302 .newhook = ng_pptpgre_newhook,
303 .rcvdata = ng_pptpgre_rcvdata,
304 .disconnect = ng_pptpgre_disconnect,
305 .cmdlist = ng_pptpgre_cmdlist,
307 NETGRAPH_INIT(pptpgre, &ng_pptpgre_typestruct);
309 #define ERROUT(x) do { error = (x); goto done; } while (0)
311 /************************************************************************
313 ************************************************************************/
316 * Node type constructor
319 ng_pptpgre_constructor(node_p node)
324 /* Allocate private structure */
325 priv = malloc(sizeof(*priv), M_NETGRAPH, M_WAITOK | M_ZERO);
327 NG_NODE_SET_PRIVATE(node, priv);
329 /* Initialize state */
330 mtx_init(&priv->uppersess.mtx, "ng_pptp", NULL, MTX_DEF);
331 ng_callout_init(&priv->uppersess.sackTimer);
332 ng_callout_init(&priv->uppersess.rackTimer);
333 priv->uppersess.node = node;
335 SLIST_INIT(&priv->uppersess.roq);
336 priv->uppersess.roq_len = 0;
337 ng_callout_init(&priv->uppersess.reorderTimer);
339 for (i = 0; i < SESSHASHSIZE; i++)
340 LIST_INIT(&priv->sesshash[i]);
342 LIST_INSERT_HEAD(&priv->sesshash[0], &priv->uppersess, sessions);
349 * Give our OK for a hook to be added.
352 ng_pptpgre_newhook(node_p node, hook_p hook, const char *name)
354 const priv_p priv = NG_NODE_PRIVATE(node);
356 /* Check hook name */
357 if (strcmp(name, NG_PPTPGRE_HOOK_UPPER) == 0) {
359 priv->uppersess.hook = hook;
360 NG_HOOK_SET_PRIVATE(hook, &priv->uppersess);
361 } else if (strcmp(name, NG_PPTPGRE_HOOK_LOWER) == 0) {
363 NG_HOOK_SET_RCVDATA(hook, ng_pptpgre_rcvdata_lower);
365 static const char hexdig[16] = "0123456789abcdef";
371 /* Parse hook name to get session ID */
372 if (strncmp(name, NG_PPTPGRE_HOOK_SESSION_P,
373 sizeof(NG_PPTPGRE_HOOK_SESSION_P) - 1) != 0)
375 hex = name + sizeof(NG_PPTPGRE_HOOK_SESSION_P) - 1;
376 for (cid = i = 0; i < 4; i++) {
377 for (j = 0; j < 16 && hex[i] != hexdig[j]; j++);
380 cid = (cid << 4) | j;
385 hpriv = malloc(sizeof(*hpriv), M_NETGRAPH, M_NOWAIT | M_ZERO);
389 /* Initialize state */
390 mtx_init(&hpriv->mtx, "ng_pptp", NULL, MTX_DEF);
391 ng_callout_init(&hpriv->sackTimer);
392 ng_callout_init(&hpriv->rackTimer);
393 hpriv->conf.cid = cid;
397 SLIST_INIT(&hpriv->roq);
399 ng_callout_init(&hpriv->reorderTimer);
401 NG_HOOK_SET_PRIVATE(hook, hpriv);
403 hash = SESSHASH(cid);
404 LIST_INSERT_HEAD(&priv->sesshash[hash], hpriv, sessions);
411 * Receive a control message.
414 ng_pptpgre_rcvmsg(node_p node, item_p item, hook_p lasthook)
416 const priv_p priv = NG_NODE_PRIVATE(node);
417 struct ng_mesg *resp = NULL;
421 NGI_GET_MSG(item, msg);
422 switch (msg->header.typecookie) {
423 case NGM_PPTPGRE_COOKIE:
424 switch (msg->header.cmd) {
425 case NGM_PPTPGRE_SET_CONFIG:
427 struct ng_pptpgre_conf *const newConf =
428 (struct ng_pptpgre_conf *) msg->data;
432 /* Check for invalid or illegal config */
433 if (msg->header.arglen != sizeof(*newConf))
435 /* Try to find session by cid. */
436 hpriv = ng_pptpgre_find_session(priv, newConf->cid);
437 /* If not present - use upper. */
439 hpriv = &priv->uppersess;
440 LIST_REMOVE(hpriv, sessions);
441 hash = SESSHASH(newConf->cid);
442 LIST_INSERT_HEAD(&priv->sesshash[hash], hpriv,
445 ng_pptpgre_reset(hpriv); /* reset on configure */
446 hpriv->conf = *newConf;
449 case NGM_PPTPGRE_GET_CONFIG:
453 if (msg->header.arglen == 2) {
454 /* Try to find session by cid. */
455 hpriv = ng_pptpgre_find_session(priv,
456 *((uint16_t *)msg->data));
459 } else if (msg->header.arglen == 0) {
461 hpriv = &priv->uppersess;
464 NG_MKRESPONSE(resp, msg, sizeof(hpriv->conf), M_NOWAIT);
467 bcopy(&hpriv->conf, resp->data, sizeof(hpriv->conf));
470 case NGM_PPTPGRE_GET_STATS:
471 case NGM_PPTPGRE_CLR_STATS:
472 case NGM_PPTPGRE_GETCLR_STATS:
474 if (msg->header.cmd != NGM_PPTPGRE_CLR_STATS) {
475 NG_MKRESPONSE(resp, msg,
476 sizeof(priv->stats), M_NOWAIT);
480 resp->data, sizeof(priv->stats));
482 if (msg->header.cmd != NGM_PPTPGRE_GET_STATS)
483 bzero(&priv->stats, sizeof(priv->stats));
496 NG_RESPOND_MSG(error, node, item, resp);
502 * Receive incoming data on a hook.
505 ng_pptpgre_rcvdata(hook_p hook, item_p item)
507 const hpriv_p hpriv = NG_HOOK_PRIVATE(hook);
510 /* If not configured, reject */
511 if (!hpriv->conf.enabled) {
516 mtx_lock(&hpriv->mtx);
518 rval = ng_pptpgre_xmit(hpriv, item);
520 mtx_assert(&hpriv->mtx, MA_NOTOWNED);
529 ng_pptpgre_disconnect(hook_p hook)
531 const node_p node = NG_HOOK_NODE(hook);
532 const priv_p priv = NG_NODE_PRIVATE(node);
533 const hpriv_p hpriv = NG_HOOK_PRIVATE(hook);
535 /* Zero out hook pointer */
536 if (hook == priv->upper) {
538 priv->uppersess.hook = NULL;
539 } else if (hook == priv->lower) {
542 /* Reset node (stops timers) */
543 ng_pptpgre_reset(hpriv);
545 LIST_REMOVE(hpriv, sessions);
546 mtx_destroy(&hpriv->mtx);
547 free(hpriv, M_NETGRAPH);
550 /* Go away if no longer connected to anything */
551 if ((NG_NODE_NUMHOOKS(node) == 0)
552 && (NG_NODE_IS_VALID(node)))
553 ng_rmnode_self(node);
561 ng_pptpgre_shutdown(node_p node)
563 const priv_p priv = NG_NODE_PRIVATE(node);
565 /* Reset node (stops timers) */
566 ng_pptpgre_reset(&priv->uppersess);
568 LIST_REMOVE(&priv->uppersess, sessions);
569 mtx_destroy(&priv->uppersess.mtx);
571 free(priv, M_NETGRAPH);
573 /* Decrement ref count */
578 /*************************************************************************
579 TRANSMIT AND RECEIVE FUNCTIONS
580 *************************************************************************/
583 * Transmit an outgoing frame, or just an ack if m is NULL.
586 ng_pptpgre_xmit(hpriv_p hpriv, item_p item)
588 const priv_p priv = NG_NODE_PRIVATE(hpriv->node);
589 u_char buf[sizeof(struct greheader) + 2 * sizeof(u_int32_t)];
590 struct greheader *const gre = (struct greheader *)buf;
594 mtx_assert(&hpriv->mtx, MA_OWNED);
601 /* Check if there's data */
604 /* Check if windowing is enabled */
605 if (hpriv->conf.enableWindowing) {
606 /* Is our transmit window full? */
607 if ((u_int32_t)PPTP_SEQ_DIFF(hpriv->xmitSeq,
608 hpriv->recvAck) >= hpriv->xmitWin) {
609 priv->stats.xmitDrops++;
614 /* Sanity check frame length */
615 if (m->m_pkthdr.len > PPTP_MAX_PAYLOAD) {
616 priv->stats.xmitTooBig++;
620 priv->stats.xmitLoneAcks++;
623 /* Build GRE header */
624 be32enc(gre, PPTP_INIT_VALUE);
625 be16enc(&gre->length, (m != NULL) ? m->m_pkthdr.len : 0);
626 be16enc(&gre->cid, hpriv->conf.peerCid);
628 /* Include sequence number if packet contains any data */
631 if (hpriv->conf.enableWindowing) {
632 hpriv->timeSent[hpriv->xmitSeq - hpriv->recvAck]
636 be32enc(&gre->data[0], hpriv->xmitSeq);
639 /* Include acknowledgement (and stop send ack timer) if needed */
640 if (hpriv->conf.enableAlwaysAck || hpriv->xmitAck != hpriv->recvSeq) {
642 be32enc(&gre->data[gre->hasSeq], hpriv->recvSeq);
643 hpriv->xmitAck = hpriv->recvSeq;
644 if (hpriv->conf.enableDelayedAck)
645 ng_uncallout(&hpriv->sackTimer, hpriv->node);
648 /* Prepend GRE header to outgoing frame */
649 grelen = sizeof(*gre) + sizeof(u_int32_t) * (gre->hasSeq + gre->hasAck);
651 MGETHDR(m, M_NOWAIT, MT_DATA);
653 priv->stats.memoryFailures++;
656 m->m_len = m->m_pkthdr.len = grelen;
657 m->m_pkthdr.rcvif = NULL;
659 M_PREPEND(m, grelen, M_NOWAIT);
660 if (m == NULL || (m->m_len < grelen
661 && (m = m_pullup(m, grelen)) == NULL)) {
662 priv->stats.memoryFailures++;
666 bcopy(gre, mtod(m, u_char *), grelen);
669 priv->stats.xmitPackets++;
670 priv->stats.xmitOctets += m->m_pkthdr.len;
673 * XXX: we should reset timer only after an item has been sent
676 if (hpriv->conf.enableWindowing &&
677 gre->hasSeq && hpriv->xmitSeq == hpriv->recvAck + 1)
678 ng_pptpgre_start_recv_ack_timer(hpriv);
680 mtx_unlock(&hpriv->mtx);
684 NG_FWD_NEW_DATA(error, item, priv->lower, m);
686 NG_SEND_DATA_ONLY(error, priv->lower, m);
692 mtx_unlock(&hpriv->mtx);
700 ng_pptpgre_ack(const hpriv_p hpriv)
702 mtx_assert(&hpriv->mtx, MA_OWNED);
703 if (!(callout_pending(&hpriv->sackTimer))) {
704 /* If delayed ACK is disabled, send it now */
705 if (!hpriv->conf.enableDelayedAck) { /* ack now */
706 ng_pptpgre_xmit(hpriv, NULL);
707 /* ng_pptpgre_xmit() drops the mutex */
711 ng_pptpgre_start_send_ack_timer(hpriv);
712 mtx_unlock(&hpriv->mtx);
715 mtx_unlock(&hpriv->mtx);
719 * Delivers packets from the queue "q" to upper layers. Frees delivered
720 * entries with the exception of one equal to "st" that is allocated
721 * on caller's stack and not on the heap.
724 ng_pptpgre_sendq(const hpriv_p hpriv, roqh *q, const struct ng_pptpgre_roq *st)
726 struct ng_pptpgre_roq *np;
730 mtx_assert(&hpriv->mtx, MA_NOTOWNED);
731 while (!SLIST_EMPTY(q)) {
733 SLIST_REMOVE_HEAD(q, next);
734 NGI_GET_M(np->item, m);
735 NG_FWD_NEW_DATA(error, np->item, hpriv->hook, m);
737 free(np, M_NETGRAPH);
743 * Handle an incoming packet. The packet includes the IP header.
746 ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
749 node_p node = NG_HOOK_NODE(hook);
750 const priv_p priv = NG_NODE_PRIVATE(node);
751 int iphlen, grelen, extralen;
752 const struct greheader *gre;
757 roqh sendq = SLIST_HEAD_INITIALIZER(sendq); /* send queue on stack */
758 struct ng_pptpgre_roq *last = NULL; /* last packet in the sendq */
759 struct ng_pptpgre_roq *np, *prev;
760 struct ng_pptpgre_roq temp = { { NULL }, NULL, 0 };
766 priv->stats.recvPackets++;
767 priv->stats.recvOctets += m->m_pkthdr.len;
769 /* Sanity check packet length */
770 if (m->m_pkthdr.len < sizeof(*ip) + sizeof(*gre)) {
771 priv->stats.recvRunts++;
775 /* Safely pull up the complete IP+GRE headers */
776 if (m->m_len < sizeof(*ip) + sizeof(*gre)) {
777 if ((m = m_pullup(m, sizeof(*ip) + sizeof(*gre))) == NULL) {
778 priv->stats.memoryFailures++;
784 ip = mtod(m, const struct ip *);
785 iphlen = ip->ip_hl << 2;
786 if (m->m_len < iphlen + sizeof(*gre)) {
787 if ((m = m_pullup(m, iphlen + sizeof(*gre))) == NULL) {
788 priv->stats.memoryFailures++;
793 ip = mtod(m, const struct ip *);
795 gre = (const struct greheader *)((const u_char *)ip + iphlen);
796 grelen = sizeof(*gre) + sizeof(u_int32_t) * (gre->hasSeq + gre->hasAck);
797 if (m->m_pkthdr.len < iphlen + grelen) {
798 priv->stats.recvRunts++;
801 if (m->m_len < iphlen + grelen) {
802 if ((m = m_pullup(m, iphlen + grelen)) == NULL) {
803 priv->stats.memoryFailures++;
808 ip = mtod(m, const struct ip *);
809 gre = (const struct greheader *)((const u_char *)ip + iphlen);
812 /* Sanity check packet length and GRE header bits */
813 extralen = m->m_pkthdr.len
814 - (iphlen + grelen + gre->hasSeq * be16dec(&gre->length));
816 priv->stats.recvBadGRE++;
819 if ((be32dec(gre) & PPTP_INIT_MASK) != PPTP_INIT_VALUE) {
820 priv->stats.recvBadGRE++;
824 hpriv = ng_pptpgre_find_session(priv, be16dec(&gre->cid));
825 if (hpriv == NULL || hpriv->hook == NULL || !hpriv->conf.enabled) {
826 priv->stats.recvBadCID++;
829 mtx_lock(&hpriv->mtx);
831 /* Look for peer ack */
833 const u_int32_t ack = be32dec(&gre->data[gre->hasSeq]);
834 const int index = ack - hpriv->recvAck - 1;
837 /* Sanity check ack value */
838 if (PPTP_SEQ_DIFF(ack, hpriv->xmitSeq) > 0) {
839 priv->stats.recvBadAcks++;
840 goto badAck; /* we never sent it! */
842 if (PPTP_SEQ_DIFF(ack, hpriv->recvAck) <= 0)
843 goto badAck; /* ack already timed out */
844 hpriv->recvAck = ack;
846 /* Update adaptive timeout stuff */
847 if (hpriv->conf.enableWindowing) {
848 sample = ng_pptpgre_time() - hpriv->timeSent[index];
849 diff = sample - hpriv->rtt;
850 hpriv->rtt += PPTP_ACK_ALPHA(diff);
853 hpriv->dev += PPTP_ACK_BETA(diff - hpriv->dev);
854 /* +2 to compensate low precision of int math */
855 hpriv->ato = hpriv->rtt + PPTP_ACK_CHI(hpriv->dev + 2);
856 if (hpriv->ato > PPTP_MAX_TIMEOUT)
857 hpriv->ato = PPTP_MAX_TIMEOUT;
858 else if (hpriv->ato < PPTP_MIN_TIMEOUT)
859 hpriv->ato = PPTP_MIN_TIMEOUT;
861 /* Shift packet transmit times in our transmit window */
862 bcopy(hpriv->timeSent + index + 1, hpriv->timeSent,
863 sizeof(*hpriv->timeSent)
864 * (PPTP_XMIT_WIN - (index + 1)));
866 /* If we sent an entire window, increase window size */
867 if (PPTP_SEQ_DIFF(ack, hpriv->winAck) >= 0
868 && hpriv->xmitWin < PPTP_XMIT_WIN) {
870 hpriv->winAck = ack + hpriv->xmitWin;
873 /* Stop/(re)start receive ACK timer as necessary */
874 ng_uncallout(&hpriv->rackTimer, hpriv->node);
875 if (hpriv->recvAck != hpriv->xmitSeq)
876 ng_pptpgre_start_recv_ack_timer(hpriv);
881 /* See if frame contains any data */
882 if (!gre->hasSeq) { /* no data to deliver */
883 priv->stats.recvLoneAcks++;
884 mtx_unlock(&hpriv->mtx);
888 seq = be32dec(&gre->data[0]);
890 diff = PPTP_SEQ_DIFF(seq, hpriv->recvSeq);
891 if (diff <= 0) { /* late or duplicate packet */
892 if (diff < 0 && reorder_max == 0) /* reorder disabled */
893 priv->stats.recvOutOfOrder++; /* late */
895 priv->stats.recvDuplicates++; /* duplicate */
896 mtx_unlock(&hpriv->mtx);
900 /* Trim mbuf down to internal payload */
901 m_adj(m, iphlen + grelen);
905 #define INIT_SENDQ(t) do { \
908 SLIST_INSERT_HEAD(&sendq, &t, next); \
910 hpriv->recvSeq = seq; \
915 /* the packet came in order, place it at the start of sendq */
918 /* The packet came too early, try to enqueue it.
920 * Check for duplicate in the queue. After this loop, "prev" will be
921 * NULL if the packet should become new head of the queue,
922 * or else it should be inserted after the "prev".
924 prev = SLIST_FIRST(&hpriv->roq);
925 SLIST_FOREACH(np, &hpriv->roq, next) {
926 diff = PPTP_SEQ_DIFF(np->seq, seq);
927 if (diff == 0) { /* do not add duplicate, drop it */
928 priv->stats.recvDuplicates++;
929 mtx_unlock(&hpriv->mtx);
932 if (diff > 0) { /* we found newer packet */
933 if (np == prev) /* that is the head of the queue */
934 prev = NULL; /* put current packet to the head */
940 priv->stats.recvOutOfOrder++; /* duplicate not found */
941 if (hpriv->roq_len < reorder_max)
942 goto enqueue; /* reorder enabled and there is a room */
945 * There is no room in the queue or reorder disabled.
947 * It the latter case, we may still have non-empty reorder queue
948 * if reorder was disabled in process of reordering.
949 * Then we correctly deliver the queue without growing it.
951 * In both cases, no malloc()'s until the queue is shortened.
953 priv->stats.recvReorderOverflow++;
954 if (prev == NULL) { /* new packet goes before the head */
955 INIT_SENDQ(temp); /* of reorder queue, so put it to sendq */
960 * Current packet goes after the head of reorder queue.
961 * Move the head to sendq to make room for current packet.
963 np = SLIST_FIRST(&hpriv->roq);
966 SLIST_REMOVE_HEAD(&hpriv->roq, next);
967 hpriv->roq_len--; /* we are allowed to use malloc() now */
968 SLIST_INSERT_HEAD(&sendq, np, next);
970 hpriv->recvSeq = np->seq;
973 np = malloc(sizeof(*np), M_NETGRAPH, M_NOWAIT | M_ZERO);
975 priv->stats.memoryFailures++;
977 * Emergency: we cannot save new data.
978 * Flush the queue delivering all queued packets preceeding
979 * current one despite of gaps.
981 while (!SLIST_EMPTY(&hpriv->roq)) {
982 np = SLIST_FIRST(&hpriv->roq);
985 SLIST_REMOVE_HEAD(&hpriv->roq, next);
988 SLIST_INSERT_HEAD(&sendq, np, next);
990 SLIST_INSERT_AFTER(last, np, next);
995 * Pretend we got all packets till the current one
996 * and acknowledge it.
998 hpriv->recvSeq = seq;
999 ng_pptpgre_ack(hpriv); /* drops lock */
1000 ng_pptpgre_sendq(hpriv, &sendq, &temp);
1001 NG_FWD_NEW_DATA(error, item, hpriv->hook, m);
1005 /* Add current (early) packet to the reorder queue. */
1009 SLIST_INSERT_HEAD(&hpriv->roq, np, next);
1011 SLIST_INSERT_AFTER(prev, np, next);
1015 /* Look if we have some packets in sequence after sendq. */
1016 while (!SLIST_EMPTY(&hpriv->roq)) {
1017 np = SLIST_FIRST(&hpriv->roq);
1018 if (PPTP_SEQ_DIFF(np->seq, hpriv->recvSeq) > 1)
1019 break; /* the gap in the sequence */
1021 /* "np" is in sequence, move it to the sendq. */
1022 SLIST_REMOVE_HEAD(&hpriv->roq, next);
1024 hpriv->recvSeq = np->seq;
1027 SLIST_INSERT_HEAD(&sendq, np, next);
1029 SLIST_INSERT_AFTER(last, np, next);
1033 if (SLIST_EMPTY(&hpriv->roq)) {
1034 if (callout_pending(&hpriv->reorderTimer))
1035 ng_uncallout(&hpriv->reorderTimer, hpriv->node);
1037 if (!callout_pending(&hpriv->reorderTimer))
1038 ng_pptpgre_start_reorder_timer(hpriv);
1041 if (SLIST_EMPTY(&sendq)) {
1042 /* Current packet has been queued, nothing to free/deliver. */
1043 mtx_unlock(&hpriv->mtx);
1047 /* We need to acknowledge last packet; do it soon... */
1048 ng_pptpgre_ack(hpriv); /* drops lock */
1049 ng_pptpgre_sendq(hpriv, &sendq, &temp);
1057 /*************************************************************************
1058 TIMER RELATED FUNCTIONS
1059 *************************************************************************/
1062 * Start a timer for the peer's acknowledging our oldest unacknowledged
1063 * sequence number. If we get an ack for this sequence number before
1064 * the timer goes off, we cancel the timer. Resets currently running
1065 * recv ack timer, if any.
1068 ng_pptpgre_start_recv_ack_timer(hpriv_p hpriv)
1072 /* Compute how long until oldest unack'd packet times out,
1073 and reset the timer to that time. */
1074 remain = (hpriv->timeSent[0] + hpriv->ato) - ng_pptpgre_time();
1078 /* Be conservative: timeout can happen up to 1 tick early */
1079 ticks = howmany(remain * hz, PPTP_TIME_SCALE) + 1;
1080 ng_callout(&hpriv->rackTimer, hpriv->node, hpriv->hook,
1081 ticks, ng_pptpgre_recv_ack_timeout, hpriv, 0);
1085 * The peer has failed to acknowledge the oldest unacknowledged sequence
1086 * number within the time allotted. Update our adaptive timeout parameters
1087 * and reset/restart the recv ack timer.
1090 ng_pptpgre_recv_ack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1092 const priv_p priv = NG_NODE_PRIVATE(node);
1093 const hpriv_p hpriv = arg1;
1095 /* Update adaptive timeout stuff */
1096 priv->stats.recvAckTimeouts++;
1097 hpriv->rtt = PPTP_ACK_DELTA(hpriv->rtt) + 1; /* +1 to avoid delta*0 case */
1098 hpriv->ato = hpriv->rtt + PPTP_ACK_CHI(hpriv->dev);
1099 if (hpriv->ato > PPTP_MAX_TIMEOUT)
1100 hpriv->ato = PPTP_MAX_TIMEOUT;
1101 else if (hpriv->ato < PPTP_MIN_TIMEOUT)
1102 hpriv->ato = PPTP_MIN_TIMEOUT;
1104 /* Reset ack and sliding window */
1105 hpriv->recvAck = hpriv->xmitSeq; /* pretend we got the ack */
1106 hpriv->xmitWin = (hpriv->xmitWin + 1) / 2; /* shrink transmit window */
1107 hpriv->winAck = hpriv->recvAck + hpriv->xmitWin; /* reset win expand time */
1111 * Start the send ack timer. This assumes the timer is not
1115 ng_pptpgre_start_send_ack_timer(hpriv_p hpriv)
1117 int ackTimeout, ticks;
1119 /* Take 1/4 of the estimated round trip time */
1120 ackTimeout = (hpriv->rtt >> 2);
1121 if (ackTimeout < PPTP_MIN_ACK_DELAY)
1122 ackTimeout = PPTP_MIN_ACK_DELAY;
1123 else if (ackTimeout > PPTP_MAX_ACK_DELAY)
1124 ackTimeout = PPTP_MAX_ACK_DELAY;
1126 /* Be conservative: timeout can happen up to 1 tick early */
1127 ticks = howmany(ackTimeout * hz, PPTP_TIME_SCALE);
1128 ng_callout(&hpriv->sackTimer, hpriv->node, hpriv->hook,
1129 ticks, ng_pptpgre_send_ack_timeout, hpriv, 0);
1133 * We've waited as long as we're willing to wait before sending an
1134 * acknowledgement to the peer for received frames. We had hoped to
1135 * be able to piggy back our acknowledgement on an outgoing data frame,
1136 * but apparently there haven't been any since. So send the ack now.
1139 ng_pptpgre_send_ack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1141 const hpriv_p hpriv = arg1;
1143 mtx_lock(&hpriv->mtx);
1144 /* Send a frame with an ack but no payload */
1145 ng_pptpgre_xmit(hpriv, NULL);
1146 mtx_assert(&hpriv->mtx, MA_NOTOWNED);
1150 * Start a timer for the reorder queue. This assumes the timer is not
1154 ng_pptpgre_start_reorder_timer(hpriv_p hpriv)
1158 /* Be conservative: timeout can happen up to 1 tick early */
1159 ticks = (((reorder_timeout * hz) + 1000 - 1) / 1000) + 1;
1160 ng_callout(&hpriv->reorderTimer, hpriv->node, hpriv->hook,
1161 ticks, ng_pptpgre_reorder_timeout, hpriv, 0);
1165 * The oldest packet spent too much time in the reorder queue.
1166 * Deliver it and next packets in sequence, if any.
1169 ng_pptpgre_reorder_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1171 const priv_p priv = NG_NODE_PRIVATE(node);
1172 const hpriv_p hpriv = arg1;
1173 roqh sendq = SLIST_HEAD_INITIALIZER(sendq);
1174 struct ng_pptpgre_roq *np, *last = NULL;
1176 priv->stats.recvReorderTimeouts++;
1177 mtx_lock(&hpriv->mtx);
1178 if (SLIST_EMPTY(&hpriv->roq)) { /* should not happen */
1179 mtx_unlock(&hpriv->mtx);
1183 last = np = SLIST_FIRST(&hpriv->roq);
1185 SLIST_REMOVE_HEAD(&hpriv->roq, next);
1186 SLIST_INSERT_HEAD(&sendq, np, next);
1188 /* Look if we have more packets in sequence */
1189 while (!SLIST_EMPTY(&hpriv->roq)) {
1190 np = SLIST_FIRST(&hpriv->roq);
1191 if (PPTP_SEQ_DIFF(np->seq, last->seq) > 1)
1192 break; /* the gap in the sequence */
1194 /* Next packet is in sequence, move it to the sendq. */
1196 SLIST_REMOVE_HEAD(&hpriv->roq, next);
1197 SLIST_INSERT_AFTER(last, np, next);
1201 hpriv->recvSeq = last->seq;
1202 if (!SLIST_EMPTY(&hpriv->roq))
1203 ng_pptpgre_start_reorder_timer(hpriv);
1205 /* We need to acknowledge last packet; do it soon... */
1206 ng_pptpgre_ack(hpriv); /* drops lock */
1207 ng_pptpgre_sendq(hpriv, &sendq, NULL);
1208 mtx_assert(&hpriv->mtx, MA_NOTOWNED);
1211 /*************************************************************************
1213 *************************************************************************/
1216 * Find the hook with a given session ID.
1219 ng_pptpgre_find_session(priv_p privp, u_int16_t cid)
1221 uint16_t hash = SESSHASH(cid);
1222 hpriv_p hpriv = NULL;
1224 LIST_FOREACH(hpriv, &privp->sesshash[hash], sessions) {
1225 if (hpriv->conf.cid == cid)
1233 * Reset state (must be called with lock held or from writer)
1236 ng_pptpgre_reset(hpriv_p hpriv)
1238 struct ng_pptpgre_roq *np;
1240 /* Reset adaptive timeout state */
1241 hpriv->ato = PPTP_MAX_TIMEOUT;
1242 hpriv->rtt = PPTP_TIME_SCALE / 10;
1243 if (hpriv->conf.peerPpd > 1) /* ppd = 0 treat as = 1 */
1244 hpriv->rtt *= hpriv->conf.peerPpd;
1246 hpriv->xmitWin = (hpriv->conf.recvWin + 1) / 2;
1247 if (hpriv->xmitWin < 2) /* often the first packet is lost */
1248 hpriv->xmitWin = 2; /* because the peer isn't ready */
1249 else if (hpriv->xmitWin > PPTP_XMIT_WIN)
1250 hpriv->xmitWin = PPTP_XMIT_WIN;
1251 hpriv->winAck = hpriv->xmitWin;
1253 /* Reset sequence numbers */
1254 hpriv->recvSeq = ~0;
1255 hpriv->recvAck = ~0;
1256 hpriv->xmitSeq = ~0;
1257 hpriv->xmitAck = ~0;
1260 ng_uncallout(&hpriv->sackTimer, hpriv->node);
1261 ng_uncallout(&hpriv->rackTimer, hpriv->node);
1262 ng_uncallout(&hpriv->reorderTimer, hpriv->node);
1264 /* Clear reorder queue */
1265 while (!SLIST_EMPTY(&hpriv->roq)) {
1266 np = SLIST_FIRST(&hpriv->roq);
1267 SLIST_REMOVE_HEAD(&hpriv->roq, next);
1268 NG_FREE_ITEM(np->item);
1269 free(np, M_NETGRAPH);
1275 * Return the current time scaled & translated to our internally used format.
1278 ng_pptpgre_time(void)
1284 t = (pptptime_t)tv.tv_sec * PPTP_TIME_SCALE;
1285 t += tv.tv_usec / (1000000 / PPTP_TIME_SCALE);