MFC:
[dragonfly.git] / sys / netgraph7 / ng_ppp.c
blob1418f9b0af8d80ca527223286e448216aa27f210
1 /*-
2 * Copyright (c) 1996-2000 Whistle Communications, Inc.
3 * All rights reserved.
5 * Subject to the following obligations and disclaimer of warranty, use and
6 * redistribution of this software, in source or object code forms, with or
7 * without modifications are expressly permitted by Whistle Communications;
8 * provided, however, that:
9 * 1. Any and all reproductions of the source or object code must include the
10 * copyright notice above and the following disclaimer of warranties; and
11 * 2. No rights are granted, in any manner or form, to use Whistle
12 * Communications, Inc. trademarks, including the mark "WHISTLE
13 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
14 * such appears in the above copyright notice or in the software.
16 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
17 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
18 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
19 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
21 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
22 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
23 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
24 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
25 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
26 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
32 * OF SUCH DAMAGE.
34 * Copyright (c) 2007 Alexander Motin <mav@alkar.net>
35 * All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice unmodified, this list of conditions, and the following
42 * disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
47 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * SUCH DAMAGE.
59 * Authors: Archie Cobbs <archie@freebsd.org>, Alexander Motin <mav@alkar.net>
61 * $FreeBSD: src/sys/netgraph/ng_ppp.c,v 1.75 2008/02/06 20:37:34 mav Exp $
62 * $DragonFly: src/sys/netgraph7/ng_ppp.c,v 1.2 2008/06/26 23:05:35 dillon Exp $
63 * $Whistle: ng_ppp.c,v 1.24 1999/11/01 09:24:52 julian Exp $
67 * PPP node type data-flow.
69 * hook xmit layer recv hook
70 * ------------------------------------
71 * inet -> -> inet
72 * ipv6 -> -> ipv6
73 * ipx -> proto -> ipx
74 * atalk -> -> atalk
75 * bypass -> -> bypass
76 * -hcomp_xmit()----------proto_recv()-
77 * vjc_ip <- <- vjc_ip
78 * vjc_comp -> header compression -> vjc_comp
79 * vjc_uncomp -> -> vjc_uncomp
80 * vjc_vjip ->
81 * -comp_xmit()-----------hcomp_recv()-
82 * compress <- compression <- decompress
83 * compress -> -> decompress
84 * -crypt_xmit()-----------comp_recv()-
85 * encrypt <- encryption <- decrypt
86 * encrypt -> -> decrypt
87 * -ml_xmit()-------------crypt_recv()-
88 * multilink
89 * -link_xmit()--------------ml_recv()-
90 * linkX <- link <- linkX
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/limits.h>
98 #include <sys/time.h>
99 #include <sys/mbuf.h>
100 #include <sys/malloc.h>
101 #include <sys/errno.h>
102 #include <sys/ctype.h>
104 #include "ng_message.h"
105 #include "netgraph.h"
106 #include "ng_parse.h"
107 #include "ng_ppp.h"
108 #include "ng_vjc.h"
110 #ifdef NG_SEPARATE_MALLOC
111 MALLOC_DEFINE(M_NETGRAPH_PPP, "netgraph_ppp", "netgraph ppp node");
112 #else
113 #define M_NETGRAPH_PPP M_NETGRAPH
114 #endif
116 #define PROT_VALID(p) (((p) & 0x0101) == 0x0001)
117 #define PROT_COMPRESSABLE(p) (((p) & 0xff00) == 0x0000)
119 /* Some PPP protocol numbers we're interested in */
120 #define PROT_ATALK 0x0029
121 #define PROT_COMPD 0x00fd
122 #define PROT_CRYPTD 0x0053
123 #define PROT_IP 0x0021
124 #define PROT_IPV6 0x0057
125 #define PROT_IPX 0x002b
126 #define PROT_LCP 0xc021
127 #define PROT_MP 0x003d
128 #define PROT_VJCOMP 0x002d
129 #define PROT_VJUNCOMP 0x002f
131 /* Multilink PPP definitions */
132 #define MP_MIN_MRRU 1500 /* per RFC 1990 */
133 #define MP_INITIAL_SEQ 0 /* per RFC 1990 */
134 #define MP_MIN_LINK_MRU 32
136 #define MP_SHORT_SEQ_MASK 0x00000fff /* short seq # mask */
137 #define MP_SHORT_SEQ_HIBIT 0x00000800 /* short seq # high bit */
138 #define MP_SHORT_FIRST_FLAG 0x00008000 /* first fragment in frame */
139 #define MP_SHORT_LAST_FLAG 0x00004000 /* last fragment in frame */
141 #define MP_LONG_SEQ_MASK 0x00ffffff /* long seq # mask */
142 #define MP_LONG_SEQ_HIBIT 0x00800000 /* long seq # high bit */
143 #define MP_LONG_FIRST_FLAG 0x80000000 /* first fragment in frame */
144 #define MP_LONG_LAST_FLAG 0x40000000 /* last fragment in frame */
146 #define MP_NOSEQ 0x7fffffff /* impossible sequence number */
148 /* Sign extension of MP sequence numbers */
149 #define MP_SHORT_EXTEND(s) (((s) & MP_SHORT_SEQ_HIBIT) ? \
150 ((s) | ~MP_SHORT_SEQ_MASK) \
151 : ((s) & MP_SHORT_SEQ_MASK))
152 #define MP_LONG_EXTEND(s) (((s) & MP_LONG_SEQ_HIBIT) ? \
153 ((s) | ~MP_LONG_SEQ_MASK) \
154 : ((s) & MP_LONG_SEQ_MASK))
156 /* Comparision of MP sequence numbers. Note: all sequence numbers
157 except priv->xseq are stored with the sign bit extended. */
158 #define MP_SHORT_SEQ_DIFF(x,y) MP_SHORT_EXTEND((x) - (y))
159 #define MP_LONG_SEQ_DIFF(x,y) MP_LONG_EXTEND((x) - (y))
161 #define MP_RECV_SEQ_DIFF(priv,x,y) \
162 ((priv)->conf.recvShortSeq ? \
163 MP_SHORT_SEQ_DIFF((x), (y)) : \
164 MP_LONG_SEQ_DIFF((x), (y)))
166 /* Increment receive sequence number */
167 #define MP_NEXT_RECV_SEQ(priv,seq) \
168 ((priv)->conf.recvShortSeq ? \
169 MP_SHORT_EXTEND((seq) + 1) : \
170 MP_LONG_EXTEND((seq) + 1))
172 /* Don't fragment transmitted packets to parts smaller than this */
173 #define MP_MIN_FRAG_LEN 32
175 /* Maximum fragment reasssembly queue length */
176 #define MP_MAX_QUEUE_LEN 128
178 /* Fragment queue scanner period */
179 #define MP_FRAGTIMER_INTERVAL (hz/2)
181 /* Average link overhead. XXX: Should be given by user-level */
182 #define MP_AVERAGE_LINK_OVERHEAD 16
184 /* Keep this equal to ng_ppp_hook_names lower! */
185 #define HOOK_INDEX_MAX 13
187 /* We store incoming fragments this way */
188 struct ng_ppp_frag {
189 int seq; /* fragment seq# */
190 uint8_t first; /* First in packet? */
191 uint8_t last; /* Last in packet? */
192 struct timeval timestamp; /* time of reception */
193 struct mbuf *data; /* Fragment data */
194 TAILQ_ENTRY(ng_ppp_frag) f_qent; /* Fragment queue */
197 /* Per-link private information */
198 struct ng_ppp_link {
199 struct ng_ppp_link_conf conf; /* link configuration */
200 struct ng_ppp_link_stat64 stats; /* link stats */
201 hook_p hook; /* connection to link data */
202 int32_t seq; /* highest rec'd seq# - MSEQ */
203 uint32_t latency; /* calculated link latency */
204 struct timeval lastWrite; /* time of last write for MP */
205 int bytesInQueue; /* bytes in the output queue for MP */
208 /* Total per-node private information */
209 struct ng_ppp_private {
210 struct ng_ppp_bund_conf conf; /* bundle config */
211 struct ng_ppp_link_stat64 bundleStats; /* bundle stats */
212 struct ng_ppp_link links[NG_PPP_MAX_LINKS];/* per-link info */
213 int32_t xseq; /* next out MP seq # */
214 int32_t mseq; /* min links[i].seq */
215 uint16_t activeLinks[NG_PPP_MAX_LINKS]; /* indicies */
216 uint16_t numActiveLinks; /* how many links up */
217 uint16_t lastLink; /* for round robin */
218 uint8_t vjCompHooked; /* VJ comp hooked up? */
219 uint8_t allLinksEqual; /* all xmit the same? */
220 hook_p hooks[HOOK_INDEX_MAX]; /* non-link hooks */
221 struct ng_ppp_frag fragsmem[MP_MAX_QUEUE_LEN]; /* fragments storage */
222 TAILQ_HEAD(ng_ppp_fraglist, ng_ppp_frag) /* fragment queue */
223 frags;
224 TAILQ_HEAD(ng_ppp_fragfreelist, ng_ppp_frag) /* free fragment queue */
225 fragsfree;
226 struct callout fragTimer; /* fraq queue check */
227 struct mtx rmtx; /* recv mutex */
228 struct mtx xmtx; /* xmit mutex */
230 typedef struct ng_ppp_private *priv_p;
232 /* Netgraph node methods */
233 static ng_constructor_t ng_ppp_constructor;
234 static ng_rcvmsg_t ng_ppp_rcvmsg;
235 static ng_shutdown_t ng_ppp_shutdown;
236 static ng_newhook_t ng_ppp_newhook;
237 static ng_rcvdata_t ng_ppp_rcvdata;
238 static ng_disconnect_t ng_ppp_disconnect;
240 static ng_rcvdata_t ng_ppp_rcvdata_inet;
241 static ng_rcvdata_t ng_ppp_rcvdata_ipv6;
242 static ng_rcvdata_t ng_ppp_rcvdata_ipx;
243 static ng_rcvdata_t ng_ppp_rcvdata_atalk;
244 static ng_rcvdata_t ng_ppp_rcvdata_bypass;
246 static ng_rcvdata_t ng_ppp_rcvdata_vjc_ip;
247 static ng_rcvdata_t ng_ppp_rcvdata_vjc_comp;
248 static ng_rcvdata_t ng_ppp_rcvdata_vjc_uncomp;
249 static ng_rcvdata_t ng_ppp_rcvdata_vjc_vjip;
251 static ng_rcvdata_t ng_ppp_rcvdata_compress;
252 static ng_rcvdata_t ng_ppp_rcvdata_decompress;
254 static ng_rcvdata_t ng_ppp_rcvdata_encrypt;
255 static ng_rcvdata_t ng_ppp_rcvdata_decrypt;
257 /* We use integer indicies to refer to the non-link hooks. */
258 static const struct {
259 char *const name;
260 ng_rcvdata_t *fn;
261 } ng_ppp_hook_names[] = {
262 #define HOOK_INDEX_ATALK 0
263 { NG_PPP_HOOK_ATALK, ng_ppp_rcvdata_atalk },
264 #define HOOK_INDEX_BYPASS 1
265 { NG_PPP_HOOK_BYPASS, ng_ppp_rcvdata_bypass },
266 #define HOOK_INDEX_COMPRESS 2
267 { NG_PPP_HOOK_COMPRESS, ng_ppp_rcvdata_compress },
268 #define HOOK_INDEX_ENCRYPT 3
269 { NG_PPP_HOOK_ENCRYPT, ng_ppp_rcvdata_encrypt },
270 #define HOOK_INDEX_DECOMPRESS 4
271 { NG_PPP_HOOK_DECOMPRESS, ng_ppp_rcvdata_decompress },
272 #define HOOK_INDEX_DECRYPT 5
273 { NG_PPP_HOOK_DECRYPT, ng_ppp_rcvdata_decrypt },
274 #define HOOK_INDEX_INET 6
275 { NG_PPP_HOOK_INET, ng_ppp_rcvdata_inet },
276 #define HOOK_INDEX_IPX 7
277 { NG_PPP_HOOK_IPX, ng_ppp_rcvdata_ipx },
278 #define HOOK_INDEX_VJC_COMP 8
279 { NG_PPP_HOOK_VJC_COMP, ng_ppp_rcvdata_vjc_comp },
280 #define HOOK_INDEX_VJC_IP 9
281 { NG_PPP_HOOK_VJC_IP, ng_ppp_rcvdata_vjc_ip },
282 #define HOOK_INDEX_VJC_UNCOMP 10
283 { NG_PPP_HOOK_VJC_UNCOMP, ng_ppp_rcvdata_vjc_uncomp },
284 #define HOOK_INDEX_VJC_VJIP 11
285 { NG_PPP_HOOK_VJC_VJIP, ng_ppp_rcvdata_vjc_vjip },
286 #define HOOK_INDEX_IPV6 12
287 { NG_PPP_HOOK_IPV6, ng_ppp_rcvdata_ipv6 },
288 { NULL, NULL }
291 /* Helper functions */
292 static int ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto,
293 uint16_t linkNum);
294 static int ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto);
295 static int ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto,
296 uint16_t linkNum);
297 static int ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto);
298 static int ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto,
299 uint16_t linkNum);
300 static int ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto);
301 static int ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto,
302 uint16_t linkNum);
303 static int ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto);
304 static int ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto,
305 uint16_t linkNum);
306 static int ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto,
307 uint16_t linkNum, int plen);
309 static int ng_ppp_bypass(node_p node, item_p item, uint16_t proto,
310 uint16_t linkNum);
312 static void ng_ppp_bump_mseq(node_p node, int32_t new_mseq);
313 static int ng_ppp_frag_drop(node_p node);
314 static int ng_ppp_check_packet(node_p node);
315 static void ng_ppp_get_packet(node_p node, struct mbuf **mp);
316 static int ng_ppp_frag_process(node_p node, item_p oitem);
317 static int ng_ppp_frag_trim(node_p node);
318 static void ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1,
319 int arg2);
320 static void ng_ppp_frag_checkstale(node_p node);
321 static void ng_ppp_frag_reset(node_p node);
322 static void ng_ppp_mp_strategy(node_p node, int len, int *distrib);
323 static int ng_ppp_intcmp(void *latency, const void *v1, const void *v2);
324 static struct mbuf *ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK);
325 static struct mbuf *ng_ppp_cutproto(struct mbuf *m, uint16_t *proto);
326 static struct mbuf *ng_ppp_prepend(struct mbuf *m, const void *buf, int len);
327 static int ng_ppp_config_valid(node_p node,
328 const struct ng_ppp_node_conf *newConf);
329 static void ng_ppp_update(node_p node, int newConf);
330 static void ng_ppp_start_frag_timer(node_p node);
331 static void ng_ppp_stop_frag_timer(node_p node);
333 /* Parse type for struct ng_ppp_mp_state_type */
334 static const struct ng_parse_fixedarray_info ng_ppp_rseq_array_info = {
335 &ng_parse_hint32_type,
336 NG_PPP_MAX_LINKS
338 static const struct ng_parse_type ng_ppp_rseq_array_type = {
339 &ng_parse_fixedarray_type,
340 &ng_ppp_rseq_array_info,
342 static const struct ng_parse_struct_field ng_ppp_mp_state_type_fields[]
343 = NG_PPP_MP_STATE_TYPE_INFO(&ng_ppp_rseq_array_type);
344 static const struct ng_parse_type ng_ppp_mp_state_type = {
345 &ng_parse_struct_type,
346 &ng_ppp_mp_state_type_fields
349 /* Parse type for struct ng_ppp_link_conf */
350 static const struct ng_parse_struct_field ng_ppp_link_type_fields[]
351 = NG_PPP_LINK_TYPE_INFO;
352 static const struct ng_parse_type ng_ppp_link_type = {
353 &ng_parse_struct_type,
354 &ng_ppp_link_type_fields
357 /* Parse type for struct ng_ppp_bund_conf */
358 static const struct ng_parse_struct_field ng_ppp_bund_type_fields[]
359 = NG_PPP_BUND_TYPE_INFO;
360 static const struct ng_parse_type ng_ppp_bund_type = {
361 &ng_parse_struct_type,
362 &ng_ppp_bund_type_fields
365 /* Parse type for struct ng_ppp_node_conf */
366 static const struct ng_parse_fixedarray_info ng_ppp_array_info = {
367 &ng_ppp_link_type,
368 NG_PPP_MAX_LINKS
370 static const struct ng_parse_type ng_ppp_link_array_type = {
371 &ng_parse_fixedarray_type,
372 &ng_ppp_array_info,
374 static const struct ng_parse_struct_field ng_ppp_conf_type_fields[]
375 = NG_PPP_CONFIG_TYPE_INFO(&ng_ppp_bund_type, &ng_ppp_link_array_type);
376 static const struct ng_parse_type ng_ppp_conf_type = {
377 &ng_parse_struct_type,
378 &ng_ppp_conf_type_fields
381 /* Parse type for struct ng_ppp_link_stat */
382 static const struct ng_parse_struct_field ng_ppp_stats_type_fields[]
383 = NG_PPP_STATS_TYPE_INFO;
384 static const struct ng_parse_type ng_ppp_stats_type = {
385 &ng_parse_struct_type,
386 &ng_ppp_stats_type_fields
389 /* Parse type for struct ng_ppp_link_stat64 */
390 static const struct ng_parse_struct_field ng_ppp_stats64_type_fields[]
391 = NG_PPP_STATS64_TYPE_INFO;
392 static const struct ng_parse_type ng_ppp_stats64_type = {
393 &ng_parse_struct_type,
394 &ng_ppp_stats64_type_fields
397 /* List of commands and how to convert arguments to/from ASCII */
398 static const struct ng_cmdlist ng_ppp_cmds[] = {
400 NGM_PPP_COOKIE,
401 NGM_PPP_SET_CONFIG,
402 "setconfig",
403 &ng_ppp_conf_type,
404 NULL
407 NGM_PPP_COOKIE,
408 NGM_PPP_GET_CONFIG,
409 "getconfig",
410 NULL,
411 &ng_ppp_conf_type
414 NGM_PPP_COOKIE,
415 NGM_PPP_GET_MP_STATE,
416 "getmpstate",
417 NULL,
418 &ng_ppp_mp_state_type
421 NGM_PPP_COOKIE,
422 NGM_PPP_GET_LINK_STATS,
423 "getstats",
424 &ng_parse_int16_type,
425 &ng_ppp_stats_type
428 NGM_PPP_COOKIE,
429 NGM_PPP_CLR_LINK_STATS,
430 "clrstats",
431 &ng_parse_int16_type,
432 NULL
435 NGM_PPP_COOKIE,
436 NGM_PPP_GETCLR_LINK_STATS,
437 "getclrstats",
438 &ng_parse_int16_type,
439 &ng_ppp_stats_type
442 NGM_PPP_COOKIE,
443 NGM_PPP_GET_LINK_STATS64,
444 "getstats64",
445 &ng_parse_int16_type,
446 &ng_ppp_stats64_type
449 NGM_PPP_COOKIE,
450 NGM_PPP_GETCLR_LINK_STATS64,
451 "getclrstats64",
452 &ng_parse_int16_type,
453 &ng_ppp_stats64_type
455 { 0 }
458 /* Node type descriptor */
459 static struct ng_type ng_ppp_typestruct = {
460 .version = NG_ABI_VERSION,
461 .name = NG_PPP_NODE_TYPE,
462 .constructor = ng_ppp_constructor,
463 .rcvmsg = ng_ppp_rcvmsg,
464 .shutdown = ng_ppp_shutdown,
465 .newhook = ng_ppp_newhook,
466 .rcvdata = ng_ppp_rcvdata,
467 .disconnect = ng_ppp_disconnect,
468 .cmdlist = ng_ppp_cmds,
470 NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
472 /* Address and control field header */
473 static const uint8_t ng_ppp_acf[2] = { 0xff, 0x03 };
475 /* Maximum time we'll let a complete incoming packet sit in the queue */
476 static const struct timeval ng_ppp_max_staleness = { 2, 0 }; /* 2 seconds */
478 #define ERROUT(x) do { error = (x); goto done; } while (0)
480 /************************************************************************
481 NETGRAPH NODE STUFF
482 ************************************************************************/
485 * Node type constructor
487 static int
488 ng_ppp_constructor(node_p node)
490 priv_p priv;
491 int i;
493 /* Allocate private structure */
494 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_PPP, M_WAITOK | M_NULLOK | M_ZERO);
495 if (priv == NULL)
496 return (ENOMEM);
498 NG_NODE_SET_PRIVATE(node, priv);
500 /* Initialize state */
501 TAILQ_INIT(&priv->frags);
502 TAILQ_INIT(&priv->fragsfree);
503 for (i = 0; i < MP_MAX_QUEUE_LEN; i++)
504 TAILQ_INSERT_TAIL(&priv->fragsfree, &priv->fragsmem[i], f_qent);
505 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
506 priv->links[i].seq = MP_NOSEQ;
507 ng_callout_init(&priv->fragTimer);
509 mtx_init(&priv->rmtx, "ng_ppp_recv", NULL, MTX_DEF);
510 mtx_init(&priv->xmtx, "ng_ppp_xmit", NULL, MTX_DEF);
512 /* Done */
513 return (0);
517 * Give our OK for a hook to be added
519 static int
520 ng_ppp_newhook(node_p node, hook_p hook, const char *name)
522 const priv_p priv = NG_NODE_PRIVATE(node);
523 hook_p *hookPtr = NULL;
524 int linkNum = -1;
525 int hookIndex = -1;
527 /* Figure out which hook it is */
528 if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX, /* a link hook? */
529 strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
530 const char *cp;
531 char *eptr;
533 cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
534 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
535 return (EINVAL);
536 linkNum = (int)strtoul(cp, &eptr, 10);
537 if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
538 return (EINVAL);
539 hookPtr = &priv->links[linkNum].hook;
540 hookIndex = ~linkNum;
542 /* See if hook is already connected. */
543 if (*hookPtr != NULL)
544 return (EISCONN);
546 /* Disallow more than one link unless multilink is enabled. */
547 if (priv->links[linkNum].conf.enableLink &&
548 !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
549 return (ENODEV);
551 } else { /* must be a non-link hook */
552 int i;
554 for (i = 0; ng_ppp_hook_names[i].name != NULL; i++) {
555 if (strcmp(name, ng_ppp_hook_names[i].name) == 0) {
556 hookPtr = &priv->hooks[i];
557 hookIndex = i;
558 break;
561 if (ng_ppp_hook_names[i].name == NULL)
562 return (EINVAL); /* no such hook */
564 /* See if hook is already connected */
565 if (*hookPtr != NULL)
566 return (EISCONN);
568 /* Every non-linkX hook have it's own function. */
569 NG_HOOK_SET_RCVDATA(hook, ng_ppp_hook_names[i].fn);
572 /* OK */
573 *hookPtr = hook;
574 NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)hookIndex);
575 ng_ppp_update(node, 0);
576 return (0);
580 * Receive a control message
582 static int
583 ng_ppp_rcvmsg(node_p node, item_p item, hook_p lasthook)
585 const priv_p priv = NG_NODE_PRIVATE(node);
586 struct ng_mesg *resp = NULL;
587 int error = 0;
588 struct ng_mesg *msg;
590 NGI_GET_MSG(item, msg);
591 switch (msg->header.typecookie) {
592 case NGM_PPP_COOKIE:
593 switch (msg->header.cmd) {
594 case NGM_PPP_SET_CONFIG:
596 struct ng_ppp_node_conf *const conf =
597 (struct ng_ppp_node_conf *)msg->data;
598 int i;
600 /* Check for invalid or illegal config */
601 if (msg->header.arglen != sizeof(*conf))
602 ERROUT(EINVAL);
603 if (!ng_ppp_config_valid(node, conf))
604 ERROUT(EINVAL);
606 /* Copy config */
607 priv->conf = conf->bund;
608 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
609 priv->links[i].conf = conf->links[i];
610 ng_ppp_update(node, 1);
611 break;
613 case NGM_PPP_GET_CONFIG:
615 struct ng_ppp_node_conf *conf;
616 int i;
618 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_WAITOK | M_NULLOK);
619 if (resp == NULL)
620 ERROUT(ENOMEM);
621 conf = (struct ng_ppp_node_conf *)resp->data;
622 conf->bund = priv->conf;
623 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
624 conf->links[i] = priv->links[i].conf;
625 break;
627 case NGM_PPP_GET_MP_STATE:
629 struct ng_ppp_mp_state *info;
630 int i;
632 NG_MKRESPONSE(resp, msg, sizeof(*info), M_WAITOK | M_NULLOK);
633 if (resp == NULL)
634 ERROUT(ENOMEM);
635 info = (struct ng_ppp_mp_state *)resp->data;
636 bzero(info, sizeof(*info));
637 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
638 if (priv->links[i].seq != MP_NOSEQ)
639 info->rseq[i] = priv->links[i].seq;
641 info->mseq = priv->mseq;
642 info->xseq = priv->xseq;
643 break;
645 case NGM_PPP_GET_LINK_STATS:
646 case NGM_PPP_CLR_LINK_STATS:
647 case NGM_PPP_GETCLR_LINK_STATS:
648 case NGM_PPP_GET_LINK_STATS64:
649 case NGM_PPP_GETCLR_LINK_STATS64:
651 struct ng_ppp_link_stat64 *stats;
652 uint16_t linkNum;
654 /* Process request. */
655 if (msg->header.arglen != sizeof(uint16_t))
656 ERROUT(EINVAL);
657 linkNum = *((uint16_t *) msg->data);
658 if (linkNum >= NG_PPP_MAX_LINKS
659 && linkNum != NG_PPP_BUNDLE_LINKNUM)
660 ERROUT(EINVAL);
661 stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
662 &priv->bundleStats : &priv->links[linkNum].stats;
664 /* Make 64bit reply. */
665 if (msg->header.cmd == NGM_PPP_GET_LINK_STATS64 ||
666 msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS64) {
667 NG_MKRESPONSE(resp, msg,
668 sizeof(struct ng_ppp_link_stat64), M_WAITOK | M_NULLOK);
669 if (resp == NULL)
670 ERROUT(ENOMEM);
671 bcopy(stats, resp->data, sizeof(*stats));
672 } else
673 /* Make 32bit reply. */
674 if (msg->header.cmd == NGM_PPP_GET_LINK_STATS ||
675 msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS) {
676 struct ng_ppp_link_stat *rs;
677 NG_MKRESPONSE(resp, msg,
678 sizeof(struct ng_ppp_link_stat), M_WAITOK | M_NULLOK);
679 if (resp == NULL)
680 ERROUT(ENOMEM);
681 rs = (struct ng_ppp_link_stat *)resp->data;
682 /* Truncate 64->32 bits. */
683 rs->xmitFrames = stats->xmitFrames;
684 rs->xmitOctets = stats->xmitOctets;
685 rs->recvFrames = stats->recvFrames;
686 rs->recvOctets = stats->recvOctets;
687 rs->badProtos = stats->badProtos;
688 rs->runts = stats->runts;
689 rs->dupFragments = stats->dupFragments;
690 rs->dropFragments = stats->dropFragments;
692 /* Clear stats. */
693 if (msg->header.cmd != NGM_PPP_GET_LINK_STATS &&
694 msg->header.cmd != NGM_PPP_GET_LINK_STATS64)
695 bzero(stats, sizeof(*stats));
696 break;
698 default:
699 error = EINVAL;
700 break;
702 break;
703 case NGM_VJC_COOKIE:
706 * Forward it to the vjc node. leave the
707 * old return address alone.
708 * If we have no hook, let NG_RESPOND_MSG
709 * clean up any remaining resources.
710 * Because we have no resp, the item will be freed
711 * along with anything it references. Don't
712 * let msg be freed twice.
714 NGI_MSG(item) = msg; /* put it back in the item */
715 msg = NULL;
716 if ((lasthook = priv->hooks[HOOK_INDEX_VJC_IP])) {
717 NG_FWD_ITEM_HOOK(error, item, lasthook);
719 return (error);
721 default:
722 error = EINVAL;
723 break;
725 done:
726 NG_RESPOND_MSG(error, node, item, resp);
727 NG_FREE_MSG(msg);
728 return (error);
732 * Destroy node
734 static int
735 ng_ppp_shutdown(node_p node)
737 const priv_p priv = NG_NODE_PRIVATE(node);
739 /* Stop fragment queue timer */
740 ng_ppp_stop_frag_timer(node);
742 /* Take down netgraph node */
743 ng_ppp_frag_reset(node);
744 mtx_destroy(&priv->rmtx);
745 mtx_destroy(&priv->xmtx);
746 bzero(priv, sizeof(*priv));
747 FREE(priv, M_NETGRAPH_PPP);
748 NG_NODE_SET_PRIVATE(node, NULL);
749 NG_NODE_UNREF(node); /* let the node escape */
750 return (0);
754 * Hook disconnection
756 static int
757 ng_ppp_disconnect(hook_p hook)
759 const node_p node = NG_HOOK_NODE(hook);
760 const priv_p priv = NG_NODE_PRIVATE(node);
761 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
763 /* Zero out hook pointer */
764 if (index < 0)
765 priv->links[~index].hook = NULL;
766 else
767 priv->hooks[index] = NULL;
769 /* Update derived info (or go away if no hooks left). */
770 if (NG_NODE_NUMHOOKS(node) > 0)
771 ng_ppp_update(node, 0);
772 else if (NG_NODE_IS_VALID(node))
773 ng_rmnode_self(node);
775 return (0);
779 * Proto layer
783 * Receive data on a hook inet.
785 static int
786 ng_ppp_rcvdata_inet(hook_p hook, item_p item)
788 const node_p node = NG_HOOK_NODE(hook);
789 const priv_p priv = NG_NODE_PRIVATE(node);
791 if (!priv->conf.enableIP) {
792 NG_FREE_ITEM(item);
793 return (ENXIO);
795 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IP));
799 * Receive data on a hook ipv6.
801 static int
802 ng_ppp_rcvdata_ipv6(hook_p hook, item_p item)
804 const node_p node = NG_HOOK_NODE(hook);
805 const priv_p priv = NG_NODE_PRIVATE(node);
807 if (!priv->conf.enableIPv6) {
808 NG_FREE_ITEM(item);
809 return (ENXIO);
811 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPV6));
815 * Receive data on a hook atalk.
817 static int
818 ng_ppp_rcvdata_atalk(hook_p hook, item_p item)
820 const node_p node = NG_HOOK_NODE(hook);
821 const priv_p priv = NG_NODE_PRIVATE(node);
823 if (!priv->conf.enableAtalk) {
824 NG_FREE_ITEM(item);
825 return (ENXIO);
827 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_ATALK));
831 * Receive data on a hook ipx
833 static int
834 ng_ppp_rcvdata_ipx(hook_p hook, item_p item)
836 const node_p node = NG_HOOK_NODE(hook);
837 const priv_p priv = NG_NODE_PRIVATE(node);
839 if (!priv->conf.enableIPX) {
840 NG_FREE_ITEM(item);
841 return (ENXIO);
843 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPX));
847 * Receive data on a hook bypass
849 static int
850 ng_ppp_rcvdata_bypass(hook_p hook, item_p item)
852 uint16_t linkNum;
853 uint16_t proto;
854 struct mbuf *m;
856 NGI_GET_M(item, m);
857 if (m->m_pkthdr.len < 4) {
858 NG_FREE_ITEM(item);
859 return (EINVAL);
861 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
862 NG_FREE_ITEM(item);
863 return (ENOBUFS);
865 linkNum = ntohs(mtod(m, uint16_t *)[0]);
866 proto = ntohs(mtod(m, uint16_t *)[1]);
867 m_adj(m, 4);
868 NGI_M(item) = m;
870 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
871 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, proto));
872 else
873 return (ng_ppp_link_xmit(NG_HOOK_NODE(hook), item, proto,
874 linkNum, 0));
877 static int
878 ng_ppp_bypass(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
880 const priv_p priv = NG_NODE_PRIVATE(node);
881 uint16_t hdr[2];
882 struct mbuf *m;
883 int error;
885 if (priv->hooks[HOOK_INDEX_BYPASS] == NULL) {
886 NG_FREE_ITEM(item);
887 return (ENXIO);
890 /* Add 4-byte bypass header. */
891 hdr[0] = htons(linkNum);
892 hdr[1] = htons(proto);
894 NGI_GET_M(item, m);
895 if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
896 NG_FREE_ITEM(item);
897 return (ENOBUFS);
899 NGI_M(item) = m;
901 /* Send packet out hook. */
902 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_BYPASS]);
903 return (error);
906 static int
907 ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
909 const priv_p priv = NG_NODE_PRIVATE(node);
910 hook_p outHook = NULL;
911 int error;
913 switch (proto) {
914 case PROT_IP:
915 if (priv->conf.enableIP)
916 outHook = priv->hooks[HOOK_INDEX_INET];
917 break;
918 case PROT_IPV6:
919 if (priv->conf.enableIPv6)
920 outHook = priv->hooks[HOOK_INDEX_IPV6];
921 break;
922 case PROT_ATALK:
923 if (priv->conf.enableAtalk)
924 outHook = priv->hooks[HOOK_INDEX_ATALK];
925 break;
926 case PROT_IPX:
927 if (priv->conf.enableIPX)
928 outHook = priv->hooks[HOOK_INDEX_IPX];
929 break;
932 if (outHook == NULL)
933 return (ng_ppp_bypass(node, item, proto, linkNum));
935 /* Send packet out hook. */
936 NG_FWD_ITEM_HOOK(error, item, outHook);
937 return (error);
941 * Header compression layer
944 static int
945 ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto)
947 const priv_p priv = NG_NODE_PRIVATE(node);
949 if (proto == PROT_IP &&
950 priv->conf.enableVJCompression &&
951 priv->vjCompHooked) {
952 int error;
954 /* Send packet out hook. */
955 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_VJC_IP]);
956 return (error);
959 return (ng_ppp_comp_xmit(node, item, proto));
963 * Receive data on a hook vjc_comp.
965 static int
966 ng_ppp_rcvdata_vjc_comp(hook_p hook, item_p item)
968 const node_p node = NG_HOOK_NODE(hook);
969 const priv_p priv = NG_NODE_PRIVATE(node);
971 if (!priv->conf.enableVJCompression) {
972 NG_FREE_ITEM(item);
973 return (ENXIO);
975 return (ng_ppp_comp_xmit(node, item, PROT_VJCOMP));
979 * Receive data on a hook vjc_uncomp.
981 static int
982 ng_ppp_rcvdata_vjc_uncomp(hook_p hook, item_p item)
984 const node_p node = NG_HOOK_NODE(hook);
985 const priv_p priv = NG_NODE_PRIVATE(node);
987 if (!priv->conf.enableVJCompression) {
988 NG_FREE_ITEM(item);
989 return (ENXIO);
991 return (ng_ppp_comp_xmit(node, item, PROT_VJUNCOMP));
995 * Receive data on a hook vjc_vjip.
997 static int
998 ng_ppp_rcvdata_vjc_vjip(hook_p hook, item_p item)
1000 const node_p node = NG_HOOK_NODE(hook);
1001 const priv_p priv = NG_NODE_PRIVATE(node);
1003 if (!priv->conf.enableVJCompression) {
1004 NG_FREE_ITEM(item);
1005 return (ENXIO);
1007 return (ng_ppp_comp_xmit(node, item, PROT_IP));
1010 static int
1011 ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1013 const priv_p priv = NG_NODE_PRIVATE(node);
1015 if (priv->conf.enableVJDecompression && priv->vjCompHooked) {
1016 hook_p outHook = NULL;
1018 switch (proto) {
1019 case PROT_VJCOMP:
1020 outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
1021 break;
1022 case PROT_VJUNCOMP:
1023 outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
1024 break;
1027 if (outHook) {
1028 int error;
1030 /* Send packet out hook. */
1031 NG_FWD_ITEM_HOOK(error, item, outHook);
1032 return (error);
1036 return (ng_ppp_proto_recv(node, item, proto, linkNum));
1040 * Receive data on a hook vjc_ip.
1042 static int
1043 ng_ppp_rcvdata_vjc_ip(hook_p hook, item_p item)
1045 const node_p node = NG_HOOK_NODE(hook);
1046 const priv_p priv = NG_NODE_PRIVATE(node);
1048 if (!priv->conf.enableVJDecompression) {
1049 NG_FREE_ITEM(item);
1050 return (ENXIO);
1052 return (ng_ppp_proto_recv(node, item, PROT_IP, NG_PPP_BUNDLE_LINKNUM));
1056 * Compression layer
1059 static int
1060 ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto)
1062 const priv_p priv = NG_NODE_PRIVATE(node);
1064 if (priv->conf.enableCompression &&
1065 proto < 0x4000 &&
1066 proto != PROT_COMPD &&
1067 proto != PROT_CRYPTD &&
1068 priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
1069 struct mbuf *m;
1070 int error;
1072 NGI_GET_M(item, m);
1073 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1074 NG_FREE_ITEM(item);
1075 return (ENOBUFS);
1077 NGI_M(item) = m;
1079 /* Send packet out hook. */
1080 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_COMPRESS]);
1081 return (error);
1084 return (ng_ppp_crypt_xmit(node, item, proto));
1088 * Receive data on a hook compress.
1090 static int
1091 ng_ppp_rcvdata_compress(hook_p hook, item_p item)
1093 const node_p node = NG_HOOK_NODE(hook);
1094 const priv_p priv = NG_NODE_PRIVATE(node);
1095 uint16_t proto;
1097 switch (priv->conf.enableCompression) {
1098 case NG_PPP_COMPRESS_NONE:
1099 NG_FREE_ITEM(item);
1100 return (ENXIO);
1101 case NG_PPP_COMPRESS_FULL:
1103 struct mbuf *m;
1105 NGI_GET_M(item, m);
1106 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1107 NG_FREE_ITEM(item);
1108 return (EIO);
1110 NGI_M(item) = m;
1111 if (!PROT_VALID(proto)) {
1112 NG_FREE_ITEM(item);
1113 return (EIO);
1116 break;
1117 default:
1118 proto = PROT_COMPD;
1119 break;
1121 return (ng_ppp_crypt_xmit(node, item, proto));
1124 static int
1125 ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1127 const priv_p priv = NG_NODE_PRIVATE(node);
1129 if (proto < 0x4000 &&
1130 ((proto == PROT_COMPD && priv->conf.enableDecompression) ||
1131 priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) &&
1132 priv->hooks[HOOK_INDEX_DECOMPRESS] != NULL) {
1133 int error;
1135 if (priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) {
1136 struct mbuf *m;
1137 NGI_GET_M(item, m);
1138 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1139 NG_FREE_ITEM(item);
1140 return (EIO);
1142 NGI_M(item) = m;
1145 /* Send packet out hook. */
1146 NG_FWD_ITEM_HOOK(error, item,
1147 priv->hooks[HOOK_INDEX_DECOMPRESS]);
1148 return (error);
1149 } else if (proto == PROT_COMPD) {
1150 /* Disabled protos MUST be silently discarded, but
1151 * unsupported MUST not. Let user-level decide this. */
1152 return (ng_ppp_bypass(node, item, proto, linkNum));
1155 return (ng_ppp_hcomp_recv(node, item, proto, linkNum));
1159 * Receive data on a hook decompress.
1161 static int
1162 ng_ppp_rcvdata_decompress(hook_p hook, item_p item)
1164 const node_p node = NG_HOOK_NODE(hook);
1165 const priv_p priv = NG_NODE_PRIVATE(node);
1166 uint16_t proto;
1167 struct mbuf *m;
1169 if (!priv->conf.enableDecompression) {
1170 NG_FREE_ITEM(item);
1171 return (ENXIO);
1173 NGI_GET_M(item, m);
1174 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1175 NG_FREE_ITEM(item);
1176 return (EIO);
1178 NGI_M(item) = m;
1179 if (!PROT_VALID(proto)) {
1180 priv->bundleStats.badProtos++;
1181 NG_FREE_ITEM(item);
1182 return (EIO);
1184 return (ng_ppp_hcomp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1188 * Encryption layer
1191 static int
1192 ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto)
1194 const priv_p priv = NG_NODE_PRIVATE(node);
1196 if (priv->conf.enableEncryption &&
1197 proto < 0x4000 &&
1198 proto != PROT_CRYPTD &&
1199 priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
1200 struct mbuf *m;
1201 int error;
1203 NGI_GET_M(item, m);
1204 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1205 NG_FREE_ITEM(item);
1206 return (ENOBUFS);
1208 NGI_M(item) = m;
1210 /* Send packet out hook. */
1211 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_ENCRYPT]);
1212 return (error);
1215 return (ng_ppp_mp_xmit(node, item, proto));
1219 * Receive data on a hook encrypt.
1221 static int
1222 ng_ppp_rcvdata_encrypt(hook_p hook, item_p item)
1224 const node_p node = NG_HOOK_NODE(hook);
1225 const priv_p priv = NG_NODE_PRIVATE(node);
1227 if (!priv->conf.enableEncryption) {
1228 NG_FREE_ITEM(item);
1229 return (ENXIO);
1231 return (ng_ppp_mp_xmit(node, item, PROT_CRYPTD));
1234 static int
1235 ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1237 const priv_p priv = NG_NODE_PRIVATE(node);
1239 if (proto == PROT_CRYPTD) {
1240 if (priv->conf.enableDecryption &&
1241 priv->hooks[HOOK_INDEX_DECRYPT] != NULL) {
1242 int error;
1244 /* Send packet out hook. */
1245 NG_FWD_ITEM_HOOK(error, item,
1246 priv->hooks[HOOK_INDEX_DECRYPT]);
1247 return (error);
1248 } else {
1249 /* Disabled protos MUST be silently discarded, but
1250 * unsupported MUST not. Let user-level decide this. */
1251 return (ng_ppp_bypass(node, item, proto, linkNum));
1255 return (ng_ppp_comp_recv(node, item, proto, linkNum));
1259 * Receive data on a hook decrypt.
1261 static int
1262 ng_ppp_rcvdata_decrypt(hook_p hook, item_p item)
1264 const node_p node = NG_HOOK_NODE(hook);
1265 const priv_p priv = NG_NODE_PRIVATE(node);
1266 uint16_t proto;
1267 struct mbuf *m;
1269 if (!priv->conf.enableDecryption) {
1270 NG_FREE_ITEM(item);
1271 return (ENXIO);
1273 NGI_GET_M(item, m);
1274 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1275 NG_FREE_ITEM(item);
1276 return (EIO);
1278 NGI_M(item) = m;
1279 if (!PROT_VALID(proto)) {
1280 priv->bundleStats.badProtos++;
1281 NG_FREE_ITEM(item);
1282 return (EIO);
1284 return (ng_ppp_comp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1288 * Link layer
1291 static int
1292 ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto, uint16_t linkNum, int plen)
1294 const priv_p priv = NG_NODE_PRIVATE(node);
1295 struct ng_ppp_link *link;
1296 int len, error;
1297 struct mbuf *m;
1298 uint16_t mru;
1300 /* Check if link correct. */
1301 if (linkNum >= NG_PPP_MAX_LINKS) {
1302 ERROUT(ENETDOWN);
1305 /* Get link pointer (optimization). */
1306 link = &priv->links[linkNum];
1308 /* Check link status (if real). */
1309 if (link->hook == NULL) {
1310 ERROUT(ENETDOWN);
1313 /* Extract mbuf. */
1314 NGI_GET_M(item, m);
1316 /* Check peer's MRU for this link. */
1317 mru = link->conf.mru;
1318 if (mru != 0 && m->m_pkthdr.len > mru) {
1319 NG_FREE_M(m);
1320 ERROUT(EMSGSIZE);
1323 /* Prepend protocol number, possibly compressed. */
1324 if ((m = ng_ppp_addproto(m, proto, link->conf.enableProtoComp)) ==
1325 NULL) {
1326 ERROUT(ENOBUFS);
1329 /* Prepend address and control field (unless compressed). */
1330 if (proto == PROT_LCP || !link->conf.enableACFComp) {
1331 if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL)
1332 ERROUT(ENOBUFS);
1335 /* Deliver frame. */
1336 len = m->m_pkthdr.len;
1337 NG_FWD_NEW_DATA(error, item, link->hook, m);
1339 mtx_lock(&priv->xmtx);
1341 /* Update link stats. */
1342 link->stats.xmitFrames++;
1343 link->stats.xmitOctets += len;
1345 /* Update bundle stats. */
1346 if (plen > 0) {
1347 priv->bundleStats.xmitFrames++;
1348 priv->bundleStats.xmitOctets += plen;
1351 /* Update 'bytes in queue' counter. */
1352 if (error == 0) {
1353 /* bytesInQueue and lastWrite required only for mp_strategy. */
1354 if (priv->conf.enableMultilink && !priv->allLinksEqual &&
1355 !priv->conf.enableRoundRobin) {
1356 /* If queue was empty, then mark this time. */
1357 if (link->bytesInQueue == 0)
1358 getmicrouptime(&link->lastWrite);
1359 link->bytesInQueue += len + MP_AVERAGE_LINK_OVERHEAD;
1360 /* Limit max queue length to 50 pkts. BW can be defined
1361 incorrectly and link may not signal overload. */
1362 if (link->bytesInQueue > 50 * 1600)
1363 link->bytesInQueue = 50 * 1600;
1366 mtx_unlock(&priv->xmtx);
1367 return (error);
1369 done:
1370 NG_FREE_ITEM(item);
1371 return (error);
1375 * Receive data on a hook linkX.
1377 static int
1378 ng_ppp_rcvdata(hook_p hook, item_p item)
1380 const node_p node = NG_HOOK_NODE(hook);
1381 const priv_p priv = NG_NODE_PRIVATE(node);
1382 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
1383 const uint16_t linkNum = (uint16_t)~index;
1384 struct ng_ppp_link * const link = &priv->links[linkNum];
1385 uint16_t proto;
1386 struct mbuf *m;
1387 int error = 0;
1389 KASSERT(linkNum < NG_PPP_MAX_LINKS,
1390 ("%s: bogus index 0x%x", __func__, index));
1392 NGI_GET_M(item, m);
1394 mtx_lock(&priv->rmtx);
1396 /* Stats */
1397 link->stats.recvFrames++;
1398 link->stats.recvOctets += m->m_pkthdr.len;
1400 /* Strip address and control fields, if present. */
1401 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1402 ERROUT(ENOBUFS);
1403 if (mtod(m, uint8_t *)[0] == 0xff &&
1404 mtod(m, uint8_t *)[1] == 0x03)
1405 m_adj(m, 2);
1407 /* Get protocol number */
1408 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1409 ERROUT(ENOBUFS);
1410 NGI_M(item) = m; /* Put changed m back into item. */
1412 if (!PROT_VALID(proto)) {
1413 link->stats.badProtos++;
1414 ERROUT(EIO);
1417 /* LCP packets must go directly to bypass. */
1418 if (proto >= 0xB000) {
1419 mtx_unlock(&priv->rmtx);
1420 return (ng_ppp_bypass(node, item, proto, linkNum));
1423 /* Other packets are denied on a disabled link. */
1424 if (!link->conf.enableLink)
1425 ERROUT(ENXIO);
1427 /* Proceed to multilink layer. Mutex will be unlocked inside. */
1428 error = ng_ppp_mp_recv(node, item, proto, linkNum);
1429 mtx_assert(&priv->rmtx, MA_NOTOWNED);
1430 return (error);
1432 done:
1433 mtx_unlock(&priv->rmtx);
1434 NG_FREE_ITEM(item);
1435 return (error);
1439 * Multilink layer
1443 * Handle an incoming multi-link fragment
1445 * The fragment reassembly algorithm is somewhat complex. This is mainly
1446 * because we are required not to reorder the reconstructed packets, yet
1447 * fragments are only guaranteed to arrive in order on a per-link basis.
1448 * In other words, when we have a complete packet ready, but the previous
1449 * packet is still incomplete, we have to decide between delivering the
1450 * complete packet and throwing away the incomplete one, or waiting to
1451 * see if the remainder of the incomplete one arrives, at which time we
1452 * can deliver both packets, in order.
1454 * This problem is exacerbated by "sequence number slew", which is when
1455 * the sequence numbers coming in from different links are far apart from
1456 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1457 * has been seen to generate sequence number slew of up to 10 on an ISDN
1458 * 2B-channel MP link. There is nothing invalid about sequence number slew
1459 * but it makes the reasssembly process have to work harder.
1461 * However, the peer is required to transmit fragments in order on each
1462 * link. That means if we define MSEQ as the minimum over all links of
1463 * the highest sequence number received on that link, then we can always
1464 * give up any hope of receiving a fragment with sequence number < MSEQ in
1465 * the future (all of this using 'wraparound' sequence number space).
1466 * Therefore we can always immediately throw away incomplete packets
1467 * missing fragments with sequence numbers < MSEQ.
1469 * Here is an overview of our algorithm:
1471 * o Received fragments are inserted into a queue, for which we
1472 * maintain these invariants between calls to this function:
1474 * - Fragments are ordered in the queue by sequence number
1475 * - If a complete packet is at the head of the queue, then
1476 * the first fragment in the packet has seq# > MSEQ + 1
1477 * (otherwise, we could deliver it immediately)
1478 * - If any fragments have seq# < MSEQ, then they are necessarily
1479 * part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1480 * we can throw them away because they'll never be completed)
1481 * - The queue contains at most MP_MAX_QUEUE_LEN fragments
1483 * o We have a periodic timer that checks the queue for the first
1484 * complete packet that has been sitting in the queue "too long".
1485 * When one is detected, all previous (incomplete) fragments are
1486 * discarded, their missing fragments are declared lost and MSEQ
1487 * is increased.
1489 * o If we recieve a fragment with seq# < MSEQ, we throw it away
1490 * because we've already delcared it lost.
1492 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1494 static int
1495 ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1497 const priv_p priv = NG_NODE_PRIVATE(node);
1498 struct ng_ppp_link *const link = &priv->links[linkNum];
1499 struct ng_ppp_frag *frag;
1500 struct ng_ppp_frag *qent;
1501 int i, diff, inserted;
1502 struct mbuf *m;
1503 int error = 0;
1505 if ((!priv->conf.enableMultilink) || proto != PROT_MP) {
1506 /* Stats */
1507 priv->bundleStats.recvFrames++;
1508 priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1510 mtx_unlock(&priv->rmtx);
1511 return (ng_ppp_crypt_recv(node, item, proto, linkNum));
1514 NGI_GET_M(item, m);
1516 /* Get a new frag struct from the free queue */
1517 if ((frag = TAILQ_FIRST(&priv->fragsfree)) == NULL) {
1518 printf("No free fragments headers in ng_ppp!\n");
1519 NG_FREE_M(m);
1520 goto process;
1523 /* Extract fragment information from MP header */
1524 if (priv->conf.recvShortSeq) {
1525 uint16_t shdr;
1527 if (m->m_pkthdr.len < 2) {
1528 link->stats.runts++;
1529 NG_FREE_M(m);
1530 ERROUT(EINVAL);
1532 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1533 ERROUT(ENOBUFS);
1535 shdr = ntohs(*mtod(m, uint16_t *));
1536 frag->seq = MP_SHORT_EXTEND(shdr);
1537 frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1538 frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1539 diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1540 m_adj(m, 2);
1541 } else {
1542 uint32_t lhdr;
1544 if (m->m_pkthdr.len < 4) {
1545 link->stats.runts++;
1546 NG_FREE_M(m);
1547 ERROUT(EINVAL);
1549 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL)
1550 ERROUT(ENOBUFS);
1552 lhdr = ntohl(*mtod(m, uint32_t *));
1553 frag->seq = MP_LONG_EXTEND(lhdr);
1554 frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1555 frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1556 diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1557 m_adj(m, 4);
1559 frag->data = m;
1560 getmicrouptime(&frag->timestamp);
1562 /* If sequence number is < MSEQ, we've already declared this
1563 fragment as lost, so we have no choice now but to drop it */
1564 if (diff < 0) {
1565 link->stats.dropFragments++;
1566 NG_FREE_M(m);
1567 ERROUT(0);
1570 /* Update highest received sequence number on this link and MSEQ */
1571 priv->mseq = link->seq = frag->seq;
1572 for (i = 0; i < priv->numActiveLinks; i++) {
1573 struct ng_ppp_link *const alink =
1574 &priv->links[priv->activeLinks[i]];
1576 if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1577 priv->mseq = alink->seq;
1580 /* Remove frag struct from free queue. */
1581 TAILQ_REMOVE(&priv->fragsfree, frag, f_qent);
1583 /* Add fragment to queue, which is sorted by sequence number */
1584 inserted = 0;
1585 TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1586 diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1587 if (diff > 0) {
1588 TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1589 inserted = 1;
1590 break;
1591 } else if (diff == 0) { /* should never happen! */
1592 link->stats.dupFragments++;
1593 NG_FREE_M(frag->data);
1594 TAILQ_INSERT_HEAD(&priv->fragsfree, frag, f_qent);
1595 ERROUT(EINVAL);
1598 if (!inserted)
1599 TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1601 process:
1602 /* Process the queue */
1603 /* NOTE: rmtx will be unlocked for sending time! */
1604 error = ng_ppp_frag_process(node, item);
1605 mtx_unlock(&priv->rmtx);
1606 return (error);
1608 done:
1609 mtx_unlock(&priv->rmtx);
1610 NG_FREE_ITEM(item);
1611 return (error);
1614 /************************************************************************
1615 HELPER STUFF
1616 ************************************************************************/
1619 * If new mseq > current then set it and update all active links
1621 static void
1622 ng_ppp_bump_mseq(node_p node, int32_t new_mseq)
1624 const priv_p priv = NG_NODE_PRIVATE(node);
1625 int i;
1627 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, new_mseq) < 0) {
1628 priv->mseq = new_mseq;
1629 for (i = 0; i < priv->numActiveLinks; i++) {
1630 struct ng_ppp_link *const alink =
1631 &priv->links[priv->activeLinks[i]];
1633 if (MP_RECV_SEQ_DIFF(priv,
1634 alink->seq, new_mseq) < 0)
1635 alink->seq = new_mseq;
1641 * Examine our list of fragments, and determine if there is a
1642 * complete and deliverable packet at the head of the list.
1643 * Return 1 if so, zero otherwise.
1645 static int
1646 ng_ppp_check_packet(node_p node)
1648 const priv_p priv = NG_NODE_PRIVATE(node);
1649 struct ng_ppp_frag *qent, *qnext;
1651 /* Check for empty queue */
1652 if (TAILQ_EMPTY(&priv->frags))
1653 return (0);
1655 /* Check first fragment is the start of a deliverable packet */
1656 qent = TAILQ_FIRST(&priv->frags);
1657 if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1658 return (0);
1660 /* Check that all the fragments are there */
1661 while (!qent->last) {
1662 qnext = TAILQ_NEXT(qent, f_qent);
1663 if (qnext == NULL) /* end of queue */
1664 return (0);
1665 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1666 return (0);
1667 qent = qnext;
1670 /* Got one */
1671 return (1);
1675 * Pull a completed packet off the head of the incoming fragment queue.
1676 * This assumes there is a completed packet there to pull off.
1678 static void
1679 ng_ppp_get_packet(node_p node, struct mbuf **mp)
1681 const priv_p priv = NG_NODE_PRIVATE(node);
1682 struct ng_ppp_frag *qent, *qnext;
1683 struct mbuf *m = NULL, *tail;
1685 qent = TAILQ_FIRST(&priv->frags);
1686 KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1687 ("%s: no packet", __func__));
1688 for (tail = NULL; qent != NULL; qent = qnext) {
1689 qnext = TAILQ_NEXT(qent, f_qent);
1690 KASSERT(!TAILQ_EMPTY(&priv->frags),
1691 ("%s: empty q", __func__));
1692 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1693 if (tail == NULL)
1694 tail = m = qent->data;
1695 else {
1696 m->m_pkthdr.len += qent->data->m_pkthdr.len;
1697 tail->m_next = qent->data;
1699 while (tail->m_next != NULL)
1700 tail = tail->m_next;
1701 if (qent->last) {
1702 qnext = NULL;
1703 /* Bump MSEQ if necessary */
1704 ng_ppp_bump_mseq(node, qent->seq);
1706 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1708 *mp = m;
1712 * Trim fragments from the queue whose packets can never be completed.
1713 * This assumes a complete packet is NOT at the beginning of the queue.
1714 * Returns 1 if fragments were removed, zero otherwise.
1716 static int
1717 ng_ppp_frag_trim(node_p node)
1719 const priv_p priv = NG_NODE_PRIVATE(node);
1720 struct ng_ppp_frag *qent, *qnext = NULL;
1721 int removed = 0;
1723 /* Scan for "dead" fragments and remove them */
1724 while (1) {
1725 int dead = 0;
1727 /* If queue is empty, we're done */
1728 if (TAILQ_EMPTY(&priv->frags))
1729 break;
1731 /* Determine whether first fragment can ever be completed */
1732 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1733 if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1734 break;
1735 qnext = TAILQ_NEXT(qent, f_qent);
1736 KASSERT(qnext != NULL,
1737 ("%s: last frag < MSEQ?", __func__));
1738 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1739 || qent->last || qnext->first) {
1740 dead = 1;
1741 break;
1744 if (!dead)
1745 break;
1747 /* Remove fragment and all others in the same packet */
1748 while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1749 KASSERT(!TAILQ_EMPTY(&priv->frags),
1750 ("%s: empty q", __func__));
1751 priv->bundleStats.dropFragments++;
1752 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1753 NG_FREE_M(qent->data);
1754 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1755 removed = 1;
1758 return (removed);
1762 * Drop fragments on queue overflow.
1763 * Returns 1 if fragments were removed, zero otherwise.
1765 static int
1766 ng_ppp_frag_drop(node_p node)
1768 const priv_p priv = NG_NODE_PRIVATE(node);
1770 /* Check queue length */
1771 if (TAILQ_EMPTY(&priv->fragsfree)) {
1772 struct ng_ppp_frag *qent;
1774 /* Get oldest fragment */
1775 KASSERT(!TAILQ_EMPTY(&priv->frags),
1776 ("%s: empty q", __func__));
1777 qent = TAILQ_FIRST(&priv->frags);
1779 /* Bump MSEQ if necessary */
1780 ng_ppp_bump_mseq(node, qent->seq);
1782 /* Drop it */
1783 priv->bundleStats.dropFragments++;
1784 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1785 NG_FREE_M(qent->data);
1786 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1788 return (1);
1790 return (0);
1794 * Run the queue, restoring the queue invariants
1796 static int
1797 ng_ppp_frag_process(node_p node, item_p oitem)
1799 const priv_p priv = NG_NODE_PRIVATE(node);
1800 struct mbuf *m;
1801 item_p item;
1802 uint16_t proto;
1804 do {
1805 /* Deliver any deliverable packets */
1806 while (ng_ppp_check_packet(node)) {
1807 ng_ppp_get_packet(node, &m);
1808 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1809 continue;
1810 if (!PROT_VALID(proto)) {
1811 priv->bundleStats.badProtos++;
1812 NG_FREE_M(m);
1813 continue;
1815 if (oitem) { /* If original item present - reuse it. */
1816 item = oitem;
1817 oitem = NULL;
1818 NGI_M(item) = m;
1819 } else {
1820 item = ng_package_data(m, NG_NOFLAGS);
1822 if (item != NULL) {
1823 /* Stats */
1824 priv->bundleStats.recvFrames++;
1825 priv->bundleStats.recvOctets +=
1826 NGI_M(item)->m_pkthdr.len;
1828 /* Drop mutex for the sending time.
1829 * Priv may change, but we are ready!
1831 mtx_unlock(&priv->rmtx);
1832 ng_ppp_crypt_recv(node, item, proto,
1833 NG_PPP_BUNDLE_LINKNUM);
1834 mtx_lock(&priv->rmtx);
1837 /* Delete dead fragments and try again */
1838 } while (ng_ppp_frag_trim(node) || ng_ppp_frag_drop(node));
1840 /* If we haven't reused original item - free it. */
1841 if (oitem) NG_FREE_ITEM(oitem);
1843 /* Done */
1844 return (0);
1848 * Check for 'stale' completed packets that need to be delivered
1850 * If a link goes down or has a temporary failure, MSEQ can get
1851 * "stuck", because no new incoming fragments appear on that link.
1852 * This can cause completed packets to never get delivered if
1853 * their sequence numbers are all > MSEQ + 1.
1855 * This routine checks how long all of the completed packets have
1856 * been sitting in the queue, and if too long, removes fragments
1857 * from the queue and increments MSEQ to allow them to be delivered.
1859 static void
1860 ng_ppp_frag_checkstale(node_p node)
1862 const priv_p priv = NG_NODE_PRIVATE(node);
1863 struct ng_ppp_frag *qent, *beg, *end;
1864 struct timeval now, age;
1865 struct mbuf *m;
1866 int seq;
1867 item_p item;
1868 int endseq;
1869 uint16_t proto;
1871 now.tv_sec = 0; /* uninitialized state */
1872 while (1) {
1874 /* If queue is empty, we're done */
1875 if (TAILQ_EMPTY(&priv->frags))
1876 break;
1878 /* Find the first complete packet in the queue */
1879 beg = end = NULL;
1880 seq = TAILQ_FIRST(&priv->frags)->seq;
1881 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1882 if (qent->first)
1883 beg = qent;
1884 else if (qent->seq != seq)
1885 beg = NULL;
1886 if (beg != NULL && qent->last) {
1887 end = qent;
1888 break;
1890 seq = MP_NEXT_RECV_SEQ(priv, seq);
1893 /* If none found, exit */
1894 if (end == NULL)
1895 break;
1897 /* Get current time (we assume we've been up for >= 1 second) */
1898 if (now.tv_sec == 0)
1899 getmicrouptime(&now);
1901 /* Check if packet has been queued too long */
1902 age = now;
1903 timevalsub(&age, &beg->timestamp);
1904 if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1905 break;
1907 /* Throw away junk fragments in front of the completed packet */
1908 while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1909 KASSERT(!TAILQ_EMPTY(&priv->frags),
1910 ("%s: empty q", __func__));
1911 priv->bundleStats.dropFragments++;
1912 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1913 NG_FREE_M(qent->data);
1914 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1917 /* Extract completed packet */
1918 endseq = end->seq;
1919 ng_ppp_get_packet(node, &m);
1921 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1922 continue;
1923 if (!PROT_VALID(proto)) {
1924 priv->bundleStats.badProtos++;
1925 NG_FREE_M(m);
1926 continue;
1929 /* Deliver packet */
1930 if ((item = ng_package_data(m, NG_NOFLAGS)) != NULL) {
1931 /* Stats */
1932 priv->bundleStats.recvFrames++;
1933 priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1935 ng_ppp_crypt_recv(node, item, proto,
1936 NG_PPP_BUNDLE_LINKNUM);
1942 * Periodically call ng_ppp_frag_checkstale()
1944 static void
1945 ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1947 /* XXX: is this needed? */
1948 if (NG_NODE_NOT_VALID(node))
1949 return;
1951 /* Scan the fragment queue */
1952 ng_ppp_frag_checkstale(node);
1954 /* Start timer again */
1955 ng_ppp_start_frag_timer(node);
1959 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1960 * the frame across the individual PPP links and do so.
1962 static int
1963 ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto)
1965 const priv_p priv = NG_NODE_PRIVATE(node);
1966 const int hdr_len = priv->conf.xmitShortSeq ? 2 : 4;
1967 int distrib[NG_PPP_MAX_LINKS];
1968 int firstFragment;
1969 int activeLinkNum;
1970 struct mbuf *m;
1971 int plen;
1972 int frags;
1973 int32_t seq;
1975 /* At least one link must be active */
1976 if (priv->numActiveLinks == 0) {
1977 NG_FREE_ITEM(item);
1978 return (ENETDOWN);
1981 /* Save length for later stats. */
1982 plen = NGI_M(item)->m_pkthdr.len;
1984 if (!priv->conf.enableMultilink) {
1985 return (ng_ppp_link_xmit(node, item, proto,
1986 priv->activeLinks[0], plen));
1989 /* Extract mbuf. */
1990 NGI_GET_M(item, m);
1992 /* Prepend protocol number, possibly compressed. */
1993 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
1994 NG_FREE_ITEM(item);
1995 return (ENOBUFS);
1998 /* Clear distribution plan */
1999 bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
2001 mtx_lock(&priv->xmtx);
2003 /* Round-robin strategy */
2004 if (priv->conf.enableRoundRobin) {
2005 activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
2006 distrib[activeLinkNum] = m->m_pkthdr.len;
2007 goto deliver;
2010 /* Strategy when all links are equivalent (optimize the common case) */
2011 if (priv->allLinksEqual) {
2012 int numFrags, fraction, remain;
2013 int i;
2015 /* Calculate optimal fragment count */
2016 numFrags = priv->numActiveLinks;
2017 if (numFrags > m->m_pkthdr.len / MP_MIN_FRAG_LEN)
2018 numFrags = m->m_pkthdr.len / MP_MIN_FRAG_LEN;
2019 if (numFrags == 0)
2020 numFrags = 1;
2022 fraction = m->m_pkthdr.len / numFrags;
2023 remain = m->m_pkthdr.len - (fraction * numFrags);
2025 /* Assign distribution */
2026 for (i = 0; i < numFrags; i++) {
2027 distrib[priv->lastLink++ % priv->numActiveLinks]
2028 = fraction + (((remain--) > 0)?1:0);
2030 goto deliver;
2033 /* Strategy when all links are not equivalent */
2034 ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
2036 deliver:
2037 /* Estimate fragments count */
2038 frags = 0;
2039 for (activeLinkNum = priv->numActiveLinks - 1;
2040 activeLinkNum >= 0; activeLinkNum--) {
2041 const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2042 struct ng_ppp_link *const link = &priv->links[linkNum];
2044 frags += (distrib[activeLinkNum] + link->conf.mru - hdr_len - 1) /
2045 (link->conf.mru - hdr_len);
2048 /* Get out initial sequence number */
2049 seq = priv->xseq;
2051 /* Update next sequence number */
2052 if (priv->conf.xmitShortSeq) {
2053 priv->xseq = (seq + frags) & MP_SHORT_SEQ_MASK;
2054 } else {
2055 priv->xseq = (seq + frags) & MP_LONG_SEQ_MASK;
2058 mtx_unlock(&priv->xmtx);
2060 /* Send alloted portions of frame out on the link(s) */
2061 for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
2062 activeLinkNum >= 0; activeLinkNum--) {
2063 const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2064 struct ng_ppp_link *const link = &priv->links[linkNum];
2066 /* Deliver fragment(s) out the next link */
2067 for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
2068 int len, lastFragment, error;
2069 struct mbuf *m2;
2071 /* Calculate fragment length; don't exceed link MTU */
2072 len = distrib[activeLinkNum];
2073 if (len > link->conf.mru - hdr_len)
2074 len = link->conf.mru - hdr_len;
2075 distrib[activeLinkNum] -= len;
2076 lastFragment = (len == m->m_pkthdr.len);
2078 /* Split off next fragment as "m2" */
2079 m2 = m;
2080 if (!lastFragment) {
2081 struct mbuf *n = m_split(m, len, MB_DONTWAIT);
2083 if (n == NULL) {
2084 NG_FREE_M(m);
2085 if (firstFragment)
2086 NG_FREE_ITEM(item);
2087 return (ENOMEM);
2089 m_tag_copy_chain(n, m, MB_DONTWAIT);
2090 m = n;
2093 /* Prepend MP header */
2094 if (priv->conf.xmitShortSeq) {
2095 uint16_t shdr;
2097 shdr = seq;
2098 seq = (seq + 1) & MP_SHORT_SEQ_MASK;
2099 if (firstFragment)
2100 shdr |= MP_SHORT_FIRST_FLAG;
2101 if (lastFragment)
2102 shdr |= MP_SHORT_LAST_FLAG;
2103 shdr = htons(shdr);
2104 m2 = ng_ppp_prepend(m2, &shdr, 2);
2105 } else {
2106 uint32_t lhdr;
2108 lhdr = seq;
2109 seq = (seq + 1) & MP_LONG_SEQ_MASK;
2110 if (firstFragment)
2111 lhdr |= MP_LONG_FIRST_FLAG;
2112 if (lastFragment)
2113 lhdr |= MP_LONG_LAST_FLAG;
2114 lhdr = htonl(lhdr);
2115 m2 = ng_ppp_prepend(m2, &lhdr, 4);
2117 if (m2 == NULL) {
2118 if (!lastFragment)
2119 m_freem(m);
2120 if (firstFragment)
2121 NG_FREE_ITEM(item);
2122 return (ENOBUFS);
2125 /* Send fragment */
2126 if (firstFragment) {
2127 NGI_M(item) = m2; /* Reuse original item. */
2128 } else {
2129 item = ng_package_data(m2, NG_NOFLAGS);
2131 if (item != NULL) {
2132 error = ng_ppp_link_xmit(node, item, PROT_MP,
2133 linkNum, (firstFragment?plen:0));
2134 if (error != 0) {
2135 if (!lastFragment)
2136 NG_FREE_M(m);
2137 return (error);
2143 /* Done */
2144 return (0);
2148 * Computing the optimal fragmentation
2149 * -----------------------------------
2151 * This routine tries to compute the optimal fragmentation pattern based
2152 * on each link's latency, bandwidth, and calculated additional latency.
2153 * The latter quantity is the additional latency caused by previously
2154 * written data that has not been transmitted yet.
2156 * This algorithm is only useful when not all of the links have the
2157 * same latency and bandwidth values.
2159 * The essential idea is to make the last bit of each fragment of the
2160 * frame arrive at the opposite end at the exact same time. This greedy
2161 * algorithm is optimal, in that no other scheduling could result in any
2162 * packet arriving any sooner unless packets are delivered out of order.
2164 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
2165 * latency l_i (in miliseconds). Consider the function function f_i(t)
2166 * which is equal to the number of bytes that will have arrived at
2167 * the peer after t miliseconds if we start writing continuously at
2168 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
2169 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
2170 * Note that the y-intersect is always <= zero because latency can't be
2171 * negative. Note also that really the function is f_i(t) except when
2172 * f_i(t) is negative, in which case the function is zero. To take
2173 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
2174 * So the actual number of bytes that will have arrived at the peer after
2175 * t miliseconds is f_i(t) * Q_i(t).
2177 * At any given time, each link has some additional latency a_i >= 0
2178 * due to previously written fragment(s) which are still in the queue.
2179 * This value is easily computed from the time since last transmission,
2180 * the previous latency value, the number of bytes written, and the
2181 * link's bandwidth.
2183 * Assume that l_i includes any a_i already, and that the links are
2184 * sorted by latency, so that l_i <= l_{i+1}.
2186 * Let N be the total number of bytes in the current frame we are sending.
2188 * Suppose we were to start writing bytes at time t = 0 on all links
2189 * simultaneously, which is the most we can possibly do. Then let
2190 * F(t) be equal to the total number of bytes received by the peer
2191 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
2193 * Our goal is simply this: fragment the frame across the links such
2194 * that the peer is able to reconstruct the completed frame as soon as
2195 * possible, i.e., at the least possible value of t. Call this value t_0.
2197 * Then it follows that F(t_0) = N. Our strategy is first to find the value
2198 * of t_0, and then deduce how many bytes to write to each link.
2200 * Rewriting F(t_0):
2202 * t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
2204 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
2205 * lie in one of these ranges. To find it, we just need to find the i such
2206 * that F(l_i) <= N <= F(l_{i+1}). Then we compute all the constant values
2207 * for Q_i() in this range, plug in the remaining values, solving for t_0.
2209 * Once t_0 is known, then the number of bytes to send on link i is
2210 * just f_i(t_0) * Q_i(t_0).
2212 * In other words, we start allocating bytes to the links one at a time.
2213 * We keep adding links until the frame is completely sent. Some links
2214 * may not get any bytes because their latency is too high.
2216 * Is all this work really worth the trouble? Depends on the situation.
2217 * The bigger the ratio of computer speed to link speed, and the more
2218 * important total bundle latency is (e.g., for interactive response time),
2219 * the more it's worth it. There is however the cost of calling this
2220 * function for every frame. The running time is O(n^2) where n is the
2221 * number of links that receive a non-zero number of bytes.
2223 * Since latency is measured in miliseconds, the "resolution" of this
2224 * algorithm is one milisecond.
2226 * To avoid this algorithm altogether, configure all links to have the
2227 * same latency and bandwidth.
2229 static void
2230 ng_ppp_mp_strategy(node_p node, int len, int *distrib)
2232 const priv_p priv = NG_NODE_PRIVATE(node);
2233 int latency[NG_PPP_MAX_LINKS];
2234 int sortByLatency[NG_PPP_MAX_LINKS];
2235 int activeLinkNum;
2236 int t0, total, topSum, botSum;
2237 struct timeval now;
2238 int i, numFragments;
2240 /* If only one link, this gets real easy */
2241 if (priv->numActiveLinks == 1) {
2242 distrib[0] = len;
2243 return;
2246 /* Get current time */
2247 getmicrouptime(&now);
2249 /* Compute latencies for each link at this point in time */
2250 for (activeLinkNum = 0;
2251 activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
2252 struct ng_ppp_link *alink;
2253 struct timeval diff;
2254 int xmitBytes;
2256 /* Start with base latency value */
2257 alink = &priv->links[priv->activeLinks[activeLinkNum]];
2258 latency[activeLinkNum] = alink->latency;
2259 sortByLatency[activeLinkNum] = activeLinkNum; /* see below */
2261 /* Any additional latency? */
2262 if (alink->bytesInQueue == 0)
2263 continue;
2265 /* Compute time delta since last write */
2266 diff = now;
2267 timevalsub(&diff, &alink->lastWrite);
2269 /* alink->bytesInQueue will be changed, mark change time. */
2270 alink->lastWrite = now;
2272 if (now.tv_sec < 0 || diff.tv_sec >= 10) { /* sanity */
2273 alink->bytesInQueue = 0;
2274 continue;
2277 /* How many bytes could have transmitted since last write? */
2278 xmitBytes = (alink->conf.bandwidth * 10 * diff.tv_sec)
2279 + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
2280 alink->bytesInQueue -= xmitBytes;
2281 if (alink->bytesInQueue < 0)
2282 alink->bytesInQueue = 0;
2283 else
2284 latency[activeLinkNum] +=
2285 (100 * alink->bytesInQueue) / alink->conf.bandwidth;
2288 /* Sort active links by latency */
2289 qsort_r(sortByLatency,
2290 priv->numActiveLinks, sizeof(*sortByLatency), latency, ng_ppp_intcmp);
2292 /* Find the interval we need (add links in sortByLatency[] order) */
2293 for (numFragments = 1;
2294 numFragments < priv->numActiveLinks; numFragments++) {
2295 for (total = i = 0; i < numFragments; i++) {
2296 int flowTime;
2298 flowTime = latency[sortByLatency[numFragments]]
2299 - latency[sortByLatency[i]];
2300 total += ((flowTime * priv->links[
2301 priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
2302 + 99) / 100;
2304 if (total >= len)
2305 break;
2308 /* Solve for t_0 in that interval */
2309 for (topSum = botSum = i = 0; i < numFragments; i++) {
2310 int bw = priv->links[
2311 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2313 topSum += latency[sortByLatency[i]] * bw; /* / 100 */
2314 botSum += bw; /* / 100 */
2316 t0 = ((len * 100) + topSum + botSum / 2) / botSum;
2318 /* Compute f_i(t_0) all i */
2319 for (total = i = 0; i < numFragments; i++) {
2320 int bw = priv->links[
2321 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2323 distrib[sortByLatency[i]] =
2324 (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
2325 total += distrib[sortByLatency[i]];
2328 /* Deal with any rounding error */
2329 if (total < len) {
2330 struct ng_ppp_link *fastLink =
2331 &priv->links[priv->activeLinks[sortByLatency[0]]];
2332 int fast = 0;
2334 /* Find the fastest link */
2335 for (i = 1; i < numFragments; i++) {
2336 struct ng_ppp_link *const link =
2337 &priv->links[priv->activeLinks[sortByLatency[i]]];
2339 if (link->conf.bandwidth > fastLink->conf.bandwidth) {
2340 fast = i;
2341 fastLink = link;
2344 distrib[sortByLatency[fast]] += len - total;
2345 } else while (total > len) {
2346 struct ng_ppp_link *slowLink =
2347 &priv->links[priv->activeLinks[sortByLatency[0]]];
2348 int delta, slow = 0;
2350 /* Find the slowest link that still has bytes to remove */
2351 for (i = 1; i < numFragments; i++) {
2352 struct ng_ppp_link *const link =
2353 &priv->links[priv->activeLinks[sortByLatency[i]]];
2355 if (distrib[sortByLatency[slow]] == 0
2356 || (distrib[sortByLatency[i]] > 0
2357 && link->conf.bandwidth <
2358 slowLink->conf.bandwidth)) {
2359 slow = i;
2360 slowLink = link;
2363 delta = total - len;
2364 if (delta > distrib[sortByLatency[slow]])
2365 delta = distrib[sortByLatency[slow]];
2366 distrib[sortByLatency[slow]] -= delta;
2367 total -= delta;
2372 * Compare two integers
2374 static int
2375 ng_ppp_intcmp(void *latency, const void *v1, const void *v2)
2377 const int index1 = *((const int *) v1);
2378 const int index2 = *((const int *) v2);
2380 return ((int *)latency)[index1] - ((int *)latency)[index2];
2384 * Prepend a possibly compressed PPP protocol number in front of a frame
2386 static struct mbuf *
2387 ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK)
2389 if (compOK && PROT_COMPRESSABLE(proto)) {
2390 uint8_t pbyte = (uint8_t)proto;
2392 return ng_ppp_prepend(m, &pbyte, 1);
2393 } else {
2394 uint16_t pword = htons((uint16_t)proto);
2396 return ng_ppp_prepend(m, &pword, 2);
2401 * Cut a possibly compressed PPP protocol number from the front of a frame.
2403 static struct mbuf *
2404 ng_ppp_cutproto(struct mbuf *m, uint16_t *proto)
2407 *proto = 0;
2408 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2409 return (NULL);
2411 *proto = *mtod(m, uint8_t *);
2412 m_adj(m, 1);
2414 if (!PROT_VALID(*proto)) {
2415 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2416 return (NULL);
2418 *proto = (*proto << 8) + *mtod(m, uint8_t *);
2419 m_adj(m, 1);
2422 return (m);
2426 * Prepend some bytes to an mbuf.
2428 static struct mbuf *
2429 ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
2431 M_PREPEND(m, len, MB_DONTWAIT);
2432 if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
2433 return (NULL);
2434 bcopy(buf, mtod(m, uint8_t *), len);
2435 return (m);
2439 * Update private information that is derived from other private information
2441 static void
2442 ng_ppp_update(node_p node, int newConf)
2444 const priv_p priv = NG_NODE_PRIVATE(node);
2445 int i;
2447 /* Update active status for VJ Compression */
2448 priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
2449 && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
2450 && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
2451 && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
2453 /* Increase latency for each link an amount equal to one MP header */
2454 if (newConf) {
2455 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2456 int hdrBytes;
2458 if (priv->links[i].conf.bandwidth == 0)
2459 continue;
2461 hdrBytes = MP_AVERAGE_LINK_OVERHEAD
2462 + (priv->links[i].conf.enableACFComp ? 0 : 2)
2463 + (priv->links[i].conf.enableProtoComp ? 1 : 2)
2464 + (priv->conf.xmitShortSeq ? 2 : 4);
2465 priv->links[i].latency =
2466 priv->links[i].conf.latency +
2467 (hdrBytes / priv->links[i].conf.bandwidth + 50) / 100;
2471 /* Update list of active links */
2472 bzero(&priv->activeLinks, sizeof(priv->activeLinks));
2473 priv->numActiveLinks = 0;
2474 priv->allLinksEqual = 1;
2475 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2476 struct ng_ppp_link *const link = &priv->links[i];
2478 /* Is link active? */
2479 if (link->conf.enableLink && link->hook != NULL) {
2480 struct ng_ppp_link *link0;
2482 /* Add link to list of active links */
2483 priv->activeLinks[priv->numActiveLinks++] = i;
2484 link0 = &priv->links[priv->activeLinks[0]];
2486 /* Determine if all links are still equal */
2487 if (link->latency != link0->latency
2488 || link->conf.bandwidth != link0->conf.bandwidth)
2489 priv->allLinksEqual = 0;
2491 /* Initialize rec'd sequence number */
2492 if (link->seq == MP_NOSEQ) {
2493 link->seq = (link == link0) ?
2494 MP_INITIAL_SEQ : link0->seq;
2496 } else
2497 link->seq = MP_NOSEQ;
2500 /* Update MP state as multi-link is active or not */
2501 if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
2502 ng_ppp_start_frag_timer(node);
2503 else {
2504 ng_ppp_stop_frag_timer(node);
2505 ng_ppp_frag_reset(node);
2506 priv->xseq = MP_INITIAL_SEQ;
2507 priv->mseq = MP_INITIAL_SEQ;
2508 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2509 struct ng_ppp_link *const link = &priv->links[i];
2511 bzero(&link->lastWrite, sizeof(link->lastWrite));
2512 link->bytesInQueue = 0;
2513 link->seq = MP_NOSEQ;
2519 * Determine if a new configuration would represent a valid change
2520 * from the current configuration and link activity status.
2522 static int
2523 ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
2525 const priv_p priv = NG_NODE_PRIVATE(node);
2526 int i, newNumLinksActive;
2528 /* Check per-link config and count how many links would be active */
2529 for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
2530 if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
2531 newNumLinksActive++;
2532 if (!newConf->links[i].enableLink)
2533 continue;
2534 if (newConf->links[i].mru < MP_MIN_LINK_MRU)
2535 return (0);
2536 if (newConf->links[i].bandwidth == 0)
2537 return (0);
2538 if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
2539 return (0);
2540 if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
2541 return (0);
2544 /* Check bundle parameters */
2545 if (newConf->bund.enableMultilink && newConf->bund.mrru < MP_MIN_MRRU)
2546 return (0);
2548 /* Disallow changes to multi-link configuration while MP is active */
2549 if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
2550 if (!priv->conf.enableMultilink
2551 != !newConf->bund.enableMultilink
2552 || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
2553 || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
2554 return (0);
2557 /* At most one link can be active unless multi-link is enabled */
2558 if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
2559 return (0);
2561 /* Configuration change would be valid */
2562 return (1);
2566 * Free all entries in the fragment queue
2568 static void
2569 ng_ppp_frag_reset(node_p node)
2571 const priv_p priv = NG_NODE_PRIVATE(node);
2572 struct ng_ppp_frag *qent, *qnext;
2574 for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
2575 qnext = TAILQ_NEXT(qent, f_qent);
2576 NG_FREE_M(qent->data);
2577 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
2579 TAILQ_INIT(&priv->frags);
2583 * Start fragment queue timer
2585 static void
2586 ng_ppp_start_frag_timer(node_p node)
2588 const priv_p priv = NG_NODE_PRIVATE(node);
2590 if (!(callout_pending(&priv->fragTimer)))
2591 ng_callout(&priv->fragTimer, node, NULL, MP_FRAGTIMER_INTERVAL,
2592 ng_ppp_frag_timeout, NULL, 0);
2596 * Stop fragment queue timer
2598 static void
2599 ng_ppp_stop_frag_timer(node_p node)
2601 const priv_p priv = NG_NODE_PRIVATE(node);
2603 if (callout_pending(&priv->fragTimer))
2604 ng_uncallout(&priv->fragTimer, node);