1 /**
2 * collectd - src/tcpconns.c
3 * Copyright (C) 2007,2008 Florian octo Forster
4 * Copyright (C) 2008 Michael Stapelberg
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 * Author:
20 * Florian octo Forster <octo at collectd.org>
21 * Michael Stapelberg <michael+git at stapelberg.de>
22 **/
24 /**
25 * Code within `HAVE_LIBKVM_NLIST' blocks is provided under the following
26 * license:
27 *
28 * $collectd: parts of tcpconns.c, 2008/08/08 03:48:30 Michael Stapelberg $
29 * $OpenBSD: inet.c,v 1.100 2007/06/19 05:28:30 ray Exp $
30 * $NetBSD: inet.c,v 1.14 1995/10/03 21:42:37 thorpej Exp $
31 *
32 * Copyright (c) 1983, 1988, 1993
33 * The Regents of the University of California. All rights reserved.
34 *
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
37 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
43 * 3. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
58 */
60 #include "collectd.h"
61 #include "common.h"
62 #include "plugin.h"
64 #if defined(__OpenBSD__) || defined(__NetBSD__)
65 #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */
66 #endif
68 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST && !KERNEL_AIX
69 # error "No applicable input method."
70 #endif
72 #if KERNEL_LINUX
73 # include <asm/types.h>
74 # include <linux/netlink.h>
75 #if HAVE_LINUX_INET_DIAG_H
76 # include <linux/inet_diag.h>
77 #endif
78 # include <arpa/inet.h>
79 /* #endif KERNEL_LINUX */
81 #elif HAVE_SYSCTLBYNAME
82 # include <sys/socketvar.h>
83 # include <sys/sysctl.h>
85 /* Some includes needed for compiling on FreeBSD */
86 #include <sys/time.h>
87 #if HAVE_SYS_TYPES_H
88 # include <sys/types.h>
89 #endif
90 #if HAVE_NET_IF_H
91 # include <net/if.h>
92 #endif
94 # include <net/route.h>
95 # include <netinet/in.h>
96 # include <netinet/in_systm.h>
97 # include <netinet/ip.h>
98 # include <netinet/ip6.h>
99 # include <netinet/in_pcb.h>
100 # include <netinet/ip_var.h>
101 # include <netinet/tcp.h>
102 # include <netinet/tcpip.h>
103 # include <netinet/tcp_seq.h>
104 # include <netinet/tcp_var.h>
105 /* #endif HAVE_SYSCTLBYNAME */
107 /* This is for OpenBSD and NetBSD. */
108 #elif HAVE_LIBKVM_NLIST
109 # include <sys/queue.h>
110 # include <net/route.h>
111 # include <netinet/in.h>
112 # include <netinet/in_systm.h>
113 # include <netinet/ip.h>
114 # include <netinet/ip_var.h>
115 # include <netinet/in_pcb.h>
116 # include <netinet/tcp.h>
117 # include <netinet/tcp_timer.h>
118 # include <netinet/tcp_var.h>
119 # include <netdb.h>
120 # include <arpa/inet.h>
121 # if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
122 # include <nlist.h>
123 # else /* HAVE_BSD_NLIST_H */
124 # include <bsd/nlist.h>
125 # endif
126 # include <kvm.h>
127 /* #endif HAVE_LIBKVM_NLIST */
129 #elif KERNEL_AIX
130 # include <arpa/inet.h>
131 # include <sys/socketvar.h>
132 #endif /* KERNEL_AIX */
134 #if KERNEL_LINUX
135 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
136 struct nlreq {
137 struct nlmsghdr nlh;
138 struct inet_diag_req r;
139 };
140 #endif
142 static const char *tcp_state[] =
143 {
144 "", /* 0 */
145 "ESTABLISHED",
146 "SYN_SENT",
147 "SYN_RECV",
148 "FIN_WAIT1",
149 "FIN_WAIT2",
150 "TIME_WAIT",
151 "CLOSED",
152 "CLOSE_WAIT",
153 "LAST_ACK",
154 "LISTEN", /* 10 */
155 "CLOSING"
156 };
158 # define TCP_STATE_LISTEN 10
159 # define TCP_STATE_MIN 1
160 # define TCP_STATE_MAX 11
161 /* #endif KERNEL_LINUX */
163 #elif HAVE_SYSCTLBYNAME
164 static const char *tcp_state[] =
165 {
166 "CLOSED",
167 "LISTEN",
168 "SYN_SENT",
169 "SYN_RECV",
170 "ESTABLISHED",
171 "CLOSE_WAIT",
172 "FIN_WAIT1",
173 "CLOSING",
174 "LAST_ACK",
175 "FIN_WAIT2",
176 "TIME_WAIT"
177 };
179 # define TCP_STATE_LISTEN 1
180 # define TCP_STATE_MIN 0
181 # define TCP_STATE_MAX 10
182 /* #endif HAVE_SYSCTLBYNAME */
184 #elif HAVE_LIBKVM_NLIST
185 static const char *tcp_state[] =
186 {
187 "CLOSED",
188 "LISTEN",
189 "SYN_SENT",
190 "SYN_RECV",
191 "ESTABLISHED",
192 "CLOSE_WAIT",
193 "FIN_WAIT1",
194 "CLOSING",
195 "LAST_ACK",
196 "FIN_WAIT2",
197 "TIME_WAIT"
198 };
200 static kvm_t *kvmd;
201 static u_long inpcbtable_off = 0;
202 struct inpcbtable *inpcbtable_ptr = NULL;
204 # define TCP_STATE_LISTEN 1
205 # define TCP_STATE_MIN 1
206 # define TCP_STATE_MAX 10
207 /* #endif HAVE_LIBKVM_NLIST */
209 #elif KERNEL_AIX
210 static const char *tcp_state[] =
211 {
212 "CLOSED",
213 "LISTEN",
214 "SYN_SENT",
215 "SYN_RECV",
216 "ESTABLISHED",
217 "CLOSE_WAIT",
218 "FIN_WAIT1",
219 "CLOSING",
220 "LAST_ACK",
221 "FIN_WAIT2",
222 "TIME_WAIT"
223 };
225 # define TCP_STATE_LISTEN 1
226 # define TCP_STATE_MIN 0
227 # define TCP_STATE_MAX 10
229 struct netinfo_conn {
230 uint32_t unknow1[2];
231 uint16_t dstport;
232 uint16_t unknow2;
233 struct in6_addr dstaddr;
234 uint16_t srcport;
235 uint16_t unknow3;
236 struct in6_addr srcaddr;
237 uint32_t unknow4[36];
238 uint16_t tcp_state;
239 uint16_t unknow5[7];
240 };
242 struct netinfo_header {
243 unsigned int proto;
244 unsigned int size;
245 };
247 # define NETINFO_TCP 3
248 extern int netinfo (int proto, void *data, int *size, int n);
249 #endif /* KERNEL_AIX */
251 #define PORT_COLLECT_LOCAL 0x01
252 #define PORT_COLLECT_REMOTE 0x02
253 #define PORT_IS_LISTENING 0x04
255 typedef struct port_entry_s
256 {
257 uint16_t port;
258 uint16_t flags;
259 uint32_t count_local[TCP_STATE_MAX + 1];
260 uint32_t count_remote[TCP_STATE_MAX + 1];
261 struct port_entry_s *next;
262 } port_entry_t;
264 static const char *config_keys[] =
265 {
266 "ListeningPorts",
267 "LocalPort",
268 "RemotePort",
269 "AllPortsSummary"
270 };
271 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
273 static int port_collect_listening = 0;
274 static int port_collect_total = 0;
275 static port_entry_t *port_list_head = NULL;
276 static uint32_t count_total[TCP_STATE_MAX + 1];
278 #if KERNEL_LINUX
279 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
280 /* This depends on linux inet_diag_req because if this structure is missing,
281 * sequence_number is useless and we get a compilation warning.
282 */
283 static uint32_t sequence_number = 0;
284 #endif
286 static enum
287 {
288 SRC_DUNNO,
289 SRC_NETLINK,
290 SRC_PROC
291 } linux_source = SRC_DUNNO;
292 #endif
294 static void conn_prepare_vl (value_list_t *vl, value_t *values)
295 {
296 vl->values = values;
297 vl->values_len = 1;
298 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
299 sstrncpy (vl->plugin, "tcpconns", sizeof (vl->plugin));
300 sstrncpy (vl->type, "tcp_connections", sizeof (vl->type));
301 }
303 static void conn_submit_port_entry (port_entry_t *pe)
304 {
305 value_t values[1];
306 value_list_t vl = VALUE_LIST_INIT;
307 int i;
309 conn_prepare_vl (&vl, values);
311 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
312 || (pe->flags & PORT_COLLECT_LOCAL))
313 {
314 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
315 "%"PRIu16"-local", pe->port);
317 for (i = 1; i <= TCP_STATE_MAX; i++)
318 {
319 vl.values[0].gauge = pe->count_local[i];
321 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
323 plugin_dispatch_values (&vl);
324 }
325 }
327 if (pe->flags & PORT_COLLECT_REMOTE)
328 {
329 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
330 "%"PRIu16"-remote", pe->port);
332 for (i = 1; i <= TCP_STATE_MAX; i++)
333 {
334 vl.values[0].gauge = pe->count_remote[i];
336 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
338 plugin_dispatch_values (&vl);
339 }
340 }
341 } /* void conn_submit */
343 static void conn_submit_port_total (void)
344 {
345 value_t values[1];
346 value_list_t vl = VALUE_LIST_INIT;
347 int i;
349 conn_prepare_vl (&vl, values);
351 sstrncpy (vl.plugin_instance, "all", sizeof (vl.plugin_instance));
353 for (i = 1; i <= TCP_STATE_MAX; i++)
354 {
355 vl.values[0].gauge = count_total[i];
357 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
359 plugin_dispatch_values (&vl);
360 }
361 }
363 static void conn_submit_all (void)
364 {
365 port_entry_t *pe;
367 if (port_collect_total)
368 conn_submit_port_total ();
370 for (pe = port_list_head; pe != NULL; pe = pe->next)
371 conn_submit_port_entry (pe);
372 } /* void conn_submit_all */
374 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
375 {
376 port_entry_t *ret;
378 ret = port_list_head;
379 while (ret != NULL)
380 {
381 if (ret->port == port)
382 break;
383 ret = ret->next;
384 }
386 if ((ret == NULL) && (create != 0))
387 {
388 ret = calloc (1, sizeof (*ret));
389 if (ret == NULL)
390 return (NULL);
392 ret->port = port;
393 ret->next = port_list_head;
394 port_list_head = ret;
395 }
397 return (ret);
398 } /* port_entry_t *conn_get_port_entry */
400 /* Removes ports that were added automatically due to the `ListeningPorts'
401 * setting but which are no longer listening. */
402 static void conn_reset_port_entry (void)
403 {
404 port_entry_t *prev = NULL;
405 port_entry_t *pe = port_list_head;
407 memset (&count_total, '\0', sizeof(count_total));
409 while (pe != NULL)
410 {
411 /* If this entry was created while reading the files (ant not when handling
412 * the configuration) remove it now. */
413 if ((pe->flags & (PORT_COLLECT_LOCAL
414 | PORT_COLLECT_REMOTE
415 | PORT_IS_LISTENING)) == 0)
416 {
417 port_entry_t *next = pe->next;
419 DEBUG ("tcpconns plugin: Removing temporary entry "
420 "for listening port %"PRIu16, pe->port);
422 if (prev == NULL)
423 port_list_head = next;
424 else
425 prev->next = next;
427 sfree (pe);
428 pe = next;
430 continue;
431 }
433 memset (pe->count_local, '\0', sizeof (pe->count_local));
434 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
435 pe->flags &= ~PORT_IS_LISTENING;
437 prev = pe;
438 pe = pe->next;
439 }
440 } /* void conn_reset_port_entry */
442 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
443 {
444 port_entry_t *pe = NULL;
446 if ((state > TCP_STATE_MAX)
447 #if TCP_STATE_MIN > 0
448 || (state < TCP_STATE_MIN)
449 #endif
450 )
451 {
452 NOTICE ("tcpconns plugin: Ignoring connection with "
453 "unknown state 0x%02"PRIx8".", state);
454 return (-1);
455 }
457 count_total[state]++;
459 /* Listening sockets */
460 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
461 {
462 pe = conn_get_port_entry (port_local, 1 /* create */);
463 if (pe != NULL)
464 pe->flags |= PORT_IS_LISTENING;
465 }
467 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
468 port_local, port_remote, tcp_state[state]);
470 pe = conn_get_port_entry (port_local, 0 /* no create */);
471 if (pe != NULL)
472 pe->count_local[state]++;
474 pe = conn_get_port_entry (port_remote, 0 /* no create */);
475 if (pe != NULL)
476 pe->count_remote[state]++;
478 return (0);
479 } /* int conn_handle_ports */
481 #if KERNEL_LINUX
482 /* Returns zero on success, less than zero on socket error and greater than
483 * zero on other errors. */
484 static int conn_read_netlink (void)
485 {
486 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
487 int fd;
488 struct sockaddr_nl nladdr;
489 struct nlreq req;
490 struct msghdr msg;
491 struct iovec iov;
492 struct inet_diag_msg *r;
493 char buf[8192];
495 /* If this fails, it's likely a permission problem. We'll fall back to
496 * reading this information from files below. */
497 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
498 if (fd < 0)
499 {
500 ERROR ("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
501 "NETLINK_INET_DIAG) failed: %s",
502 sstrerror (errno, buf, sizeof (buf)));
503 return (-1);
504 }
506 memset(&nladdr, 0, sizeof(nladdr));
507 nladdr.nl_family = AF_NETLINK;
509 memset(&req, 0, sizeof(req));
510 req.nlh.nlmsg_len = sizeof(req);
511 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
512 /* NLM_F_ROOT: return the complete table instead of a single entry.
513 * NLM_F_MATCH: return all entries matching criteria (not implemented)
514 * NLM_F_REQUEST: must be set on all request messages */
515 req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
516 req.nlh.nlmsg_pid = 0;
517 /* The sequence_number is used to track our messages. Since netlink is not
518 * reliable, we don't want to end up with a corrupt or incomplete old
519 * message in case the system is/was out of memory. */
520 req.nlh.nlmsg_seq = ++sequence_number;
521 req.r.idiag_family = AF_INET;
522 req.r.idiag_states = 0xfff;
523 req.r.idiag_ext = 0;
525 memset(&iov, 0, sizeof(iov));
526 iov.iov_base = &req;
527 iov.iov_len = sizeof(req);
529 memset(&msg, 0, sizeof(msg));
530 msg.msg_name = (void*)&nladdr;
531 msg.msg_namelen = sizeof(nladdr);
532 msg.msg_iov = &iov;
533 msg.msg_iovlen = 1;
535 if (sendmsg (fd, &msg, 0) < 0)
536 {
537 ERROR ("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
538 sstrerror (errno, buf, sizeof (buf)));
539 close (fd);
540 return (-1);
541 }
543 iov.iov_base = buf;
544 iov.iov_len = sizeof(buf);
546 while (1)
547 {
548 int status;
549 struct nlmsghdr *h;
551 memset(&msg, 0, sizeof(msg));
552 msg.msg_name = (void*)&nladdr;
553 msg.msg_namelen = sizeof(nladdr);
554 msg.msg_iov = &iov;
555 msg.msg_iovlen = 1;
557 status = recvmsg(fd, (void *) &msg, /* flags = */ 0);
558 if (status < 0)
559 {
560 if ((errno == EINTR) || (errno == EAGAIN))
561 continue;
563 ERROR ("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
564 sstrerror (errno, buf, sizeof (buf)));
565 close (fd);
566 return (-1);
567 }
568 else if (status == 0)
569 {
570 close (fd);
571 DEBUG ("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
572 "reply from netlink socket.");
573 return (0);
574 }
576 h = (struct nlmsghdr*)buf;
577 while (NLMSG_OK(h, status))
578 {
579 if (h->nlmsg_seq != sequence_number)
580 {
581 h = NLMSG_NEXT(h, status);
582 continue;
583 }
585 if (h->nlmsg_type == NLMSG_DONE)
586 {
587 close (fd);
588 return (0);
589 }
590 else if (h->nlmsg_type == NLMSG_ERROR)
591 {
592 struct nlmsgerr *msg_error;
594 msg_error = NLMSG_DATA(h);
595 WARNING ("tcpconns plugin: conn_read_netlink: Received error %i.",
596 msg_error->error);
598 close (fd);
599 return (1);
600 }
602 r = NLMSG_DATA(h);
604 /* This code does not (need to) distinguish between IPv4 and IPv6. */
605 conn_handle_ports (ntohs(r->id.idiag_sport),
606 ntohs(r->id.idiag_dport),
607 r->idiag_state);
609 h = NLMSG_NEXT(h, status);
610 } /* while (NLMSG_OK) */
611 } /* while (1) */
613 /* Not reached because the while() loop above handles the exit condition. */
614 return (0);
615 #else
616 return (1);
617 #endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
618 } /* int conn_read_netlink */
620 static int conn_handle_line (char *buffer)
621 {
622 char *fields[32];
623 int fields_len;
625 char *endptr;
627 char *port_local_str;
628 char *port_remote_str;
629 uint16_t port_local;
630 uint16_t port_remote;
632 uint8_t state;
634 int buffer_len = strlen (buffer);
636 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
637 buffer[--buffer_len] = '\0';
638 if (buffer_len <= 0)
639 return (-1);
641 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
642 if (fields_len < 12)
643 {
644 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
645 return (-1);
646 }
648 port_local_str = strchr (fields[1], ':');
649 port_remote_str = strchr (fields[2], ':');
651 if ((port_local_str == NULL) || (port_remote_str == NULL))
652 return (-1);
653 port_local_str++;
654 port_remote_str++;
655 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
656 return (-1);
658 endptr = NULL;
659 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
660 if ((endptr == NULL) || (*endptr != '\0'))
661 return (-1);
663 endptr = NULL;
664 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
665 if ((endptr == NULL) || (*endptr != '\0'))
666 return (-1);
668 endptr = NULL;
669 state = (uint8_t) strtol (fields[3], &endptr, 16);
670 if ((endptr == NULL) || (*endptr != '\0'))
671 return (-1);
673 return (conn_handle_ports (port_local, port_remote, state));
674 } /* int conn_handle_line */
676 static int conn_read_file (const char *file)
677 {
678 FILE *fh;
679 char buffer[1024];
681 fh = fopen (file, "r");
682 if (fh == NULL)
683 return (-1);
685 while (fgets (buffer, sizeof (buffer), fh) != NULL)
686 {
687 conn_handle_line (buffer);
688 } /* while (fgets) */
690 fclose (fh);
692 return (0);
693 } /* int conn_read_file */
694 /* #endif KERNEL_LINUX */
696 #elif HAVE_SYSCTLBYNAME
697 /* #endif HAVE_SYSCTLBYNAME */
699 #elif HAVE_LIBKVM_NLIST
700 #endif /* HAVE_LIBKVM_NLIST */
702 static int conn_config (const char *key, const char *value)
703 {
704 if (strcasecmp (key, "ListeningPorts") == 0)
705 {
706 if (IS_TRUE (value))
707 port_collect_listening = 1;
708 else
709 port_collect_listening = 0;
710 }
711 else if ((strcasecmp (key, "LocalPort") == 0)
712 || (strcasecmp (key, "RemotePort") == 0))
713 {
714 port_entry_t *pe;
715 int port = atoi (value);
717 if ((port < 1) || (port > 65535))
718 {
719 ERROR ("tcpconns plugin: Invalid port: %i", port);
720 return (1);
721 }
723 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
724 if (pe == NULL)
725 {
726 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
727 return (1);
728 }
730 if (strcasecmp (key, "LocalPort") == 0)
731 pe->flags |= PORT_COLLECT_LOCAL;
732 else
733 pe->flags |= PORT_COLLECT_REMOTE;
734 }
735 else if (strcasecmp (key, "AllPortsSummary") == 0)
736 {
737 if (IS_TRUE (value))
738 port_collect_total = 1;
739 else
740 port_collect_total = 0;
741 }
742 else
743 {
744 return (-1);
745 }
747 return (0);
748 } /* int conn_config */
750 #if KERNEL_LINUX
751 static int conn_init (void)
752 {
753 if (port_collect_total == 0 && port_list_head == NULL)
754 port_collect_listening = 1;
756 return (0);
757 } /* int conn_init */
759 static int conn_read (void)
760 {
761 int status;
763 conn_reset_port_entry ();
765 if (linux_source == SRC_NETLINK)
766 {
767 status = conn_read_netlink ();
768 }
769 else if (linux_source == SRC_PROC)
770 {
771 int errors_num = 0;
773 if (conn_read_file ("/proc/net/tcp") != 0)
774 errors_num++;
775 if (conn_read_file ("/proc/net/tcp6") != 0)
776 errors_num++;
778 if (errors_num < 2)
779 status = 0;
780 else
781 status = ENOENT;
782 }
783 else /* if (linux_source == SRC_DUNNO) */
784 {
785 /* Try to use netlink for getting this data, it is _much_ faster on systems
786 * with a large amount of connections. */
787 status = conn_read_netlink ();
788 if (status == 0)
789 {
790 INFO ("tcpconns plugin: Reading from netlink succeeded. "
791 "Will use the netlink method from now on.");
792 linux_source = SRC_NETLINK;
793 }
794 else
795 {
796 INFO ("tcpconns plugin: Reading from netlink failed. "
797 "Will read from /proc from now on.");
798 linux_source = SRC_PROC;
800 /* return success here to avoid the "plugin failed" message. */
801 return (0);
802 }
803 }
805 if (status == 0)
806 conn_submit_all ();
807 else
808 return (status);
810 return (0);
811 } /* int conn_read */
812 /* #endif KERNEL_LINUX */
814 #elif HAVE_SYSCTLBYNAME
815 static int conn_read (void)
816 {
817 int status;
818 char *buffer;
819 size_t buffer_len;;
821 struct xinpgen *in_orig;
822 struct xinpgen *in_ptr;
824 conn_reset_port_entry ();
826 buffer_len = 0;
827 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
828 if (status < 0)
829 {
830 ERROR ("tcpconns plugin: sysctlbyname failed.");
831 return (-1);
832 }
834 buffer = malloc (buffer_len);
835 if (buffer == NULL)
836 {
837 ERROR ("tcpconns plugin: malloc failed.");
838 return (-1);
839 }
841 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
842 if (status < 0)
843 {
844 ERROR ("tcpconns plugin: sysctlbyname failed.");
845 sfree (buffer);
846 return (-1);
847 }
849 if (buffer_len <= sizeof (struct xinpgen))
850 {
851 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
852 sfree (buffer);
853 return (-1);
854 }
856 in_orig = (struct xinpgen *) buffer;
857 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
858 in_ptr->xig_len > sizeof (struct xinpgen);
859 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
860 {
861 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
862 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
863 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
865 /* Ignore non-TCP sockets */
866 if (so->xso_protocol != IPPROTO_TCP)
867 continue;
869 /* Ignore PCBs which were freed during copyout. */
870 if (inp->inp_gencnt > in_orig->xig_gen)
871 continue;
873 if (((inp->inp_vflag & INP_IPV4) == 0)
874 && ((inp->inp_vflag & INP_IPV6) == 0))
875 continue;
877 conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
878 tp->t_state);
879 } /* for (in_ptr) */
881 in_orig = NULL;
882 in_ptr = NULL;
883 sfree (buffer);
885 conn_submit_all ();
887 return (0);
888 } /* int conn_read */
889 /* #endif HAVE_SYSCTLBYNAME */
891 #elif HAVE_LIBKVM_NLIST
892 static int kread (u_long addr, void *buf, int size)
893 {
894 int status;
896 status = kvm_read (kvmd, addr, buf, size);
897 if (status != size)
898 {
899 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
900 status, size, kvm_geterr (kvmd));
901 return (-1);
902 }
903 return (0);
904 } /* int kread */
906 static int conn_init (void)
907 {
908 char buf[_POSIX2_LINE_MAX];
909 struct nlist nl[] =
910 {
911 #define N_TCBTABLE 0
912 { "_tcbtable" },
913 { "" }
914 };
915 int status;
917 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
918 if (kvmd == NULL)
919 {
920 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
921 return (-1);
922 }
924 status = kvm_nlist (kvmd, nl);
925 if (status < 0)
926 {
927 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
928 return (-1);
929 }
931 if (nl[N_TCBTABLE].n_type == 0)
932 {
933 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
934 "N_TCBTABLE is invalid.");
935 return (-1);
936 }
938 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
939 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
941 return (0);
942 } /* int conn_init */
944 static int conn_read (void)
945 {
946 struct inpcbtable table;
947 #if !defined(__OpenBSD__) && (defined(__NetBSD_Version__) && __NetBSD_Version__ <= 699002700)
948 struct inpcb *head;
949 #endif
950 struct inpcb *next;
951 struct inpcb inpcb;
952 struct tcpcb tcpcb;
953 int status;
955 conn_reset_port_entry ();
957 /* Read the pcbtable from the kernel */
958 status = kread (inpcbtable_off, &table, sizeof (table));
959 if (status != 0)
960 return (-1);
962 #if defined(__OpenBSD__) || (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
963 /* inpt_queue is a TAILQ on OpenBSD */
964 /* Get the first pcb */
965 next = (struct inpcb *)TAILQ_FIRST (&table.inpt_queue);
966 while (next)
967 #else
968 /* Get the `head' pcb */
969 head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
970 /* Get the first pcb */
971 next = (struct inpcb *)CIRCLEQ_FIRST (&table.inpt_queue);
973 while (next != head)
974 #endif
975 {
976 /* Read the pcb pointed to by `next' into `inpcb' */
977 status = kread ((u_long) next, &inpcb, sizeof (inpcb));
978 if (status != 0)
979 return (-1);
981 /* Advance `next' */
982 #if defined(__OpenBSD__) || (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
983 /* inpt_queue is a TAILQ on OpenBSD */
984 next = (struct inpcb *)TAILQ_NEXT (&inpcb, inp_queue);
985 #else
986 next = (struct inpcb *)CIRCLEQ_NEXT (&inpcb, inp_queue);
987 #endif
989 /* Ignore sockets, that are not connected. */
990 #ifdef __NetBSD__
991 if (inpcb.inp_af == AF_INET6)
992 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
993 #else
994 if (!(inpcb.inp_flags & INP_IPV6)
995 && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
996 continue;
997 if ((inpcb.inp_flags & INP_IPV6)
998 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
999 continue;
1000 #endif
1002 status = kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
1003 if (status != 0)
1004 return (-1);
1005 conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
1006 } /* while (next != head) */
1008 conn_submit_all ();
1010 return (0);
1011 }
1012 /* #endif HAVE_LIBKVM_NLIST */
1014 #elif KERNEL_AIX
1016 static int conn_read (void)
1017 {
1018 int size;
1019 int i;
1020 int nconn;
1021 void *data;
1022 struct netinfo_header *header;
1023 struct netinfo_conn *conn;
1025 conn_reset_port_entry ();
1027 size = netinfo(NETINFO_TCP, 0, 0, 0);
1028 if (size < 0)
1029 {
1030 ERROR ("tcpconns plugin: netinfo failed return: %i", size);
1031 return (-1);
1032 }
1034 if (size == 0)
1035 return (0);
1037 if ((size - sizeof (struct netinfo_header)) % sizeof (struct netinfo_conn))
1038 {
1039 ERROR ("tcpconns plugin: invalid buffer size");
1040 return (-1);
1041 }
1043 data = malloc(size);
1044 if (data == NULL)
1045 {
1046 ERROR ("tcpconns plugin: malloc failed");
1047 return (-1);
1048 }
1050 if (netinfo(NETINFO_TCP, data, &size, 0) < 0)
1051 {
1052 ERROR ("tcpconns plugin: netinfo failed");
1053 free(data);
1054 return (-1);
1055 }
1057 header = (struct netinfo_header *)data;
1058 nconn = header->size;
1059 conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1061 for (i=0; i < nconn; conn++, i++)
1062 {
1063 conn_handle_ports (conn->srcport, conn->dstport, conn->tcp_state);
1064 }
1066 free(data);
1068 conn_submit_all ();
1070 return (0);
1071 }
1072 #endif /* KERNEL_AIX */
1074 void module_register (void)
1075 {
1076 plugin_register_config ("tcpconns", conn_config,
1077 config_keys, config_keys_num);
1078 #if KERNEL_LINUX
1079 plugin_register_init ("tcpconns", conn_init);
1080 #elif HAVE_SYSCTLBYNAME
1081 /* no initialization */
1082 #elif HAVE_LIBKVM_NLIST
1083 plugin_register_init ("tcpconns", conn_init);
1084 #elif KERNEL_AIX
1085 /* no initialization */
1086 #endif
1087 plugin_register_read ("tcpconns", conn_read);
1088 } /* void module_register */
1090 /*
1091 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :
1092 */