xref: /freebsd/sys/netgraph/netflow/ng_netflow.c (revision 3ef51c5fb9163f2aafb1c14729e06a8bf0c4d113)
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 	/* Initialize fib data */
229 	priv->maxfibs = rt_numfibs;
230 	priv->fib_data = malloc(sizeof(fib_export_p) * priv->maxfibs,
231 	    M_NETGRAPH, M_WAITOK | M_ZERO);
232 
233 	/* Make node and its data point at each other */
234 	NG_NODE_SET_PRIVATE(node, priv);
235 	priv->node = node;
236 
237 	/* Initialize timeouts to default values */
238 	priv->info.nfinfo_inact_t = INACTIVE_TIMEOUT;
239 	priv->info.nfinfo_act_t = ACTIVE_TIMEOUT;
240 
241 	/* Set default config */
242 	for (i = 0; i < NG_NETFLOW_MAXIFACES; i++)
243 		priv->ifaces[i].info.conf = NG_NETFLOW_CONF_INGRESS;
244 
245 	/* Initialize callout handle */
246 	callout_init(&priv->exp_callout, CALLOUT_MPSAFE);
247 
248 	/* Allocate memory and set up flow cache */
249 	ng_netflow_cache_init(priv);
250 
251 	return (0);
252 }
253 
254 /*
255  * ng_netflow supports two hooks: data and export.
256  * Incoming traffic is expected on data, and expired
257  * netflow datagrams are sent to export.
258  */
259 static int
260 ng_netflow_newhook(node_p node, hook_p hook, const char *name)
261 {
262 	const priv_p priv = NG_NODE_PRIVATE(node);
263 
264 	if (strncmp(name, NG_NETFLOW_HOOK_DATA,	/* an iface hook? */
265 	    strlen(NG_NETFLOW_HOOK_DATA)) == 0) {
266 		iface_p iface;
267 		int ifnum = -1;
268 		const char *cp;
269 		char *eptr;
270 
271 		cp = name + strlen(NG_NETFLOW_HOOK_DATA);
272 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
273 			return (EINVAL);
274 
275 		ifnum = (int)strtoul(cp, &eptr, 10);
276 		if (*eptr != '\0' || ifnum < 0 || ifnum >= NG_NETFLOW_MAXIFACES)
277 			return (EINVAL);
278 
279 		/* See if hook is already connected */
280 		if (priv->ifaces[ifnum].hook != NULL)
281 			return (EISCONN);
282 
283 		iface = &priv->ifaces[ifnum];
284 
285 		/* Link private info and hook together */
286 		NG_HOOK_SET_PRIVATE(hook, iface);
287 		iface->hook = hook;
288 
289 		/*
290 		 * In most cases traffic accounting is done on an
291 		 * Ethernet interface, so default data link type
292 		 * will be DLT_EN10MB.
293 		 */
294 		iface->info.ifinfo_dlt = DLT_EN10MB;
295 
296 	} else if (strncmp(name, NG_NETFLOW_HOOK_OUT,
297 	    strlen(NG_NETFLOW_HOOK_OUT)) == 0) {
298 		iface_p iface;
299 		int ifnum = -1;
300 		const char *cp;
301 		char *eptr;
302 
303 		cp = name + strlen(NG_NETFLOW_HOOK_OUT);
304 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
305 			return (EINVAL);
306 
307 		ifnum = (int)strtoul(cp, &eptr, 10);
308 		if (*eptr != '\0' || ifnum < 0 || ifnum >= NG_NETFLOW_MAXIFACES)
309 			return (EINVAL);
310 
311 		/* See if hook is already connected */
312 		if (priv->ifaces[ifnum].out != NULL)
313 			return (EISCONN);
314 
315 		iface = &priv->ifaces[ifnum];
316 
317 		/* Link private info and hook together */
318 		NG_HOOK_SET_PRIVATE(hook, iface);
319 		iface->out = hook;
320 
321 	} else if (strcmp(name, NG_NETFLOW_HOOK_EXPORT) == 0) {
322 
323 		if (priv->export != NULL)
324 			return (EISCONN);
325 
326 		/* Netflow version 5 supports 32-bit counters only */
327 		if (CNTR_MAX == UINT64_MAX)
328 			return (EINVAL);
329 
330 		priv->export = hook;
331 
332 		/* Exporter is ready. Let's schedule expiry. */
333 		callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
334 		    (void *)priv);
335 	} else if (strcmp(name, NG_NETFLOW_HOOK_EXPORT9) == 0) {
336 
337 		if (priv->export9 != NULL)
338 			return (EISCONN);
339 
340 		priv->export9 = hook;
341 
342 		/* Exporter is ready. Let's schedule expiry. */
343 		callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
344 		    (void *)priv);
345 	} else
346 		return (EINVAL);
347 
348 	return (0);
349 }
350 
351 /* Get a netgraph control message. */
352 static int
353 ng_netflow_rcvmsg (node_p node, item_p item, hook_p lasthook)
354 {
355 	const priv_p priv = NG_NODE_PRIVATE(node);
356 	struct ng_mesg *resp = NULL;
357 	int error = 0;
358 	struct ng_mesg *msg;
359 
360 	NGI_GET_MSG(item, msg);
361 
362 	/* Deal with message according to cookie and command */
363 	switch (msg->header.typecookie) {
364 	case NGM_NETFLOW_COOKIE:
365 		switch (msg->header.cmd) {
366 		case NGM_NETFLOW_INFO:
367 		{
368 			struct ng_netflow_info *i;
369 
370 			NG_MKRESPONSE(resp, msg, sizeof(struct ng_netflow_info),
371 			    M_NOWAIT);
372 			i = (struct ng_netflow_info *)resp->data;
373 			ng_netflow_copyinfo(priv, i);
374 
375 			break;
376 		}
377 		case NGM_NETFLOW_IFINFO:
378 		{
379 			struct ng_netflow_ifinfo *i;
380 			const uint16_t *index;
381 
382 			if (msg->header.arglen != sizeof(uint16_t))
383 				 ERROUT(EINVAL);
384 
385 			index  = (uint16_t *)msg->data;
386 			if (*index >= NG_NETFLOW_MAXIFACES)
387 				ERROUT(EINVAL);
388 
389 			/* connected iface? */
390 			if (priv->ifaces[*index].hook == NULL)
391 				 ERROUT(EINVAL);
392 
393 			NG_MKRESPONSE(resp, msg,
394 			     sizeof(struct ng_netflow_ifinfo), M_NOWAIT);
395 			i = (struct ng_netflow_ifinfo *)resp->data;
396 			memcpy((void *)i, (void *)&priv->ifaces[*index].info,
397 			    sizeof(priv->ifaces[*index].info));
398 
399 			break;
400 		}
401 		case NGM_NETFLOW_SETDLT:
402 		{
403 			struct ng_netflow_setdlt *set;
404 			struct ng_netflow_iface *iface;
405 
406 			if (msg->header.arglen != sizeof(struct ng_netflow_setdlt))
407 				ERROUT(EINVAL);
408 
409 			set = (struct ng_netflow_setdlt *)msg->data;
410 			if (set->iface >= NG_NETFLOW_MAXIFACES)
411 				ERROUT(EINVAL);
412 			iface = &priv->ifaces[set->iface];
413 
414 			/* connected iface? */
415 			if (iface->hook == NULL)
416 				ERROUT(EINVAL);
417 
418 			switch (set->dlt) {
419 			case	DLT_EN10MB:
420 				iface->info.ifinfo_dlt = DLT_EN10MB;
421 				break;
422 			case	DLT_RAW:
423 				iface->info.ifinfo_dlt = DLT_RAW;
424 				break;
425 			default:
426 				ERROUT(EINVAL);
427 			}
428 			break;
429 		}
430 		case NGM_NETFLOW_SETIFINDEX:
431 		{
432 			struct ng_netflow_setifindex *set;
433 			struct ng_netflow_iface *iface;
434 
435 			if (msg->header.arglen != sizeof(struct ng_netflow_setifindex))
436 				ERROUT(EINVAL);
437 
438 			set = (struct ng_netflow_setifindex *)msg->data;
439 			if (set->iface >= NG_NETFLOW_MAXIFACES)
440 				ERROUT(EINVAL);
441 			iface = &priv->ifaces[set->iface];
442 
443 			/* connected iface? */
444 			if (iface->hook == NULL)
445 				ERROUT(EINVAL);
446 
447 			iface->info.ifinfo_index = set->index;
448 
449 			break;
450 		}
451 		case NGM_NETFLOW_SETTIMEOUTS:
452 		{
453 			struct ng_netflow_settimeouts *set;
454 
455 			if (msg->header.arglen != sizeof(struct ng_netflow_settimeouts))
456 				ERROUT(EINVAL);
457 
458 			set = (struct ng_netflow_settimeouts *)msg->data;
459 
460 			priv->info.nfinfo_inact_t = set->inactive_timeout;
461 			priv->info.nfinfo_act_t = set->active_timeout;
462 
463 			break;
464 		}
465 		case NGM_NETFLOW_SETCONFIG:
466 		{
467 			struct ng_netflow_setconfig *set;
468 
469 			if (msg->header.arglen != sizeof(struct ng_netflow_setconfig))
470 				ERROUT(EINVAL);
471 
472 			set = (struct ng_netflow_setconfig *)msg->data;
473 
474 			if (set->iface >= NG_NETFLOW_MAXIFACES)
475 				ERROUT(EINVAL);
476 
477 			priv->ifaces[set->iface].info.conf = set->conf;
478 
479 			break;
480 		}
481 		case NGM_NETFLOW_SETTEMPLATE:
482 		{
483 			struct ng_netflow_settemplate *set;
484 
485 			if (msg->header.arglen != sizeof(struct ng_netflow_settemplate))
486 				ERROUT(EINVAL);
487 
488 			set = (struct ng_netflow_settemplate *)msg->data;
489 
490 			priv->templ_packets = set->packets;
491 			priv->templ_time = set->time;
492 
493 			break;
494 		}
495 		case NGM_NETFLOW_SETMTU:
496 		{
497 			struct ng_netflow_setmtu *set;
498 
499 			if (msg->header.arglen != sizeof(struct ng_netflow_setmtu))
500 				ERROUT(EINVAL);
501 
502 			set = (struct ng_netflow_setmtu *)msg->data;
503 			if ((set->mtu < MIN_MTU) || (set->mtu > MAX_MTU))
504 				ERROUT(EINVAL);
505 
506 			priv->mtu = set->mtu;
507 
508 			break;
509 		}
510 		case NGM_NETFLOW_SHOW:
511 		{
512 			if (msg->header.arglen != sizeof(struct ngnf_show_header))
513 				ERROUT(EINVAL);
514 
515 			NG_MKRESPONSE(resp, msg, NGRESP_SIZE, M_NOWAIT);
516 
517 			if (!resp)
518 				ERROUT(ENOMEM);
519 
520 			error = ng_netflow_flow_show(priv,
521 			    (struct ngnf_show_header *)msg->data,
522 			    (struct ngnf_show_header *)resp->data);
523 
524 			if (error)
525 				NG_FREE_MSG(resp);
526 
527 			break;
528 		}
529 		default:
530 			ERROUT(EINVAL);		/* unknown command */
531 			break;
532 		}
533 		break;
534 	default:
535 		ERROUT(EINVAL);		/* incorrect cookie */
536 		break;
537 	}
538 
539 	/*
540 	 * Take care of synchronous response, if any.
541 	 * Free memory and return.
542 	 */
543 done:
544 	NG_RESPOND_MSG(error, node, item, resp);
545 	NG_FREE_MSG(msg);
546 
547 	return (error);
548 }
549 
550 /* Receive data on hook. */
551 static int
552 ng_netflow_rcvdata (hook_p hook, item_p item)
553 {
554 	const node_p node = NG_HOOK_NODE(hook);
555 	const priv_p priv = NG_NODE_PRIVATE(node);
556 	const iface_p iface = NG_HOOK_PRIVATE(hook);
557 	hook_p out;
558 	struct mbuf *m = NULL, *m_old = NULL;
559 	struct ip *ip = NULL;
560 	struct ip6_hdr *ip6 = NULL;
561 	struct m_tag *mtag;
562 	int pullup_len = 0, off;
563 	uint8_t upper_proto = 0, is_frag = 0;
564 	int error = 0, bypass = 0, acct = 0;
565 	unsigned int src_if_index;
566 	caddr_t upper_ptr = NULL;
567 	fib_export_p fe;
568 	uint32_t fib;
569 
570 	if ((hook == priv->export) || (hook == priv->export9)) {
571 		/*
572 		 * Data arrived on export hook.
573 		 * This must not happen.
574 		 */
575 		log(LOG_ERR, "ng_netflow: incoming data on export hook!\n");
576 		ERROUT(EINVAL);
577 	};
578 
579 	if (hook == iface->hook) {
580 		if ((iface->info.conf & NG_NETFLOW_CONF_INGRESS) == 0)
581 			bypass = 1;
582 		out = iface->out;
583 	} else if (hook == iface->out) {
584 		if ((iface->info.conf & NG_NETFLOW_CONF_EGRESS) == 0)
585 			bypass = 1;
586 		out = iface->hook;
587 	} else
588 		ERROUT(EINVAL);
589 
590 	if ((!bypass) &&
591 	    (iface->info.conf & (NG_NETFLOW_CONF_ONCE | NG_NETFLOW_CONF_THISONCE))) {
592 		mtag = m_tag_locate(NGI_M(item), MTAG_NETFLOW,
593 		    MTAG_NETFLOW_CALLED, NULL);
594 		while (mtag != NULL) {
595 			if ((iface->info.conf & NG_NETFLOW_CONF_ONCE) ||
596 			    ((ng_ID_t *)(mtag + 1))[0] == NG_NODE_ID(node)) {
597 				bypass = 1;
598 				break;
599 			}
600 			mtag = m_tag_locate(NGI_M(item), MTAG_NETFLOW,
601 			    MTAG_NETFLOW_CALLED, mtag);
602 		}
603 	}
604 
605 	if (bypass) {
606 		if (out == NULL)
607 			ERROUT(ENOTCONN);
608 
609 		NG_FWD_ITEM_HOOK(error, item, out);
610 		return (error);
611 	}
612 
613 	if (iface->info.conf & (NG_NETFLOW_CONF_ONCE | NG_NETFLOW_CONF_THISONCE)) {
614 		mtag = m_tag_alloc(MTAG_NETFLOW, MTAG_NETFLOW_CALLED,
615 		    sizeof(ng_ID_t), M_NOWAIT);
616 		if (mtag) {
617 			((ng_ID_t *)(mtag + 1))[0] = NG_NODE_ID(node);
618 			m_tag_prepend(NGI_M(item), mtag);
619 		}
620 	}
621 
622 	NGI_GET_M(item, m);
623 	m_old = m;
624 
625 	/* Increase counters. */
626 	iface->info.ifinfo_packets++;
627 
628 	/*
629 	 * Depending on interface data link type and packet contents
630 	 * we pullup enough data, so that ng_netflow_flow_add() does not
631 	 * need to know about mbuf at all. We keep current length of data
632 	 * needed to be contiguous in pullup_len. mtod() is done at the
633 	 * very end one more time, since m can had changed after pulluping.
634 	 *
635 	 * In case of unrecognized data we don't return error, but just
636 	 * pass data to downstream hook, if it is available.
637 	 */
638 
639 #define	M_CHECK(length)	do {					\
640 	pullup_len += length;					\
641 	if (((m)->m_pkthdr.len < (pullup_len)) ||		\
642 	   ((pullup_len) > MHLEN)) {				\
643 		error = EINVAL;					\
644 		goto bypass;					\
645 	} 							\
646 	if ((m)->m_len < (pullup_len) &&			\
647 	   (((m) = m_pullup((m),(pullup_len))) == NULL)) {	\
648 		error = ENOBUFS;				\
649 		goto done;					\
650 	}							\
651 } while (0)
652 
653 	switch (iface->info.ifinfo_dlt) {
654 	case DLT_EN10MB:	/* Ethernet */
655 	    {
656 		struct ether_header *eh;
657 		uint16_t etype;
658 
659 		M_CHECK(sizeof(struct ether_header));
660 		eh = mtod(m, struct ether_header *);
661 
662 		/* Make sure this is IP frame. */
663 		etype = ntohs(eh->ether_type);
664 		switch (etype) {
665 		case ETHERTYPE_IP:
666 			M_CHECK(sizeof(struct ip));
667 			eh = mtod(m, struct ether_header *);
668 			ip = (struct ip *)(eh + 1);
669 			break;
670 #ifdef INET6
671 		case ETHERTYPE_IPV6:
672 			/*
673 			 * m_pullup() called by M_CHECK() pullups
674 			 * kern.ipc.max_protohdr (default 60 bytes) which is enough
675 			 */
676 			M_CHECK(sizeof(struct ip6_hdr));
677 			eh = mtod(m, struct ether_header *);
678 			ip6 = (struct ip6_hdr *)(eh + 1);
679 			break;
680 #endif
681 		case ETHERTYPE_VLAN:
682 		    {
683 			struct ether_vlan_header *evh;
684 
685 			M_CHECK(sizeof(struct ether_vlan_header) -
686 			    sizeof(struct ether_header));
687 			evh = mtod(m, struct ether_vlan_header *);
688 			etype = ntohs(evh->evl_proto);
689 
690 			if (etype == ETHERTYPE_IP) {
691 				M_CHECK(sizeof(struct ip));
692 				ip = (struct ip *)(evh + 1);
693 				break;
694 #ifdef INET6
695 			} else if (etype == ETHERTYPE_IPV6) {
696 				M_CHECK(sizeof(struct ip6_hdr));
697 				ip6 = (struct ip6_hdr *)(evh + 1);
698 				break;
699 #endif
700 			}
701 		    }
702 		default:
703 			goto bypass;	/* pass this frame */
704 		}
705 		break;
706 	    }
707 	case DLT_RAW:		/* IP packets */
708 		M_CHECK(sizeof(struct ip));
709 		ip = mtod(m, struct ip *);
710 #ifdef INET6
711 		/* If INET6 is not defined IPv6 packets will be discarded in ng_netflow_flow_add() */
712 		if (ip->ip_v == IP6VERSION) {
713 			/* IPv6 packet */
714 			ip = NULL;
715 			M_CHECK(sizeof(struct ip6_hdr));
716 			ip6 = mtod(m, struct ip6_hdr *);
717 		}
718 #endif
719 		break;
720 	default:
721 		goto bypass;
722 		break;
723 	}
724 
725 	off = pullup_len;
726 
727 	if ((ip != NULL) && ((ip->ip_off & htons(IP_OFFMASK)) == 0)) {
728 		if ((ip->ip_v != IPVERSION) ||
729 		    ((ip->ip_hl << 2) < sizeof(struct ip)))
730 			goto bypass;
731 		/*
732 		 * In case of IPv4 header with options, we haven't pulled
733 		 * up enough, yet.
734 		 */
735 		M_CHECK((ip->ip_hl << 2) - sizeof(struct ip));
736 
737 		/* Save upper layer offset and proto */
738 		off = pullup_len;
739 		upper_proto = ip->ip_p;
740 
741 		/*
742 		 * XXX: in case of wrong upper layer header we will forward this packet
743 		 * but skip this record in netflow
744 		 */
745 		switch (ip->ip_p) {
746 		case IPPROTO_TCP:
747 			M_CHECK(sizeof(struct tcphdr));
748 			break;
749 		case IPPROTO_UDP:
750 			M_CHECK(sizeof(struct udphdr));
751 			break;
752 		case IPPROTO_SCTP:
753 			M_CHECK(sizeof(struct sctphdr));
754 			break;
755 		}
756 	} else if (ip != NULL) {
757 		/* Nothing to save except upper layer proto, since this is packet fragment */
758 		is_frag = 1;
759 		upper_proto = ip->ip_p;
760 		if ((ip->ip_v != IPVERSION) ||
761 		    ((ip->ip_hl << 2) < sizeof(struct ip)))
762 			goto bypass;
763 #ifdef INET6
764 	} else if (ip6 != NULL) {
765 		/* Check if we can export */
766 		if (priv->export9 == NULL)
767 			goto bypass;
768 
769 		/* Loop thru IPv6 extended headers to get upper layer header / frag */
770 		int cur = ip6->ip6_nxt, hdr_off = 0;
771 		struct ip6_ext *ip6e;
772 		struct ip6_frag *ip6f;
773 
774 		/* Save upper layer info */
775 		off = pullup_len;
776 		upper_proto = cur;
777 
778 		if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
779 			goto bypass;
780 
781 		while (42) {
782 			switch (cur) {
783 			/*
784 			 * Same as in IPv4, we can forward 'bad' packet without accounting
785 			 */
786 			case IPPROTO_TCP:
787 				M_CHECK(sizeof(struct tcphdr));
788 				goto loopend;
789 			case IPPROTO_UDP:
790 				M_CHECK(sizeof(struct udphdr));
791 				goto loopend;
792 			case IPPROTO_SCTP:
793 				M_CHECK(sizeof(struct sctphdr));
794 				goto loopend;
795 
796 			/* Loop until 'real' upper layer headers */
797 			case IPPROTO_HOPOPTS:
798 			case IPPROTO_ROUTING:
799 			case IPPROTO_DSTOPTS:
800 				M_CHECK(sizeof(struct ip6_ext));
801 				ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
802 				upper_proto = ip6e->ip6e_nxt;
803 				hdr_off = (ip6e->ip6e_len + 1) << 3;
804 				break;
805 
806 			/* RFC4302, can be before DSTOPTS */
807 			case IPPROTO_AH:
808 				M_CHECK(sizeof(struct ip6_ext));
809 				ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
810 				upper_proto = ip6e->ip6e_nxt;
811 				hdr_off = (ip6e->ip6e_len + 2) << 2;
812 				break;
813 
814 			case IPPROTO_FRAGMENT:
815 				M_CHECK(sizeof(struct ip6_frag));
816 				ip6f = (struct ip6_frag *)(mtod(m, caddr_t) + off);
817 				upper_proto = ip6f->ip6f_nxt;
818 				hdr_off = sizeof(struct ip6_frag);
819 				off += hdr_off;
820 				is_frag = 1;
821 				goto loopend;
822 
823 #if 0
824 			case IPPROTO_NONE:
825 				goto loopend;
826 #endif
827 			/* Any unknow header (new extension or IPv6/IPv4 header for tunnels) */
828 			default:
829 				goto loopend;
830 			}
831 
832 			off += hdr_off;
833 			cur = upper_proto;
834 		}
835 #endif
836 	}
837 #undef	M_CHECK
838 
839 #ifdef INET6
840 loopend:
841 #endif
842 	/* Just in case of real reallocation in M_CHECK() / m_pullup() */
843 	if (m != m_old) {
844 		atomic_fetchadd_32(&priv->info.nfinfo_realloc_mbuf, 1);
845 		ip = NULL;
846 		ip6 = NULL;
847 		switch (iface->info.ifinfo_dlt) {
848 		case DLT_EN10MB:	/* Ethernet */
849 		    {
850 			struct ether_header *eh;
851 
852 			eh = mtod(m, struct ether_header *);
853 			switch (ntohs(eh->ether_type)) {
854 			case ETHERTYPE_IP:
855 				ip = (struct ip *)(eh + 1);
856 				break;
857 #ifdef INET6
858 			case ETHERTYPE_IPV6:
859 				ip6 = (struct ip6_hdr *)(eh + 1);
860 				break;
861 #endif
862 			case ETHERTYPE_VLAN:
863 			    {
864 				struct ether_vlan_header *evh;
865 
866 				evh = mtod(m, struct ether_vlan_header *);
867 				if (ntohs(evh->evl_proto) == ETHERTYPE_IP) {
868 					ip = (struct ip *)(evh + 1);
869 					break;
870 #ifdef INET6
871 				} else if (ntohs(evh->evl_proto) == ETHERTYPE_IPV6) {
872 					ip6 = (struct ip6_hdr *)(evh + 1);
873 					break;
874 #endif
875 				}
876 			    }
877 			default:
878 				panic("ng_netflow entered deadcode");
879 			}
880 			break;
881 		    }
882 		case DLT_RAW:		/* IP packets */
883 			ip = mtod(m, struct ip *);
884 #ifdef INET6
885 			if (ip->ip_v == IP6VERSION) {
886 				/* IPv6 packet */
887 				ip = NULL;
888 				ip6 = mtod(m, struct ip6_hdr *);
889 			}
890 #endif
891  			break;
892  		default:
893  			panic("ng_netflow entered deadcode");
894  		}
895  	}
896 
897 	upper_ptr = (caddr_t)(mtod(m, caddr_t) + off);
898 
899 	/* Determine packet input interface. Prefer configured. */
900 	src_if_index = 0;
901 	if (hook == iface->out || iface->info.ifinfo_index == 0) {
902 		if (m->m_pkthdr.rcvif != NULL)
903 			src_if_index = m->m_pkthdr.rcvif->if_index;
904 	} else
905 		src_if_index = iface->info.ifinfo_index;
906 
907 	/* Check packet FIB */
908 	fib = M_GETFIB(m);
909 	if (fib >= priv->maxfibs) {
910 		CTR2(KTR_NET, "ng_netflow_rcvdata(): packet fib %d is out of "
911 		    "range of available fibs: 0 .. %d",
912 		    fib, priv->maxfibs);
913 		goto bypass;
914 	}
915 
916 	if ((fe = priv_to_fib(priv, fib)) == NULL) {
917 		/* Setup new FIB */
918 		if (ng_netflow_fib_init(priv, fib) != 0) {
919 			/* malloc() failed */
920 			goto bypass;
921 		}
922 
923 		fe = priv_to_fib(priv, fib);
924 	}
925 
926 	if (ip != NULL)
927 		error = ng_netflow_flow_add(priv, fe, ip, upper_ptr, upper_proto, is_frag, src_if_index);
928 #ifdef INET6
929 	else if (ip6 != NULL)
930 		error = ng_netflow_flow6_add(priv, fe, ip6, upper_ptr, upper_proto, is_frag, src_if_index);
931 #endif
932 	else
933 		goto bypass;
934 
935 	acct = 1;
936 bypass:
937 	if (out != NULL) {
938 		if (acct == 0) {
939 			/* Accounting failure */
940 			if (ip != NULL) {
941 				atomic_fetchadd_32(&priv->info.nfinfo_spackets, 1);
942 				priv->info.nfinfo_sbytes += m_length(m, NULL);
943 			} else if (ip6 != NULL) {
944 				atomic_fetchadd_32(&priv->info.nfinfo_spackets6, 1);
945 				priv->info.nfinfo_sbytes6 += m_length(m, NULL);
946 			}
947 		}
948 
949 		/* XXX: error gets overwritten here */
950 		NG_FWD_NEW_DATA(error, item, out, m);
951 		return (error);
952 	}
953 done:
954 	if (item)
955 		NG_FREE_ITEM(item);
956 	if (m)
957 		NG_FREE_M(m);
958 
959 	return (error);
960 }
961 
962 /* We will be shut down in a moment */
963 static int
964 ng_netflow_close(node_p node)
965 {
966 	const priv_p priv = NG_NODE_PRIVATE(node);
967 
968 	callout_drain(&priv->exp_callout);
969 	ng_netflow_cache_flush(priv);
970 
971 	return (0);
972 }
973 
974 /* Do local shutdown processing. */
975 static int
976 ng_netflow_rmnode(node_p node)
977 {
978 	const priv_p priv = NG_NODE_PRIVATE(node);
979 
980 	NG_NODE_SET_PRIVATE(node, NULL);
981 	NG_NODE_UNREF(priv->node);
982 
983 	free(priv->fib_data, M_NETGRAPH);
984 	free(priv, M_NETGRAPH);
985 
986 	return (0);
987 }
988 
989 /* Hook disconnection. */
990 static int
991 ng_netflow_disconnect(hook_p hook)
992 {
993 	node_p node = NG_HOOK_NODE(hook);
994 	priv_p priv = NG_NODE_PRIVATE(node);
995 	iface_p iface = NG_HOOK_PRIVATE(hook);
996 
997 	if (iface != NULL) {
998 		if (iface->hook == hook)
999 			iface->hook = NULL;
1000 		if (iface->out == hook)
1001 			iface->out = NULL;
1002 	}
1003 
1004 	/* if export hook disconnected stop running expire(). */
1005 	if (hook == priv->export) {
1006 		if (priv->export9 == NULL)
1007 			callout_drain(&priv->exp_callout);
1008 		priv->export = NULL;
1009 	}
1010 
1011 	if (hook == priv->export9) {
1012 		if (priv->export == NULL)
1013 			callout_drain(&priv->exp_callout);
1014 		priv->export9 = NULL;
1015 	}
1016 
1017 	/* Removal of the last link destroys the node. */
1018 	if (NG_NODE_NUMHOOKS(node) == 0)
1019 		ng_rmnode_self(node);
1020 
1021 	return (0);
1022 }
1023