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