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