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