Merge branch 'collectd-5.8'
[collectd.git] / src / tcpconns.c
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 collectd.org>
21  *   Michael Stapelberg <michael+git at stapelberg.de>
22  **/
23
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  */
59
60 #include "collectd.h"
61
62 #include "common.h"
63 #include "plugin.h"
64
65 #if defined(__OpenBSD__)
66 #define HAVE_KVM_GETFILES 1
67 #endif
68
69 #if defined(__NetBSD__)
70 #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */
71 #endif
72
73 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_KVM_GETFILES &&               \
74     !HAVE_LIBKVM_NLIST && !KERNEL_AIX
75 #error "No applicable input method."
76 #endif
77
78 #if KERNEL_LINUX
79 #include <linux/netlink.h>
80 #if HAVE_LINUX_INET_DIAG_H
81 #include <linux/inet_diag.h>
82 #endif
83 #include <arpa/inet.h>
84 /* #endif KERNEL_LINUX */
85
86 #elif HAVE_SYSCTLBYNAME
87 #include <sys/socketvar.h>
88 #include <sys/sysctl.h>
89
90 /* Some includes needed for compiling on FreeBSD */
91 #include <sys/time.h>
92 #if HAVE_SYS_TYPES_H
93 #include <sys/types.h>
94 #endif
95 #if HAVE_NET_IF_H
96 #include <net/if.h>
97 #endif
98
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 */
111
112 #elif HAVE_KVM_GETFILES
113 #include <sys/sysctl.h>
114 #include <sys/types.h>
115 #define _KERNEL /* for DTYPE_SOCKET */
116 #include <sys/file.h>
117 #undef _KERNEL
118
119 #include <netinet/in.h>
120
121 #include <kvm.h>
122 /* #endif HAVE_KVM_GETFILES */
123
124 /* This is for NetBSD. */
125 #elif HAVE_LIBKVM_NLIST
126 #include <arpa/inet.h>
127 #include <net/route.h>
128 #include <netdb.h>
129 #include <netinet/in.h>
130 #include <netinet/in_pcb.h>
131 #include <netinet/in_systm.h>
132 #include <netinet/ip.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
139 #include <nlist.h>
140 #else /* HAVE_BSD_NLIST_H */
141 #include <bsd/nlist.h>
142 #endif
143 #include <kvm.h>
144 /* #endif HAVE_LIBKVM_NLIST */
145
146 #elif KERNEL_AIX
147 #include <arpa/inet.h>
148 #include <sys/socketvar.h>
149 #endif /* KERNEL_AIX */
150
151 #if KERNEL_LINUX
152 #if HAVE_STRUCT_LINUX_INET_DIAG_REQ
153 struct nlreq {
154   struct nlmsghdr nlh;
155   struct inet_diag_req r;
156 };
157 #endif
158
159 static const char *tcp_state[] = {"", /* 0 */
160                                   "ESTABLISHED",
161                                   "SYN_SENT",
162                                   "SYN_RECV",
163                                   "FIN_WAIT1",
164                                   "FIN_WAIT2",
165                                   "TIME_WAIT",
166                                   "CLOSED",
167                                   "CLOSE_WAIT",
168                                   "LAST_ACK",
169                                   "LISTEN", /* 10 */
170                                   "CLOSING"};
171
172 #define TCP_STATE_LISTEN 10
173 #define TCP_STATE_MIN 1
174 #define TCP_STATE_MAX 11
175 /* #endif KERNEL_LINUX */
176
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"};
182
183 #define TCP_STATE_LISTEN 1
184 #define TCP_STATE_MIN 0
185 #define TCP_STATE_MAX 10
186 /* #endif HAVE_SYSCTLBYNAME */
187
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"};
193
194 #define TCP_STATE_LISTEN 1
195 #define TCP_STATE_MIN 0
196 #define TCP_STATE_MAX 10
197
198 static kvm_t *kvmd;
199 /* #endif HAVE_KVM_GETFILES */
200
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"};
206
207 static kvm_t *kvmd;
208 static u_long inpcbtable_off;
209 struct inpcbtable *inpcbtable_ptr = NULL;
210
211 #define TCP_STATE_LISTEN 1
212 #define TCP_STATE_MIN 1
213 #define TCP_STATE_MAX 10
214 /* #endif HAVE_LIBKVM_NLIST */
215
216 #elif KERNEL_AIX
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"};
221
222 #define TCP_STATE_LISTEN 1
223 #define TCP_STATE_MIN 0
224 #define TCP_STATE_MAX 10
225
226 struct netinfo_conn {
227   uint32_t unknow1[2];
228   uint16_t dstport;
229   uint16_t unknow2;
230   struct in6_addr dstaddr;
231   uint16_t srcport;
232   uint16_t unknow3;
233   struct in6_addr srcaddr;
234   uint32_t unknow4[36];
235   uint16_t tcp_state;
236   uint16_t unknow5[7];
237 };
238
239 struct netinfo_header {
240   unsigned int proto;
241   unsigned int size;
242 };
243
244 #define NETINFO_TCP 3
245 extern int netinfo(int proto, void *data, int *size, int n);
246 #endif /* KERNEL_AIX */
247
248 #define PORT_COLLECT_LOCAL 0x01
249 #define PORT_COLLECT_REMOTE 0x02
250 #define PORT_IS_LISTENING 0x04
251
252 typedef struct port_entry_s {
253   uint16_t port;
254   uint16_t flags;
255   uint32_t count_local[TCP_STATE_MAX + 1];
256   uint32_t count_remote[TCP_STATE_MAX + 1];
257   struct port_entry_s *next;
258 } port_entry_t;
259
260 static const char *config_keys[] = {"ListeningPorts", "LocalPort", "RemotePort",
261                                     "AllPortsSummary"};
262 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
263
264 static int port_collect_listening;
265 static int port_collect_total;
266 static port_entry_t *port_list_head;
267 static uint32_t count_total[TCP_STATE_MAX + 1];
268
269 #if KERNEL_LINUX
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.
273  */
274 static uint32_t sequence_number;
275 #endif
276
277 static enum { SRC_DUNNO, SRC_NETLINK, SRC_PROC } linux_source = SRC_DUNNO;
278 #endif
279
280 static void conn_prepare_vl(value_list_t *vl, value_t *values) {
281   vl->values = values;
282   vl->values_len = 1;
283   sstrncpy(vl->plugin, "tcpconns", sizeof(vl->plugin));
284   sstrncpy(vl->type, "tcp_connections", sizeof(vl->type));
285 }
286
287 static void conn_submit_port_entry(port_entry_t *pe) {
288   value_t values[1];
289   value_list_t vl = VALUE_LIST_INIT;
290
291   conn_prepare_vl(&vl, values);
292
293   if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING)) ||
294       (pe->flags & PORT_COLLECT_LOCAL)) {
295     snprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
296              "%" PRIu16 "-local", pe->port);
297
298     for (int i = 1; i <= TCP_STATE_MAX; i++) {
299       vl.values[0].gauge = pe->count_local[i];
300
301       sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
302
303       plugin_dispatch_values(&vl);
304     }
305   }
306
307   if (pe->flags & PORT_COLLECT_REMOTE) {
308     snprintf(vl.plugin_instance, sizeof(vl.plugin_instance),
309              "%" PRIu16 "-remote", pe->port);
310
311     for (int i = 1; i <= TCP_STATE_MAX; i++) {
312       vl.values[0].gauge = pe->count_remote[i];
313
314       sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
315
316       plugin_dispatch_values(&vl);
317     }
318   }
319 } /* void conn_submit */
320
321 static void conn_submit_port_total(void) {
322   value_t values[1];
323   value_list_t vl = VALUE_LIST_INIT;
324
325   conn_prepare_vl(&vl, values);
326
327   sstrncpy(vl.plugin_instance, "all", sizeof(vl.plugin_instance));
328
329   for (int i = 1; i <= TCP_STATE_MAX; i++) {
330     vl.values[0].gauge = count_total[i];
331
332     sstrncpy(vl.type_instance, tcp_state[i], sizeof(vl.type_instance));
333
334     plugin_dispatch_values(&vl);
335   }
336 }
337
338 static void conn_submit_all(void) {
339   if (port_collect_total)
340     conn_submit_port_total();
341
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 */
345
346 static port_entry_t *conn_get_port_entry(uint16_t port, int create) {
347   port_entry_t *ret;
348
349   ret = port_list_head;
350   while (ret != NULL) {
351     if (ret->port == port)
352       break;
353     ret = ret->next;
354   }
355
356   if ((ret == NULL) && (create != 0)) {
357     ret = calloc(1, sizeof(*ret));
358     if (ret == NULL)
359       return NULL;
360
361     ret->port = port;
362     ret->next = port_list_head;
363     port_list_head = ret;
364   }
365
366   return ret;
367 } /* port_entry_t *conn_get_port_entry */
368
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;
374
375   memset(&count_total, '\0', sizeof(count_total));
376
377   while (pe != NULL) {
378     /* If this entry was created while reading the files (ant not when handling
379      * the configuration) remove it now. */
380     if ((pe->flags &
381          (PORT_COLLECT_LOCAL | PORT_COLLECT_REMOTE | PORT_IS_LISTENING)) == 0) {
382       port_entry_t *next = pe->next;
383
384       DEBUG("tcpconns plugin: Removing temporary entry "
385             "for listening port %" PRIu16,
386             pe->port);
387
388       if (prev == NULL)
389         port_list_head = next;
390       else
391         prev->next = next;
392
393       sfree(pe);
394       pe = next;
395
396       continue;
397     }
398
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;
402
403     prev = pe;
404     pe = pe->next;
405   }
406 } /* void conn_reset_port_entry */
407
408 static int conn_handle_ports(uint16_t port_local, uint16_t port_remote,
409                              uint8_t state) {
410   port_entry_t *pe = NULL;
411
412   if ((state > TCP_STATE_MAX)
413 #if TCP_STATE_MIN > 0
414       || (state < TCP_STATE_MIN)
415 #endif
416           ) {
417     NOTICE("tcpconns plugin: Ignoring connection with "
418            "unknown state 0x%02" PRIx8 ".",
419            state);
420     return -1;
421   }
422
423   count_total[state]++;
424
425   /* Listening sockets */
426   if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0)) {
427     pe = conn_get_port_entry(port_local, 1 /* create */);
428     if (pe != NULL)
429       pe->flags |= PORT_IS_LISTENING;
430   }
431
432   DEBUG("tcpconns plugin: Connection %" PRIu16 " <-> %" PRIu16 " (%s)",
433         port_local, port_remote, tcp_state[state]);
434
435   pe = conn_get_port_entry(port_local, 0 /* no create */);
436   if (pe != NULL)
437     pe->count_local[state]++;
438
439   pe = conn_get_port_entry(port_remote, 0 /* no create */);
440   if (pe != NULL)
441     pe->count_remote[state]++;
442
443   return 0;
444 } /* int conn_handle_ports */
445
446 #if KERNEL_LINUX
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
451   int fd;
452   struct inet_diag_msg *r;
453   char buf[8192];
454
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);
458   if (fd < 0) {
459     ERROR("tcpconns plugin: conn_read_netlink: socket(AF_NETLINK, SOCK_RAW, "
460           "NETLINK_INET_DIAG) failed: %s",
461           STRERRNO);
462     return -1;
463   }
464
465   struct sockaddr_nl nladdr = {.nl_family = AF_NETLINK};
466
467   struct nlreq req = {
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,
474       .nlh.nlmsg_pid = 0,
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,
481       .r.idiag_ext = 0};
482
483   struct iovec iov = {.iov_base = &req, .iov_len = sizeof(req)};
484
485   struct msghdr msg = {.msg_name = (void *)&nladdr,
486                        .msg_namelen = sizeof(nladdr),
487                        .msg_iov = &iov,
488                        .msg_iovlen = 1};
489
490   if (sendmsg(fd, &msg, 0) < 0) {
491     ERROR("tcpconns plugin: conn_read_netlink: sendmsg(2) failed: %s",
492           STRERRNO);
493     close(fd);
494     return -1;
495   }
496
497   iov.iov_base = buf;
498   iov.iov_len = sizeof(buf);
499
500   while (1) {
501     int status;
502     struct nlmsghdr *h;
503
504     memset(&msg, 0, sizeof(msg));
505     msg.msg_name = (void *)&nladdr;
506     msg.msg_namelen = sizeof(nladdr);
507     msg.msg_iov = &iov;
508     msg.msg_iovlen = 1;
509
510     status = recvmsg(fd, (void *)&msg, /* flags = */ 0);
511     if (status < 0) {
512       if ((errno == EINTR) || (errno == EAGAIN))
513         continue;
514
515       ERROR("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
516             STRERRNO);
517       close(fd);
518       return -1;
519     } else if (status == 0) {
520       close(fd);
521       DEBUG("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
522             "reply from netlink socket.");
523       return 0;
524     }
525
526     h = (struct nlmsghdr *)buf;
527     while (NLMSG_OK(h, status)) {
528       if (h->nlmsg_seq != sequence_number) {
529         h = NLMSG_NEXT(h, status);
530         continue;
531       }
532
533       if (h->nlmsg_type == NLMSG_DONE) {
534         close(fd);
535         return 0;
536       } else if (h->nlmsg_type == NLMSG_ERROR) {
537         struct nlmsgerr *msg_error;
538
539         msg_error = NLMSG_DATA(h);
540         WARNING("tcpconns plugin: conn_read_netlink: Received error %i.",
541                 msg_error->error);
542
543         close(fd);
544         return 1;
545       }
546
547       r = NLMSG_DATA(h);
548
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),
551                         r->idiag_state);
552
553       h = NLMSG_NEXT(h, status);
554     } /* while (NLMSG_OK) */
555   }   /* while (1) */
556
557   /* Not reached because the while() loop above handles the exit condition. */
558   return 0;
559 #else
560   return 1;
561 #endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
562 } /* int conn_read_netlink */
563
564 static int conn_handle_line(char *buffer) {
565   char *fields[32];
566   int fields_len;
567
568   char *endptr;
569
570   char *port_local_str;
571   char *port_remote_str;
572   uint16_t port_local;
573   uint16_t port_remote;
574
575   uint8_t state;
576
577   int buffer_len = strlen(buffer);
578
579   while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
580     buffer[--buffer_len] = '\0';
581   if (buffer_len <= 0)
582     return -1;
583
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);
587     return -1;
588   }
589
590   port_local_str = strchr(fields[1], ':');
591   port_remote_str = strchr(fields[2], ':');
592
593   if ((port_local_str == NULL) || (port_remote_str == NULL))
594     return -1;
595   port_local_str++;
596   port_remote_str++;
597   if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
598     return -1;
599
600   endptr = NULL;
601   port_local = (uint16_t)strtol(port_local_str, &endptr, 16);
602   if ((endptr == NULL) || (*endptr != '\0'))
603     return -1;
604
605   endptr = NULL;
606   port_remote = (uint16_t)strtol(port_remote_str, &endptr, 16);
607   if ((endptr == NULL) || (*endptr != '\0'))
608     return -1;
609
610   endptr = NULL;
611   state = (uint8_t)strtol(fields[3], &endptr, 16);
612   if ((endptr == NULL) || (*endptr != '\0'))
613     return -1;
614
615   return conn_handle_ports(port_local, port_remote, state);
616 } /* int conn_handle_line */
617
618 static int conn_read_file(const char *file) {
619   FILE *fh;
620   char buffer[1024];
621
622   fh = fopen(file, "r");
623   if (fh == NULL)
624     return -1;
625
626   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
627     conn_handle_line(buffer);
628   } /* while (fgets) */
629
630   fclose(fh);
631
632   return 0;
633 } /* int conn_read_file */
634 /* #endif KERNEL_LINUX */
635
636 #elif HAVE_SYSCTLBYNAME
637 /* #endif HAVE_SYSCTLBYNAME */
638
639 #elif HAVE_LIBKVM_NLIST
640 #endif /* HAVE_LIBKVM_NLIST */
641
642 static int conn_config(const char *key, const char *value) {
643   if (strcasecmp(key, "ListeningPorts") == 0) {
644     if (IS_TRUE(value))
645       port_collect_listening = 1;
646     else
647       port_collect_listening = 0;
648   } else if ((strcasecmp(key, "LocalPort") == 0) ||
649              (strcasecmp(key, "RemotePort") == 0)) {
650     port_entry_t *pe;
651     int port = atoi(value);
652
653     if ((port < 1) || (port > 65535)) {
654       ERROR("tcpconns plugin: Invalid port: %i", port);
655       return 1;
656     }
657
658     pe = conn_get_port_entry((uint16_t)port, 1 /* create */);
659     if (pe == NULL) {
660       ERROR("tcpconns plugin: conn_get_port_entry failed.");
661       return 1;
662     }
663
664     if (strcasecmp(key, "LocalPort") == 0)
665       pe->flags |= PORT_COLLECT_LOCAL;
666     else
667       pe->flags |= PORT_COLLECT_REMOTE;
668   } else if (strcasecmp(key, "AllPortsSummary") == 0) {
669     if (IS_TRUE(value))
670       port_collect_total = 1;
671     else
672       port_collect_total = 0;
673   } else {
674     return -1;
675   }
676
677   return 0;
678 } /* int conn_config */
679
680 #if KERNEL_LINUX
681 static int conn_init(void) {
682   if (port_collect_total == 0 && port_list_head == NULL)
683     port_collect_listening = 1;
684
685   return 0;
686 } /* int conn_init */
687
688 static int conn_read(void) {
689   int status;
690
691   conn_reset_port_entry();
692
693   if (linux_source == SRC_NETLINK) {
694     status = conn_read_netlink();
695   } else if (linux_source == SRC_PROC) {
696     int errors_num = 0;
697
698     if (conn_read_file("/proc/net/tcp") != 0)
699       errors_num++;
700     if (conn_read_file("/proc/net/tcp6") != 0)
701       errors_num++;
702
703     if (errors_num < 2)
704       status = 0;
705     else
706       status = ENOENT;
707   } else /* if (linux_source == SRC_DUNNO) */
708   {
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();
712     if (status == 0) {
713       INFO("tcpconns plugin: Reading from netlink succeeded. "
714            "Will use the netlink method from now on.");
715       linux_source = SRC_NETLINK;
716     } else {
717       INFO("tcpconns plugin: Reading from netlink failed. "
718            "Will read from /proc from now on.");
719       linux_source = SRC_PROC;
720
721       /* return success here to avoid the "plugin failed" message. */
722       return 0;
723     }
724   }
725
726   if (status == 0)
727     conn_submit_all();
728   else
729     return status;
730
731   return 0;
732 } /* int conn_read */
733 /* #endif KERNEL_LINUX */
734
735 #elif HAVE_SYSCTLBYNAME
736 static int conn_read(void) {
737   int status;
738   char *buffer;
739   size_t buffer_len;
740   ;
741
742   struct xinpgen *in_orig;
743   struct xinpgen *in_ptr;
744
745   conn_reset_port_entry();
746
747   buffer_len = 0;
748   status = sysctlbyname("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
749   if (status < 0) {
750     ERROR("tcpconns plugin: sysctlbyname failed.");
751     return -1;
752   }
753
754   buffer = malloc(buffer_len);
755   if (buffer == NULL) {
756     ERROR("tcpconns plugin: malloc failed.");
757     return -1;
758   }
759
760   status = sysctlbyname("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
761   if (status < 0) {
762     ERROR("tcpconns plugin: sysctlbyname failed.");
763     sfree(buffer);
764     return -1;
765   }
766
767   if (buffer_len <= sizeof(struct xinpgen)) {
768     ERROR("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
769     sfree(buffer);
770     return -1;
771   }
772
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 #if __FreeBSD_version >= 1200026
778     struct xtcpcb *tp = (struct xtcpcb *)in_ptr;
779     struct xinpcb *inp = &tp->xt_inp;
780     struct xsocket *so = &inp->xi_socket;
781 #else
782     struct tcpcb *tp = &((struct xtcpcb *)in_ptr)->xt_tp;
783     struct inpcb *inp = &((struct xtcpcb *)in_ptr)->xt_inp;
784     struct xsocket *so = &((struct xtcpcb *)in_ptr)->xt_socket;
785 #endif
786
787     /* Ignore non-TCP sockets */
788     if (so->xso_protocol != IPPROTO_TCP)
789       continue;
790
791     /* Ignore PCBs which were freed during copyout. */
792     if (inp->inp_gencnt > in_orig->xig_gen)
793       continue;
794
795     if (((inp->inp_vflag & INP_IPV4) == 0) &&
796         ((inp->inp_vflag & INP_IPV6) == 0))
797       continue;
798
799     conn_handle_ports(ntohs(inp->inp_lport), ntohs(inp->inp_fport),
800                       tp->t_state);
801   } /* for (in_ptr) */
802
803   in_orig = NULL;
804   in_ptr = NULL;
805   sfree(buffer);
806
807   conn_submit_all();
808
809   return 0;
810 } /* int conn_read */
811   /* #endif HAVE_SYSCTLBYNAME */
812
813 #elif HAVE_KVM_GETFILES
814
815 static int conn_init(void) {
816   char buf[_POSIX2_LINE_MAX];
817
818   kvmd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
819   if (kvmd == NULL) {
820     ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
821     return -1;
822   }
823
824   return 0;
825 } /* int conn_init */
826
827 static int conn_read(void) {
828   struct kinfo_file *kf;
829   int i, fcnt;
830
831   conn_reset_port_entry();
832
833   kf = kvm_getfiles(kvmd, KERN_FILE_BYFILE, DTYPE_SOCKET, sizeof(*kf), &fcnt);
834   if (kf == NULL) {
835     ERROR("tcpconns plugin: kvm_getfiles failed.");
836     return -1;
837   }
838
839   for (i = 0; i < fcnt; i++) {
840     if (kf[i].so_protocol != IPPROTO_TCP)
841       continue;
842     if (kf[i].inp_fport == 0)
843       continue;
844     conn_handle_ports(ntohs(kf[i].inp_lport), ntohs(kf[i].inp_fport),
845                       kf[i].t_state);
846   }
847
848   conn_submit_all();
849
850   return 0;
851 }
852 /* int conn_read */
853 /* #endif HAVE_KVM_GETFILES */
854
855 #elif HAVE_LIBKVM_NLIST
856 static int kread(u_long addr, void *buf, int size) {
857   int status;
858
859   status = kvm_read(kvmd, addr, buf, size);
860   if (status != size) {
861     ERROR("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
862           status, size, kvm_geterr(kvmd));
863     return -1;
864   }
865   return 0;
866 } /* int kread */
867
868 static int conn_init(void) {
869   char buf[_POSIX2_LINE_MAX];
870   struct nlist nl[] = {
871 #define N_TCBTABLE 0
872       {"_tcbtable"}, {""}};
873   int status;
874
875   kvmd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, buf);
876   if (kvmd == NULL) {
877     ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
878     return -1;
879   }
880
881   status = kvm_nlist(kvmd, nl);
882   if (status < 0) {
883     ERROR("tcpconns plugin: kvm_nlist failed with status %i.", status);
884     return -1;
885   }
886
887   if (nl[N_TCBTABLE].n_type == 0) {
888     ERROR("tcpconns plugin: Error looking up kernel's namelist: "
889           "N_TCBTABLE is invalid.");
890     return -1;
891   }
892
893   inpcbtable_off = (u_long)nl[N_TCBTABLE].n_value;
894   inpcbtable_ptr = (struct inpcbtable *)nl[N_TCBTABLE].n_value;
895
896   return 0;
897 } /* int conn_init */
898
899 static int conn_read(void) {
900   struct inpcbtable table;
901 #if !defined(__OpenBSD__) &&                                                   \
902     (defined(__NetBSD_Version__) && __NetBSD_Version__ <= 699002700)
903   struct inpcb *head;
904 #endif
905   struct inpcb *next;
906   struct inpcb inpcb;
907   struct tcpcb tcpcb;
908   int status;
909
910   conn_reset_port_entry();
911
912   /* Read the pcbtable from the kernel */
913   status = kread(inpcbtable_off, &table, sizeof(table));
914   if (status != 0)
915     return -1;
916
917 #if defined(__OpenBSD__) ||                                                    \
918     (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
919   /* inpt_queue is a TAILQ on OpenBSD */
920   /* Get the first pcb */
921   next = (struct inpcb *)TAILQ_FIRST(&table.inpt_queue);
922   while (next)
923 #else
924   /* Get the `head' pcb */
925   head = (struct inpcb *)&(inpcbtable_ptr->inpt_queue);
926   /* Get the first pcb */
927   next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue);
928
929   while (next != head)
930 #endif
931   {
932     /* Read the pcb pointed to by `next' into `inpcb' */
933     status = kread((u_long)next, &inpcb, sizeof(inpcb));
934     if (status != 0)
935       return -1;
936
937 /* Advance `next' */
938 #if defined(__OpenBSD__) ||                                                    \
939     (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
940     /* inpt_queue is a TAILQ on OpenBSD */
941     next = (struct inpcb *)TAILQ_NEXT(&inpcb, inp_queue);
942 #else
943     next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue);
944 #endif
945
946 /* Ignore sockets, that are not connected. */
947 #ifdef __NetBSD__
948     if (inpcb.inp_af == AF_INET6)
949       continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
950 #else
951     if (!(inpcb.inp_flags & INP_IPV6) &&
952         (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
953       continue;
954     if ((inpcb.inp_flags & INP_IPV6) &&
955         IN6_IS_ADDR_UNSPECIFIED(&inpcb.inp_laddr6))
956       continue;
957 #endif
958
959     status = kread((u_long)inpcb.inp_ppcb, &tcpcb, sizeof(tcpcb));
960     if (status != 0)
961       return -1;
962     conn_handle_ports(ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport),
963                       tcpcb.t_state);
964   } /* while (next != head) */
965
966   conn_submit_all();
967
968   return 0;
969 }
970 /* #endif HAVE_LIBKVM_NLIST */
971
972 #elif KERNEL_AIX
973
974 static int conn_read(void) {
975   int size;
976   int nconn;
977   void *data;
978   struct netinfo_header *header;
979   struct netinfo_conn *conn;
980
981   conn_reset_port_entry();
982
983   size = netinfo(NETINFO_TCP, 0, 0, 0);
984   if (size < 0) {
985     ERROR("tcpconns plugin: netinfo failed return: %i", size);
986     return -1;
987   }
988
989   if (size == 0)
990     return 0;
991
992   if ((size - sizeof(struct netinfo_header)) % sizeof(struct netinfo_conn)) {
993     ERROR("tcpconns plugin: invalid buffer size");
994     return -1;
995   }
996
997   data = malloc(size);
998   if (data == NULL) {
999     ERROR("tcpconns plugin: malloc failed");
1000     return -1;
1001   }
1002
1003   if (netinfo(NETINFO_TCP, data, &size, 0) < 0) {
1004     ERROR("tcpconns plugin: netinfo failed");
1005     free(data);
1006     return -1;
1007   }
1008
1009   header = (struct netinfo_header *)data;
1010   nconn = header->size;
1011   conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1012
1013   for (int i = 0; i < nconn; conn++, i++) {
1014     conn_handle_ports(conn->srcport, conn->dstport, conn->tcp_state);
1015   }
1016
1017   free(data);
1018
1019   conn_submit_all();
1020
1021   return 0;
1022 }
1023 #endif /* KERNEL_AIX */
1024
1025 void module_register(void) {
1026   plugin_register_config("tcpconns", conn_config, config_keys, config_keys_num);
1027 #if KERNEL_LINUX
1028   plugin_register_init("tcpconns", conn_init);
1029 #elif HAVE_SYSCTLBYNAME
1030   /* no initialization */
1031 #elif HAVE_LIBKVM_NLIST
1032   plugin_register_init("tcpconns", conn_init);
1033 #elif KERNEL_AIX
1034 /* no initialization */
1035 #endif
1036   plugin_register_read("tcpconns", conn_read);
1037 } /* void module_register */