aa1fa38b037b08977efac02443f85cfb95cd9f49
[collectd.git] / src / tcpconns.c
1 /**
2  * collectd - src/tcpconns.c
3  * Copyright (C) 2007  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 /**
23  * Code within `HAVE_LIBKVM_NLIST' blocks is provided under the following
24  * license:
25  *
26  * $collectd: parts of tcpconns.c, 2008/08/08 03:48:30 Michael Stapelberg $
27  * $OpenBSD: inet.c,v 1.100 2007/06/19 05:28:30 ray Exp $
28  * $NetBSD: inet.c,v 1.14 1995/10/03 21:42:37 thorpej Exp $
29  *
30  * Copyright (c) 1983, 1988, 1993
31  *      The Regents of the University of California.  All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the University nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57
58 #include "collectd.h"
59 #include "common.h"
60 #include "plugin.h"
61
62 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST
63 # error "No applicable input method."
64 #endif
65
66 #if KERNEL_LINUX
67 /* #endif KERNEL_LINUX */
68
69 #elif HAVE_SYSCTLBYNAME
70 # include <sys/socketvar.h>
71 # include <sys/sysctl.h>
72
73 /* Some includes needed for compiling on FreeBSD */
74 #include <sys/time.h>
75 #if HAVE_SYS_TYPES_H
76 # include <sys/types.h>
77 #endif
78 #if HAVE_SYS_SOCKET_H
79 # include <sys/socket.h>
80 #endif
81 #if HAVE_NET_IF_H
82 # include <net/if.h>
83 #endif
84
85 # include <net/route.h>
86 # include <netinet/in.h>
87 # include <netinet/in_systm.h>
88 # include <netinet/ip.h>
89 # include <netinet/ip6.h>
90 # include <netinet/in_pcb.h>
91 # include <netinet/ip_var.h>
92 # include <netinet/tcp.h>
93 # include <netinet/tcpip.h>
94 # include <netinet/tcp_seq.h>
95 # include <netinet/tcp_var.h>
96 /* #endif HAVE_SYSCTLBYNAME */
97
98 /* This is for OpenBSD and possibly NetBSD. */
99 #elif HAVE_LIBKVM_NLIST
100 # include <sys/queue.h>
101 # include <sys/socket.h>
102 # include <net/route.h>
103 # include <netinet/in.h>
104 # include <netinet/in_systm.h>
105 # include <netinet/ip.h>
106 # include <netinet/in_pcb.h>
107 # include <netinet/tcp.h>
108 # include <netinet/tcp_timer.h>
109 # include <netinet/tcp_var.h>
110 # include <netdb.h>
111 # include <arpa/inet.h>
112 # include <nlist.h>
113 # include <kvm.h>
114 #endif /* HAVE_LIBKVM_NLIST */
115
116 #if KERNEL_LINUX
117 static const char *tcp_state[] =
118 {
119   "", /* 0 */
120   "ESTABLISHED",
121   "SYN_SENT",
122   "SYN_RECV",
123   "FIN_WAIT1",
124   "FIN_WAIT2",
125   "TIME_WAIT",
126   "CLOSED",
127   "CLOSE_WAIT",
128   "LAST_ACK",
129   "LISTEN", /* 10 */
130   "CLOSING"
131 };
132
133 # define TCP_STATE_LISTEN 10
134 # define TCP_STATE_MIN 1
135 # define TCP_STATE_MAX 11
136 /* #endif KERNEL_LINUX */
137
138 #elif HAVE_SYSCTLBYNAME
139 static const char *tcp_state[] =
140 {
141   "CLOSED",
142   "LISTEN",
143   "SYN_SENT",
144   "SYN_RECV",
145   "ESTABLISHED",
146   "CLOSE_WAIT",
147   "FIN_WAIT1",
148   "CLOSING",
149   "LAST_ACK",
150   "FIN_WAIT2",
151   "TIME_WAIT"
152 };
153
154 # define TCP_STATE_LISTEN 1
155 # define TCP_STATE_MIN 0
156 # define TCP_STATE_MAX 10
157 /* #endif HAVE_SYSCTLBYNAME */
158
159 #elif HAVE_LIBKVM_NLIST
160 static const char *tcp_state[] =
161 {
162   "CLOSED",
163   "LISTEN",
164   "SYN_SENT",
165   "SYN_RECV",
166   "ESTABLISHED",
167   "CLOSE_WAIT",
168   "FIN_WAIT1",
169   "CLOSING",
170   "LAST_ACK",
171   "FIN_WAIT2",
172   "TIME_WAIT"
173 };
174
175 static kvm_t *kvmd;
176 static u_long      inpcbtable_off = 0;
177 struct inpcbtable *inpcbtable_ptr = NULL;
178
179 # define TCP_STATE_LISTEN 1
180 # define TCP_STATE_MIN 1
181 # define TCP_STATE_MAX 10
182 #endif /* HAVE_LIBKVM_NLIST */
183
184 #define PORT_COLLECT_LOCAL  0x01
185 #define PORT_COLLECT_REMOTE 0x02
186 #define PORT_IS_LISTENING   0x04
187
188 typedef struct port_entry_s
189 {
190   uint16_t port;
191   uint16_t flags;
192   uint32_t count_local[TCP_STATE_MAX + 1];
193   uint32_t count_remote[TCP_STATE_MAX + 1];
194   struct port_entry_s *next;
195 } port_entry_t;
196
197 static const char *config_keys[] =
198 {
199   "ListeningPorts",
200   "LocalPort",
201   "RemotePort"
202 };
203 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
204
205 static int port_collect_listening = 0;
206 static port_entry_t *port_list_head = NULL;
207
208 static void conn_submit_port_entry (port_entry_t *pe)
209 {
210   value_t values[1];
211   value_list_t vl = VALUE_LIST_INIT;
212   int i;
213
214   vl.values = values;
215   vl.values_len = 1;
216   vl.time = time (NULL);
217   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
218   sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
219   sstrncpy (vl.type, "tcp_connections", sizeof (vl.type));
220
221   if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
222       || (pe->flags & PORT_COLLECT_LOCAL))
223   {
224     ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
225         "%"PRIu16"-local", pe->port);
226
227     for (i = 1; i <= TCP_STATE_MAX; i++)
228     {
229       vl.values[0].gauge = pe->count_local[i];
230
231       sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
232
233       plugin_dispatch_values (&vl);
234     }
235   }
236
237   if (pe->flags & PORT_COLLECT_REMOTE)
238   {
239     ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
240         "%"PRIu16"-remote", pe->port);
241
242     for (i = 1; i <= TCP_STATE_MAX; i++)
243     {
244       vl.values[0].gauge = pe->count_remote[i];
245
246       sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
247
248       plugin_dispatch_values (&vl);
249     }
250   }
251 } /* void conn_submit */
252
253 static void conn_submit_all (void)
254 {
255   port_entry_t *pe;
256
257   for (pe = port_list_head; pe != NULL; pe = pe->next)
258     conn_submit_port_entry (pe);
259 } /* void conn_submit_all */
260
261 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
262 {
263   port_entry_t *ret;
264
265   ret = port_list_head;
266   while (ret != NULL)
267   {
268     if (ret->port == port)
269       break;
270     ret = ret->next;
271   }
272
273   if ((ret == NULL) && (create != 0))
274   {
275     ret = (port_entry_t *) malloc (sizeof (port_entry_t));
276     if (ret == NULL)
277       return (NULL);
278     memset (ret, '\0', sizeof (port_entry_t));
279
280     ret->port = port;
281     ret->next = port_list_head;
282     port_list_head = ret;
283   }
284
285   return (ret);
286 } /* port_entry_t *conn_get_port_entry */
287
288 /* Removes ports that were added automatically due to the `ListeningPorts'
289  * setting but which are no longer listening. */
290 static void conn_reset_port_entry (void)
291 {
292   port_entry_t *prev = NULL;
293   port_entry_t *pe = port_list_head;
294
295   while (pe != NULL)
296   {
297     /* If this entry was created while reading the files (ant not when handling
298      * the configuration) remove it now. */
299     if ((pe->flags & (PORT_COLLECT_LOCAL
300             | PORT_COLLECT_REMOTE
301             | PORT_IS_LISTENING)) == 0)
302     {
303       port_entry_t *next = pe->next;
304
305       DEBUG ("tcpconns plugin: Removing temporary entry "
306           "for listening port %"PRIu16, pe->port);
307
308       if (prev == NULL)
309         port_list_head = next;
310       else
311         prev->next = next;
312
313       sfree (pe);
314       pe = next;
315
316       continue;
317     }
318
319     memset (pe->count_local, '\0', sizeof (pe->count_local));
320     memset (pe->count_remote, '\0', sizeof (pe->count_remote));
321     pe->flags &= ~PORT_IS_LISTENING;
322
323     pe = pe->next;
324   }
325 } /* void conn_reset_port_entry */
326
327 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
328 {
329   port_entry_t *pe = NULL;
330
331   if ((state > TCP_STATE_MAX)
332 #if TCP_STATE_MIN > 0
333       || (state < TCP_STATE_MIN)
334 #endif
335      )
336   {
337     NOTICE ("tcpconns plugin: Ignoring connection with "
338         "unknown state 0x%02"PRIx8".", state);
339     return (-1);
340   }
341
342   /* Listening sockets */
343   if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
344   {
345     pe = conn_get_port_entry (port_local, 1 /* create */);
346     if (pe != NULL)
347       pe->flags |= PORT_IS_LISTENING;
348   }
349
350   DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
351       port_local, port_remote, tcp_state[state]);
352
353   pe = conn_get_port_entry (port_local, 0 /* no create */);
354   if (pe != NULL)
355     pe->count_local[state]++;
356
357   pe = conn_get_port_entry (port_remote, 0 /* no create */);
358   if (pe != NULL)
359     pe->count_remote[state]++;
360
361   return (0);
362 } /* int conn_handle_ports */
363
364 #if KERNEL_LINUX
365 static int conn_handle_line (char *buffer)
366 {
367   char *fields[32];
368   int   fields_len;
369
370   char *endptr;
371
372   char *port_local_str;
373   char *port_remote_str;
374   uint16_t port_local;
375   uint16_t port_remote;
376
377   uint8_t state;
378
379   int buffer_len = strlen (buffer);
380
381   while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
382     buffer[--buffer_len] = '\0';
383   if (buffer_len <= 0)
384     return (-1);
385
386   fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
387   if (fields_len < 12)
388   {
389     DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
390     return (-1);
391   }
392
393   port_local_str  = strchr (fields[1], ':');
394   port_remote_str = strchr (fields[2], ':');
395
396   if ((port_local_str == NULL) || (port_remote_str == NULL))
397     return (-1);
398   port_local_str++;
399   port_remote_str++;
400   if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
401     return (-1);
402
403   endptr = NULL;
404   port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
405   if ((endptr == NULL) || (*endptr != '\0'))
406     return (-1);
407
408   endptr = NULL;
409   port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
410   if ((endptr == NULL) || (*endptr != '\0'))
411     return (-1);
412
413   endptr = NULL;
414   state = (uint8_t) strtol (fields[3], &endptr, 16);
415   if ((endptr == NULL) || (*endptr != '\0'))
416     return (-1);
417
418   return (conn_handle_ports (port_local, port_remote, state));
419 } /* int conn_handle_line */
420
421 static int conn_read_file (const char *file)
422 {
423   FILE *fh;
424   char buffer[1024];
425
426   fh = fopen (file, "r");
427   if (fh == NULL)
428     return (-1);
429
430   while (fgets (buffer, sizeof (buffer), fh) != NULL)
431   {
432     conn_handle_line (buffer);
433   } /* while (fgets) */
434
435   fclose (fh);
436
437   return (0);
438 } /* int conn_read_file */
439 /* #endif KERNEL_LINUX */
440
441 #elif HAVE_SYSCTLBYNAME
442 /* #endif HAVE_SYSCTLBYNAME */
443
444 #elif HAVE_LIBKVM_NLIST
445 #endif /* HAVE_LIBKVM_NLIST */
446
447 static int conn_config (const char *key, const char *value)
448 {
449   if (strcasecmp (key, "ListeningPorts") == 0)
450   {
451     if ((strcasecmp (value, "Yes") == 0)
452         || (strcasecmp (value, "True") == 0)
453         || (strcasecmp (value, "On") == 0))
454       port_collect_listening = 1;
455     else
456       port_collect_listening = 0;
457   }
458   else if ((strcasecmp (key, "LocalPort") == 0)
459       || (strcasecmp (key, "RemotePort") == 0))
460   {
461       port_entry_t *pe;
462       int port = atoi (value);
463
464       if ((port < 1) || (port > 65535))
465       {
466         ERROR ("tcpconns plugin: Invalid port: %i", port);
467         return (1);
468       }
469
470       pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
471       if (pe == NULL)
472       {
473         ERROR ("tcpconns plugin: conn_get_port_entry failed.");
474         return (1);
475       }
476
477       if (strcasecmp (key, "LocalPort") == 0)
478         pe->flags |= PORT_COLLECT_LOCAL;
479       else
480         pe->flags |= PORT_COLLECT_REMOTE;
481   }
482   else
483   {
484     return (-1);
485   }
486
487   return (0);
488 } /* int conn_config */
489
490 #if KERNEL_LINUX
491 static int conn_init (void)
492 {
493   if (port_list_head == NULL)
494     port_collect_listening = 1;
495
496   return (0);
497 } /* int conn_init */
498
499 static int conn_read (void)
500 {
501   int errors_num = 0;
502
503   conn_reset_port_entry ();
504
505   if (conn_read_file ("/proc/net/tcp") != 0)
506     errors_num++;
507   if (conn_read_file ("/proc/net/tcp6") != 0)
508     errors_num++;
509
510   if (errors_num < 2)
511   {
512     conn_submit_all ();
513   }
514   else
515   {
516     ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
517         "coult be read.");
518     return (-1);
519   }
520
521   return (0);
522 } /* int conn_read */
523 /* #endif KERNEL_LINUX */
524
525 #elif HAVE_SYSCTLBYNAME
526 static int conn_read (void)
527 {
528   int status;
529   char *buffer;
530   size_t buffer_len;;
531
532   struct xinpgen *in_orig;
533   struct xinpgen *in_ptr;
534
535   conn_reset_port_entry ();
536
537   buffer_len = 0;
538   status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
539   if (status < 0)
540   {
541     ERROR ("tcpconns plugin: sysctlbyname failed.");
542     return (-1);
543   }
544
545   buffer = (char *) malloc (buffer_len);
546   if (buffer == NULL)
547   {
548     ERROR ("tcpconns plugin: malloc failed.");
549     return (-1);
550   }
551
552   status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
553   if (status < 0)
554   {
555     ERROR ("tcpconns plugin: sysctlbyname failed.");
556     sfree (buffer);
557     return (-1);
558   }
559
560   if (buffer_len <= sizeof (struct xinpgen))
561   {
562     ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
563     sfree (buffer);
564     return (-1);
565   }
566
567   in_orig = (struct xinpgen *) buffer;
568   for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
569       in_ptr->xig_len > sizeof (struct xinpgen);
570       in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
571   {
572     struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
573     struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
574     struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
575
576     /* Ignore non-TCP sockets */
577     if (so->xso_protocol != IPPROTO_TCP)
578       continue;
579
580     /* Ignore PCBs which were freed during copyout. */
581     if (inp->inp_gencnt > in_orig->xig_gen)
582       continue;
583
584     if (((inp->inp_vflag & INP_IPV4) == 0)
585         && ((inp->inp_vflag & INP_IPV6) == 0))
586       continue;
587
588     conn_handle_ports (ntohs (inp->inp_lport), ntohs (inp->inp_fport),
589         tp->t_state);
590   } /* for (in_ptr) */
591
592   in_orig = NULL;
593   in_ptr = NULL;
594   sfree (buffer);
595
596   conn_submit_all ();
597
598   return (0);
599 } /* int conn_read */
600 /* #endif HAVE_SYSCTLBYNAME */
601
602 #elif HAVE_LIBKVM_NLIST
603 static int kread (u_long addr, void *buf, int size)
604 {
605   int status;
606
607   status = kvm_read (kvmd, addr, buf, size);
608   if (status != size)
609   {
610     ERROR ("tcpconns plugin: kvm_read failed (got %i, expected %i): %s\n",
611         status, size, kvm_geterr (kvmd));
612     return (-1);
613   }
614   return (0);
615 } /* int kread */
616
617 static int conn_init (void)
618 {
619   char buf[_POSIX2_LINE_MAX];
620   struct nlist nl[] =
621   {
622 #define N_TCBTABLE 0
623     { "_tcbtable" },
624     { "" }
625   };
626   int status;
627
628   kvmd = kvm_openfiles (NULL, NULL, NULL, O_RDONLY, buf);
629   if (kvmd == NULL)
630   {
631     ERROR ("tcpconns plugin: kvm_openfiles failed: %s", buf);
632     return (-1);
633   }
634
635   status = kvm_nlist (kvmd, nl);
636   if (status < 0)
637   {
638     ERROR ("tcpconns plugin: kvm_nlist failed with status %i.", status);
639     return (-1);
640   }
641
642   if (nl[N_TCBTABLE].n_type == 0)
643   {
644     ERROR ("tcpconns plugin: Error looking up kernel's namelist: "
645         "N_TCBTABLE is invalid.");
646     return (-1);
647   }
648
649   inpcbtable_off = (u_long) nl[N_TCBTABLE].n_value;
650   inpcbtable_ptr = (struct inpcbtable *) nl[N_TCBTABLE].n_value;
651
652   return (0);
653 } /* int conn_init */
654
655 static int conn_read (void)
656 {
657   struct inpcbtable table;
658   struct inpcb *head;
659   struct inpcb *next;
660   struct inpcb inpcb;
661   struct tcpcb tcpcb;
662   int status;
663
664   conn_reset_port_entry ();
665
666   /* Read the pcbtable from the kernel */
667   status = kread (inpcbtable_off, &table, sizeof (table));
668   if (status != 0)
669     return (-1);
670
671   /* Get the `head' pcb */
672   head = (struct inpcb *) &(inpcbtable_ptr->inpt_queue);
673   /* Get the first pcb */
674   next = CIRCLEQ_FIRST (&table.inpt_queue);
675
676   while (next != head)
677   {
678     /* Read the pcb pointed to by `next' into `inpcb' */
679     kread ((u_long) next, &inpcb, sizeof (inpcb));
680
681     /* Advance `next' */
682     next = CIRCLEQ_NEXT (&inpcb, inp_queue);
683
684     /* Ignore sockets, that are not connected. */
685     if (!(inpcb.inp_flags & INP_IPV6)
686         && (inet_lnaof(inpcb.inp_laddr) == INADDR_ANY))
687       continue;
688     if ((inpcb.inp_flags & INP_IPV6)
689         && IN6_IS_ADDR_UNSPECIFIED (&inpcb.inp_laddr6))
690       continue;
691
692     kread ((u_long) inpcb.inp_ppcb, &tcpcb, sizeof (tcpcb));
693     conn_handle_ports (ntohs(inpcb.inp_lport), ntohs(inpcb.inp_fport), tcpcb.t_state);
694   } /* while (next != head) */
695
696   conn_submit_all ();
697
698   return (0);
699 }
700 #endif /* HAVE_LIBKVM_NLIST */
701
702 void module_register (void)
703 {
704         plugin_register_config ("tcpconns", conn_config,
705                         config_keys, config_keys_num);
706 #if KERNEL_LINUX
707         plugin_register_init ("tcpconns", conn_init);
708 #elif HAVE_SYSCTLBYNAME
709         /* no initialization */
710 #elif HAVE_LIBKVM_NLIST
711         plugin_register_init ("tcpconns", conn_init);
712 #endif
713         plugin_register_read ("tcpconns", conn_read);
714 } /* void module_register */
715
716 /*
717  * vim: set shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker :
718  */