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