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 verplant.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
69 # error "No applicable input method."
70 #endif
72 #if KERNEL_LINUX
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 */
80 #include <sys/time.h>
81 #if HAVE_SYS_TYPES_H
82 # include <sys/types.h>
83 #endif
84 #if HAVE_SYS_SOCKET_H
85 # include <sys/socket.h>
86 #endif
87 #if HAVE_NET_IF_H
88 # include <net/if.h>
89 #endif
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>
117 # include <netdb.h>
118 # include <arpa/inet.h>
119 # if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
120 # include <nlist.h>
121 # else /* HAVE_BSD_NLIST_H */
122 # include <bsd/nlist.h>
123 # endif
124 # include <kvm.h>
125 #endif /* HAVE_LIBKVM_NLIST */
127 #if KERNEL_LINUX
128 static const char *tcp_state[] =
129 {
130 "", /* 0 */
131 "ESTABLISHED",
132 "SYN_SENT",
133 "SYN_RECV",
134 "FIN_WAIT1",
135 "FIN_WAIT2",
136 "TIME_WAIT",
137 "CLOSED",
138 "CLOSE_WAIT",
139 "LAST_ACK",
140 "LISTEN", /* 10 */
141 "CLOSING"
142 };
144 # define TCP_STATE_LISTEN 10
145 # define TCP_STATE_MIN 1
146 # define TCP_STATE_MAX 11
147 /* #endif KERNEL_LINUX */
149 #elif HAVE_SYSCTLBYNAME
150 static const char *tcp_state[] =
151 {
152 "CLOSED",
153 "LISTEN",
154 "SYN_SENT",
155 "SYN_RECV",
156 "ESTABLISHED",
157 "CLOSE_WAIT",
158 "FIN_WAIT1",
159 "CLOSING",
160 "LAST_ACK",
161 "FIN_WAIT2",
162 "TIME_WAIT"
163 };
165 # define TCP_STATE_LISTEN 1
166 # define TCP_STATE_MIN 0
167 # define TCP_STATE_MAX 10
168 /* #endif HAVE_SYSCTLBYNAME */
170 #elif HAVE_LIBKVM_NLIST
171 static const char *tcp_state[] =
172 {
173 "CLOSED",
174 "LISTEN",
175 "SYN_SENT",
176 "SYN_RECV",
177 "ESTABLISHED",
178 "CLOSE_WAIT",
179 "FIN_WAIT1",
180 "CLOSING",
181 "LAST_ACK",
182 "FIN_WAIT2",
183 "TIME_WAIT"
184 };
186 static kvm_t *kvmd;
187 static u_long inpcbtable_off = 0;
188 struct inpcbtable *inpcbtable_ptr = NULL;
190 # define TCP_STATE_LISTEN 1
191 # define TCP_STATE_MIN 1
192 # define TCP_STATE_MAX 10
193 #endif /* HAVE_LIBKVM_NLIST */
195 #define PORT_COLLECT_LOCAL 0x01
196 #define PORT_COLLECT_REMOTE 0x02
197 #define PORT_IS_LISTENING 0x04
199 typedef struct port_entry_s
200 {
201 uint16_t port;
202 uint16_t flags;
203 uint32_t count_local[TCP_STATE_MAX + 1];
204 uint32_t count_remote[TCP_STATE_MAX + 1];
205 struct port_entry_s *next;
206 } port_entry_t;
208 static const char *config_keys[] =
209 {
210 "ListeningPorts",
211 "LocalPort",
212 "RemotePort"
213 };
214 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
216 static int port_collect_listening = 0;
217 static port_entry_t *port_list_head = NULL;
219 static void conn_submit_port_entry (port_entry_t *pe)
220 {
221 value_t values[1];
222 value_list_t vl = VALUE_LIST_INIT;
223 int i;
225 vl.values = values;
226 vl.values_len = 1;
227 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
228 sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
229 sstrncpy (vl.type, "tcp_connections", sizeof (vl.type));
231 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
232 || (pe->flags & PORT_COLLECT_LOCAL))
233 {
234 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
235 "%"PRIu16"-local", pe->port);
237 for (i = 1; i <= TCP_STATE_MAX; i++)
238 {
239 vl.values[0].gauge = pe->count_local[i];
241 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
243 plugin_dispatch_values (&vl);
244 }
245 }
247 if (pe->flags & PORT_COLLECT_REMOTE)
248 {
249 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
250 "%"PRIu16"-remote", pe->port);
252 for (i = 1; i <= TCP_STATE_MAX; i++)
253 {
254 vl.values[0].gauge = pe->count_remote[i];
256 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
258 plugin_dispatch_values (&vl);
259 }
260 }
261 } /* void conn_submit */
263 static void conn_submit_all (void)
264 {
265 port_entry_t *pe;
267 for (pe = port_list_head; pe != NULL; pe = pe->next)
268 conn_submit_port_entry (pe);
269 } /* void conn_submit_all */
271 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
272 {
273 port_entry_t *ret;
275 ret = port_list_head;
276 while (ret != NULL)
277 {
278 if (ret->port == port)
279 break;
280 ret = ret->next;
281 }
283 if ((ret == NULL) && (create != 0))
284 {
285 ret = (port_entry_t *) malloc (sizeof (port_entry_t));
286 if (ret == NULL)
287 return (NULL);
288 memset (ret, '\0', sizeof (port_entry_t));
290 ret->port = port;
291 ret->next = port_list_head;
292 port_list_head = ret;
293 }
295 return (ret);
296 } /* port_entry_t *conn_get_port_entry */
298 /* Removes ports that were added automatically due to the `ListeningPorts'
299 * setting but which are no longer listening. */
300 static void conn_reset_port_entry (void)
301 {
302 port_entry_t *prev = NULL;
303 port_entry_t *pe = port_list_head;
305 while (pe != NULL)
306 {
307 /* If this entry was created while reading the files (ant not when handling
308 * the configuration) remove it now. */
309 if ((pe->flags & (PORT_COLLECT_LOCAL
310 | PORT_COLLECT_REMOTE
311 | PORT_IS_LISTENING)) == 0)
312 {
313 port_entry_t *next = pe->next;
315 DEBUG ("tcpconns plugin: Removing temporary entry "
316 "for listening port %"PRIu16, pe->port);
318 if (prev == NULL)
319 port_list_head = next;
320 else
321 prev->next = next;
323 sfree (pe);
324 pe = next;
326 continue;
327 }
329 memset (pe->count_local, '\0', sizeof (pe->count_local));
330 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
331 pe->flags &= ~PORT_IS_LISTENING;
333 pe = pe->next;
334 }
335 } /* void conn_reset_port_entry */
337 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
338 {
339 port_entry_t *pe = NULL;
341 if ((state > TCP_STATE_MAX)
342 #if TCP_STATE_MIN > 0
343 || (state < TCP_STATE_MIN)
344 #endif
345 )
346 {
347 NOTICE ("tcpconns plugin: Ignoring connection with "
348 "unknown state 0x%02"PRIx8".", state);
349 return (-1);
350 }
352 /* Listening sockets */
353 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
354 {
355 pe = conn_get_port_entry (port_local, 1 /* create */);
356 if (pe != NULL)
357 pe->flags |= PORT_IS_LISTENING;
358 }
360 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
361 port_local, port_remote, tcp_state[state]);
363 pe = conn_get_port_entry (port_local, 0 /* no create */);
364 if (pe != NULL)
365 pe->count_local[state]++;
367 pe = conn_get_port_entry (port_remote, 0 /* no create */);
368 if (pe != NULL)
369 pe->count_remote[state]++;
371 return (0);
372 } /* int conn_handle_ports */
374 #if KERNEL_LINUX
375 static int conn_handle_line (char *buffer)
376 {
377 char *fields[32];
378 int fields_len;
380 char *endptr;
382 char *port_local_str;
383 char *port_remote_str;
384 uint16_t port_local;
385 uint16_t port_remote;
387 uint8_t state;
389 int buffer_len = strlen (buffer);
391 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
392 buffer[--buffer_len] = '\0';
393 if (buffer_len <= 0)
394 return (-1);
396 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
397 if (fields_len < 12)
398 {
399 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
400 return (-1);
401 }
403 port_local_str = strchr (fields[1], ':');
404 port_remote_str = strchr (fields[2], ':');
406 if ((port_local_str == NULL) || (port_remote_str == NULL))
407 return (-1);
408 port_local_str++;
409 port_remote_str++;
410 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
411 return (-1);
413 endptr = NULL;
414 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
415 if ((endptr == NULL) || (*endptr != '\0'))
416 return (-1);
418 endptr = NULL;
419 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
420 if ((endptr == NULL) || (*endptr != '\0'))
421 return (-1);
423 endptr = NULL;
424 state = (uint8_t) strtol (fields[3], &endptr, 16);
425 if ((endptr == NULL) || (*endptr != '\0'))
426 return (-1);
428 return (conn_handle_ports (port_local, port_remote, state));
429 } /* int conn_handle_line */
431 static int conn_read_file (const char *file)
432 {
433 FILE *fh;
434 char buffer[1024];
436 fh = fopen (file, "r");
437 if (fh == NULL)
438 return (-1);
440 while (fgets (buffer, sizeof (buffer), fh) != NULL)
441 {
442 conn_handle_line (buffer);
443 } /* while (fgets) */
445 fclose (fh);
447 return (0);
448 } /* int conn_read_file */
449 /* #endif KERNEL_LINUX */
451 #elif HAVE_SYSCTLBYNAME
452 /* #endif HAVE_SYSCTLBYNAME */
454 #elif HAVE_LIBKVM_NLIST
455 #endif /* HAVE_LIBKVM_NLIST */
457 static int conn_config (const char *key, const char *value)
458 {
459 if (strcasecmp (key, "ListeningPorts") == 0)
460 {
461 if (IS_TRUE (value))
462 port_collect_listening = 1;
463 else
464 port_collect_listening = 0;
465 }
466 else if ((strcasecmp (key, "LocalPort") == 0)
467 || (strcasecmp (key, "RemotePort") == 0))
468 {
469 port_entry_t *pe;
470 int port = atoi (value);
472 if ((port < 1) || (port > 65535))
473 {
474 ERROR ("tcpconns plugin: Invalid port: %i", port);
475 return (1);
476 }
478 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
479 if (pe == NULL)
480 {
481 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
482 return (1);
483 }
485 if (strcasecmp (key, "LocalPort") == 0)
486 pe->flags |= PORT_COLLECT_LOCAL;
487 else
488 pe->flags |= PORT_COLLECT_REMOTE;
489 }
490 else
491 {
492 return (-1);
493 }
495 return (0);
496 } /* int conn_config */
498 #if KERNEL_LINUX
499 static int conn_init (void)
500 {
501 if (port_list_head == NULL)
502 port_collect_listening = 1;
504 return (0);
505 } /* int conn_init */
507 static int conn_read (void)
508 {
509 int errors_num = 0;
511 conn_reset_port_entry ();
513 if (conn_read_file ("/proc/net/tcp") != 0)
514 errors_num++;
515 if (conn_read_file ("/proc/net/tcp6") != 0)
516 errors_num++;
518 if (errors_num < 2)
519 {
520 conn_submit_all ();
521 }
522 else
523 {
524 ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
525 "coult be read.");
526 return (-1);
527 }
529 return (0);
530 } /* int conn_read */
531 /* #endif KERNEL_LINUX */
533 #elif HAVE_SYSCTLBYNAME
534 static int conn_read (void)
535 {
536 int status;
537 char *buffer;
538 size_t buffer_len;;
540 struct xinpgen *in_orig;
541 struct xinpgen *in_ptr;
543 conn_reset_port_entry ();
545 buffer_len = 0;
546 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
547 if (status < 0)
548 {
549 ERROR ("tcpconns plugin: sysctlbyname failed.");
550 return (-1);
551 }
553 buffer = (char *) malloc (buffer_len);
554 if (buffer == NULL)
555 {
556 ERROR ("tcpconns plugin: malloc failed.");
557 return (-1);
558 }
560 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
561 if (status < 0)
562 {
563 ERROR ("tcpconns plugin: sysctlbyname failed.");
564 sfree (buffer);
565 return (-1);
566 }
568 if (buffer_len <= sizeof (struct xinpgen))
569 {
570 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
571 sfree (buffer);
572 return (-1);
573 }
575 in_orig = (struct xinpgen *) buffer;
576 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
577 in_ptr->xig_len > sizeof (struct xinpgen);
578 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
579 {
580 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
581 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
582 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
584 /* Ignore non-TCP sockets */
585 if (so->xso_protocol != IPPROTO_TCP)
586 continue;
588 /* Ignore PCBs which were freed during copyout. */
589 if (inp->inp_gencnt > in_orig->xig_gen)
590 continue;
592 if (((inp->inp_vflag & INP_IPV4) == 0)
593 && ((inp->inp_vflag & INP_IPV6) == 0))
594 continue;
596 conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
597 tp->t_state);
598 } /* for (in_ptr) */
600 in_orig = NULL;
601 in_ptr = NULL;
602 sfree (buffer);
604 conn_submit_all ();
606 return (0);
607 } /* int conn_read */
608 /* #endif HAVE_SYSCTLBYNAME */
610 #elif HAVE_LIBKVM_NLIST
611 static int kread (u_long addr, void *buf, int size)
612 {
613 int status;
615 status = kvm_read (kvmd, addr, buf, size);
616 if (status != size)
617 {
618 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
619 status, size, kvm_geterr (kvmd));
620 return (-1);
621 }
622 return (0);
623 } /* int kread */
625 static int conn_init (void)
626 {
627 char buf[_POSIX2_LINE_MAX];
628 struct nlist nl[] =
629 {
630 #define N_TCBTABLE 0
631 { "_tcbtable" },
632 { "" }
633 };
634 int status;
636 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
637 if (kvmd == NULL)
638 {
639 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
640 return (-1);
641 }
643 status = kvm_nlist (kvmd, nl);
644 if (status < 0)
645 {
646 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
647 return (-1);
648 }
650 if (nl[N_TCBTABLE].n_type == 0)
651 {
652 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
653 "N_TCBTABLE is invalid.");
654 return (-1);
655 }
657 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
658 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
660 return (0);
661 } /* int conn_init */
663 static int conn_read (void)
664 {
665 struct inpcbtable table;
666 struct inpcb *head;
667 struct inpcb *next;
668 struct inpcb inpcb;
669 struct tcpcb tcpcb;
670 int status;
672 conn_reset_port_entry ();
674 /* Read the pcbtable from the kernel */
675 status = kread (inpcbtable_off, &table, sizeof (table));
676 if (status != 0)
677 return (-1);
679 /* Get the `head' pcb */
680 head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
681 /* Get the first pcb */
682 next = (struct inpcb *)CIRCLEQ_FIRST (&table.inpt_queue);
684 while (next != head)
685 {
686 /* Read the pcb pointed to by `next' into `inpcb' */
687 kread ((u_long) next, &inpcb, sizeof (inpcb));
689 /* Advance `next' */
690 next = (struct inpcb *)CIRCLEQ_NEXT (&inpcb, inp_queue);
692 /* Ignore sockets, that are not connected. */
693 #ifdef __NetBSD__
694 if (inpcb.inp_af == AF_INET6)
695 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
696 #else
697 if (!(inpcb.inp_flags & INP_IPV6)
698 && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
699 continue;
700 if ((inpcb.inp_flags & INP_IPV6)
701 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
702 continue;
703 #endif
705 kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
706 conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
707 } /* while (next != head) */
709 conn_submit_all ();
711 return (0);
712 }
713 #endif /* HAVE_LIBKVM_NLIST */
715 void module_register (void)
716 {
717 plugin_register_config ("tcpconns", conn_config,
718 config_keys, config_keys_num);
719 #if KERNEL_LINUX
720 plugin_register_init ("tcpconns", conn_init);
721 #elif HAVE_SYSCTLBYNAME
722 /* no initialization */
723 #elif HAVE_LIBKVM_NLIST
724 plugin_register_init ("tcpconns", conn_init);
725 #endif
726 plugin_register_read ("tcpconns", conn_read);
727 } /* void module_register */
729 /*
730 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :
731 */