Fix compile time issues
[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 "plugin.h"
63 #include "utils/common/common.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     struct nlmsghdr *h;
502
503     memset(&msg, 0, sizeof(msg));
504     msg.msg_name = (void *)&nladdr;
505     msg.msg_namelen = sizeof(nladdr);
506     msg.msg_iov = &iov;
507     msg.msg_iovlen = 1;
508
509     ssize_t status = recvmsg(fd, (void *)&msg, /* flags = */ 0);
510     if (status < 0) {
511       if ((errno == EINTR) || (errno == EAGAIN))
512         continue;
513
514       ERROR("tcpconns plugin: conn_read_netlink: recvmsg(2) failed: %s",
515             STRERRNO);
516       close(fd);
517       return -1;
518     } else if (status == 0) {
519       close(fd);
520       DEBUG("tcpconns plugin: conn_read_netlink: Unexpected zero-sized "
521             "reply from netlink socket.");
522       return 0;
523     }
524
525     h = (struct nlmsghdr *)buf;
526     while (NLMSG_OK(h, status)) {
527       if (h->nlmsg_seq != sequence_number) {
528         h = NLMSG_NEXT(h, status);
529         continue;
530       }
531
532       if (h->nlmsg_type == NLMSG_DONE) {
533         close(fd);
534         return 0;
535       } else if (h->nlmsg_type == NLMSG_ERROR) {
536         struct nlmsgerr *msg_error;
537
538         msg_error = NLMSG_DATA(h);
539         WARNING("tcpconns plugin: conn_read_netlink: Received error %i.",
540                 msg_error->error);
541
542         close(fd);
543         return 1;
544       }
545
546       r = NLMSG_DATA(h);
547
548       /* This code does not (need to) distinguish between IPv4 and IPv6. */
549       conn_handle_ports(ntohs(r->id.idiag_sport), ntohs(r->id.idiag_dport),
550                         r->idiag_state);
551
552       h = NLMSG_NEXT(h, status);
553     } /* while (NLMSG_OK) */
554   }   /* while (1) */
555
556   /* Not reached because the while() loop above handles the exit condition. */
557   return 0;
558 #else
559   return 1;
560 #endif /* HAVE_STRUCT_LINUX_INET_DIAG_REQ */
561 } /* int conn_read_netlink */
562
563 static int conn_handle_line(char *buffer) {
564   char *fields[32];
565   int fields_len;
566
567   char *endptr;
568
569   char *port_local_str;
570   char *port_remote_str;
571   uint16_t port_local;
572   uint16_t port_remote;
573
574   uint8_t state;
575
576   size_t buffer_len = strlen(buffer);
577
578   while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
579     buffer[--buffer_len] = '\0';
580   if (buffer_len == 0)
581     return -1;
582
583   fields_len = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
584   if (fields_len < 12) {
585     DEBUG("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
586     return -1;
587   }
588
589   port_local_str = strchr(fields[1], ':');
590   port_remote_str = strchr(fields[2], ':');
591
592   if ((port_local_str == NULL) || (port_remote_str == NULL))
593     return -1;
594   port_local_str++;
595   port_remote_str++;
596   if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
597     return -1;
598
599   endptr = NULL;
600   port_local = (uint16_t)strtol(port_local_str, &endptr, 16);
601   if ((endptr == NULL) || (*endptr != '\0'))
602     return -1;
603
604   endptr = NULL;
605   port_remote = (uint16_t)strtol(port_remote_str, &endptr, 16);
606   if ((endptr == NULL) || (*endptr != '\0'))
607     return -1;
608
609   endptr = NULL;
610   state = (uint8_t)strtol(fields[3], &endptr, 16);
611   if ((endptr == NULL) || (*endptr != '\0'))
612     return -1;
613
614   return conn_handle_ports(port_local, port_remote, state);
615 } /* int conn_handle_line */
616
617 static int conn_read_file(const char *file) {
618   FILE *fh;
619   char buffer[1024];
620
621   fh = fopen(file, "r");
622   if (fh == NULL)
623     return -1;
624
625   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
626     conn_handle_line(buffer);
627   } /* while (fgets) */
628
629   fclose(fh);
630
631   return 0;
632 } /* int conn_read_file */
633   /* #endif KERNEL_LINUX */
634
635 #elif HAVE_SYSCTLBYNAME
636   /* #endif HAVE_SYSCTLBYNAME */
637
638 #elif HAVE_LIBKVM_NLIST
639 #endif /* HAVE_LIBKVM_NLIST */
640
641 static int conn_config(const char *key, const char *value) {
642   if (strcasecmp(key, "ListeningPorts") == 0) {
643     if (IS_TRUE(value))
644       port_collect_listening = 1;
645     else
646       port_collect_listening = 0;
647   } else if ((strcasecmp(key, "LocalPort") == 0) ||
648              (strcasecmp(key, "RemotePort") == 0)) {
649     port_entry_t *pe;
650     int port = atoi(value);
651
652     if ((port < 1) || (port > 65535)) {
653       ERROR("tcpconns plugin: Invalid port: %i", port);
654       return 1;
655     }
656
657     pe = conn_get_port_entry((uint16_t)port, 1 /* create */);
658     if (pe == NULL) {
659       ERROR("tcpconns plugin: conn_get_port_entry failed.");
660       return 1;
661     }
662
663     if (strcasecmp(key, "LocalPort") == 0)
664       pe->flags |= PORT_COLLECT_LOCAL;
665     else
666       pe->flags |= PORT_COLLECT_REMOTE;
667   } else if (strcasecmp(key, "AllPortsSummary") == 0) {
668     if (IS_TRUE(value))
669       port_collect_total = 1;
670     else
671       port_collect_total = 0;
672   } else {
673     return -1;
674   }
675
676   return 0;
677 } /* int conn_config */
678
679 #if KERNEL_LINUX
680 static int conn_init(void) {
681   if (port_collect_total == 0 && port_list_head == NULL)
682     port_collect_listening = 1;
683
684   return 0;
685 } /* int conn_init */
686
687 static int conn_read(void) {
688   int status;
689
690   conn_reset_port_entry();
691
692   if (linux_source == SRC_NETLINK) {
693     status = conn_read_netlink();
694   } else if (linux_source == SRC_PROC) {
695     int errors_num = 0;
696
697     if (conn_read_file("/proc/net/tcp") != 0)
698       errors_num++;
699     if (conn_read_file("/proc/net/tcp6") != 0)
700       errors_num++;
701
702     if (errors_num < 2)
703       status = 0;
704     else
705       status = ENOENT;
706   } else /* if (linux_source == SRC_DUNNO) */
707   {
708     /* Try to use netlink for getting this data, it is _much_ faster on systems
709      * with a large amount of connections. */
710     status = conn_read_netlink();
711     if (status == 0) {
712       INFO("tcpconns plugin: Reading from netlink succeeded. "
713            "Will use the netlink method from now on.");
714       linux_source = SRC_NETLINK;
715     } else {
716       INFO("tcpconns plugin: Reading from netlink failed. "
717            "Will read from /proc from now on.");
718       linux_source = SRC_PROC;
719
720       /* return success here to avoid the "plugin failed" message. */
721       return 0;
722     }
723   }
724
725   if (status == 0)
726     conn_submit_all();
727   else
728     return status;
729
730   return 0;
731 } /* int conn_read */
732   /* #endif KERNEL_LINUX */
733
734 #elif HAVE_SYSCTLBYNAME
735 static int conn_read(void) {
736   int status;
737   char *buffer;
738   size_t buffer_len;
739   ;
740
741   struct xinpgen *in_orig;
742   struct xinpgen *in_ptr;
743
744   conn_reset_port_entry();
745
746   buffer_len = 0;
747   status = sysctlbyname("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
748   if (status < 0) {
749     ERROR("tcpconns plugin: sysctlbyname failed.");
750     return -1;
751   }
752
753   buffer = malloc(buffer_len);
754   if (buffer == NULL) {
755     ERROR("tcpconns plugin: malloc failed.");
756     return -1;
757   }
758
759   status = sysctlbyname("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
760   if (status < 0) {
761     ERROR("tcpconns plugin: sysctlbyname failed.");
762     sfree(buffer);
763     return -1;
764   }
765
766   if (buffer_len <= sizeof(struct xinpgen)) {
767     ERROR("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
768     sfree(buffer);
769     return -1;
770   }
771
772   in_orig = (struct xinpgen *)buffer;
773   for (in_ptr = (struct xinpgen *)(((char *)in_orig) + in_orig->xig_len);
774        in_ptr->xig_len > sizeof(struct xinpgen);
775        in_ptr = (struct xinpgen *)(((char *)in_ptr) + in_ptr->xig_len)) {
776 #if __FreeBSD_version >= 1200026
777     struct xtcpcb *tp = (struct xtcpcb *)in_ptr;
778     struct xinpcb *inp = &tp->xt_inp;
779     struct xsocket *so = &inp->xi_socket;
780 #else
781     struct tcpcb *tp = &((struct xtcpcb *)in_ptr)->xt_tp;
782     struct inpcb *inp = &((struct xtcpcb *)in_ptr)->xt_inp;
783     struct xsocket *so = &((struct xtcpcb *)in_ptr)->xt_socket;
784 #endif
785
786     /* Ignore non-TCP sockets */
787     if (so->xso_protocol != IPPROTO_TCP)
788       continue;
789
790     /* Ignore PCBs which were freed during copyout. */
791     if (inp->inp_gencnt > in_orig->xig_gen)
792       continue;
793
794     if (((inp->inp_vflag & INP_IPV4) == 0) &&
795         ((inp->inp_vflag & INP_IPV6) == 0))
796       continue;
797
798     conn_handle_ports(ntohs(inp->inp_lport), ntohs(inp->inp_fport),
799                       tp->t_state);
800   } /* for (in_ptr) */
801
802   in_orig = NULL;
803   in_ptr = NULL;
804   sfree(buffer);
805
806   conn_submit_all();
807
808   return 0;
809 } /* int conn_read */
810   /* #endif HAVE_SYSCTLBYNAME */
811
812 #elif HAVE_KVM_GETFILES
813
814 static int conn_init(void) {
815   char buf[_POSIX2_LINE_MAX];
816
817   kvmd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
818   if (kvmd == NULL) {
819     ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
820     return -1;
821   }
822
823   return 0;
824 } /* int conn_init */
825
826 static int conn_read(void) {
827   struct kinfo_file *kf;
828   int i, fcnt;
829
830   conn_reset_port_entry();
831
832   kf = kvm_getfiles(kvmd, KERN_FILE_BYFILE, DTYPE_SOCKET, sizeof(*kf), &fcnt);
833   if (kf == NULL) {
834     ERROR("tcpconns plugin: kvm_getfiles failed.");
835     return -1;
836   }
837
838   for (i = 0; i < fcnt; i++) {
839     if (kf[i].so_protocol != IPPROTO_TCP)
840       continue;
841     if (kf[i].inp_fport == 0)
842       continue;
843     conn_handle_ports(ntohs(kf[i].inp_lport), ntohs(kf[i].inp_fport),
844                       kf[i].t_state);
845   }
846
847   conn_submit_all();
848
849   return 0;
850 }
851   /* int conn_read */
852   /* #endif HAVE_KVM_GETFILES */
853
854 #elif HAVE_LIBKVM_NLIST
855 static int kread(u_long addr, void *buf, int size) {
856   int status;
857
858   status = kvm_read(kvmd, addr, buf, size);
859   if (status != size) {
860     ERROR("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
861           status, size, kvm_geterr(kvmd));
862     return -1;
863   }
864   return 0;
865 } /* int kread */
866
867 static int conn_init(void) {
868   char buf[_POSIX2_LINE_MAX];
869   struct nlist nl[] = {
870 #define N_TCBTABLE 0
871       {"_tcbtable"}, {""}};
872   int status;
873
874   kvmd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, buf);
875   if (kvmd == NULL) {
876     ERROR("tcpconns plugin: kvm_openfiles failed: %s", buf);
877     return -1;
878   }
879
880   status = kvm_nlist(kvmd, nl);
881   if (status < 0) {
882     ERROR("tcpconns plugin: kvm_nlist failed with status %i.", status);
883     return -1;
884   }
885
886   if (nl[N_TCBTABLE].n_type == 0) {
887     ERROR("tcpconns plugin: Error looking up kernel's namelist: "
888           "N_TCBTABLE is invalid.");
889     return -1;
890   }
891
892   inpcbtable_off = (u_long)nl[N_TCBTABLE].n_value;
893   inpcbtable_ptr = (struct inpcbtable *)nl[N_TCBTABLE].n_value;
894
895   return 0;
896 } /* int conn_init */
897
898 static int conn_read(void) {
899   struct inpcbtable table;
900 #if !defined(__OpenBSD__) &&                                                   \
901     (defined(__NetBSD_Version__) && __NetBSD_Version__ <= 699002700)
902   struct inpcb *head;
903 #endif
904   struct inpcb *next;
905   struct inpcb inpcb;
906   struct tcpcb tcpcb;
907   int status;
908
909   conn_reset_port_entry();
910
911   /* Read the pcbtable from the kernel */
912   status = kread(inpcbtable_off, &table, sizeof(table));
913   if (status != 0)
914     return -1;
915
916 #if defined(__OpenBSD__) ||                                                    \
917     (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
918   /* inpt_queue is a TAILQ on OpenBSD */
919   /* Get the first pcb */
920   next = (struct inpcb *)TAILQ_FIRST(&table.inpt_queue);
921   while (next)
922 #else
923   /* Get the `head' pcb */
924   head = (struct inpcb *)&(inpcbtable_ptr->inpt_queue);
925   /* Get the first pcb */
926   next = (struct inpcb *)CIRCLEQ_FIRST(&table.inpt_queue);
927
928   while (next != head)
929 #endif
930   {
931     /* Read the pcb pointed to by `next' into `inpcb' */
932     status = kread((u_long)next, &inpcb, sizeof(inpcb));
933     if (status != 0)
934       return -1;
935
936 /* Advance `next' */
937 #if defined(__OpenBSD__) ||                                                    \
938     (defined(__NetBSD_Version__) && __NetBSD_Version__ > 699002700)
939     /* inpt_queue is a TAILQ on OpenBSD */
940     next = (struct inpcb *)TAILQ_NEXT(&inpcb, inp_queue);
941 #else
942     next = (struct inpcb *)CIRCLEQ_NEXT(&inpcb, inp_queue);
943 #endif
944
945 /* Ignore sockets, that are not connected. */
946 #ifdef __NetBSD__
947     if (inpcb.inp_af == AF_INET6)
948       continue; /* XXX see netbsd/src/usr.bin/netstat/inet6.c */
949 #else
950     if (!(inpcb.inp_flags & INP_IPV6) &&
951         (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
952       continue;
953     if ((inpcb.inp_flags & INP_IPV6) &&
954         IN6_IS_ADDR_UNSPECIFIED(&inpcb.inp_laddr6))
955       continue;
956 #endif
957
958     status = kread((u_long)inpcb.inp_ppcb, &tcpcb, sizeof(tcpcb));
959     if (status != 0)
960       return -1;
961     conn_handle_ports(ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport),
962                       tcpcb.t_state);
963   } /* while (next != head) */
964
965   conn_submit_all();
966
967   return 0;
968 }
969   /* #endif HAVE_LIBKVM_NLIST */
970
971 #elif KERNEL_AIX
972
973 static int conn_read(void) {
974   int size;
975   int nconn;
976   void *data;
977   struct netinfo_header *header;
978   struct netinfo_conn *conn;
979
980   conn_reset_port_entry();
981
982   size = netinfo(NETINFO_TCP, 0, 0, 0);
983   if (size < 0) {
984     ERROR("tcpconns plugin: netinfo failed return: %i", size);
985     return -1;
986   }
987
988   if (size == 0)
989     return 0;
990
991   if ((size - sizeof(struct netinfo_header)) % sizeof(struct netinfo_conn)) {
992     ERROR("tcpconns plugin: invalid buffer size");
993     return -1;
994   }
995
996   data = malloc(size);
997   if (data == NULL) {
998     ERROR("tcpconns plugin: malloc failed");
999     return -1;
1000   }
1001
1002   if (netinfo(NETINFO_TCP, data, &size, 0) < 0) {
1003     ERROR("tcpconns plugin: netinfo failed");
1004     free(data);
1005     return -1;
1006   }
1007
1008   header = (struct netinfo_header *)data;
1009   nconn = header->size;
1010   conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header));
1011
1012   for (int i = 0; i < nconn; conn++, i++) {
1013     conn_handle_ports(conn->srcport, conn->dstport, conn->tcp_state);
1014   }
1015
1016   free(data);
1017
1018   conn_submit_all();
1019
1020   return 0;
1021 }
1022 #endif /* KERNEL_AIX */
1023
1024 void module_register(void) {
1025   plugin_register_config("tcpconns", conn_config, config_keys, config_keys_num);
1026 #if KERNEL_LINUX
1027   plugin_register_init("tcpconns", conn_init);
1028 #elif HAVE_SYSCTLBYNAME
1029   /* no initialization */
1030 #elif HAVE_LIBKVM_NLIST
1031   plugin_register_init("tcpconns", conn_init);
1032 #elif KERNEL_AIX
1033 /* no initialization */
1034 #endif
1035   plugin_register_read("tcpconns", conn_read);
1036 } /* void module_register */