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