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