2 * collectd - src/tcpconns.c
3 * Copyright (C) 2007,2008 Florian octo Forster
4 * Copyright (C) 2008 Michael Stapelberg
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.
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.
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
20 * Florian octo Forster <octo at verplant.org>
21 * Michael Stapelberg <michael+git at stapelberg.de>
25 * Code within `HAVE_LIBKVM_NLIST' blocks is provided under the following
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 $
32 * Copyright (c) 1983, 1988, 1993
33 * The Regents of the University of California. All rights reserved.
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
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.
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
64 #if defined(__OpenBSD__) || defined(__NetBSD__)
65 #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */
68 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST && !KERNEL_AIX
69 # error "No applicable input method."
73 /* #endif KERNEL_LINUX */
75 #elif HAVE_SYSCTLBYNAME
76 # include <sys/socketvar.h>
77 # include <sys/sysctl.h>
79 /* Some includes needed for compiling on FreeBSD */
82 # include <sys/types.h>
85 # include <sys/socket.h>
91 # include <net/route.h>
92 # include <netinet/in.h>
93 # include <netinet/in_systm.h>
94 # include <netinet/ip.h>
95 # include <netinet/ip6.h>
96 # include <netinet/in_pcb.h>
97 # include <netinet/ip_var.h>
98 # include <netinet/tcp.h>
99 # include <netinet/tcpip.h>
100 # include <netinet/tcp_seq.h>
101 # include <netinet/tcp_var.h>
102 /* #endif HAVE_SYSCTLBYNAME */
104 /* This is for OpenBSD and NetBSD. */
105 #elif HAVE_LIBKVM_NLIST
106 # include <sys/queue.h>
107 # include <sys/socket.h>
108 # include <net/route.h>
109 # include <netinet/in.h>
110 # include <netinet/in_systm.h>
111 # include <netinet/ip.h>
112 # include <netinet/ip_var.h>
113 # include <netinet/in_pcb.h>
114 # include <netinet/tcp.h>
115 # include <netinet/tcp_timer.h>
116 # include <netinet/tcp_var.h>
118 # include <arpa/inet.h>
121 /* #endif HAVE_LIBKVM_NLIST */
124 # include <arpa/inet.h>
125 # include <sys/socketvar.h>
126 #endif /* KERNEL_AIX */
129 static const char *tcp_state[] =
145 # define TCP_STATE_LISTEN 10
146 # define TCP_STATE_MIN 1
147 # define TCP_STATE_MAX 11
148 /* #endif KERNEL_LINUX */
150 #elif HAVE_SYSCTLBYNAME
151 static const char *tcp_state[] =
166 # define TCP_STATE_LISTEN 1
167 # define TCP_STATE_MIN 0
168 # define TCP_STATE_MAX 10
169 /* #endif HAVE_SYSCTLBYNAME */
171 #elif HAVE_LIBKVM_NLIST
172 static const char *tcp_state[] =
188 static u_long inpcbtable_off = 0;
189 struct inpcbtable *inpcbtable_ptr = NULL;
191 # define TCP_STATE_LISTEN 1
192 # define TCP_STATE_MIN 1
193 # define TCP_STATE_MAX 10
194 /* #endif HAVE_LIBKVM_NLIST */
197 static const char *tcp_state[] =
212 # define TCP_STATE_LISTEN 1
213 # define TCP_STATE_MIN 0
214 # define TCP_STATE_MAX 10
216 struct netinfo_conn {
220 struct in6_addr dstaddr;
223 struct in6_addr srcaddr;
224 uint32_t unknow4[36];
229 struct netinfo_header {
234 # define NETINFO_TCP 3
235 extern int netinfo (int proto, void *data, int *size, int n);
236 #endif /* KERNEL_AIX */
238 #define PORT_COLLECT_LOCAL 0x01
239 #define PORT_COLLECT_REMOTE 0x02
240 #define PORT_IS_LISTENING 0x04
242 typedef struct port_entry_s
246 uint32_t count_local[TCP_STATE_MAX + 1];
247 uint32_t count_remote[TCP_STATE_MAX + 1];
248 struct port_entry_s *next;
251 static const char *config_keys[] =
257 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
259 static int port_collect_listening = 0;
260 static port_entry_t *port_list_head = NULL;
262 static void conn_submit_port_entry (port_entry_t *pe)
265 value_list_t vl = VALUE_LIST_INIT;
270 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
271 sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
272 sstrncpy (vl.type, "tcp_connections", sizeof (vl.type));
274 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
275 || (pe->flags & PORT_COLLECT_LOCAL))
277 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
278 "%"PRIu16"-local", pe->port);
280 for (i = 1; i <= TCP_STATE_MAX; i++)
282 vl.values[0].gauge = pe->count_local[i];
284 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
286 plugin_dispatch_values (&vl);
290 if (pe->flags & PORT_COLLECT_REMOTE)
292 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
293 "%"PRIu16"-remote", pe->port);
295 for (i = 1; i <= TCP_STATE_MAX; i++)
297 vl.values[0].gauge = pe->count_remote[i];
299 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
301 plugin_dispatch_values (&vl);
304 } /* void conn_submit */
306 static void conn_submit_all (void)
310 for (pe = port_list_head; pe != NULL; pe = pe->next)
311 conn_submit_port_entry (pe);
312 } /* void conn_submit_all */
314 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
318 ret = port_list_head;
321 if (ret->port == port)
326 if ((ret == NULL) && (create != 0))
328 ret = (port_entry_t *) malloc (sizeof (port_entry_t));
331 memset (ret, '\0', sizeof (port_entry_t));
334 ret->next = port_list_head;
335 port_list_head = ret;
339 } /* port_entry_t *conn_get_port_entry */
341 /* Removes ports that were added automatically due to the `ListeningPorts'
342 * setting but which are no longer listening. */
343 static void conn_reset_port_entry (void)
345 port_entry_t *prev = NULL;
346 port_entry_t *pe = port_list_head;
350 /* If this entry was created while reading the files (ant not when handling
351 * the configuration) remove it now. */
352 if ((pe->flags & (PORT_COLLECT_LOCAL
353 | PORT_COLLECT_REMOTE
354 | PORT_IS_LISTENING)) == 0)
356 port_entry_t *next = pe->next;
358 DEBUG ("tcpconns plugin: Removing temporary entry "
359 "for listening port %"PRIu16, pe->port);
362 port_list_head = next;
372 memset (pe->count_local, '\0', sizeof (pe->count_local));
373 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
374 pe->flags &= ~PORT_IS_LISTENING;
378 } /* void conn_reset_port_entry */
380 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
382 port_entry_t *pe = NULL;
384 if ((state > TCP_STATE_MAX)
385 #if TCP_STATE_MIN > 0
386 || (state < TCP_STATE_MIN)
390 NOTICE ("tcpconns plugin: Ignoring connection with "
391 "unknown state 0x%02"PRIx8".", state);
395 /* Listening sockets */
396 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
398 pe = conn_get_port_entry (port_local, 1 /* create */);
400 pe->flags |= PORT_IS_LISTENING;
403 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
404 port_local, port_remote, tcp_state[state]);
406 pe = conn_get_port_entry (port_local, 0 /* no create */);
408 pe->count_local[state]++;
410 pe = conn_get_port_entry (port_remote, 0 /* no create */);
412 pe->count_remote[state]++;
415 } /* int conn_handle_ports */
418 static int conn_handle_line (char *buffer)
425 char *port_local_str;
426 char *port_remote_str;
428 uint16_t port_remote;
432 int buffer_len = strlen (buffer);
434 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
435 buffer[--buffer_len] = '\0';
439 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
442 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
446 port_local_str = strchr (fields[1], ':');
447 port_remote_str = strchr (fields[2], ':');
449 if ((port_local_str == NULL) || (port_remote_str == NULL))
453 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
457 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
458 if ((endptr == NULL) || (*endptr != '\0'))
462 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
463 if ((endptr == NULL) || (*endptr != '\0'))
467 state = (uint8_t) strtol (fields[3], &endptr, 16);
468 if ((endptr == NULL) || (*endptr != '\0'))
471 return (conn_handle_ports (port_local, port_remote, state));
472 } /* int conn_handle_line */
474 static int conn_read_file (const char *file)
479 fh = fopen (file, "r");
483 while (fgets (buffer, sizeof (buffer), fh) != NULL)
485 conn_handle_line (buffer);
486 } /* while (fgets) */
491 } /* int conn_read_file */
492 /* #endif KERNEL_LINUX */
494 #elif HAVE_SYSCTLBYNAME
495 /* #endif HAVE_SYSCTLBYNAME */
497 #elif HAVE_LIBKVM_NLIST
498 #endif /* HAVE_LIBKVM_NLIST */
500 static int conn_config (const char *key, const char *value)
502 if (strcasecmp (key, "ListeningPorts") == 0)
505 port_collect_listening = 1;
507 port_collect_listening = 0;
509 else if ((strcasecmp (key, "LocalPort") == 0)
510 || (strcasecmp (key, "RemotePort") == 0))
513 int port = atoi (value);
515 if ((port < 1) || (port > 65535))
517 ERROR ("tcpconns plugin: Invalid port: %i", port);
521 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
524 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
528 if (strcasecmp (key, "LocalPort") == 0)
529 pe->flags |= PORT_COLLECT_LOCAL;
531 pe->flags |= PORT_COLLECT_REMOTE;
539 } /* int conn_config */
542 static int conn_init (void)
544 if (port_list_head == NULL)
545 port_collect_listening = 1;
548 } /* int conn_init */
550 static int conn_read (void)
554 conn_reset_port_entry ();
556 if (conn_read_file ("/proc/net/tcp") != 0)
558 if (conn_read_file ("/proc/net/tcp6") != 0)
567 ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
573 } /* int conn_read */
574 /* #endif KERNEL_LINUX */
576 #elif HAVE_SYSCTLBYNAME
577 static int conn_read (void)
583 struct xinpgen *in_orig;
584 struct xinpgen *in_ptr;
586 conn_reset_port_entry ();
589 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
592 ERROR ("tcpconns plugin: sysctlbyname failed.");
596 buffer = (char *) malloc (buffer_len);
599 ERROR ("tcpconns plugin: malloc failed.");
603 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
606 ERROR ("tcpconns plugin: sysctlbyname failed.");
611 if (buffer_len <= sizeof (struct xinpgen))
613 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
618 in_orig = (struct xinpgen *) buffer;
619 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
620 in_ptr->xig_len > sizeof (struct xinpgen);
621 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
623 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
624 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
625 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
627 /* Ignore non-TCP sockets */
628 if (so->xso_protocol != IPPROTO_TCP)
631 /* Ignore PCBs which were freed during copyout. */
632 if (inp->inp_gencnt > in_orig->xig_gen)
635 if (((inp->inp_vflag & INP_IPV4) == 0)
636 && ((inp->inp_vflag & INP_IPV6) == 0))
639 conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
650 } /* int conn_read */
651 /* #endif HAVE_SYSCTLBYNAME */
653 #elif HAVE_LIBKVM_NLIST
654 static int kread (u_long addr, void *buf, int size)
658 status = kvm_read (kvmd, addr, buf, size);
661 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
662 status, size, kvm_geterr (kvmd));
668 static int conn_init (void)
670 char buf[_POSIX2_LINE_MAX];
679 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
682 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
686 status = kvm_nlist (kvmd, nl);
689 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
693 if (nl[N_TCBTABLE].n_type == 0)
695 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
696 "N_TCBTABLE is invalid.");
700 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
701 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
704 } /* int conn_init */
706 static int conn_read (void)
708 struct inpcbtable table;
715 conn_reset_port_entry ();
717 /* Read the pcbtable from the kernel */
718 status = kread (inpcbtable_off, &table, sizeof (table));
722 /* Get the `head' pcb */
723 head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
724 /* Get the first pcb */
725 next = (struct inpcb *)CIRCLEQ_FIRST (&table.inpt_queue);
729 /* Read the pcb pointed to by `next' into `inpcb' */
730 kread ((u_long) next, &inpcb, sizeof (inpcb));
733 next = (struct inpcb *)CIRCLEQ_NEXT (&inpcb, inp_queue);
735 /* Ignore sockets, that are not connected. */
737 if (inpcb.inp_af == AF_INET6)
738 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
740 if (!(inpcb.inp_flags & INP_IPV6)
741 && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
743 if ((inpcb.inp_flags & INP_IPV6)
744 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
748 kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
749 conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
750 } /* while (next != head) */
756 /* #endif HAVE_LIBKVM_NLIST */
760 static int conn_read (void)
766 struct netinfo_header *header;
767 struct netinfo_conn *conn;
769 conn_reset_port_entry ();
771 size = netinfo(NETINFO_TCP, 0, 0, 0);
774 ERROR ("tcpconns plugin: netinfo failed return: %i", size);
781 if ((size - sizeof (struct netinfo_header)) % sizeof (struct netinfo_conn))
783 ERROR ("tcpconns plugin: invalid buffer size");
790 ERROR ("tcpconns plugin: malloc failed");
794 if (netinfo(NETINFO_TCP, data, &size, 0) < 0)
796 ERROR ("tcpconns plugin: netinfo failed");
801 header = (struct netinfo_header *)data;
802 nconn = header->size;
803 conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
805 for (i=0; i < nconn; conn++, i++)
807 conn_handle_ports (conn->srcport, conn->dstport, conn->tcp_state);
816 #endif /* KERNEL_AIX */
818 void module_register (void)
820 plugin_register_config ("tcpconns", conn_config,
821 config_keys, config_keys_num);
823 plugin_register_init ("tcpconns", conn_init);
824 #elif HAVE_SYSCTLBYNAME
825 /* no initialization */
826 #elif HAVE_LIBKVM_NLIST
827 plugin_register_init ("tcpconns", conn_init);
829 /* no initialization */
831 plugin_register_read ("tcpconns", conn_read);
832 } /* void module_register */
835 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :