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