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 && \
74 !HAVE_LIBKVM_NLIST && !KERNEL_AIX
75 #error "No applicable input method."
79 #include <asm/types.h>
80 #include <linux/netlink.h>
81 #if HAVE_LINUX_INET_DIAG_H
82 #include <linux/inet_diag.h>
84 #include <arpa/inet.h>
85 /* #endif KERNEL_LINUX */
87 #elif HAVE_SYSCTLBYNAME
88 #include <sys/socketvar.h>
89 #include <sys/sysctl.h>
91 /* Some includes needed for compiling on FreeBSD */
94 #include <sys/types.h>
100 #include <net/route.h>
101 #include <netinet/in.h>
102 #include <netinet/in_pcb.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip6.h>
106 #include <netinet/ip_var.h>
107 #include <netinet/tcp.h>
108 #include <netinet/tcp_seq.h>
109 #include <netinet/tcp_var.h>
110 #include <netinet/tcpip.h>
111 /* #endif HAVE_SYSCTLBYNAME */
113 #elif HAVE_KVM_GETFILES
114 #include <sys/sysctl.h>
115 #include <sys/types.h>
116 #define _KERNEL /* for DTYPE_SOCKET */
117 #include <sys/file.h>
120 #include <netinet/in.h>
123 /* #endif HAVE_KVM_GETFILES */
125 /* This is for NetBSD. */
126 #elif HAVE_LIBKVM_NLIST
127 #include <arpa/inet.h>
128 #include <net/route.h>
130 #include <netinet/in.h>
131 #include <netinet/in_pcb.h>
132 #include <netinet/in_systm.h>
133 #include <netinet/ip.h>
134 #include <netinet/ip_var.h>
135 #include <netinet/tcp.h>
136 #include <netinet/tcp_timer.h>
137 #include <netinet/tcp_var.h>
138 #include <sys/queue.h>
139 #if !defined(HAVE_BSD_NLIST_H) || !HAVE_BSD_NLIST_H
141 #else /* HAVE_BSD_NLIST_H */
142 #include <bsd/nlist.h>
145 /* #endif HAVE_LIBKVM_NLIST */
148 #include <arpa/inet.h>
149 #include <sys/socketvar.h>
150 #endif /* KERNEL_AIX */
153 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
156 struct inet_diag_req r;
160 static const char *tcp_state[] = {"", /* 0 */
173 #define TCP_STATE_LISTEN 10
174 #define TCP_STATE_MIN 1
175 #define TCP_STATE_MAX 11
176 /* #endif KERNEL_LINUX */
178 #elif HAVE_SYSCTLBYNAME
179 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
180 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
181 "FIN_WAIT1", "CLOSING", "LAST_ACK",
182 "FIN_WAIT2", "TIME_WAIT"};
184 #define TCP_STATE_LISTEN 1
185 #define TCP_STATE_MIN 0
186 #define TCP_STATE_MAX 10
187 /* #endif HAVE_SYSCTLBYNAME */
189 #elif HAVE_KVM_GETFILES
190 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
191 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
192 "FIN_WAIT1", "CLOSING", "LAST_ACK",
193 "FIN_WAIT2", "TIME_WAIT"};
195 #define TCP_STATE_LISTEN 1
196 #define TCP_STATE_MIN 0
197 #define TCP_STATE_MAX 10
200 /* #endif HAVE_KVM_GETFILES */
202 #elif HAVE_LIBKVM_NLIST
203 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
204 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
205 "FIN_WAIT1", "CLOSING", "LAST_ACK",
206 "FIN_WAIT2", "TIME_WAIT"};
209 static u_long inpcbtable_off = 0;
210 struct inpcbtable *inpcbtable_ptr = NULL;
212 #define TCP_STATE_LISTEN 1
213 #define TCP_STATE_MIN 1
214 #define TCP_STATE_MAX 10
215 /* #endif HAVE_LIBKVM_NLIST */
218 static const char *tcp_state[] = {"CLOSED", "LISTEN", "SYN_SENT",
219 "SYN_RECV", "ESTABLISHED", "CLOSE_WAIT",
220 "FIN_WAIT1", "CLOSING", "LAST_ACK",
221 "FIN_WAIT2", "TIME_WAIT"};
223 #define TCP_STATE_LISTEN 1
224 #define TCP_STATE_MIN 0
225 #define TCP_STATE_MAX 10
227 struct netinfo_conn {
231 struct in6_addr dstaddr;
234 struct in6_addr srcaddr;
235 uint32_t unknow4[36];
240 struct netinfo_header {
245 #define NETINFO_TCP 3
246 extern int netinfo(int proto, void *data, int *size, int n);
247 #endif /* KERNEL_AIX */
249 #define PORT_COLLECT_LOCAL 0x01
250 #define PORT_COLLECT_REMOTE 0x02
251 #define PORT_IS_LISTENING 0x04
253 typedef struct port_entry_s {
256 uint32_t count_local[TCP_STATE_MAX + 1];
257 uint32_t count_remote[TCP_STATE_MAX + 1];
258 struct port_entry_s *next;
261 static const char *config_keys[] = {"ListeningPorts", "LocalPort", "RemotePort",
263 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
265 static int port_collect_listening = 0;
266 static int port_collect_total = 0;
267 static port_entry_t *port_list_head = NULL;
268 static uint32_t count_total[TCP_STATE_MAX + 1];
271 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
272 /* This depends on linux inet_diag_req because if this structure is missing,
273 * sequence_number is useless and we get a compilation warning.
275 static uint32_t sequence_number = 0;
278 static enum { SRC_DUNNO, SRC_NETLINK, SRC_PROC } linux_source = SRC_DUNNO;
281 static void conn_prepare_vl(value_list_t *vl, value_t *values) {
284 sstrncpy(vl->plugin, "tcpconns", sizeof(vl->plugin));
285 sstrncpy(vl->type, "tcp_connections", sizeof(vl->type));
288 static void conn_submit_port_entry(port_entry_t *pe) {
290 value_list_t vl = VALUE_LIST_INIT;
292 conn_prepare_vl(&vl, values);
294 if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING)) ||
295 (pe->flags & PORT_COLLECT_LOCAL)) {
296 snprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
297 "%" PRIu16 "-local", pe->port);
299 for (int i = 1; i <= TCP_STATE_MAX; i++) {
300 vl.values[0].gauge = pe->count_local[i];
302 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
304 plugin_dispatch_values(&vl);
308 if (pe->flags & PORT_COLLECT_REMOTE) {
309 snprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
310 "%" PRIu16 "-remote", pe->port);
312 for (int i = 1; i <= TCP_STATE_MAX; i++) {
313 vl.values[0].gauge = pe->count_remote[i];
315 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
317 plugin_dispatch_values(&vl);
320 } /* void conn_submit */
322 static void conn_submit_port_total(void) {
324 value_list_t vl = VALUE_LIST_INIT;
326 conn_prepare_vl(&vl, values);
328 sstrncpy(vl.plugin_instance, "all", sizeof(vl.plugin_instance));
330 for (int i = 1; i <= TCP_STATE_MAX; i++) {
331 vl.values[0].gauge = count_total[i];
333 sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
335 plugin_dispatch_values(&vl);
339 static void conn_submit_all(void) {
340 if (port_collect_total)
341 conn_submit_port_total();
343 for (port_entry_t *pe = port_list_head; pe != NULL; pe = pe->next)
344 conn_submit_port_entry(pe);
345 } /* void conn_submit_all */
347 static port_entry_t *conn_get_port_entry(uint16_t port, int create) {
350 ret = port_list_head;
351 while (ret != NULL) {
352 if (ret->port == port)
357 if ((ret == NULL) && (create != 0)) {
358 ret = calloc(1, sizeof(*ret));
363 ret->next = port_list_head;
364 port_list_head = ret;
368 } /* port_entry_t *conn_get_port_entry */
370 /* Removes ports that were added automatically due to the `ListeningPorts'
371 * setting but which are no longer listening. */
372 static void conn_reset_port_entry(void) {
373 port_entry_t *prev = NULL;
374 port_entry_t *pe = port_list_head;
376 memset(&count_total, '\0', sizeof(count_total));
379 /* If this entry was created while reading the files (ant not when handling
380 * the configuration) remove it now. */
382 (PORT_COLLECT_LOCAL | PORT_COLLECT_REMOTE | PORT_IS_LISTENING)) == 0) {
383 port_entry_t *next = pe->next;
385 DEBUG("tcpconns plugin: Removing temporary entry "
386 "for listening port %" PRIu16,
390 port_list_head = next;
400 memset(pe->count_local, '\0', sizeof(pe->count_local));
401 memset(pe->count_remote, '\0', sizeof(pe->count_remote));
402 pe->flags &= ~PORT_IS_LISTENING;
407 } /* void conn_reset_port_entry */
409 static int conn_handle_ports(uint16_t port_local, uint16_t port_remote,
411 port_entry_t *pe = NULL;
413 if ((state > TCP_STATE_MAX)
414 #if TCP_STATE_MIN > 0
415 || (state < TCP_STATE_MIN)
418 NOTICE("tcpconns plugin: Ignoring connection with "
419 "unknown state 0x%02" PRIx8 ".",
424 count_total[state]++;
426 /* Listening sockets */
427 if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0)) {
428 pe = conn_get_port_entry(port_local, 1 /* create */);
430 pe->flags |= PORT_IS_LISTENING;
433 DEBUG("tcpconns plugin: Connection %" PRIu16 " <-> %" PRIu16 " (%s)",
434 port_local, port_remote, tcp_state[state]);
436 pe = conn_get_port_entry(port_local, 0 /* no create */);
438 pe->count_local[state]++;
440 pe = conn_get_port_entry(port_remote, 0 /* no create */);
442 pe->count_remote[state]++;
445 } /* int conn_handle_ports */
448 /* Returns zero on success, less than zero on socket error and greater than
449 * zero on other errors. */
450 static int conn_read_netlink(void) {
451 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
453 struct inet_diag_msg *r;
456 /* If this fails, it's likely a permission problem. We'll fall back to
457 * reading this information from files below. */
458 fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG);
460 ERROR("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
461 "NETLINK_INET_DIAG) failed: %s",
462 sstrerror(errno, buf, sizeof(buf)));
466 struct sockaddr_nl nladdr = {.nl_family = AF_NETLINK};
469 .nlh.nlmsg_len = sizeof(req),
470 .nlh.nlmsg_type = TCPDIAG_GETSOCK,
471 /* NLM_F_ROOT: return the complete table instead of a single entry.
472 * NLM_F_MATCH: return all entries matching criteria (not implemented)
473 * NLM_F_REQUEST: must be set on all request messages */
474 .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
476 /* The sequence_number is used to track our messages. Since netlink is not
477 * reliable, we don't want to end up with a corrupt or incomplete old
478 * message in case the system is/was out of memory. */
479 .nlh.nlmsg_seq = ++sequence_number,
480 .r.idiag_family = AF_INET,
481 .r.idiag_states = 0xfff,
484 struct iovec iov = {.iov_base = &req, .iov_len = sizeof(req)};
486 struct msghdr msg = {.msg_name = (void *)&nladdr,
487 .msg_namelen = sizeof(nladdr),
491 if (sendmsg(fd, &msg, 0) < 0) {
492 ERROR("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
493 sstrerror(errno, buf, sizeof(buf)));
499 iov.iov_len = sizeof(buf);
505 memset(&msg, 0, sizeof(msg));
506 msg.msg_name = (void *)&nladdr;
507 msg.msg_namelen = sizeof(nladdr);
511 status = recvmsg(fd, (void *)&msg, /* flags = */ 0);
513 if ((errno == EINTR) || (errno == EAGAIN))
516 ERROR("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
517 sstrerror(errno, buf, sizeof(buf)));
520 } else if (status == 0) {
522 DEBUG("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
523 "reply from netlink socket.");
527 h = (struct nlmsghdr *)buf;
528 while (NLMSG_OK(h, status)) {
529 if (h->nlmsg_seq != sequence_number) {
530 h = NLMSG_NEXT(h, status);
534 if (h->nlmsg_type == NLMSG_DONE) {
537 } else if (h->nlmsg_type == NLMSG_ERROR) {
538 struct nlmsgerr *msg_error;
540 msg_error = NLMSG_DATA(h);
541 WARNING("tcpconns plugin: conn_read_netlink: Received error %i.",
550 /* This code does not (need to) distinguish between IPv4 and IPv6. */
551 conn_handle_ports(ntohs(r->id.idiag_sport), ntohs(r->id.idiag_dport),
554 h = NLMSG_NEXT(h, status);
555 } /* while (NLMSG_OK) */
558 /* Not reached because the while() loop above handles the exit condition. */
562 #endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
563 } /* int conn_read_netlink */
565 static int conn_handle_line(char *buffer) {
571 char *port_local_str;
572 char *port_remote_str;
574 uint16_t port_remote;
578 int buffer_len = strlen(buffer);
580 while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
581 buffer[--buffer_len] = '\0';
585 fields_len = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
586 if (fields_len < 12) {
587 DEBUG("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
591 port_local_str = strchr(fields[1], ':');
592 port_remote_str = strchr(fields[2], ':');
594 if ((port_local_str == NULL) || (port_remote_str == NULL))
598 if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
602 port_local = (uint16_t)strtol(port_local_str, &endptr, 16);
603 if ((endptr == NULL) || (*endptr != '\0'))
607 port_remote = (uint16_t)strtol(port_remote_str, &endptr, 16);
608 if ((endptr == NULL) || (*endptr != '\0'))
612 state = (uint8_t)strtol(fields[3], &endptr, 16);
613 if ((endptr == NULL) || (*endptr != '\0'))
616 return conn_handle_ports(port_local, port_remote, state);
617 } /* int conn_handle_line */
619 static int conn_read_file(const char *file) {
623 fh = fopen(file, "r");
627 while (fgets(buffer, sizeof(buffer), fh) != NULL) {
628 conn_handle_line(buffer);
629 } /* while (fgets) */
634 } /* int conn_read_file */
635 /* #endif KERNEL_LINUX */
637 #elif HAVE_SYSCTLBYNAME
638 /* #endif HAVE_SYSCTLBYNAME */
640 #elif HAVE_LIBKVM_NLIST
641 #endif /* HAVE_LIBKVM_NLIST */
643 static int conn_config(const char *key, const char *value) {
644 if (strcasecmp(key, "ListeningPorts") == 0) {
646 port_collect_listening = 1;
648 port_collect_listening = 0;
649 } else if ((strcasecmp(key, "LocalPort") == 0) ||
650 (strcasecmp(key, "RemotePort") == 0)) {
652 int port = atoi(value);
654 if ((port < 1) || (port > 65535)) {
655 ERROR("tcpconns plugin: Invalid port: %i", port);
659 pe = conn_get_port_entry((uint16_t)port, 1 /* create */);
661 ERROR("tcpconns plugin: conn_get_port_entry failed.");
665 if (strcasecmp(key, "LocalPort") == 0)
666 pe->flags |= PORT_COLLECT_LOCAL;
668 pe->flags |= PORT_COLLECT_REMOTE;
669 } else if (strcasecmp(key, "AllPortsSummary") == 0) {
671 port_collect_total = 1;
673 port_collect_total = 0;
679 } /* int conn_config */
682 static int conn_init(void) {
683 if (port_collect_total == 0 && port_list_head == NULL)
684 port_collect_listening = 1;
687 } /* int conn_init */
689 static int conn_read(void) {
692 conn_reset_port_entry();
694 if (linux_source == SRC_NETLINK) {
695 status = conn_read_netlink();
696 } else if (linux_source == SRC_PROC) {
699 if (conn_read_file("/proc/net/tcp") != 0)
701 if (conn_read_file("/proc/net/tcp6") != 0)
708 } else /* if (linux_source == SRC_DUNNO) */
710 /* Try to use netlink for getting this data, it is _much_ faster on systems
711 * with a large amount of connections. */
712 status = conn_read_netlink();
714 INFO("tcpconns plugin: Reading from netlink succeeded. "
715 "Will use the netlink method from now on.");
716 linux_source = SRC_NETLINK;
718 INFO("tcpconns plugin: Reading from netlink failed. "
719 "Will read from /proc from now on.");
720 linux_source = SRC_PROC;
722 /* return success here to avoid the "plugin failed" message. */
733 } /* int conn_read */
734 /* #endif KERNEL_LINUX */
736 #elif HAVE_SYSCTLBYNAME
737 static int conn_read(void) {
743 struct xinpgen *in_orig;
744 struct xinpgen *in_ptr;
746 conn_reset_port_entry();
749 status = sysctlbyname("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
751 ERROR("tcpconns plugin: sysctlbyname failed.");
755 buffer = malloc(buffer_len);
756 if (buffer == NULL) {
757 ERROR("tcpconns plugin: malloc failed.");
761 status = sysctlbyname("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
763 ERROR("tcpconns plugin: sysctlbyname failed.");
768 if (buffer_len <= sizeof(struct xinpgen)) {
769 ERROR("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
774 in_orig = (struct xinpgen *)buffer;
775 for (in_ptr = (struct xinpgen *)(((char *)in_orig) + in_orig->xig_len);
776 in_ptr->xig_len > sizeof(struct xinpgen);
777 in_ptr = (struct xinpgen *)(((char *)in_ptr) + in_ptr->xig_len)) {
778 #if __FreeBSD_version >= 1200026
779 struct xtcpcb *tp = (struct xtcpcb *)in_ptr;
780 struct xinpcb *inp = &tp->xt_inp;
781 struct xsocket *so = &inp->xi_socket;
783 struct tcpcb *tp = &((struct xtcpcb *)in_ptr)->xt_tp;
784 struct inpcb *inp = &((struct xtcpcb *)in_ptr)->xt_inp;
785 struct xsocket *so = &((struct xtcpcb *)in_ptr)->xt_socket;
788 /* Ignore non-TCP sockets */
789 if (so->xso_protocol != IPPROTO_TCP)
792 /* Ignore PCBs which were freed during copyout. */
793 if (inp->inp_gencnt > in_orig->xig_gen)
796 if (((inp->inp_vflag & INP_IPV4) == 0) &&
797 ((inp->inp_vflag & INP_IPV6) == 0))
800 conn_handle_ports(ntohs(inp->inp_lport), ntohs(inp->inp_fport),
811 } /* int conn_read */
812 /* #endif HAVE_SYSCTLBYNAME */
814 #elif HAVE_KVM_GETFILES
816 static int conn_init(void) {
817 char buf[_POSIX2_LINE_MAX];
819 kvmd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
821 ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
826 } /* int conn_init */
828 static int conn_read(void) {
829 struct kinfo_file *kf;
832 conn_reset_port_entry();
834 kf = kvm_getfiles(kvmd, KERN_FILE_BYFILE, DTYPE_SOCKET, sizeof(*kf), &fcnt);
836 ERROR("tcpconns plugin: kvm_getfiles failed.");
840 for (i = 0; i < fcnt; i++) {
841 if (kf[i].so_protocol != IPPROTO_TCP)
843 if (kf[i].inp_fport == 0)
845 conn_handle_ports(ntohs(kf[i].inp_lport), ntohs(kf[i].inp_fport),
854 /* #endif HAVE_KVM_GETFILES */
856 #elif HAVE_LIBKVM_NLIST
857 static int kread(u_long addr, void *buf, int size) {
860 status = kvm_read(kvmd, addr, buf, size);
861 if (status != size) {
862 ERROR("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
863 status, size, kvm_geterr(kvmd));
869 static int conn_init(void) {
870 char buf[_POSIX2_LINE_MAX];
871 struct nlist nl[] = {
873 {"_tcbtable"}, {""}};
876 kvmd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, buf);
878 ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
882 status = kvm_nlist(kvmd, nl);
884 ERROR("tcpconns plugin: kvm_nlist failed with status %i.", status);
888 if (nl[N_TCBTABLE].n_type == 0) {
889 ERROR("tcpconns plugin: Error looking up kernel's namelist: "
890 "N_TCBTABLE is invalid.");
894 inpcbtable_off = (u_long)nl[N_TCBTABLE].n_value;
895 inpcbtable_ptr = (struct inpcbtable *)nl[N_TCBTABLE].n_value;
898 } /* int conn_init */
900 static int conn_read(void) {
901 struct inpcbtable table;
902 #if !defined(__OpenBSD__) && \
903 (defined(__NetBSD_Version__) && __NetBSD_Version__ <= 699002700)
911 conn_reset_port_entry();
913 /* Read the pcbtable from the kernel */
914 status = kread(inpcbtable_off, &table, sizeof(table));
918 #if defined(__OpenBSD__) || \
919 (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
920 /* inpt_queue is a TAILQ on OpenBSD */
921 /* Get the first pcb */
922 next = (struct inpcb *)TAILQ_FIRST(&table.inpt_queue);
925 /* Get the `head' pcb */
926 head = (struct inpcb *)&(inpcbtable_ptr->inpt_queue);
927 /* Get the first pcb */
928 next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue);
933 /* Read the pcb pointed to by `next' into `inpcb' */
934 status = kread((u_long)next, &inpcb, sizeof(inpcb));
939 #if defined(__OpenBSD__) || \
940 (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
941 /* inpt_queue is a TAILQ on OpenBSD */
942 next = (struct inpcb *)TAILQ_NEXT(&inpcb, inp_queue);
944 next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue);
947 /* Ignore sockets, that are not connected. */
949 if (inpcb.inp_af == AF_INET6)
950 continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
952 if (!(inpcb.inp_flags & INP_IPV6) &&
953 (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
955 if ((inpcb.inp_flags & INP_IPV6) &&
956 IN6_IS_ADDR_UNSPECIFIED(&inpcb.inp_laddr6))
960 status = kread((u_long)inpcb.inp_ppcb, &tcpcb, sizeof(tcpcb));
963 conn_handle_ports(ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport),
965 } /* while (next != head) */
971 /* #endif HAVE_LIBKVM_NLIST */
975 static int conn_read(void) {
979 struct netinfo_header *header;
980 struct netinfo_conn *conn;
982 conn_reset_port_entry();
984 size = netinfo(NETINFO_TCP, 0, 0, 0);
986 ERROR("tcpconns plugin: netinfo failed return: %i", size);
993 if ((size - sizeof(struct netinfo_header)) % sizeof(struct netinfo_conn)) {
994 ERROR("tcpconns plugin: invalid buffer size");
1000 ERROR("tcpconns plugin: malloc failed");
1004 if (netinfo(NETINFO_TCP, data, &size, 0) < 0) {
1005 ERROR("tcpconns plugin: netinfo failed");
1010 header = (struct netinfo_header *)data;
1011 nconn = header->size;
1012 conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1014 for (int i = 0; i < nconn; conn++, i++) {
1015 conn_handle_ports(conn->srcport, conn->dstport, conn->tcp_state);
1024 #endif /* KERNEL_AIX */
1026 void module_register(void) {
1027 plugin_register_config("tcpconns", conn_config, config_keys, config_keys_num);
1029 plugin_register_init("tcpconns", conn_init);
1030 #elif HAVE_SYSCTLBYNAME
1031 /* no initialization */
1032 #elif HAVE_LIBKVM_NLIST
1033 plugin_register_init("tcpconns", conn_init);
1035 /* no initialization */
1037 plugin_register_read("tcpconns", conn_read);
1038 } /* void module_register */