2 * collectd - src/tcpconns.c
3 * Copyright (C) 2007 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
23 * Code within `HAVE_LIBKVM_NLIST' blocks is provided under the following
26 * $collectd: parts of tcpconns.c, 2008/08/08 03:48:30 Michael Stapelberg $
27 * $OpenBSD: inet.c,v 1.100 2007/06/19 05:28:30 ray Exp $
28 * $NetBSD: inet.c,v 1.14 1995/10/03 21:42:37 thorpej Exp $
30 * Copyright (c) 1983, 1988, 1993
31 * The Regents of the University of California. All rights reserved.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. Neither the name of the University nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
45 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST
63 # error "No applicable input method."
67 /* #endif KERNEL_LINUX */
69 #elif HAVE_SYSCTLBYNAME
70 # include <sys/socketvar.h>
71 # include <sys/sysctl.h>
73 /* Some includes needed for compiling on FreeBSD */
76 # include <sys/types.h>
79 # include <sys/socket.h>
85 # include <net/route.h>
86 # include <netinet/in.h>
87 # include <netinet/in_systm.h>
88 # include <netinet/ip.h>
89 # include <netinet/ip6.h>
90 # include <netinet/in_pcb.h>
91 # include <netinet/ip_var.h>
92 # include <netinet/tcp.h>
93 # include <netinet/tcpip.h>
94 # include <netinet/tcp_seq.h>
95 # include <netinet/tcp_var.h>
96 /* #endif HAVE_SYSCTLBYNAME */
98 /* This is for OpenBSD and possibly NetBSD. */
99 #elif HAVE_LIBKVM_NLIST
100 # include <sys/queue.h>
101 # include <sys/socket.h>
102 # include <net/route.h>
103 # include <netinet/in.h>
104 # include <netinet/in_systm.h>
105 # include <netinet/ip.h>
106 # include <netinet/in_pcb.h>
107 # include <netinet/tcp.h>
108 # include <netinet/tcp_timer.h>
109 # include <netinet/tcp_var.h>
111 # include <arpa/inet.h>
114 #endif /* HAVE_LIBKVM_NLIST */
117 static const char *tcp_state[] =
133 # define TCP_STATE_LISTEN 10
134 # define TCP_STATE_MIN 1
135 # define TCP_STATE_MAX 11
136 /* #endif KERNEL_LINUX */
138 #elif HAVE_SYSCTLBYNAME
139 static const char *tcp_state[] =
154 # define TCP_STATE_LISTEN 1
155 # define TCP_STATE_MIN 0
156 # define TCP_STATE_MAX 10
157 /* #endif HAVE_SYSCTLBYNAME */
159 #elif HAVE_LIBKVM_NLIST
160 static const char *tcp_state[] =
176 static u_long inpcbtable_off = 0;
177 struct inpcbtable *inpcbtable_ptr = NULL;
179 # define TCP_STATE_LISTEN 1
180 # define TCP_STATE_MIN 1
181 # define TCP_STATE_MAX 10
182 #endif /* HAVE_LIBKVM_NLIST */
184 #define PORT_COLLECT_LOCAL 0x01
185 #define PORT_COLLECT_REMOTE 0x02
186 #define PORT_IS_LISTENING 0x04
188 typedef struct port_entry_s
192 uint32_t count_local[TCP_STATE_MAX + 1];
193 uint32_t count_remote[TCP_STATE_MAX + 1];
194 struct port_entry_s *next;
197 static const char *config_keys[] =
203 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
205 static int port_collect_listening = 0;
206 static port_entry_t *port_list_head = NULL;
208 static void conn_submit_port_entry (port_entry_t *pe)
211 value_list_t vl = VALUE_LIST_INIT;
216 vl.time = time (NULL);
217 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
218 sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
219 sstrncpy (vl.type, "tcp_connections", sizeof (vl.type));
221 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
222 || (pe->flags & PORT_COLLECT_LOCAL))
224 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
225 "%"PRIu16"-local", pe->port);
227 for (i = 1; i <= TCP_STATE_MAX; i++)
229 vl.values[0].gauge = pe->count_local[i];
231 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
233 plugin_dispatch_values (&vl);
237 if (pe->flags & PORT_COLLECT_REMOTE)
239 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
240 "%"PRIu16"-remote", pe->port);
242 for (i = 1; i <= TCP_STATE_MAX; i++)
244 vl.values[0].gauge = pe->count_remote[i];
246 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
248 plugin_dispatch_values (&vl);
251 } /* void conn_submit */
253 static void conn_submit_all (void)
257 for (pe = port_list_head; pe != NULL; pe = pe->next)
258 conn_submit_port_entry (pe);
259 } /* void conn_submit_all */
261 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
265 ret = port_list_head;
268 if (ret->port == port)
273 if ((ret == NULL) && (create != 0))
275 ret = (port_entry_t *) malloc (sizeof (port_entry_t));
278 memset (ret, '\0', sizeof (port_entry_t));
281 ret->next = port_list_head;
282 port_list_head = ret;
286 } /* port_entry_t *conn_get_port_entry */
288 /* Removes ports that were added automatically due to the `ListeningPorts'
289 * setting but which are no longer listening. */
290 static void conn_reset_port_entry (void)
292 port_entry_t *prev = NULL;
293 port_entry_t *pe = port_list_head;
297 /* If this entry was created while reading the files (ant not when handling
298 * the configuration) remove it now. */
299 if ((pe->flags & (PORT_COLLECT_LOCAL
300 | PORT_COLLECT_REMOTE
301 | PORT_IS_LISTENING)) == 0)
303 port_entry_t *next = pe->next;
305 DEBUG ("tcpconns plugin: Removing temporary entry "
306 "for listening port %"PRIu16, pe->port);
309 port_list_head = next;
319 memset (pe->count_local, '\0', sizeof (pe->count_local));
320 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
321 pe->flags &= ~PORT_IS_LISTENING;
325 } /* void conn_reset_port_entry */
327 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
329 port_entry_t *pe = NULL;
331 if ((state > TCP_STATE_MAX)
332 #if TCP_STATE_MIN > 0
333 || (state < TCP_STATE_MIN)
337 NOTICE ("tcpconns plugin: Ignoring connection with "
338 "unknown state 0x%02"PRIx8".", state);
342 /* Listening sockets */
343 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
345 pe = conn_get_port_entry (port_local, 1 /* create */);
347 pe->flags |= PORT_IS_LISTENING;
350 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
351 port_local, port_remote, tcp_state[state]);
353 pe = conn_get_port_entry (port_local, 0 /* no create */);
355 pe->count_local[state]++;
357 pe = conn_get_port_entry (port_remote, 0 /* no create */);
359 pe->count_remote[state]++;
362 } /* int conn_handle_ports */
365 static int conn_handle_line (char *buffer)
372 char *port_local_str;
373 char *port_remote_str;
375 uint16_t port_remote;
379 int buffer_len = strlen (buffer);
381 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
382 buffer[--buffer_len] = '\0';
386 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
389 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
393 port_local_str = strchr (fields[1], ':');
394 port_remote_str = strchr (fields[2], ':');
396 if ((port_local_str == NULL) || (port_remote_str == NULL))
400 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
404 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
405 if ((endptr == NULL) || (*endptr != '\0'))
409 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
410 if ((endptr == NULL) || (*endptr != '\0'))
414 state = (uint8_t) strtol (fields[3], &endptr, 16);
415 if ((endptr == NULL) || (*endptr != '\0'))
418 return (conn_handle_ports (port_local, port_remote, state));
419 } /* int conn_handle_line */
421 static int conn_read_file (const char *file)
426 fh = fopen (file, "r");
430 while (fgets (buffer, sizeof (buffer), fh) != NULL)
432 conn_handle_line (buffer);
433 } /* while (fgets) */
438 } /* int conn_read_file */
439 /* #endif KERNEL_LINUX */
441 #elif HAVE_SYSCTLBYNAME
442 /* #endif HAVE_SYSCTLBYNAME */
444 #elif HAVE_LIBKVM_NLIST
445 #endif /* HAVE_LIBKVM_NLIST */
447 static int conn_config (const char *key, const char *value)
449 if (strcasecmp (key, "ListeningPorts") == 0)
451 if ((strcasecmp (value, "Yes") == 0)
452 || (strcasecmp (value, "True") == 0)
453 || (strcasecmp (value, "On") == 0))
454 port_collect_listening = 1;
456 port_collect_listening = 0;
458 else if ((strcasecmp (key, "LocalPort") == 0)
459 || (strcasecmp (key, "RemotePort") == 0))
462 int port = atoi (value);
464 if ((port < 1) || (port > 65535))
466 ERROR ("tcpconns plugin: Invalid port: %i", port);
470 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
473 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
477 if (strcasecmp (key, "LocalPort") == 0)
478 pe->flags |= PORT_COLLECT_LOCAL;
480 pe->flags |= PORT_COLLECT_REMOTE;
488 } /* int conn_config */
491 static int conn_init (void)
493 if (port_list_head == NULL)
494 port_collect_listening = 1;
497 } /* int conn_init */
499 static int conn_read (void)
503 conn_reset_port_entry ();
505 if (conn_read_file ("/proc/net/tcp") != 0)
507 if (conn_read_file ("/proc/net/tcp6") != 0)
516 ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
522 } /* int conn_read */
523 /* #endif KERNEL_LINUX */
525 #elif HAVE_SYSCTLBYNAME
526 static int conn_read (void)
532 struct xinpgen *in_orig;
533 struct xinpgen *in_ptr;
535 conn_reset_port_entry ();
538 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
541 ERROR ("tcpconns plugin: sysctlbyname failed.");
545 buffer = (char *) malloc (buffer_len);
548 ERROR ("tcpconns plugin: malloc failed.");
552 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
555 ERROR ("tcpconns plugin: sysctlbyname failed.");
560 if (buffer_len <= sizeof (struct xinpgen))
562 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
567 in_orig = (struct xinpgen *) buffer;
568 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
569 in_ptr->xig_len > sizeof (struct xinpgen);
570 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
572 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
573 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
574 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
576 /* Ignore non-TCP sockets */
577 if (so->xso_protocol != IPPROTO_TCP)
580 /* Ignore PCBs which were freed during copyout. */
581 if (inp->inp_gencnt > in_orig->xig_gen)
584 if (((inp->inp_vflag & INP_IPV4) == 0)
585 && ((inp->inp_vflag & INP_IPV6) == 0))
588 conn_handle_ports (inp->inp_lport, inp->inp_fport, tp->t_state);
598 } /* int conn_read */
599 /* #endif HAVE_SYSCTLBYNAME */
601 #elif HAVE_LIBKVM_NLIST
602 static int kread (u_long addr, void *buf, int size)
606 status = kvm_read (kvmd, addr, buf, size);
609 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
610 status, size, kvm_geterr (kvmd));
616 static int conn_init (void)
618 char buf[_POSIX2_LINE_MAX];
627 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
630 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
634 status = kvm_nlist (kvmd, nl);
637 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
641 if (nl[N_TCBTABLE].n_type == 0)
643 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
644 "N_TCBTABLE is invalid.");
648 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
649 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
652 } /* int conn_init */
654 static int conn_read (void)
656 struct inpcbtable table;
663 conn_reset_port_entry ();
665 /* Read the pcbtable from the kernel */
666 status = kread (inpcbtable_off, &table, sizeof (table));
670 /* Get the `head' pcb */
671 head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
672 /* Get the first pcb */
673 next = CIRCLEQ_FIRST (&table.inpt_queue);
677 /* Read the pcb pointed to by `next' into `inpcb' */
678 kread ((u_long) next, &inpcb, sizeof (inpcb));
681 next = CIRCLEQ_NEXT (&inpcb, inp_queue);
683 /* Ignore sockets, that are not connected. */
684 if (!(inpcb.inp_flags & INP_IPV6)
685 && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
687 if ((inpcb.inp_flags & INP_IPV6)
688 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
691 kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
692 conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
693 } /* while (next != head) */
699 #endif /* HAVE_LIBKVM_NLIST */
701 void module_register (void)
703 plugin_register_config ("tcpconns", conn_config,
704 config_keys, config_keys_num);
706 plugin_register_init ("tcpconns", conn_init);
707 #elif HAVE_SYSCTLBYNAME
708 /* no initialization */
709 #elif HAVE_LIBKVM_NLIST
710 plugin_register_init ("tcpconns", conn_init);
712 plugin_register_read ("tcpconns", conn_read);
713 } /* void module_register */
716 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :