1 /**
2 * collectd - src/tcpconns.c
3 * Copyright (C) 2007 Florian octo Forster
4 *
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.
8 *
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.
13 *
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
17 *
18 * Author:
19 * Florian octo Forster <octo at verplant.org>
20 **/
22 /**
23 * Code within `HAVE_LIBKVM_NLIST' blocks is provided under the following
24 * license:
25 *
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 $
29 *
30 * Copyright (c) 1983, 1988, 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
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.
44 *
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
55 * SUCH DAMAGE.
56 */
58 #include "collectd.h"
59 #include "common.h"
60 #include "plugin.h"
62 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST
63 # error "No applicable input method."
64 #endif
66 #if KERNEL_LINUX
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 */
74 #include <sys/time.h>
75 #if HAVE_SYS_TYPES_H
76 # include <sys/types.h>
77 #endif
78 #if HAVE_SYS_SOCKET_H
79 # include <sys/socket.h>
80 #endif
81 #if HAVE_NET_IF_H
82 # include <net/if.h>
83 #endif
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>
110 # include <netdb.h>
111 # include <arpa/inet.h>
112 # include <nlist.h>
113 # include <kvm.h>
114 #endif /* HAVE_LIBKVM_NLIST */
116 #if KERNEL_LINUX
117 static const char *tcp_state[] =
118 {
119 "", /* 0 */
120 "ESTABLISHED",
121 "SYN_SENT",
122 "SYN_RECV",
123 "FIN_WAIT1",
124 "FIN_WAIT2",
125 "TIME_WAIT",
126 "CLOSED",
127 "CLOSE_WAIT",
128 "LAST_ACK",
129 "LISTEN", /* 10 */
130 "CLOSING"
131 };
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[] =
140 {
141 "CLOSED",
142 "LISTEN",
143 "SYN_SENT",
144 "SYN_RECV",
145 "ESTABLISHED",
146 "CLOSE_WAIT",
147 "FIN_WAIT1",
148 "CLOSING",
149 "LAST_ACK",
150 "FIN_WAIT2",
151 "TIME_WAIT"
152 };
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[] =
161 {
162 "CLOSED",
163 "LISTEN",
164 "SYN_SENT",
165 "SYN_RECV",
166 "ESTABLISHED",
167 "CLOSE_WAIT",
168 "FIN_WAIT1",
169 "CLOSING",
170 "LAST_ACK",
171 "FIN_WAIT2",
172 "TIME_WAIT"
173 };
175 static kvm_t *kvmd;
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
189 {
190 uint16_t port;
191 uint16_t flags;
192 uint32_t count_local[TCP_STATE_MAX + 1];
193 uint32_t count_remote[TCP_STATE_MAX + 1];
194 struct port_entry_s *next;
195 } port_entry_t;
197 static const char *config_keys[] =
198 {
199 "ListeningPorts",
200 "LocalPort",
201 "RemotePort"
202 };
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)
209 {
210 value_t values[1];
211 value_list_t vl = VALUE_LIST_INIT;
212 int i;
214 vl.values = values;
215 vl.values_len = 1;
216 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
217 sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
218 sstrncpy (vl.type, "tcp_connections", sizeof (vl.type));
220 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
221 || (pe->flags & PORT_COLLECT_LOCAL))
222 {
223 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
224 "%"PRIu16"-local", pe->port);
226 for (i = 1; i <= TCP_STATE_MAX; i++)
227 {
228 vl.values[0].gauge = pe->count_local[i];
230 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
232 plugin_dispatch_values (&vl);
233 }
234 }
236 if (pe->flags & PORT_COLLECT_REMOTE)
237 {
238 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
239 "%"PRIu16"-remote", pe->port);
241 for (i = 1; i <= TCP_STATE_MAX; i++)
242 {
243 vl.values[0].gauge = pe->count_remote[i];
245 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
247 plugin_dispatch_values (&vl);
248 }
249 }
250 } /* void conn_submit */
252 static void conn_submit_all (void)
253 {
254 port_entry_t *pe;
256 for (pe = port_list_head; pe != NULL; pe = pe->next)
257 conn_submit_port_entry (pe);
258 } /* void conn_submit_all */
260 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
261 {
262 port_entry_t *ret;
264 ret = port_list_head;
265 while (ret != NULL)
266 {
267 if (ret->port == port)
268 break;
269 ret = ret->next;
270 }
272 if ((ret == NULL) && (create != 0))
273 {
274 ret = (port_entry_t *) malloc (sizeof (port_entry_t));
275 if (ret == NULL)
276 return (NULL);
277 memset (ret, '\0', sizeof (port_entry_t));
279 ret->port = port;
280 ret->next = port_list_head;
281 port_list_head = ret;
282 }
284 return (ret);
285 } /* port_entry_t *conn_get_port_entry */
287 /* Removes ports that were added automatically due to the `ListeningPorts'
288 * setting but which are no longer listening. */
289 static void conn_reset_port_entry (void)
290 {
291 port_entry_t *prev = NULL;
292 port_entry_t *pe = port_list_head;
294 while (pe != NULL)
295 {
296 /* If this entry was created while reading the files (ant not when handling
297 * the configuration) remove it now. */
298 if ((pe->flags & (PORT_COLLECT_LOCAL
299 | PORT_COLLECT_REMOTE
300 | PORT_IS_LISTENING)) == 0)
301 {
302 port_entry_t *next = pe->next;
304 DEBUG ("tcpconns plugin: Removing temporary entry "
305 "for listening port %"PRIu16, pe->port);
307 if (prev == NULL)
308 port_list_head = next;
309 else
310 prev->next = next;
312 sfree (pe);
313 pe = next;
315 continue;
316 }
318 memset (pe->count_local, '\0', sizeof (pe->count_local));
319 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
320 pe->flags &= ~PORT_IS_LISTENING;
322 pe = pe->next;
323 }
324 } /* void conn_reset_port_entry */
326 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
327 {
328 port_entry_t *pe = NULL;
330 if ((state > TCP_STATE_MAX)
331 #if TCP_STATE_MIN > 0
332 || (state < TCP_STATE_MIN)
333 #endif
334 )
335 {
336 NOTICE ("tcpconns plugin: Ignoring connection with "
337 "unknown state 0x%02"PRIx8".", state);
338 return (-1);
339 }
341 /* Listening sockets */
342 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
343 {
344 pe = conn_get_port_entry (port_local, 1 /* create */);
345 if (pe != NULL)
346 pe->flags |= PORT_IS_LISTENING;
347 }
349 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
350 port_local, port_remote, tcp_state[state]);
352 pe = conn_get_port_entry (port_local, 0 /* no create */);
353 if (pe != NULL)
354 pe->count_local[state]++;
356 pe = conn_get_port_entry (port_remote, 0 /* no create */);
357 if (pe != NULL)
358 pe->count_remote[state]++;
360 return (0);
361 } /* int conn_handle_ports */
363 #if KERNEL_LINUX
364 static int conn_handle_line (char *buffer)
365 {
366 char *fields[32];
367 int fields_len;
369 char *endptr;
371 char *port_local_str;
372 char *port_remote_str;
373 uint16_t port_local;
374 uint16_t port_remote;
376 uint8_t state;
378 int buffer_len = strlen (buffer);
380 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
381 buffer[--buffer_len] = '\0';
382 if (buffer_len <= 0)
383 return (-1);
385 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
386 if (fields_len < 12)
387 {
388 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
389 return (-1);
390 }
392 port_local_str = strchr (fields[1], ':');
393 port_remote_str = strchr (fields[2], ':');
395 if ((port_local_str == NULL) || (port_remote_str == NULL))
396 return (-1);
397 port_local_str++;
398 port_remote_str++;
399 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
400 return (-1);
402 endptr = NULL;
403 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
404 if ((endptr == NULL) || (*endptr != '\0'))
405 return (-1);
407 endptr = NULL;
408 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
409 if ((endptr == NULL) || (*endptr != '\0'))
410 return (-1);
412 endptr = NULL;
413 state = (uint8_t) strtol (fields[3], &endptr, 16);
414 if ((endptr == NULL) || (*endptr != '\0'))
415 return (-1);
417 return (conn_handle_ports (port_local, port_remote, state));
418 } /* int conn_handle_line */
420 static int conn_read_file (const char *file)
421 {
422 FILE *fh;
423 char buffer[1024];
425 fh = fopen (file, "r");
426 if (fh == NULL)
427 return (-1);
429 while (fgets (buffer, sizeof (buffer), fh) != NULL)
430 {
431 conn_handle_line (buffer);
432 } /* while (fgets) */
434 fclose (fh);
436 return (0);
437 } /* int conn_read_file */
438 /* #endif KERNEL_LINUX */
440 #elif HAVE_SYSCTLBYNAME
441 /* #endif HAVE_SYSCTLBYNAME */
443 #elif HAVE_LIBKVM_NLIST
444 #endif /* HAVE_LIBKVM_NLIST */
446 static int conn_config (const char *key, const char *value)
447 {
448 if (strcasecmp (key, "ListeningPorts") == 0)
449 {
450 if ((strcasecmp (value, "Yes") == 0)
451 || (strcasecmp (value, "True") == 0)
452 || (strcasecmp (value, "On") == 0))
453 port_collect_listening = 1;
454 else
455 port_collect_listening = 0;
456 }
457 else if ((strcasecmp (key, "LocalPort") == 0)
458 || (strcasecmp (key, "RemotePort") == 0))
459 {
460 port_entry_t *pe;
461 int port = atoi (value);
463 if ((port < 1) || (port > 65535))
464 {
465 ERROR ("tcpconns plugin: Invalid port: %i", port);
466 return (1);
467 }
469 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
470 if (pe == NULL)
471 {
472 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
473 return (1);
474 }
476 if (strcasecmp (key, "LocalPort") == 0)
477 pe->flags |= PORT_COLLECT_LOCAL;
478 else
479 pe->flags |= PORT_COLLECT_REMOTE;
480 }
481 else
482 {
483 return (-1);
484 }
486 return (0);
487 } /* int conn_config */
489 #if KERNEL_LINUX
490 static int conn_init (void)
491 {
492 if (port_list_head == NULL)
493 port_collect_listening = 1;
495 return (0);
496 } /* int conn_init */
498 static int conn_read (void)
499 {
500 int errors_num = 0;
502 conn_reset_port_entry ();
504 if (conn_read_file ("/proc/net/tcp") != 0)
505 errors_num++;
506 if (conn_read_file ("/proc/net/tcp6") != 0)
507 errors_num++;
509 if (errors_num < 2)
510 {
511 conn_submit_all ();
512 }
513 else
514 {
515 ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
516 "coult be read.");
517 return (-1);
518 }
520 return (0);
521 } /* int conn_read */
522 /* #endif KERNEL_LINUX */
524 #elif HAVE_SYSCTLBYNAME
525 static int conn_read (void)
526 {
527 int status;
528 char *buffer;
529 size_t buffer_len;;
531 struct xinpgen *in_orig;
532 struct xinpgen *in_ptr;
534 conn_reset_port_entry ();
536 buffer_len = 0;
537 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
538 if (status < 0)
539 {
540 ERROR ("tcpconns plugin: sysctlbyname failed.");
541 return (-1);
542 }
544 buffer = (char *) malloc (buffer_len);
545 if (buffer == NULL)
546 {
547 ERROR ("tcpconns plugin: malloc failed.");
548 return (-1);
549 }
551 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
552 if (status < 0)
553 {
554 ERROR ("tcpconns plugin: sysctlbyname failed.");
555 sfree (buffer);
556 return (-1);
557 }
559 if (buffer_len <= sizeof (struct xinpgen))
560 {
561 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
562 sfree (buffer);
563 return (-1);
564 }
566 in_orig = (struct xinpgen *) buffer;
567 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
568 in_ptr->xig_len > sizeof (struct xinpgen);
569 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
570 {
571 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
572 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
573 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
575 /* Ignore non-TCP sockets */
576 if (so->xso_protocol != IPPROTO_TCP)
577 continue;
579 /* Ignore PCBs which were freed during copyout. */
580 if (inp->inp_gencnt > in_orig->xig_gen)
581 continue;
583 if (((inp->inp_vflag & INP_IPV4) == 0)
584 && ((inp->inp_vflag & INP_IPV6) == 0))
585 continue;
587 conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
588 tp->t_state);
589 } /* for (in_ptr) */
591 in_orig = NULL;
592 in_ptr = NULL;
593 sfree (buffer);
595 conn_submit_all ();
597 return (0);
598 } /* int conn_read */
599 /* #endif HAVE_SYSCTLBYNAME */
601 #elif HAVE_LIBKVM_NLIST
602 static int kread (u_long addr, void *buf, int size)
603 {
604 int status;
606 status = kvm_read (kvmd, addr, buf, size);
607 if (status != size)
608 {
609 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
610 status, size, kvm_geterr (kvmd));
611 return (-1);
612 }
613 return (0);
614 } /* int kread */
616 static int conn_init (void)
617 {
618 char buf[_POSIX2_LINE_MAX];
619 struct nlist nl[] =
620 {
621 #define N_TCBTABLE 0
622 { "_tcbtable" },
623 { "" }
624 };
625 int status;
627 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
628 if (kvmd == NULL)
629 {
630 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
631 return (-1);
632 }
634 status = kvm_nlist (kvmd, nl);
635 if (status < 0)
636 {
637 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
638 return (-1);
639 }
641 if (nl[N_TCBTABLE].n_type == 0)
642 {
643 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
644 "N_TCBTABLE is invalid.");
645 return (-1);
646 }
648 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
649 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
651 return (0);
652 } /* int conn_init */
654 static int conn_read (void)
655 {
656 struct inpcbtable table;
657 struct inpcb *head;
658 struct inpcb *next;
659 struct inpcb inpcb;
660 struct tcpcb tcpcb;
661 int status;
663 conn_reset_port_entry ();
665 /* Read the pcbtable from the kernel */
666 status = kread (inpcbtable_off, &table, sizeof (table));
667 if (status != 0)
668 return (-1);
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);
675 while (next != head)
676 {
677 /* Read the pcb pointed to by `next' into `inpcb' */
678 kread ((u_long) next, &inpcb, sizeof (inpcb));
680 /* Advance `next' */
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))
686 continue;
687 if ((inpcb.inp_flags & INP_IPV6)
688 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
689 continue;
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) */
695 conn_submit_all ();
697 return (0);
698 }
699 #endif /* HAVE_LIBKVM_NLIST */
701 void module_register (void)
702 {
703 plugin_register_config ("tcpconns", conn_config,
704 config_keys, config_keys_num);
705 #if KERNEL_LINUX
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);
711 #endif
712 plugin_register_read ("tcpconns", conn_read);
713 } /* void module_register */
715 /*
716 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :
717 */