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 && !KERNEL_AIX
69 # error "No applicable input method."
70 #endif
72 #if KERNEL_LINUX
73 # include <asm/types.h>
74 /* sys/socket.h is necessary to compile when using netlink on older systems. */
75 # include <sys/socket.h>
76 # include <linux/netlink.h>
77 # include <linux/inet_diag.h>
78 # include <sys/socket.h>
79 # include <arpa/inet.h>
80 /* #endif KERNEL_LINUX */
82 #elif HAVE_SYSCTLBYNAME
83 # include <sys/socketvar.h>
84 # include <sys/sysctl.h>
86 /* Some includes needed for compiling on FreeBSD */
87 #include <sys/time.h>
88 #if HAVE_SYS_TYPES_H
89 # include <sys/types.h>
90 #endif
91 #if HAVE_SYS_SOCKET_H
92 # include <sys/socket.h>
93 #endif
94 #if HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
98 # include <net/route.h>
99 # include <netinet/in.h>
100 # include <netinet/in_systm.h>
101 # include <netinet/ip.h>
102 # include <netinet/ip6.h>
103 # include <netinet/in_pcb.h>
104 # include <netinet/ip_var.h>
105 # include <netinet/tcp.h>
106 # include <netinet/tcpip.h>
107 # include <netinet/tcp_seq.h>
108 # include <netinet/tcp_var.h>
109 /* #endif HAVE_SYSCTLBYNAME */
111 /* This is for OpenBSD and NetBSD. */
112 #elif HAVE_LIBKVM_NLIST
113 # include <sys/queue.h>
114 # include <sys/socket.h>
115 # include <net/route.h>
116 # include <netinet/in.h>
117 # include <netinet/in_systm.h>
118 # include <netinet/ip.h>
119 # include <netinet/ip_var.h>
120 # include <netinet/in_pcb.h>
121 # include <netinet/tcp.h>
122 # include <netinet/tcp_timer.h>
123 # include <netinet/tcp_var.h>
124 # include <netdb.h>
125 # include <arpa/inet.h>
126 # if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
127 # include <nlist.h>
128 # else /* HAVE_BSD_NLIST_H */
129 # include <bsd/nlist.h>
130 # endif
131 # include <kvm.h>
132 /* #endif HAVE_LIBKVM_NLIST */
134 #elif KERNEL_AIX
135 # include <arpa/inet.h>
136 # include <sys/socketvar.h>
137 #endif /* KERNEL_AIX */
139 #if KERNEL_LINUX
140 struct nlreq {
141 struct nlmsghdr nlh;
142 struct inet_diag_req r;
143 };
145 static const char *tcp_state[] =
146 {
147 "", /* 0 */
148 "ESTABLISHED",
149 "SYN_SENT",
150 "SYN_RECV",
151 "FIN_WAIT1",
152 "FIN_WAIT2",
153 "TIME_WAIT",
154 "CLOSED",
155 "CLOSE_WAIT",
156 "LAST_ACK",
157 "LISTEN", /* 10 */
158 "CLOSING"
159 };
161 # define TCP_STATE_LISTEN 10
162 # define TCP_STATE_MIN 1
163 # define TCP_STATE_MAX 11
164 /* #endif KERNEL_LINUX */
166 #elif HAVE_SYSCTLBYNAME
167 static const char *tcp_state[] =
168 {
169 "CLOSED",
170 "LISTEN",
171 "SYN_SENT",
172 "SYN_RECV",
173 "ESTABLISHED",
174 "CLOSE_WAIT",
175 "FIN_WAIT1",
176 "CLOSING",
177 "LAST_ACK",
178 "FIN_WAIT2",
179 "TIME_WAIT"
180 };
182 # define TCP_STATE_LISTEN 1
183 # define TCP_STATE_MIN 0
184 # define TCP_STATE_MAX 10
185 /* #endif HAVE_SYSCTLBYNAME */
187 #elif HAVE_LIBKVM_NLIST
188 static const char *tcp_state[] =
189 {
190 "CLOSED",
191 "LISTEN",
192 "SYN_SENT",
193 "SYN_RECV",
194 "ESTABLISHED",
195 "CLOSE_WAIT",
196 "FIN_WAIT1",
197 "CLOSING",
198 "LAST_ACK",
199 "FIN_WAIT2",
200 "TIME_WAIT"
201 };
203 static kvm_t *kvmd;
204 static u_long inpcbtable_off = 0;
205 struct inpcbtable *inpcbtable_ptr = NULL;
207 # define TCP_STATE_LISTEN 1
208 # define TCP_STATE_MIN 1
209 # define TCP_STATE_MAX 10
210 /* #endif HAVE_LIBKVM_NLIST */
212 #elif KERNEL_AIX
213 static const char *tcp_state[] =
214 {
215 "CLOSED",
216 "LISTEN",
217 "SYN_SENT",
218 "SYN_RCVD",
219 "ESTABLISHED",
220 "CLOSE_WAIT",
221 "FIN_WAIT_1",
222 "CLOSING",
223 "LAST_ACK",
224 "FIN_WAIT_2",
225 "TIME_WAIT"
226 };
228 # define TCP_STATE_LISTEN 1
229 # define TCP_STATE_MIN 0
230 # define TCP_STATE_MAX 10
232 struct netinfo_conn {
233 uint32_t unknow1[2];
234 uint16_t dstport;
235 uint16_t unknow2;
236 struct in6_addr dstaddr;
237 uint16_t srcport;
238 uint16_t unknow3;
239 struct in6_addr srcaddr;
240 uint32_t unknow4[36];
241 uint16_t tcp_state;
242 uint16_t unknow5[7];
243 };
245 struct netinfo_header {
246 unsigned int proto;
247 unsigned int size;
248 };
250 # define NETINFO_TCP 3
251 extern int netinfo (int proto, void *data, int *size, int n);
252 #endif /* KERNEL_AIX */
254 #define PORT_COLLECT_LOCAL 0x01
255 #define PORT_COLLECT_REMOTE 0x02
256 #define PORT_IS_LISTENING 0x04
258 typedef struct port_entry_s
259 {
260 uint16_t port;
261 uint16_t flags;
262 uint32_t count_local[TCP_STATE_MAX + 1];
263 uint32_t count_remote[TCP_STATE_MAX + 1];
264 struct port_entry_s *next;
265 } port_entry_t;
267 static const char *config_keys[] =
268 {
269 "ListeningPorts",
270 "LocalPort",
271 "RemotePort",
272 "AllPortsSummary"
273 };
274 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
276 static int port_collect_listening = 0;
277 static int port_collect_total = 0;
278 static port_entry_t *port_list_head = NULL;
279 static uint32_t count_total[TCP_STATE_MAX + 1];
281 #if KERNEL_LINUX
282 static uint32_t sequence_number = 0;
284 enum
285 {
286 SRC_DUNNO,
287 SRC_NETLINK,
288 SRC_PROC
289 } linux_source = SRC_DUNNO;
290 #endif
292 static void conn_prepare_vl (value_list_t *vl, value_t *values)
293 {
294 vl->values = values;
295 vl->values_len = 1;
296 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
297 sstrncpy (vl->plugin, "tcpconns", sizeof (vl->plugin));
298 sstrncpy (vl->type, "tcp_connections", sizeof (vl->type));
299 }
301 static void conn_submit_port_entry (port_entry_t *pe)
302 {
303 value_t values[1];
304 value_list_t vl = VALUE_LIST_INIT;
305 int i;
307 conn_prepare_vl (&vl, values);
309 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
310 || (pe->flags & PORT_COLLECT_LOCAL))
311 {
312 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
313 "%"PRIu16"-local", pe->port);
315 for (i = 1; i <= TCP_STATE_MAX; i++)
316 {
317 vl.values[0].gauge = pe->count_local[i];
319 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
321 plugin_dispatch_values (&vl);
322 }
323 }
325 if (pe->flags & PORT_COLLECT_REMOTE)
326 {
327 ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
328 "%"PRIu16"-remote", pe->port);
330 for (i = 1; i <= TCP_STATE_MAX; i++)
331 {
332 vl.values[0].gauge = pe->count_remote[i];
334 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
336 plugin_dispatch_values (&vl);
337 }
338 }
339 } /* void conn_submit */
341 static void conn_submit_port_total (void)
342 {
343 value_t values[1];
344 value_list_t vl = VALUE_LIST_INIT;
345 int i;
347 conn_prepare_vl (&vl, values);
349 sstrncpy (vl.plugin_instance, "all", sizeof (vl.plugin_instance));
351 for (i = 1; i <= TCP_STATE_MAX; i++)
352 {
353 vl.values[0].gauge = count_total[i];
355 sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
357 plugin_dispatch_values (&vl);
358 }
359 }
361 static void conn_submit_all (void)
362 {
363 port_entry_t *pe;
365 if (port_collect_total)
366 conn_submit_port_total ();
368 for (pe = port_list_head; pe != NULL; pe = pe->next)
369 conn_submit_port_entry (pe);
370 } /* void conn_submit_all */
372 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
373 {
374 port_entry_t *ret;
376 ret = port_list_head;
377 while (ret != NULL)
378 {
379 if (ret->port == port)
380 break;
381 ret = ret->next;
382 }
384 if ((ret == NULL) && (create != 0))
385 {
386 ret = (port_entry_t *) malloc (sizeof (port_entry_t));
387 if (ret == NULL)
388 return (NULL);
389 memset (ret, '\0', sizeof (port_entry_t));
391 ret->port = port;
392 ret->next = port_list_head;
393 port_list_head = ret;
394 }
396 return (ret);
397 } /* port_entry_t *conn_get_port_entry */
399 /* Removes ports that were added automatically due to the `ListeningPorts'
400 * setting but which are no longer listening. */
401 static void conn_reset_port_entry (void)
402 {
403 port_entry_t *prev = NULL;
404 port_entry_t *pe = port_list_head;
406 memset (&count_total, '\0', sizeof(count_total));
408 while (pe != NULL)
409 {
410 /* If this entry was created while reading the files (ant not when handling
411 * the configuration) remove it now. */
412 if ((pe->flags & (PORT_COLLECT_LOCAL
413 | PORT_COLLECT_REMOTE
414 | PORT_IS_LISTENING)) == 0)
415 {
416 port_entry_t *next = pe->next;
418 DEBUG ("tcpconns plugin: Removing temporary entry "
419 "for listening port %"PRIu16, pe->port);
421 if (prev == NULL)
422 port_list_head = next;
423 else
424 prev->next = next;
426 sfree (pe);
427 pe = next;
429 continue;
430 }
432 memset (pe->count_local, '\0', sizeof (pe->count_local));
433 memset (pe->count_remote, '\0', sizeof (pe->count_remote));
434 pe->flags &= ~PORT_IS_LISTENING;
436 pe = pe->next;
437 }
438 } /* void conn_reset_port_entry */
440 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
441 {
442 port_entry_t *pe = NULL;
444 if ((state > TCP_STATE_MAX)
445 #if TCP_STATE_MIN > 0
446 || (state < TCP_STATE_MIN)
447 #endif
448 )
449 {
450 NOTICE ("tcpconns plugin: Ignoring connection with "
451 "unknown state 0x%02"PRIx8".", state);
452 return (-1);
453 }
455 count_total[state]++;
457 /* Listening sockets */
458 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
459 {
460 pe = conn_get_port_entry (port_local, 1 /* create */);
461 if (pe != NULL)
462 pe->flags |= PORT_IS_LISTENING;
463 }
465 DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
466 port_local, port_remote, tcp_state[state]);
468 pe = conn_get_port_entry (port_local, 0 /* no create */);
469 if (pe != NULL)
470 pe->count_local[state]++;
472 pe = conn_get_port_entry (port_remote, 0 /* no create */);
473 if (pe != NULL)
474 pe->count_remote[state]++;
476 return (0);
477 } /* int conn_handle_ports */
479 #if KERNEL_LINUX
480 /* Returns zero on success, less than zero on socket error and greater than
481 * zero on other errors. */
482 static int conn_read_netlink (void)
483 {
484 int fd;
485 struct sockaddr_nl nladdr;
486 struct nlreq req;
487 struct msghdr msg;
488 struct iovec iov;
489 struct inet_diag_msg *r;
490 char buf[8192];
492 /* If this fails, it's likely a permission problem. We'll fall back to
493 * reading this information from files below. */
494 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
495 if (fd < 0)
496 {
497 ERROR ("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
498 "NETLINK_INET_DIAG) failed: %s",
499 sstrerror (errno, buf, sizeof (buf)));
500 return (-1);
501 }
503 memset(&nladdr, 0, sizeof(nladdr));
504 nladdr.nl_family = AF_NETLINK;
506 memset(&req, 0, sizeof(req));
507 req.nlh.nlmsg_len = sizeof(req);
508 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
509 /* NLM_F_ROOT: return the complete table instead of a single entry.
510 * NLM_F_MATCH: return all entries matching criteria (not implemented)
511 * NLM_F_REQUEST: must be set on all request messages */
512 req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
513 req.nlh.nlmsg_pid = 0;
514 /* The sequence_number is used to track our messages. Since netlink is not
515 * reliable, we don't want to end up with a corrupt or incomplete old
516 * message in case the system is/was out of memory. */
517 req.nlh.nlmsg_seq = ++sequence_number;
518 req.r.idiag_family = AF_INET;
519 req.r.idiag_states = 0xfff;
520 req.r.idiag_ext = 0;
522 memset(&iov, 0, sizeof(iov));
523 iov.iov_base = &req;
524 iov.iov_len = sizeof(req);
526 memset(&msg, 0, sizeof(msg));
527 msg.msg_name = (void*)&nladdr;
528 msg.msg_namelen = sizeof(nladdr);
529 msg.msg_iov = &iov;
530 msg.msg_iovlen = 1;
532 if (sendmsg (fd, &msg, 0) < 0)
533 {
534 ERROR ("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
535 sstrerror (errno, buf, sizeof (buf)));
536 close (fd);
537 return (-1);
538 }
540 iov.iov_base = buf;
541 iov.iov_len = sizeof(buf);
543 while (1)
544 {
545 int status;
546 struct nlmsghdr *h;
548 memset(&msg, 0, sizeof(msg));
549 msg.msg_name = (void*)&nladdr;
550 msg.msg_namelen = sizeof(nladdr);
551 msg.msg_iov = &iov;
552 msg.msg_iovlen = 1;
554 status = recvmsg(fd, (void *) &msg, /* flags = */ 0);
555 if (status < 0)
556 {
557 if ((errno == EINTR) || (errno == EAGAIN))
558 continue;
560 ERROR ("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
561 sstrerror (errno, buf, sizeof (buf)));
562 close (fd);
563 return (-1);
564 }
565 else if (status == 0)
566 {
567 close (fd);
568 DEBUG ("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
569 "reply from netlink socket.");
570 return (0);
571 }
573 h = (struct nlmsghdr*)buf;
574 while (NLMSG_OK(h, status))
575 {
576 if (h->nlmsg_seq != sequence_number)
577 {
578 h = NLMSG_NEXT(h, status);
579 continue;
580 }
582 if (h->nlmsg_type == NLMSG_DONE)
583 {
584 close (fd);
585 return (0);
586 }
587 else if (h->nlmsg_type == NLMSG_ERROR)
588 {
589 struct nlmsgerr *msg_error;
591 msg_error = NLMSG_DATA(h);
592 WARNING ("tcpconns plugin: conn_read_netlink: Received error %i.",
593 msg_error->error);
595 close (fd);
596 return (1);
597 }
599 r = NLMSG_DATA(h);
601 /* This code does not (need to) distinguish between IPv4 and IPv6. */
602 conn_handle_ports (ntohs(r->id.idiag_sport),
603 ntohs(r->id.idiag_dport),
604 r->idiag_state);
606 h = NLMSG_NEXT(h, status);
607 } /* while (NLMSG_OK) */
608 } /* while (1) */
610 /* Not reached because the while() loop above handles the exit condition. */
611 return (0);
612 } /* int conn_read_netlink */
614 static int conn_handle_line (char *buffer)
615 {
616 char *fields[32];
617 int fields_len;
619 char *endptr;
621 char *port_local_str;
622 char *port_remote_str;
623 uint16_t port_local;
624 uint16_t port_remote;
626 uint8_t state;
628 int buffer_len = strlen (buffer);
630 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
631 buffer[--buffer_len] = '\0';
632 if (buffer_len <= 0)
633 return (-1);
635 fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
636 if (fields_len < 12)
637 {
638 DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
639 return (-1);
640 }
642 port_local_str = strchr (fields[1], ':');
643 port_remote_str = strchr (fields[2], ':');
645 if ((port_local_str == NULL) || (port_remote_str == NULL))
646 return (-1);
647 port_local_str++;
648 port_remote_str++;
649 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
650 return (-1);
652 endptr = NULL;
653 port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
654 if ((endptr == NULL) || (*endptr != '\0'))
655 return (-1);
657 endptr = NULL;
658 port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
659 if ((endptr == NULL) || (*endptr != '\0'))
660 return (-1);
662 endptr = NULL;
663 state = (uint8_t) strtol (fields[3], &endptr, 16);
664 if ((endptr == NULL) || (*endptr != '\0'))
665 return (-1);
667 return (conn_handle_ports (port_local, port_remote, state));
668 } /* int conn_handle_line */
670 static int conn_read_file (const char *file)
671 {
672 FILE *fh;
673 char buffer[1024];
675 fh = fopen (file, "r");
676 if (fh == NULL)
677 return (-1);
679 while (fgets (buffer, sizeof (buffer), fh) != NULL)
680 {
681 conn_handle_line (buffer);
682 } /* while (fgets) */
684 fclose (fh);
686 return (0);
687 } /* int conn_read_file */
688 /* #endif KERNEL_LINUX */
690 #elif HAVE_SYSCTLBYNAME
691 /* #endif HAVE_SYSCTLBYNAME */
693 #elif HAVE_LIBKVM_NLIST
694 #endif /* HAVE_LIBKVM_NLIST */
696 static int conn_config (const char *key, const char *value)
697 {
698 if (strcasecmp (key, "ListeningPorts") == 0)
699 {
700 if (IS_TRUE (value))
701 port_collect_listening = 1;
702 else
703 port_collect_listening = 0;
704 }
705 else if ((strcasecmp (key, "LocalPort") == 0)
706 || (strcasecmp (key, "RemotePort") == 0))
707 {
708 port_entry_t *pe;
709 int port = atoi (value);
711 if ((port < 1) || (port > 65535))
712 {
713 ERROR ("tcpconns plugin: Invalid port: %i", port);
714 return (1);
715 }
717 pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
718 if (pe == NULL)
719 {
720 ERROR ("tcpconns plugin: conn_get_port_entry failed.");
721 return (1);
722 }
724 if (strcasecmp (key, "LocalPort") == 0)
725 pe->flags |= PORT_COLLECT_LOCAL;
726 else
727 pe->flags |= PORT_COLLECT_REMOTE;
728 }
729 else if (strcasecmp (key, "AllPortsSummary") == 0)
730 {
731 if (IS_TRUE (value))
732 port_collect_total = 1;
733 else
734 port_collect_total = 0;
735 }
736 else
737 {
738 return (-1);
739 }
741 return (0);
742 } /* int conn_config */
744 #if KERNEL_LINUX
745 static int conn_init (void)
746 {
747 if (port_list_head == NULL)
748 port_collect_listening = 1;
750 return (0);
751 } /* int conn_init */
753 static int conn_read (void)
754 {
755 int status;
757 conn_reset_port_entry ();
759 if (linux_source == SRC_NETLINK)
760 {
761 status = conn_read_netlink ();
762 }
763 else if (linux_source == SRC_PROC)
764 {
765 int errors_num = 0;
767 if (conn_read_file ("/proc/net/tcp") != 0)
768 errors_num++;
769 if (conn_read_file ("/proc/net/tcp6") != 0)
770 errors_num++;
772 if (errors_num < 2)
773 status = 0;
774 else
775 status = ENOENT;
776 }
777 else /* if (linux_source == SRC_DUNNO) */
778 {
779 /* Try to use netlink for getting this data, it is _much_ faster on systems
780 * with a large amount of connections. */
781 status = conn_read_netlink ();
782 if (status == 0)
783 {
784 INFO ("tcpconns plugin: Reading from netlink succeeded. "
785 "Will use the netlink method from now on.");
786 linux_source = SRC_NETLINK;
787 }
788 else
789 {
790 INFO ("tcpconns plugin: Reading from netlink failed. "
791 "Will read from /proc from now on.");
792 linux_source = SRC_PROC;
794 /* return success here to avoid the "plugin failed" message. */
795 return (0);
796 }
797 }
799 if (status == 0)
800 conn_submit_all ();
801 else
802 return (status);
804 return (0);
805 } /* int conn_read */
806 /* #endif KERNEL_LINUX */
808 #elif HAVE_SYSCTLBYNAME
809 static int conn_read (void)
810 {
811 int status;
812 char *buffer;
813 size_t buffer_len;;
815 struct xinpgen *in_orig;
816 struct xinpgen *in_ptr;
818 conn_reset_port_entry ();
820 buffer_len = 0;
821 status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
822 if (status < 0)
823 {
824 ERROR ("tcpconns plugin: sysctlbyname failed.");
825 return (-1);
826 }
828 buffer = (char *) malloc (buffer_len);
829 if (buffer == NULL)
830 {
831 ERROR ("tcpconns plugin: malloc failed.");
832 return (-1);
833 }
835 status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
836 if (status < 0)
837 {
838 ERROR ("tcpconns plugin: sysctlbyname failed.");
839 sfree (buffer);
840 return (-1);
841 }
843 if (buffer_len <= sizeof (struct xinpgen))
844 {
845 ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
846 sfree (buffer);
847 return (-1);
848 }
850 in_orig = (struct xinpgen *) buffer;
851 for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
852 in_ptr->xig_len > sizeof (struct xinpgen);
853 in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
854 {
855 struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
856 struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
857 struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
859 /* Ignore non-TCP sockets */
860 if (so->xso_protocol != IPPROTO_TCP)
861 continue;
863 /* Ignore PCBs which were freed during copyout. */
864 if (inp->inp_gencnt > in_orig->xig_gen)
865 continue;
867 if (((inp->inp_vflag & INP_IPV4) == 0)
868 && ((inp->inp_vflag & INP_IPV6) == 0))
869 continue;
871 conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
872 tp->t_state);
873 } /* for (in_ptr) */
875 in_orig = NULL;
876 in_ptr = NULL;
877 sfree (buffer);
879 conn_submit_all ();
881 return (0);
882 } /* int conn_read */
883 /* #endif HAVE_SYSCTLBYNAME */
885 #elif HAVE_LIBKVM_NLIST
886 static int kread (u_long addr, void *buf, int size)
887 {
888 int status;
890 status = kvm_read (kvmd, addr, buf, size);
891 if (status != size)
892 {
893 ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
894 status, size, kvm_geterr (kvmd));
895 return (-1);
896 }
897 return (0);
898 } /* int kread */
900 static int conn_init (void)
901 {
902 char buf[_POSIX2_LINE_MAX];
903 struct nlist nl[] =
904 {
905 #define N_TCBTABLE 0
906 { "_tcbtable" },
907 { "" }
908 };
909 int status;
911 kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
912 if (kvmd == NULL)
913 {
914 ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
915 return (-1);
916 }
918 status = kvm_nlist (kvmd, nl);
919 if (status < 0)
920 {
921 ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
922 return (-1);
923 }
925 if (nl[N_TCBTABLE].n_type == 0)
926 {
927 ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
928 "N_TCBTABLE is invalid.");
929 return (-1);
930 }
932 inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
933 inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
935 return (0);
936 } /* int conn_init */
938 static int conn_read (void)
939 {
940 struct inpcbtable table;
941 struct inpcb *head;
942 struct inpcb *next;
943 struct inpcb inpcb;
944 struct tcpcb tcpcb;
945 int status;
947 conn_reset_port_entry ();
949 /* Read the pcbtable from the kernel */
950 status = kread (inpcbtable_off, &table, sizeof (table));
951 if (status != 0)
952 return (-1);
954 /* Get the `head' pcb */
955 head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
956 /* Get the first pcb */
957 next = (struct inpcb *)CIRCLEQ_FIRST (&table.inpt_queue);
959 while (next != head)
960 {
961 /* Read the pcb pointed to by `next' into `inpcb' */
962 kread ((u_long) next, &inpcb, sizeof (inpcb));
964 /* Advance `next' */
965 next = (struct inpcb *)CIRCLEQ_NEXT (&inpcb, inp_queue);
967 /* Ignore sockets, that are not connected. */
968 #ifdef __NetBSD__
969 if (inpcb.inp_af == AF_INET6)
970 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
971 #else
972 if (!(inpcb.inp_flags & INP_IPV6)
973 && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
974 continue;
975 if ((inpcb.inp_flags & INP_IPV6)
976 && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
977 continue;
978 #endif
980 kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
981 conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
982 } /* while (next != head) */
984 conn_submit_all ();
986 return (0);
987 }
988 /* #endif HAVE_LIBKVM_NLIST */
990 #elif KERNEL_AIX
992 static int conn_read (void)
993 {
994 int size;
995 int i;
996 int nconn;
997 void *data;
998 struct netinfo_header *header;
999 struct netinfo_conn *conn;
1001 conn_reset_port_entry ();
1003 size = netinfo(NETINFO_TCP, 0, 0, 0);
1004 if (size < 0)
1005 {
1006 ERROR ("tcpconns plugin: netinfo failed return: %i", size);
1007 return (-1);
1008 }
1010 if (size == 0)
1011 return (0);
1013 if ((size - sizeof (struct netinfo_header)) % sizeof (struct netinfo_conn))
1014 {
1015 ERROR ("tcpconns plugin: invalid buffer size");
1016 return (-1);
1017 }
1019 data = malloc(size);
1020 if (data == NULL)
1021 {
1022 ERROR ("tcpconns plugin: malloc failed");
1023 return (-1);
1024 }
1026 if (netinfo(NETINFO_TCP, data, &size, 0) < 0)
1027 {
1028 ERROR ("tcpconns plugin: netinfo failed");
1029 free(data);
1030 return (-1);
1031 }
1033 header = (struct netinfo_header *)data;
1034 nconn = header->size;
1035 conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1037 for (i=0; i < nconn; conn++, i++)
1038 {
1039 conn_handle_ports (conn->srcport, conn->dstport, conn->tcp_state);
1040 }
1042 free(data);
1044 conn_submit_all ();
1046 return (0);
1047 }
1048 #endif /* KERNEL_AIX */
1050 void module_register (void)
1051 {
1052 plugin_register_config ("tcpconns", conn_config,
1053 config_keys, config_keys_num);
1054 #if KERNEL_LINUX
1055 plugin_register_init ("tcpconns", conn_init);
1056 #elif HAVE_SYSCTLBYNAME
1057 /* no initialization */
1058 #elif HAVE_LIBKVM_NLIST
1059 plugin_register_init ("tcpconns", conn_init);
1060 #elif KERNEL_AIX
1061 /* no initialization */
1062 #endif
1063 plugin_register_read ("tcpconns", conn_read);
1064 } /* void module_register */
1066 /*
1067 * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :
1068 */