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 collectd.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
65 #if defined(__OpenBSD__)
66 #define HAVE_KVM_GETFILES 1
69 #if defined(__NetBSD__)
70 #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */
73 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_KVM_GETFILES && !HAVE_LIBKVM_NLIST && !KERNEL_AIX
74 #error "No applicable input method."
78 #include <asm/types.h>
79 #include <linux/netlink.h>
80 #if HAVE_LINUX_INET_DIAG_H
81 #include <linux/inet_diag.h>
83 #include <arpa/inet.h>
84 /* #endif KERNEL_LINUX */
86 #elif HAVE_SYSCTLBYNAME
87 #include <sys/socketvar.h>
88 #include <sys/sysctl.h>
90 /* Some includes needed for compiling on FreeBSD */
93 #include <sys/types.h>
99 #include <net/route.h>
100 #include <netinet/in.h>
101 #include <netinet/in_pcb.h>
102 #include <netinet/in_systm.h>
103 #include <netinet/ip.h>
104 #include <netinet/ip6.h>
105 #include <netinet/ip_var.h>
106 #include <netinet/tcp.h>
107 #include <netinet/tcp_seq.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet/tcpip.h>
110 /* #endif HAVE_SYSCTLBYNAME */
112 #elif HAVE_KVM_GETFILES
113 #include <sys/types.h>
114 #include <sys/sysctl.h>
115 #define _KERNEL /* for DTYPE_SOCKET */
116 #include <sys/file.h>
119 #include <netinet/in.h>
122 /* #endif HAVE_KVM_GETFILES */
124 /* This is for NetBSD. */
125 #elif HAVE_LIBKVM_NLIST
126 #include <arpa/inet.h>
127 #include <net/route.h>
129 #include <netinet/in.h>
130 #include <netinet/ip.h>
131 #include <netinet/in_pcb.h>
132 #include <netinet/in_systm.h>
133 #include <netinet/ip_var.h>
134 #include <netinet/tcp.h>
135 #include <netinet/tcp_timer.h>
136 #include <netinet/tcp_var.h>
137 #include <sys/queue.h>
138 #if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
140 #else /* HAVE_BSD_NLIST_H */
141 #include <bsd/nlist.h>
144 /* #endif HAVE_LIBKVM_NLIST */
147 #include <arpa/inet.h>
148 #include <sys/socketvar.h>
149 #endif /* KERNEL_AIX */
152 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
155 struct inet_diag_req r;
159 static const char *tcp_state[] = {"", /* 0 */
172 #define TCP_STATE_LISTEN 10
173 #define TCP_STATE_MIN 1
174 #define TCP_STATE_MAX 11
175 /* #endif KERNEL_LINUX */
177 #elif HAVE_SYSCTLBYNAME
178 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
179 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
180 "FIN_WAIT1", "CLOSING", "LAST_ACK",
181 "FIN_WAIT2", "TIME_WAIT"};
183 #define TCP_STATE_LISTEN 1
184 #define TCP_STATE_MIN 0
185 #define TCP_STATE_MAX 10
186 /* #endif HAVE_SYSCTLBYNAME */
188 #elif HAVE_KVM_GETFILES
189 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
190 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
191 "FIN_WAIT1", "CLOSING", "LAST_ACK",
192 "FIN_WAIT2", "TIME_WAIT"};
194 #define TCP_STATE_LISTEN 1
195 #define TCP_STATE_MIN 0
196 #define TCP_STATE_MAX 10
199 /* #endif HAVE_KVM_GETFILES */
201 #elif HAVE_LIBKVM_NLIST
202 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
203 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
204 "FIN_WAIT1", "CLOSING", "LAST_ACK",
205 "FIN_WAIT2", "TIME_WAIT"};
208 static u_long inpcbtable_off = 0;
209 struct inpcbtable *inpcbtable_ptr = NULL;
211 #define TCP_STATE_LISTEN 1
212 #define TCP_STATE_MIN 1
213 #define TCP_STATE_MAX 10
214 /* #endif HAVE_LIBKVM_NLIST */
217 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
218 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
219 "FIN_WAIT1", "CLOSING", "LAST_ACK",
220 "FIN_WAIT2", "TIME_WAIT"};
222 #define TCP_STATE_LISTEN 1
223 #define TCP_STATE_MIN 0
224 #define TCP_STATE_MAX 10
226 struct netinfo_conn {
230 struct in6_addr dstaddr;
233 struct in6_addr srcaddr;
234 uint32_t unknow4[36];
239 struct netinfo_header {
244 #define NETINFO_TCP 3
245 extern int netinfo(int proto, void *data, int *size, int n);
246 #endif /* KERNEL_AIX */
248 #define PORT_COLLECT_LOCAL 0x01
249 #define PORT_COLLECT_REMOTE 0x02
250 #define PORT_IS_LISTENING 0x04
252 typedef struct port_entry_s {
255 uint32_t count_local[TCP_STATE_MAX + 1];
256 uint32_t count_remote[TCP_STATE_MAX + 1];
257 struct port_entry_s *next;
260 static const char *config_keys[] = {"ListeningPorts", "LocalPort", "RemotePort",
262 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
264 static int port_collect_listening = 0;
265 static int port_collect_total = 0;
266 static port_entry_t *port_list_head = NULL;
267 static uint32_t count_total[TCP_STATE_MAX + 1];
270 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
271 /* This depends on linux inet_diag_req because if this structure is missing,
272 * sequence_number is useless and we get a compilation warning.
274 static uint32_t sequence_number = 0;
277 static enum { SRC_DUNNO, SRC_NETLINK, SRC_PROC } linux_source = SRC_DUNNO;
280 static void conn_prepare_vl(value_list_t *vl, value_t *values) {
283 sstrncpy(vl->plugin, "tcpconns", sizeof(vl->plugin));
284 sstrncpy(vl->type, "tcp_connections", sizeof(vl->type));
287 static void conn_submit_port_entry(port_entry_t *pe) {
289 value_list_t vl = VALUE_LIST_INIT;
291 conn_prepare_vl(&vl, values);
293 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING)) ||
294 (pe->flags & PORT_COLLECT_LOCAL)) {
295 ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
296 "%" PRIu16 "-local", pe->port);
298 for (int i = 1; i <= TCP_STATE_MAX; i++) {
299 vl.values[0].gauge = pe->count_local[i];
301 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
303 plugin_dispatch_values(&vl);
307 if (pe->flags & PORT_COLLECT_REMOTE) {
308 ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
309 "%" PRIu16 "-remote", pe->port);
311 for (int i = 1; i <= TCP_STATE_MAX; i++) {
312 vl.values[0].gauge = pe->count_remote[i];
314 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
316 plugin_dispatch_values(&vl);
319 } /* void conn_submit */
321 static void conn_submit_port_total(void) {
323 value_list_t vl = VALUE_LIST_INIT;
325 conn_prepare_vl(&vl, values);
327 sstrncpy(vl.plugin_instance, "all", sizeof(vl.plugin_instance));
329 for (int i = 1; i <= TCP_STATE_MAX; i++) {
330 vl.values[0].gauge = count_total[i];
332 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
334 plugin_dispatch_values(&vl);
338 static void conn_submit_all(void) {
339 if (port_collect_total)
340 conn_submit_port_total();
342 for (port_entry_t *pe = port_list_head; pe != NULL; pe = pe->next)
343 conn_submit_port_entry(pe);
344 } /* void conn_submit_all */
346 static port_entry_t *conn_get_port_entry(uint16_t port, int create) {
349 ret = port_list_head;
350 while (ret != NULL) {
351 if (ret->port == port)
356 if ((ret == NULL) && (create != 0)) {
357 ret = calloc(1, sizeof(*ret));
362 ret->next = port_list_head;
363 port_list_head = ret;
367 } /* port_entry_t *conn_get_port_entry */
369 /* Removes ports that were added automatically due to the `ListeningPorts'
370 * setting but which are no longer listening. */
371 static void conn_reset_port_entry(void) {
372 port_entry_t *prev = NULL;
373 port_entry_t *pe = port_list_head;
375 memset(&count_total, '\0', sizeof(count_total));
378 /* If this entry was created while reading the files (ant not when handling
379 * the configuration) remove it now. */
381 (PORT_COLLECT_LOCAL | PORT_COLLECT_REMOTE | PORT_IS_LISTENING)) == 0) {
382 port_entry_t *next = pe->next;
384 DEBUG("tcpconns plugin: Removing temporary entry "
385 "for listening port %" PRIu16,
389 port_list_head = next;
399 memset(pe->count_local, '\0', sizeof(pe->count_local));
400 memset(pe->count_remote, '\0', sizeof(pe->count_remote));
401 pe->flags &= ~PORT_IS_LISTENING;
406 } /* void conn_reset_port_entry */
408 static int conn_handle_ports(uint16_t port_local, uint16_t port_remote,
410 port_entry_t *pe = NULL;
412 if ((state > TCP_STATE_MAX)
413 #if TCP_STATE_MIN > 0
414 || (state < TCP_STATE_MIN)
417 NOTICE("tcpconns plugin: Ignoring connection with "
418 "unknown state 0x%02" PRIx8 ".",
423 count_total[state]++;
425 /* Listening sockets */
426 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0)) {
427 pe = conn_get_port_entry(port_local, 1 /* create */);
429 pe->flags |= PORT_IS_LISTENING;
432 DEBUG("tcpconns plugin: Connection %" PRIu16 " <-> %" PRIu16 " (%s)",
433 port_local, port_remote, tcp_state[state]);
435 pe = conn_get_port_entry(port_local, 0 /* no create */);
437 pe->count_local[state]++;
439 pe = conn_get_port_entry(port_remote, 0 /* no create */);
441 pe->count_remote[state]++;
444 } /* int conn_handle_ports */
447 /* Returns zero on success, less than zero on socket error and greater than
448 * zero on other errors. */
449 static int conn_read_netlink(void) {
450 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
452 struct inet_diag_msg *r;
455 /* If this fails, it's likely a permission problem. We'll fall back to
456 * reading this information from files below. */
457 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
459 ERROR("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
460 "NETLINK_INET_DIAG) failed: %s",
461 sstrerror(errno, buf, sizeof(buf)));
465 struct sockaddr_nl nladdr = {.nl_family = AF_NETLINK};
468 .nlh.nlmsg_len = sizeof(req),
469 .nlh.nlmsg_type = TCPDIAG_GETSOCK,
470 /* NLM_F_ROOT: return the complete table instead of a single entry.
471 * NLM_F_MATCH: return all entries matching criteria (not implemented)
472 * NLM_F_REQUEST: must be set on all request messages */
473 .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
475 /* The sequence_number is used to track our messages. Since netlink is not
476 * reliable, we don't want to end up with a corrupt or incomplete old
477 * message in case the system is/was out of memory. */
478 .nlh.nlmsg_seq = ++sequence_number,
479 .r.idiag_family = AF_INET,
480 .r.idiag_states = 0xfff,
483 struct iovec iov = {.iov_base = &req, .iov_len = sizeof(req)};
485 struct msghdr msg = {.msg_name = (void *)&nladdr,
486 .msg_namelen = sizeof(nladdr),
490 if (sendmsg(fd, &msg, 0) < 0) {
491 ERROR("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
492 sstrerror(errno, buf, sizeof(buf)));
498 iov.iov_len = sizeof(buf);
504 memset(&msg, 0, sizeof(msg));
505 msg.msg_name = (void *)&nladdr;
506 msg.msg_namelen = sizeof(nladdr);
510 status = recvmsg(fd, (void *)&msg, /* flags = */ 0);
512 if ((errno == EINTR) || (errno == EAGAIN))
515 ERROR("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
516 sstrerror(errno, buf, sizeof(buf)));
519 } else if (status == 0) {
521 DEBUG("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
522 "reply from netlink socket.");
526 h = (struct nlmsghdr *)buf;
527 while (NLMSG_OK(h, status)) {
528 if (h->nlmsg_seq != sequence_number) {
529 h = NLMSG_NEXT(h, status);
533 if (h->nlmsg_type == NLMSG_DONE) {
536 } else if (h->nlmsg_type == NLMSG_ERROR) {
537 struct nlmsgerr *msg_error;
539 msg_error = NLMSG_DATA(h);
540 WARNING("tcpconns plugin: conn_read_netlink: Received error %i.",
549 /* This code does not (need to) distinguish between IPv4 and IPv6. */
550 conn_handle_ports(ntohs(r->id.idiag_sport), ntohs(r->id.idiag_dport),
553 h = NLMSG_NEXT(h, status);
554 } /* while (NLMSG_OK) */
557 /* Not reached because the while() loop above handles the exit condition. */
561 #endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
562 } /* int conn_read_netlink */
564 static int conn_handle_line(char *buffer) {
570 char *port_local_str;
571 char *port_remote_str;
573 uint16_t port_remote;
577 int buffer_len = strlen(buffer);
579 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
580 buffer[--buffer_len] = '\0';
584 fields_len = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
585 if (fields_len < 12) {
586 DEBUG("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
590 port_local_str = strchr(fields[1], ':');
591 port_remote_str = strchr(fields[2], ':');
593 if ((port_local_str == NULL) || (port_remote_str == NULL))
597 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
601 port_local = (uint16_t)strtol(port_local_str, &endptr, 16);
602 if ((endptr == NULL) || (*endptr != '\0'))
606 port_remote = (uint16_t)strtol(port_remote_str, &endptr, 16);
607 if ((endptr == NULL) || (*endptr != '\0'))
611 state = (uint8_t)strtol(fields[3], &endptr, 16);
612 if ((endptr == NULL) || (*endptr != '\0'))
615 return (conn_handle_ports(port_local, port_remote, state));
616 } /* int conn_handle_line */
618 static int conn_read_file(const char *file) {
622 fh = fopen(file, "r");
626 while (fgets(buffer, sizeof(buffer), fh) != NULL) {
627 conn_handle_line(buffer);
628 } /* while (fgets) */
633 } /* int conn_read_file */
634 /* #endif KERNEL_LINUX */
636 #elif HAVE_SYSCTLBYNAME
637 /* #endif HAVE_SYSCTLBYNAME */
639 #elif HAVE_LIBKVM_NLIST
640 #endif /* HAVE_LIBKVM_NLIST */
642 static int conn_config(const char *key, const char *value) {
643 if (strcasecmp(key, "ListeningPorts") == 0) {
645 port_collect_listening = 1;
647 port_collect_listening = 0;
648 } else if ((strcasecmp(key, "LocalPort") == 0) ||
649 (strcasecmp(key, "RemotePort") == 0)) {
651 int port = atoi(value);
653 if ((port < 1) || (port > 65535)) {
654 ERROR("tcpconns plugin: Invalid port: %i", port);
658 pe = conn_get_port_entry((uint16_t)port, 1 /* create */);
660 ERROR("tcpconns plugin: conn_get_port_entry failed.");
664 if (strcasecmp(key, "LocalPort") == 0)
665 pe->flags |= PORT_COLLECT_LOCAL;
667 pe->flags |= PORT_COLLECT_REMOTE;
668 } else if (strcasecmp(key, "AllPortsSummary") == 0) {
670 port_collect_total = 1;
672 port_collect_total = 0;
678 } /* int conn_config */
681 static int conn_init(void) {
682 if (port_collect_total == 0 && port_list_head == NULL)
683 port_collect_listening = 1;
686 } /* int conn_init */
688 static int conn_read(void) {
691 conn_reset_port_entry();
693 if (linux_source == SRC_NETLINK) {
694 status = conn_read_netlink();
695 } else if (linux_source == SRC_PROC) {
698 if (conn_read_file("/proc/net/tcp") != 0)
700 if (conn_read_file("/proc/net/tcp6") != 0)
707 } else /* if (linux_source == SRC_DUNNO) */
709 /* Try to use netlink for getting this data, it is _much_ faster on systems
710 * with a large amount of connections. */
711 status = conn_read_netlink();
713 INFO("tcpconns plugin: Reading from netlink succeeded. "
714 "Will use the netlink method from now on.");
715 linux_source = SRC_NETLINK;
717 INFO("tcpconns plugin: Reading from netlink failed. "
718 "Will read from /proc from now on.");
719 linux_source = SRC_PROC;
721 /* return success here to avoid the "plugin failed" message. */
732 } /* int conn_read */
733 /* #endif KERNEL_LINUX */
735 #elif HAVE_SYSCTLBYNAME
736 static int conn_read(void) {
742 struct xinpgen *in_orig;
743 struct xinpgen *in_ptr;
745 conn_reset_port_entry();
748 status = sysctlbyname("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
750 ERROR("tcpconns plugin: sysctlbyname failed.");
754 buffer = malloc(buffer_len);
755 if (buffer == NULL) {
756 ERROR("tcpconns plugin: malloc failed.");
760 status = sysctlbyname("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
762 ERROR("tcpconns plugin: sysctlbyname failed.");
767 if (buffer_len <= sizeof(struct xinpgen)) {
768 ERROR("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
773 in_orig = (struct xinpgen *)buffer;
774 for (in_ptr = (struct xinpgen *)(((char *)in_orig) + in_orig->xig_len);
775 in_ptr->xig_len > sizeof(struct xinpgen);
776 in_ptr = (struct xinpgen *)(((char *)in_ptr) + in_ptr->xig_len)) {
777 struct tcpcb *tp = &((struct xtcpcb *)in_ptr)->xt_tp;
778 struct inpcb *inp = &((struct xtcpcb *)in_ptr)->xt_inp;
779 struct xsocket *so = &((struct xtcpcb *)in_ptr)->xt_socket;
781 /* Ignore non-TCP sockets */
782 if (so->xso_protocol != IPPROTO_TCP)
785 /* Ignore PCBs which were freed during copyout. */
786 if (inp->inp_gencnt > in_orig->xig_gen)
789 if (((inp->inp_vflag & INP_IPV4) == 0) &&
790 ((inp->inp_vflag & INP_IPV6) == 0))
793 conn_handle_ports(ntohs(inp->inp_lport), ntohs(inp->inp_fport),
804 } /* int conn_read */
805 /* #endif HAVE_SYSCTLBYNAME */
807 #elif HAVE_KVM_GETFILES
809 static int conn_init(void) {
810 char buf[_POSIX2_LINE_MAX];
812 kvmd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
814 ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
819 } /* int conn_init */
821 static int conn_read(void) {
822 struct kinfo_file *kf;
825 conn_reset_port_entry();
827 kf = kvm_getfiles(kvmd, KERN_FILE_BYFILE, DTYPE_SOCKET,
830 ERROR("tcpconns plugin: kvm_getfiles failed.");
834 for (i = 0; i < fcnt; i++) {
835 if (kf[i].so_protocol != IPPROTO_TCP)
837 if (kf[i].inp_fport == 0)
839 conn_handle_ports(ntohs(kf[i].inp_lport), ntohs(kf[i].inp_fport),
848 /* #endif HAVE_KVM_GETFILES */
850 #elif HAVE_LIBKVM_NLIST
851 static int kread(u_long addr, void *buf, int size) {
854 status = kvm_read(kvmd, addr, buf, size);
855 if (status != size) {
856 ERROR("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
857 status, size, kvm_geterr(kvmd));
863 static int conn_init(void) {
864 char buf[_POSIX2_LINE_MAX];
865 struct nlist nl[] = {
867 {"_tcbtable"}, {""}};
870 kvmd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, buf);
872 ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
876 status = kvm_nlist(kvmd, nl);
878 ERROR("tcpconns plugin: kvm_nlist failed with status %i.", status);
882 if (nl[N_TCBTABLE].n_type == 0) {
883 ERROR("tcpconns plugin: Error looking up kernel's namelist: "
884 "N_TCBTABLE is invalid.");
888 inpcbtable_off = (u_long)nl[N_TCBTABLE].n_value;
889 inpcbtable_ptr = (struct inpcbtable *)nl[N_TCBTABLE].n_value;
892 } /* int conn_init */
894 static int conn_read(void) {
895 struct inpcbtable table;
896 #if !defined(__OpenBSD__) && \
897 (defined(__NetBSD_Version__) && __NetBSD_Version__ <= 699002700)
905 conn_reset_port_entry();
907 /* Read the pcbtable from the kernel */
908 status = kread(inpcbtable_off, &table, sizeof(table));
912 #if defined(__OpenBSD__) || \
913 (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
914 /* inpt_queue is a TAILQ on OpenBSD */
915 /* Get the first pcb */
916 next = (struct inpcb *)TAILQ_FIRST(&table.inpt_queue);
919 /* Get the `head' pcb */
920 head = (struct inpcb *)&(inpcbtable_ptr->inpt_queue);
921 /* Get the first pcb */
922 next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue);
927 /* Read the pcb pointed to by `next' into `inpcb' */
928 status = kread((u_long)next, &inpcb, sizeof(inpcb));
933 #if defined(__OpenBSD__) || \
934 (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
935 /* inpt_queue is a TAILQ on OpenBSD */
936 next = (struct inpcb *)TAILQ_NEXT(&inpcb, inp_queue);
938 next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue);
941 /* Ignore sockets, that are not connected. */
943 if (inpcb.inp_af == AF_INET6)
944 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
946 if (!(inpcb.inp_flags & INP_IPV6) &&
947 (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
949 if ((inpcb.inp_flags & INP_IPV6) &&
950 IN6_IS_ADDR_UNSPECIFIED(&inpcb.inp_laddr6))
954 status = kread((u_long)inpcb.inp_ppcb, &tcpcb, sizeof(tcpcb));
957 conn_handle_ports(ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport),
959 } /* while (next != head) */
965 /* #endif HAVE_LIBKVM_NLIST */
969 static int conn_read(void) {
973 struct netinfo_header *header;
974 struct netinfo_conn *conn;
976 conn_reset_port_entry();
978 size = netinfo(NETINFO_TCP, 0, 0, 0);
980 ERROR("tcpconns plugin: netinfo failed return: %i", size);
987 if ((size - sizeof(struct netinfo_header)) % sizeof(struct netinfo_conn)) {
988 ERROR("tcpconns plugin: invalid buffer size");
994 ERROR("tcpconns plugin: malloc failed");
998 if (netinfo(NETINFO_TCP, data, &size, 0) < 0) {
999 ERROR("tcpconns plugin: netinfo failed");
1004 header = (struct netinfo_header *)data;
1005 nconn = header->size;
1006 conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1008 for (int i = 0; i < nconn; conn++, i++) {
1009 conn_handle_ports(conn->srcport, conn->dstport, conn->tcp_state);
1018 #endif /* KERNEL_AIX */
1020 void module_register(void) {
1021 plugin_register_config("tcpconns", conn_config, config_keys, config_keys_num);
1023 plugin_register_init("tcpconns", conn_init);
1024 #elif HAVE_SYSCTLBYNAME
1025 /* no initialization */
1026 #elif HAVE_LIBKVM_NLIST
1027 plugin_register_init("tcpconns", conn_init);
1029 /* no initialization */
1031 plugin_register_read("tcpconns", conn_read);
1032 } /* void module_register */