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