xref: /freebsd/sys/netgraph/netflow/ng_netflow.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
1 /*-
2  * Copyright (c) 2010-2011 Alexander V. Chernikov <melifaro@ipfw.ru>
3  * Copyright (c) 2004-2005 Gleb Smirnoff <glebius@FreeBSD.org>
4  * Copyright (c) 2001-2003 Roman V. Palagin <romanp@unshadow.net>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $SourceForge: ng_netflow.c,v 1.30 2004/09/05 11:37:43 glebius Exp $
29  */
30 
31 static const char rcs_id[] =
32     "@(#) $FreeBSD$";
33 
34 #include "opt_inet6.h"
35 #include "opt_route.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/limits.h>
41 #include <sys/mbuf.h>
42 #include <sys/socket.h>
43 #include <sys/syslog.h>
44 #include <sys/ctype.h>
45 
46 #include <net/if.h>
47 #include <net/ethernet.h>
48 #include <net/route.h>
49 #include <net/if_arp.h>
50 #include <net/if_var.h>
51 #include <net/if_vlan_var.h>
52 #include <net/bpf.h>
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip6.h>
57 #include <netinet/tcp.h>
58 #include <netinet/udp.h>
59 #include <netinet/sctp.h>
60 
61 #include <netgraph/ng_message.h>
62 #include <netgraph/ng_parse.h>
63 #include <netgraph/netgraph.h>
64 #include <netgraph/netflow/netflow.h>
65 #include <netgraph/netflow/netflow_v9.h>
66 #include <netgraph/netflow/ng_netflow.h>
67 
68 /* Netgraph methods */
69 static ng_constructor_t	ng_netflow_constructor;
70 static ng_rcvmsg_t	ng_netflow_rcvmsg;
71 static ng_close_t	ng_netflow_close;
72 static ng_shutdown_t	ng_netflow_rmnode;
73 static ng_newhook_t	ng_netflow_newhook;
74 static ng_rcvdata_t	ng_netflow_rcvdata;
75 static ng_disconnect_t	ng_netflow_disconnect;
76 
77 /* Parse type for struct ng_netflow_info */
78 static const struct ng_parse_struct_field ng_netflow_info_type_fields[]
79 	= NG_NETFLOW_INFO_TYPE;
80 static const struct ng_parse_type ng_netflow_info_type = {
81 	&ng_parse_struct_type,
82 	&ng_netflow_info_type_fields
83 };
84 
85 /*  Parse type for struct ng_netflow_ifinfo */
86 static const struct ng_parse_struct_field ng_netflow_ifinfo_type_fields[]
87 	= NG_NETFLOW_IFINFO_TYPE;
88 static const struct ng_parse_type ng_netflow_ifinfo_type = {
89 	&ng_parse_struct_type,
90 	&ng_netflow_ifinfo_type_fields
91 };
92 
93 /* Parse type for struct ng_netflow_setdlt */
94 static const struct ng_parse_struct_field ng_netflow_setdlt_type_fields[]
95 	= NG_NETFLOW_SETDLT_TYPE;
96 static const struct ng_parse_type ng_netflow_setdlt_type = {
97 	&ng_parse_struct_type,
98 	&ng_netflow_setdlt_type_fields
99 };
100 
101 /* Parse type for ng_netflow_setifindex */
102 static const struct ng_parse_struct_field ng_netflow_setifindex_type_fields[]
103 	= NG_NETFLOW_SETIFINDEX_TYPE;
104 static const struct ng_parse_type ng_netflow_setifindex_type = {
105 	&ng_parse_struct_type,
106 	&ng_netflow_setifindex_type_fields
107 };
108 
109 /* Parse type for ng_netflow_settimeouts */
110 static const struct ng_parse_struct_field ng_netflow_settimeouts_type_fields[]
111 	= NG_NETFLOW_SETTIMEOUTS_TYPE;
112 static const struct ng_parse_type ng_netflow_settimeouts_type = {
113 	&ng_parse_struct_type,
114 	&ng_netflow_settimeouts_type_fields
115 };
116 
117 /* Parse type for ng_netflow_setconfig */
118 static const struct ng_parse_struct_field ng_netflow_setconfig_type_fields[]
119 	= NG_NETFLOW_SETCONFIG_TYPE;
120 static const struct ng_parse_type ng_netflow_setconfig_type = {
121 	&ng_parse_struct_type,
122 	&ng_netflow_setconfig_type_fields
123 };
124 
125 /* Parse type for ng_netflow_settemplate */
126 static const struct ng_parse_struct_field ng_netflow_settemplate_type_fields[]
127 	= NG_NETFLOW_SETTEMPLATE_TYPE;
128 static const struct ng_parse_type ng_netflow_settemplate_type = {
129 	&ng_parse_struct_type,
130 	&ng_netflow_settemplate_type_fields
131 };
132 
133 /* Parse type for ng_netflow_setmtu */
134 static const struct ng_parse_struct_field ng_netflow_setmtu_type_fields[]
135 	= NG_NETFLOW_SETMTU_TYPE;
136 static const struct ng_parse_type ng_netflow_setmtu_type = {
137 	&ng_parse_struct_type,
138 	&ng_netflow_setmtu_type_fields
139 };
140 
141 /* List of commands and how to convert arguments to/from ASCII */
142 static const struct ng_cmdlist ng_netflow_cmds[] = {
143        {
144 	 NGM_NETFLOW_COOKIE,
145 	 NGM_NETFLOW_INFO,
146 	 "info",
147 	 NULL,
148 	 &ng_netflow_info_type
149        },
150        {
151 	NGM_NETFLOW_COOKIE,
152 	NGM_NETFLOW_IFINFO,
153 	"ifinfo",
154 	&ng_parse_uint16_type,
155 	&ng_netflow_ifinfo_type
156        },
157        {
158 	NGM_NETFLOW_COOKIE,
159 	NGM_NETFLOW_SETDLT,
160 	"setdlt",
161 	&ng_netflow_setdlt_type,
162 	NULL
163        },
164        {
165 	NGM_NETFLOW_COOKIE,
166 	NGM_NETFLOW_SETIFINDEX,
167 	"setifindex",
168 	&ng_netflow_setifindex_type,
169 	NULL
170        },
171        {
172 	NGM_NETFLOW_COOKIE,
173 	NGM_NETFLOW_SETTIMEOUTS,
174 	"settimeouts",
175 	&ng_netflow_settimeouts_type,
176 	NULL
177        },
178        {
179 	NGM_NETFLOW_COOKIE,
180 	NGM_NETFLOW_SETCONFIG,
181 	"setconfig",
182 	&ng_netflow_setconfig_type,
183 	NULL
184        },
185        {
186 	NGM_NETFLOW_COOKIE,
187 	NGM_NETFLOW_SETTEMPLATE,
188 	"settemplate",
189 	&ng_netflow_settemplate_type,
190 	NULL
191        },
192        {
193 	NGM_NETFLOW_COOKIE,
194 	NGM_NETFLOW_SETMTU,
195 	"setmtu",
196 	&ng_netflow_setmtu_type,
197 	NULL
198        },
199        { 0 }
200 };
201 
202 
203 /* Netgraph node type descriptor */
204 static struct ng_type ng_netflow_typestruct = {
205 	.version =	NG_ABI_VERSION,
206 	.name =		NG_NETFLOW_NODE_TYPE,
207 	.constructor =	ng_netflow_constructor,
208 	.rcvmsg =	ng_netflow_rcvmsg,
209 	.close =	ng_netflow_close,
210 	.shutdown =	ng_netflow_rmnode,
211 	.newhook =	ng_netflow_newhook,
212 	.rcvdata =	ng_netflow_rcvdata,
213 	.disconnect =	ng_netflow_disconnect,
214 	.cmdlist =	ng_netflow_cmds,
215 };
216 NETGRAPH_INIT(netflow, &ng_netflow_typestruct);
217 
218 /* Called at node creation */
219 static int
220 ng_netflow_constructor(node_p node)
221 {
222 	priv_p priv;
223 	int i;
224 
225 	/* Initialize private data */
226 	priv = malloc(sizeof(*priv), M_NETGRAPH, M_WAITOK | M_ZERO);
227 
228 	/* Make node and its data point at each other */
229 	NG_NODE_SET_PRIVATE(node, priv);
230 	priv->node = node;
231 
232 	/* Initialize timeouts to default values */
233 	priv->info.nfinfo_inact_t = INACTIVE_TIMEOUT;
234 	priv->info.nfinfo_act_t = ACTIVE_TIMEOUT;
235 
236 	/* Set default config */
237 	for (i = 0; i < NG_NETFLOW_MAXIFACES; i++)
238 		priv->ifaces[i].info.conf = NG_NETFLOW_CONF_INGRESS;
239 
240 	/* Initialize callout handle */
241 	callout_init(&priv->exp_callout, CALLOUT_MPSAFE);
242 
243 	/* Allocate memory and set up flow cache */
244 	ng_netflow_cache_init(priv);
245 
246 	return (0);
247 }
248 
249 /*
250  * ng_netflow supports two hooks: data and export.
251  * Incoming traffic is expected on data, and expired
252  * netflow datagrams are sent to export.
253  */
254 static int
255 ng_netflow_newhook(node_p node, hook_p hook, const char *name)
256 {
257 	const priv_p priv = NG_NODE_PRIVATE(node);
258 
259 	if (strncmp(name, NG_NETFLOW_HOOK_DATA,	/* an iface hook? */
260 	    strlen(NG_NETFLOW_HOOK_DATA)) == 0) {
261 		iface_p iface;
262 		int ifnum = -1;
263 		const char *cp;
264 		char *eptr;
265 
266 		cp = name + strlen(NG_NETFLOW_HOOK_DATA);
267 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
268 			return (EINVAL);
269 
270 		ifnum = (int)strtoul(cp, &eptr, 10);
271 		if (*eptr != '\0' || ifnum < 0 || ifnum >= NG_NETFLOW_MAXIFACES)
272 			return (EINVAL);
273 
274 		/* See if hook is already connected */
275 		if (priv->ifaces[ifnum].hook != NULL)
276 			return (EISCONN);
277 
278 		iface = &priv->ifaces[ifnum];
279 
280 		/* Link private info and hook together */
281 		NG_HOOK_SET_PRIVATE(hook, iface);
282 		iface->hook = hook;
283 
284 		/*
285 		 * In most cases traffic accounting is done on an
286 		 * Ethernet interface, so default data link type
287 		 * will be DLT_EN10MB.
288 		 */
289 		iface->info.ifinfo_dlt = DLT_EN10MB;
290 
291 	} else if (strncmp(name, NG_NETFLOW_HOOK_OUT,
292 	    strlen(NG_NETFLOW_HOOK_OUT)) == 0) {
293 		iface_p iface;
294 		int ifnum = -1;
295 		const char *cp;
296 		char *eptr;
297 
298 		cp = name + strlen(NG_NETFLOW_HOOK_OUT);
299 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
300 			return (EINVAL);
301 
302 		ifnum = (int)strtoul(cp, &eptr, 10);
303 		if (*eptr != '\0' || ifnum < 0 || ifnum >= NG_NETFLOW_MAXIFACES)
304 			return (EINVAL);
305 
306 		/* See if hook is already connected */
307 		if (priv->ifaces[ifnum].out != NULL)
308 			return (EISCONN);
309 
310 		iface = &priv->ifaces[ifnum];
311 
312 		/* Link private info and hook together */
313 		NG_HOOK_SET_PRIVATE(hook, iface);
314 		iface->out = hook;
315 
316 	} else if (strcmp(name, NG_NETFLOW_HOOK_EXPORT) == 0) {
317 
318 		if (priv->export != NULL)
319 			return (EISCONN);
320 
321 		/* Netflow version 5 supports 32-bit counters only */
322 		if (CNTR_MAX == UINT64_MAX)
323 			return (EINVAL);
324 
325 		priv->export = hook;
326 
327 		/* Exporter is ready. Let's schedule expiry. */
328 		callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
329 		    (void *)priv);
330 	} else if (strcmp(name, NG_NETFLOW_HOOK_EXPORT9) == 0) {
331 
332 		if (priv->export9 != NULL)
333 			return (EISCONN);
334 
335 		priv->export9 = hook;
336 
337 		/* Exporter is ready. Let's schedule expiry. */
338 		callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
339 		    (void *)priv);
340 	} else
341 		return (EINVAL);
342 
343 	return (0);
344 }
345 
346 /* Get a netgraph control message. */
347 static int
348 ng_netflow_rcvmsg (node_p node, item_p item, hook_p lasthook)
349 {
350 	const priv_p priv = NG_NODE_PRIVATE(node);
351 	struct ng_mesg *resp = NULL;
352 	int error = 0;
353 	struct ng_mesg *msg;
354 
355 	NGI_GET_MSG(item, msg);
356 
357 	/* Deal with message according to cookie and command */
358 	switch (msg->header.typecookie) {
359 	case NGM_NETFLOW_COOKIE:
360 		switch (msg->header.cmd) {
361 		case NGM_NETFLOW_INFO:
362 		{
363 			struct ng_netflow_info *i;
364 
365 			NG_MKRESPONSE(resp, msg, sizeof(struct ng_netflow_info),
366 			    M_NOWAIT);
367 			i = (struct ng_netflow_info *)resp->data;
368 			ng_netflow_copyinfo(priv, i);
369 
370 			break;
371 		}
372 		case NGM_NETFLOW_IFINFO:
373 		{
374 			struct ng_netflow_ifinfo *i;
375 			const uint16_t *index;
376 
377 			if (msg->header.arglen != sizeof(uint16_t))
378 				 ERROUT(EINVAL);
379 
380 			index  = (uint16_t *)msg->data;
381 			if (*index >= NG_NETFLOW_MAXIFACES)
382 				ERROUT(EINVAL);
383 
384 			/* connected iface? */
385 			if (priv->ifaces[*index].hook == NULL)
386 				 ERROUT(EINVAL);
387 
388 			NG_MKRESPONSE(resp, msg,
389 			     sizeof(struct ng_netflow_ifinfo), M_NOWAIT);
390 			i = (struct ng_netflow_ifinfo *)resp->data;
391 			memcpy((void *)i, (void *)&priv->ifaces[*index].info,
392 			    sizeof(priv->ifaces[*index].info));
393 
394 			break;
395 		}
396 		case NGM_NETFLOW_SETDLT:
397 		{
398 			struct ng_netflow_setdlt *set;
399 			struct ng_netflow_iface *iface;
400 
401 			if (msg->header.arglen != sizeof(struct ng_netflow_setdlt))
402 				ERROUT(EINVAL);
403 
404 			set = (struct ng_netflow_setdlt *)msg->data;
405 			if (set->iface >= NG_NETFLOW_MAXIFACES)
406 				ERROUT(EINVAL);
407 			iface = &priv->ifaces[set->iface];
408 
409 			/* connected iface? */
410 			if (iface->hook == NULL)
411 				ERROUT(EINVAL);
412 
413 			switch (set->dlt) {
414 			case	DLT_EN10MB:
415 				iface->info.ifinfo_dlt = DLT_EN10MB;
416 				break;
417 			case	DLT_RAW:
418 				iface->info.ifinfo_dlt = DLT_RAW;
419 				break;
420 			default:
421 				ERROUT(EINVAL);
422 			}
423 			break;
424 		}
425 		case NGM_NETFLOW_SETIFINDEX:
426 		{
427 			struct ng_netflow_setifindex *set;
428 			struct ng_netflow_iface *iface;
429 
430 			if (msg->header.arglen != sizeof(struct ng_netflow_setifindex))
431 				ERROUT(EINVAL);
432 
433 			set = (struct ng_netflow_setifindex *)msg->data;
434 			if (set->iface >= NG_NETFLOW_MAXIFACES)
435 				ERROUT(EINVAL);
436 			iface = &priv->ifaces[set->iface];
437 
438 			/* connected iface? */
439 			if (iface->hook == NULL)
440 				ERROUT(EINVAL);
441 
442 			iface->info.ifinfo_index = set->index;
443 
444 			break;
445 		}
446 		case NGM_NETFLOW_SETTIMEOUTS:
447 		{
448 			struct ng_netflow_settimeouts *set;
449 
450 			if (msg->header.arglen != sizeof(struct ng_netflow_settimeouts))
451 				ERROUT(EINVAL);
452 
453 			set = (struct ng_netflow_settimeouts *)msg->data;
454 
455 			priv->info.nfinfo_inact_t = set->inactive_timeout;
456 			priv->info.nfinfo_act_t = set->active_timeout;
457 
458 			break;
459 		}
460 		case NGM_NETFLOW_SETCONFIG:
461 		{
462 			struct ng_netflow_setconfig *set;
463 
464 			if (msg->header.arglen != sizeof(struct ng_netflow_setconfig))
465 				ERROUT(EINVAL);
466 
467 			set = (struct ng_netflow_setconfig *)msg->data;
468 
469 			if (set->iface >= NG_NETFLOW_MAXIFACES)
470 				ERROUT(EINVAL);
471 
472 			priv->ifaces[set->iface].info.conf = set->conf;
473 
474 			break;
475 		}
476 		case NGM_NETFLOW_SETTEMPLATE:
477 		{
478 			struct ng_netflow_settemplate *set;
479 
480 			if (msg->header.arglen != sizeof(struct ng_netflow_settemplate))
481 				ERROUT(EINVAL);
482 
483 			set = (struct ng_netflow_settemplate *)msg->data;
484 
485 			priv->templ_packets = set->packets;
486 			priv->templ_time = set->time;
487 
488 			break;
489 		}
490 		case NGM_NETFLOW_SETMTU:
491 		{
492 			struct ng_netflow_setmtu *set;
493 
494 			if (msg->header.arglen != sizeof(struct ng_netflow_setmtu))
495 				ERROUT(EINVAL);
496 
497 			set = (struct ng_netflow_setmtu *)msg->data;
498 			if ((set->mtu < MIN_MTU) || (set->mtu > MAX_MTU))
499 				ERROUT(EINVAL);
500 
501 			priv->mtu = set->mtu;
502 
503 			break;
504 		}
505 		case NGM_NETFLOW_SHOW:
506 		{
507 			uint32_t *last;
508 
509 			if (msg->header.arglen != sizeof(uint32_t))
510 				ERROUT(EINVAL);
511 
512 			last = (uint32_t *)msg->data;
513 
514 			NG_MKRESPONSE(resp, msg, NGRESP_SIZE, M_NOWAIT);
515 
516 			if (!resp)
517 				ERROUT(ENOMEM);
518 
519 			error = ng_netflow_flow_show(priv, *last, resp);
520 
521 			break;
522 		}
523 		default:
524 			ERROUT(EINVAL);		/* unknown command */
525 			break;
526 		}
527 		break;
528 	default:
529 		ERROUT(EINVAL);		/* incorrect cookie */
530 		break;
531 	}
532 
533 	/*
534 	 * Take care of synchronous response, if any.
535 	 * Free memory and return.
536 	 */
537 done:
538 	NG_RESPOND_MSG(error, node, item, resp);
539 	NG_FREE_MSG(msg);
540 
541 	return (error);
542 }
543 
544 /* Receive data on hook. */
545 static int
546 ng_netflow_rcvdata (hook_p hook, item_p item)
547 {
548 	const node_p node = NG_HOOK_NODE(hook);
549 	const priv_p priv = NG_NODE_PRIVATE(node);
550 	const iface_p iface = NG_HOOK_PRIVATE(hook);
551 	hook_p out;
552 	struct mbuf *m = NULL, *m_old = NULL;
553 	struct ip *ip = NULL;
554 	struct ip6_hdr *ip6 = NULL;
555 	struct m_tag *mtag;
556 	int pullup_len = 0, off;
557 	uint8_t upper_proto = 0, is_frag = 0;
558 	int error = 0, bypass = 0, acct = 0;
559 	unsigned int src_if_index;
560 	caddr_t upper_ptr = NULL;
561 	fib_export_p fe;
562 	uint32_t fib;
563 
564 	if ((hook == priv->export) || (hook == priv->export9)) {
565 		/*
566 		 * Data arrived on export hook.
567 		 * This must not happen.
568 		 */
569 		log(LOG_ERR, "ng_netflow: incoming data on export hook!\n");
570 		ERROUT(EINVAL);
571 	};
572 
573 	if (hook == iface->hook) {
574 		if ((iface->info.conf & NG_NETFLOW_CONF_INGRESS) == 0)
575 			bypass = 1;
576 		out = iface->out;
577 	} else if (hook == iface->out) {
578 		if ((iface->info.conf & NG_NETFLOW_CONF_EGRESS) == 0)
579 			bypass = 1;
580 		out = iface->hook;
581 	} else
582 		ERROUT(EINVAL);
583 
584 	if ((!bypass) &&
585 	    (iface->info.conf & (NG_NETFLOW_CONF_ONCE | NG_NETFLOW_CONF_THISONCE))) {
586 		mtag = m_tag_locate(NGI_M(item), MTAG_NETFLOW,
587 		    MTAG_NETFLOW_CALLED, NULL);
588 		while (mtag != NULL) {
589 			if ((iface->info.conf & NG_NETFLOW_CONF_ONCE) ||
590 			    ((ng_ID_t *)(mtag + 1))[0] == NG_NODE_ID(node)) {
591 				bypass = 1;
592 				break;
593 			}
594 			mtag = m_tag_locate(NGI_M(item), MTAG_NETFLOW,
595 			    MTAG_NETFLOW_CALLED, mtag);
596 		}
597 	}
598 
599 	if (bypass) {
600 		if (out == NULL)
601 			ERROUT(ENOTCONN);
602 
603 		NG_FWD_ITEM_HOOK(error, item, out);
604 		return (error);
605 	}
606 
607 	if (iface->info.conf & (NG_NETFLOW_CONF_ONCE | NG_NETFLOW_CONF_THISONCE)) {
608 		mtag = m_tag_alloc(MTAG_NETFLOW, MTAG_NETFLOW_CALLED,
609 		    sizeof(ng_ID_t), M_NOWAIT);
610 		if (mtag) {
611 			((ng_ID_t *)(mtag + 1))[0] = NG_NODE_ID(node);
612 			m_tag_prepend(NGI_M(item), mtag);
613 		}
614 	}
615 
616 	NGI_GET_M(item, m);
617 	m_old = m;
618 
619 	/* Increase counters. */
620 	iface->info.ifinfo_packets++;
621 
622 	/*
623 	 * Depending on interface data link type and packet contents
624 	 * we pullup enough data, so that ng_netflow_flow_add() does not
625 	 * need to know about mbuf at all. We keep current length of data
626 	 * needed to be contiguous in pullup_len. mtod() is done at the
627 	 * very end one more time, since m can had changed after pulluping.
628 	 *
629 	 * In case of unrecognized data we don't return error, but just
630 	 * pass data to downstream hook, if it is available.
631 	 */
632 
633 #define	M_CHECK(length)	do {					\
634 	pullup_len += length;					\
635 	if (((m)->m_pkthdr.len < (pullup_len)) ||		\
636 	   ((pullup_len) > MHLEN)) {				\
637 		error = EINVAL;					\
638 		goto bypass;					\
639 	} 							\
640 	if ((m)->m_len < (pullup_len) &&			\
641 	   (((m) = m_pullup((m),(pullup_len))) == NULL)) {	\
642 		error = ENOBUFS;				\
643 		goto done;					\
644 	}							\
645 } while (0)
646 
647 	switch (iface->info.ifinfo_dlt) {
648 	case DLT_EN10MB:	/* Ethernet */
649 	    {
650 		struct ether_header *eh;
651 		uint16_t etype;
652 
653 		M_CHECK(sizeof(struct ether_header));
654 		eh = mtod(m, struct ether_header *);
655 
656 		/* Make sure this is IP frame. */
657 		etype = ntohs(eh->ether_type);
658 		switch (etype) {
659 		case ETHERTYPE_IP:
660 			M_CHECK(sizeof(struct ip));
661 			eh = mtod(m, struct ether_header *);
662 			ip = (struct ip *)(eh + 1);
663 			break;
664 #ifdef INET6
665 		case ETHERTYPE_IPV6:
666 			/*
667 			 * m_pullup() called by M_CHECK() pullups
668 			 * kern.ipc.max_protohdr (default 60 bytes) which is enough
669 			 */
670 			M_CHECK(sizeof(struct ip6_hdr));
671 			eh = mtod(m, struct ether_header *);
672 			ip6 = (struct ip6_hdr *)(eh + 1);
673 			break;
674 #endif
675 		case ETHERTYPE_VLAN:
676 		    {
677 			struct ether_vlan_header *evh;
678 
679 			M_CHECK(sizeof(struct ether_vlan_header) -
680 			    sizeof(struct ether_header));
681 			evh = mtod(m, struct ether_vlan_header *);
682 			etype = ntohs(evh->evl_proto);
683 
684 			if (etype == ETHERTYPE_IP) {
685 				M_CHECK(sizeof(struct ip));
686 				ip = (struct ip *)(evh + 1);
687 				break;
688 #ifdef INET6
689 			} else if (etype == ETHERTYPE_IPV6) {
690 				M_CHECK(sizeof(struct ip6_hdr));
691 				ip6 = (struct ip6_hdr *)(evh + 1);
692 				break;
693 #endif
694 			}
695 		    }
696 		default:
697 			goto bypass;	/* pass this frame */
698 		}
699 		break;
700 	    }
701 	case DLT_RAW:		/* IP packets */
702 		M_CHECK(sizeof(struct ip));
703 		ip = mtod(m, struct ip *);
704 #ifdef INET6
705 		/* If INET6 is not defined IPv6 packets will be discarded in ng_netflow_flow_add() */
706 		if (ip->ip_v == IP6VERSION) {
707 			/* IPv6 packet */
708 			ip = NULL;
709 			M_CHECK(sizeof(struct ip6_hdr));
710 			ip6 = mtod(m, struct ip6_hdr *);
711 		}
712 #endif
713 		break;
714 	default:
715 		goto bypass;
716 		break;
717 	}
718 
719 	off = pullup_len;
720 
721 	if ((ip != NULL) && ((ip->ip_off & htons(IP_OFFMASK)) == 0)) {
722 		if ((ip->ip_v != IPVERSION) ||
723 		    ((ip->ip_hl << 2) < sizeof(struct ip)))
724 			goto bypass;
725 		/*
726 		 * In case of IPv4 header with options, we haven't pulled
727 		 * up enough, yet.
728 		 */
729 		M_CHECK((ip->ip_hl << 2) - sizeof(struct ip));
730 
731 		/* Save upper layer offset and proto */
732 		off = pullup_len;
733 		upper_proto = ip->ip_p;
734 
735 		/*
736 		 * XXX: in case of wrong upper layer header we will forward this packet
737 		 * but skip this record in netflow
738 		 */
739 		switch (ip->ip_p) {
740 		case IPPROTO_TCP:
741 			M_CHECK(sizeof(struct tcphdr));
742 			break;
743 		case IPPROTO_UDP:
744 			M_CHECK(sizeof(struct udphdr));
745 			break;
746 		case IPPROTO_SCTP:
747 			M_CHECK(sizeof(struct sctphdr));
748 			break;
749 		}
750 	} else if (ip != NULL) {
751 		/* Nothing to save except upper layer proto, since this is packet fragment */
752 		is_frag = 1;
753 		upper_proto = ip->ip_p;
754 		if ((ip->ip_v != IPVERSION) ||
755 		    ((ip->ip_hl << 2) < sizeof(struct ip)))
756 			goto bypass;
757 #ifdef INET6
758 	} else if (ip6 != NULL) {
759 		/* Check if we can export */
760 		if (priv->export9 == NULL)
761 			goto bypass;
762 
763 		/* Loop thru IPv6 extended headers to get upper layer header / frag */
764 		int cur = ip6->ip6_nxt, hdr_off = 0;
765 		struct ip6_ext *ip6e;
766 		struct ip6_frag *ip6f;
767 
768 		/* Save upper layer info */
769 		off = pullup_len;
770 		upper_proto = cur;
771 
772 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
773 			goto bypass;
774 
775 		while (42) {
776 			switch (cur) {
777 			/*
778 			 * Same as in IPv4, we can forward 'bad' packet without accounting
779 			 */
780 			case IPPROTO_TCP:
781 				M_CHECK(sizeof(struct tcphdr));
782 				goto loopend;
783 			case IPPROTO_UDP:
784 				M_CHECK(sizeof(struct udphdr));
785 				goto loopend;
786 			case IPPROTO_SCTP:
787 				M_CHECK(sizeof(struct sctphdr));
788 				goto loopend;
789 
790 			/* Loop until 'real' upper layer headers */
791 			case IPPROTO_HOPOPTS:
792 			case IPPROTO_ROUTING:
793 			case IPPROTO_DSTOPTS:
794 				M_CHECK(sizeof(struct ip6_ext));
795 				ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
796 				upper_proto = ip6e->ip6e_nxt;
797 				hdr_off = (ip6e->ip6e_len + 1) << 3;
798 				break;
799 
800 			/* RFC4302, can be before DSTOPTS */
801 			case IPPROTO_AH:
802 				M_CHECK(sizeof(struct ip6_ext));
803 				ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
804 				upper_proto = ip6e->ip6e_nxt;
805 				hdr_off = (ip6e->ip6e_len + 2) << 2;
806 				break;
807 
808 			case IPPROTO_FRAGMENT:
809 				M_CHECK(sizeof(struct ip6_frag));
810 				ip6f = (struct ip6_frag *)(mtod(m, caddr_t) + off);
811 				upper_proto = ip6f->ip6f_nxt;
812 				hdr_off = sizeof(struct ip6_frag);
813 				off += hdr_off;
814 				is_frag = 1;
815 				goto loopend;
816 
817 #if 0
818 			case IPPROTO_NONE:
819 				goto loopend;
820 #endif
821 			/* Any unknow header (new extension or IPv6/IPv4 header for tunnels) */
822 			default:
823 				goto loopend;
824 			}
825 
826 			off += hdr_off;
827 			cur = upper_proto;
828 		}
829 #endif
830 	}
831 #undef	M_CHECK
832 
833 #ifdef INET6
834 loopend:
835 #endif
836 	/* Just in case of real reallocation in M_CHECK() / m_pullup() */
837 	if (m != m_old) {
838 		atomic_fetchadd_32(&priv->info.nfinfo_realloc_mbuf, 1);
839 		ip = NULL;
840 		ip6 = NULL;
841 		switch (iface->info.ifinfo_dlt) {
842 		case DLT_EN10MB:	/* Ethernet */
843 		    {
844 			struct ether_header *eh;
845 
846 			eh = mtod(m, struct ether_header *);
847 			switch (ntohs(eh->ether_type)) {
848 			case ETHERTYPE_IP:
849 				ip = (struct ip *)(eh + 1);
850 				break;
851 #ifdef INET6
852 			case ETHERTYPE_IPV6:
853 				ip6 = (struct ip6_hdr *)(eh + 1);
854 				break;
855 #endif
856 			case ETHERTYPE_VLAN:
857 			    {
858 				struct ether_vlan_header *evh;
859 
860 				evh = mtod(m, struct ether_vlan_header *);
861 				if (ntohs(evh->evl_proto) == ETHERTYPE_IP) {
862 					ip = (struct ip *)(evh + 1);
863 					break;
864 #ifdef INET6
865 				} else if (ntohs(evh->evl_proto) == ETHERTYPE_IPV6) {
866 					ip6 = (struct ip6_hdr *)(evh + 1);
867 					break;
868 #endif
869 				}
870 			    }
871 			default:
872 				panic("ng_netflow entered deadcode");
873 			}
874 			break;
875 		    }
876 		case DLT_RAW:		/* IP packets */
877 			ip = mtod(m, struct ip *);
878 #ifdef INET6
879 			if (ip->ip_v == IP6VERSION) {
880 				/* IPv6 packet */
881 				ip = NULL;
882 				ip6 = mtod(m, struct ip6_hdr *);
883 			}
884 #endif
885  			break;
886  		default:
887  			panic("ng_netflow entered deadcode");
888  		}
889  	}
890 
891 	upper_ptr = (caddr_t)(mtod(m, caddr_t) + off);
892 
893 	/* Determine packet input interface. Prefer configured. */
894 	src_if_index = 0;
895 	if (hook == iface->out || iface->info.ifinfo_index == 0) {
896 		if (m->m_pkthdr.rcvif != NULL)
897 			src_if_index = m->m_pkthdr.rcvif->if_index;
898 	} else
899 		src_if_index = iface->info.ifinfo_index;
900 
901 	/* Check packet FIB */
902 	fib = M_GETFIB(m);
903 	if (fib >= RT_NUMFIBS) {
904 		CTR2(KTR_NET, "ng_netflow_rcvdata(): packet fib %d is out of range of available fibs: 0 .. %d", fib, RT_NUMFIBS);
905 		goto bypass;
906 	}
907 
908 	if ((fe = priv_to_fib(priv, fib)) == NULL) {
909 		/* Setup new FIB */
910 		if (ng_netflow_fib_init(priv, fib) != 0) {
911 			/* malloc() failed */
912 			goto bypass;
913 		}
914 
915 		fe = priv_to_fib(priv, fib);
916 	}
917 
918 	if (ip != NULL)
919 		error = ng_netflow_flow_add(priv, fe, ip, upper_ptr, upper_proto, is_frag, src_if_index);
920 #ifdef INET6
921 	else if (ip6 != NULL)
922 		error = ng_netflow_flow6_add(priv, fe, ip6, upper_ptr, upper_proto, is_frag, src_if_index);
923 #endif
924 	else
925 		goto bypass;
926 
927 	acct = 1;
928 bypass:
929 	if (out != NULL) {
930 		if (acct == 0) {
931 			/* Accounting failure */
932 			if (ip != NULL) {
933 				atomic_fetchadd_32(&priv->info.nfinfo_spackets, 1);
934 				priv->info.nfinfo_sbytes += m_length(m, NULL);
935 			} else if (ip6 != NULL) {
936 				atomic_fetchadd_32(&priv->info.nfinfo_spackets6, 1);
937 				priv->info.nfinfo_sbytes6 += m_length(m, NULL);
938 			}
939 		}
940 
941 		/* XXX: error gets overwritten here */
942 		NG_FWD_NEW_DATA(error, item, out, m);
943 		return (error);
944 	}
945 done:
946 	if (item)
947 		NG_FREE_ITEM(item);
948 	if (m)
949 		NG_FREE_M(m);
950 
951 	return (error);
952 }
953 
954 /* We will be shut down in a moment */
955 static int
956 ng_netflow_close(node_p node)
957 {
958 	const priv_p priv = NG_NODE_PRIVATE(node);
959 
960 	callout_drain(&priv->exp_callout);
961 	ng_netflow_cache_flush(priv);
962 
963 	return (0);
964 }
965 
966 /* Do local shutdown processing. */
967 static int
968 ng_netflow_rmnode(node_p node)
969 {
970 	const priv_p priv = NG_NODE_PRIVATE(node);
971 
972 	NG_NODE_SET_PRIVATE(node, NULL);
973 	NG_NODE_UNREF(priv->node);
974 
975 	free(priv, M_NETGRAPH);
976 
977 	return (0);
978 }
979 
980 /* Hook disconnection. */
981 static int
982 ng_netflow_disconnect(hook_p hook)
983 {
984 	node_p node = NG_HOOK_NODE(hook);
985 	priv_p priv = NG_NODE_PRIVATE(node);
986 	iface_p iface = NG_HOOK_PRIVATE(hook);
987 
988 	if (iface != NULL) {
989 		if (iface->hook == hook)
990 			iface->hook = NULL;
991 		if (iface->out == hook)
992 			iface->out = NULL;
993 	}
994 
995 	/* if export hook disconnected stop running expire(). */
996 	if (hook == priv->export) {
997 		if (priv->export9 == NULL)
998 			callout_drain(&priv->exp_callout);
999 		priv->export = NULL;
1000 	}
1001 
1002 	if (hook == priv->export9) {
1003 		if (priv->export == NULL)
1004 			callout_drain(&priv->exp_callout);
1005 		priv->export9 = NULL;
1006 	}
1007 
1008 	/* Removal of the last link destroys the node. */
1009 	if (NG_NODE_NUMHOOKS(node) == 0)
1010 		ng_rmnode_self(node);
1011 
1012 	return (0);
1013 }
1014