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