Merge branch 'collectd-4.3' into collectd-4.4
[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 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25
26 #if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME
27 # error "No applicable input method."
28 #endif
29
30 #if KERNEL_LINUX
31 /* #endif KERNEL_LINUX */
32
33 #elif HAVE_SYSCTLBYNAME
34 # include <sys/socketvar.h>
35 # include <sys/sysctl.h>
36
37 /* Some includes needed for compiling on FreeBSD */
38 #include <sys/time.h>
39 #if HAVE_SYS_TYPES_H
40 # include <sys/types.h>
41 #endif
42 #if HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #if HAVE_NET_IF_H
46 # include <net/if.h>
47 #endif
48
49 # include <net/route.h>
50 # include <netinet/in.h>
51 # include <netinet/in_systm.h>
52 # include <netinet/ip.h>
53 # include <netinet/ip6.h>
54 # include <netinet/in_pcb.h>
55 # include <netinet/ip_var.h>
56 # include <netinet/tcp.h>
57 # include <netinet/tcpip.h>
58 # include <netinet/tcp_seq.h>
59 # include <netinet/tcp_var.h>
60 #endif /* HAVE_SYSCTLBYNAME */
61
62 #if KERNEL_LINUX
63 static const char *tcp_state[] =
64 {
65   "", /* 0 */
66   "ESTABLISHED",
67   "SYN_SENT",
68   "SYN_RECV",
69   "FIN_WAIT1",
70   "FIN_WAIT2",
71   "TIME_WAIT",
72   "CLOSED",
73   "CLOSE_WAIT",
74   "LAST_ACK",
75   "LISTEN", /* 10 */
76   "CLOSING"
77 };
78
79 # define TCP_STATE_LISTEN 10
80 # define TCP_STATE_MIN 1
81 # define TCP_STATE_MAX 11
82 /* #endif KERNEL_LINUX */
83
84 #elif HAVE_SYSCTLBYNAME
85 static const char *tcp_state[] =
86 {
87   "CLOSED",
88   "LISTEN",
89   "SYN_SENT",
90   "SYN_RECV",
91   "ESTABLISHED",
92   "CLOSE_WAIT",
93   "FIN_WAIT1",
94   "CLOSING",
95   "LAST_ACK",
96   "FIN_WAIT2",
97   "TIME_WAIT"
98 };
99
100 # define TCP_STATE_LISTEN 1
101 # define TCP_STATE_MIN 0
102 # define TCP_STATE_MAX 10
103 #endif /* HAVE_SYSCTLBYNAME */
104
105 #define PORT_COLLECT_LOCAL  0x01
106 #define PORT_COLLECT_REMOTE 0x02
107 #define PORT_IS_LISTENING   0x04
108
109 typedef struct port_entry_s
110 {
111   uint16_t port;
112   uint16_t flags;
113   uint32_t count_local[TCP_STATE_MAX + 1];
114   uint32_t count_remote[TCP_STATE_MAX + 1];
115   struct port_entry_s *next;
116 } port_entry_t;
117
118 static const char *config_keys[] =
119 {
120   "ListeningPorts",
121   "LocalPort",
122   "RemotePort"
123 };
124 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
125
126 static int port_collect_listening = 0;
127 static port_entry_t *port_list_head = NULL;
128
129 static void conn_submit_port_entry (port_entry_t *pe)
130 {
131   value_t values[1];
132   value_list_t vl = VALUE_LIST_INIT;
133   int i;
134
135   vl.values = values;
136   vl.values_len = 1;
137   vl.time = time (NULL);
138   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
139   sstrncpy (vl.plugin, "tcpconns", sizeof (vl.plugin));
140
141   if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
142       || (pe->flags & PORT_COLLECT_LOCAL))
143   {
144     snprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
145         "%"PRIu16"-local", pe->port);
146     vl.plugin_instance[sizeof (vl.plugin_instance) - 1] = '\0';
147
148     for (i = 1; i <= TCP_STATE_MAX; i++)
149     {
150       vl.values[0].gauge = pe->count_local[i];
151
152       strncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
153       vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
154
155       plugin_dispatch_values ("tcp_connections", &vl);
156     }
157   }
158
159   if (pe->flags & PORT_COLLECT_REMOTE)
160   {
161     snprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
162         "%"PRIu16"-remote", pe->port);
163     vl.plugin_instance[sizeof (vl.plugin_instance) - 1] = '\0';
164
165     for (i = 1; i <= TCP_STATE_MAX; i++)
166     {
167       vl.values[0].gauge = pe->count_remote[i];
168
169       strncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
170       vl.type_instance[sizeof (vl.type_instance) - 1] = '\0';
171
172       plugin_dispatch_values ("tcp_connections", &vl);
173     }
174   }
175 } /* void conn_submit */
176
177 static void conn_submit_all (void)
178 {
179   port_entry_t *pe;
180
181   for (pe = port_list_head; pe != NULL; pe = pe->next)
182     conn_submit_port_entry (pe);
183 } /* void conn_submit_all */
184
185 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
186 {
187   port_entry_t *ret;
188
189   ret = port_list_head;
190   while (ret != NULL)
191   {
192     if (ret->port == port)
193       break;
194     ret = ret->next;
195   }
196
197   if ((ret == NULL) && (create != 0))
198   {
199     ret = (port_entry_t *) malloc (sizeof (port_entry_t));
200     if (ret == NULL)
201       return (NULL);
202     memset (ret, '\0', sizeof (port_entry_t));
203
204     ret->port = port;
205     ret->next = port_list_head;
206     port_list_head = ret;
207   }
208
209   return (ret);
210 } /* port_entry_t *conn_get_port_entry */
211
212 /* Removes ports that were added automatically due to the `ListeningPorts'
213  * setting but which are no longer listening. */
214 static void conn_reset_port_entry (void)
215 {
216   port_entry_t *prev = NULL;
217   port_entry_t *pe = port_list_head;
218
219   while (pe != NULL)
220   {
221     /* If this entry was created while reading the files (ant not when handling
222      * the configuration) remove it now. */
223     if ((pe->flags & (PORT_COLLECT_LOCAL
224             | PORT_COLLECT_REMOTE
225             | PORT_IS_LISTENING)) == 0)
226     {
227       port_entry_t *next = pe->next;
228
229       DEBUG ("tcpconns plugin: Removing temporary entry "
230           "for listening port %"PRIu16, pe->port);
231
232       if (prev == NULL)
233         port_list_head = next;
234       else
235         prev->next = next;
236
237       sfree (pe);
238       pe = next;
239
240       continue;
241     }
242
243     memset (pe->count_local, '\0', sizeof (pe->count_local));
244     memset (pe->count_remote, '\0', sizeof (pe->count_remote));
245     pe->flags &= ~PORT_IS_LISTENING;
246
247     pe = pe->next;
248   }
249 } /* void conn_reset_port_entry */
250
251 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
252 {
253   port_entry_t *pe = NULL;
254
255   if ((state > TCP_STATE_MAX)
256 #if TCP_STATE_MIN > 0
257       || (state < TCP_STATE_MIN)
258 #endif
259      )
260   {
261     NOTICE ("tcpconns plugin: Ignoring connection with "
262         "unknown state 0x%02"PRIx8".", state);
263     return (-1);
264   }
265
266   /* Listening sockets */
267   if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
268   {
269     pe = conn_get_port_entry (port_local, 1 /* create */);
270     if (pe != NULL)
271       pe->flags |= PORT_IS_LISTENING;
272   }
273
274   DEBUG ("tcpconns plugin: Connection %"PRIu16" <-> %"PRIu16" (%s)",
275       port_local, port_remote, tcp_state[state]);
276
277   pe = conn_get_port_entry (port_local, 0 /* no create */);
278   if (pe != NULL)
279     pe->count_local[state]++;
280
281   pe = conn_get_port_entry (port_remote, 0 /* no create */);
282   if (pe != NULL)
283     pe->count_remote[state]++;
284
285   return (0);
286 } /* int conn_handle_ports */
287
288 #if KERNEL_LINUX
289 static int conn_handle_line (char *buffer)
290 {
291   char *fields[32];
292   int   fields_len;
293
294   char *endptr;
295
296   char *port_local_str;
297   char *port_remote_str;
298   uint16_t port_local;
299   uint16_t port_remote;
300
301   uint8_t state;
302
303   int buffer_len = strlen (buffer);
304
305   while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
306     buffer[--buffer_len] = '\0';
307   if (buffer_len <= 0)
308     return (-1);
309
310   fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
311   if (fields_len < 12)
312   {
313     DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
314     return (-1);
315   }
316
317   port_local_str  = strchr (fields[1], ':');
318   port_remote_str = strchr (fields[2], ':');
319
320   if ((port_local_str == NULL) || (port_remote_str == NULL))
321     return (-1);
322   port_local_str++;
323   port_remote_str++;
324   if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
325     return (-1);
326
327   endptr = NULL;
328   port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
329   if ((endptr == NULL) || (*endptr != '\0'))
330     return (-1);
331
332   endptr = NULL;
333   port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
334   if ((endptr == NULL) || (*endptr != '\0'))
335     return (-1);
336
337   endptr = NULL;
338   state = (uint8_t) strtol (fields[3], &endptr, 16);
339   if ((endptr == NULL) || (*endptr != '\0'))
340     return (-1);
341
342   return (conn_handle_ports (port_local, port_remote, state));
343 } /* int conn_handle_line */
344
345 static int conn_read_file (const char *file)
346 {
347   FILE *fh;
348   char buffer[1024];
349
350   fh = fopen (file, "r");
351   if (fh == NULL)
352     return (-1);
353
354   while (fgets (buffer, sizeof (buffer), fh) != NULL)
355   {
356     conn_handle_line (buffer);
357   } /* while (fgets) */
358
359   fclose (fh);
360
361   return (0);
362 } /* int conn_read_file */
363 /* #endif KERNEL_LINUX */
364
365 #elif HAVE_SYSCTLBYNAME
366 #endif /* HAVE_SYSCTLBYNAME */
367
368 static int conn_config (const char *key, const char *value)
369 {
370   if (strcasecmp (key, "ListeningPorts") == 0)
371   {
372     if ((strcasecmp (value, "Yes") == 0)
373         || (strcasecmp (value, "True") == 0)
374         || (strcasecmp (value, "On") == 0))
375       port_collect_listening = 1;
376     else
377       port_collect_listening = 0;
378   }
379   else if ((strcasecmp (key, "LocalPort") == 0)
380       || (strcasecmp (key, "RemotePort") == 0))
381   {
382       port_entry_t *pe;
383       int port = atoi (value);
384
385       if ((port < 1) || (port > 65535))
386       {
387         ERROR ("tcpconns plugin: Invalid port: %i", port);
388         return (1);
389       }
390
391       pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
392       if (pe == NULL)
393       {
394         ERROR ("tcpconns plugin: conn_get_port_entry failed.");
395         return (1);
396       }
397
398       if (strcasecmp (key, "LocalPort") == 0)
399         pe->flags |= PORT_COLLECT_LOCAL;
400       else
401         pe->flags |= PORT_COLLECT_REMOTE;
402   }
403   else
404   {
405     return (-1);
406   }
407
408   return (0);
409 } /* int conn_config */
410
411 #if KERNEL_LINUX
412 static int conn_init (void)
413 {
414   if (port_list_head == NULL)
415     port_collect_listening = 1;
416
417   return (0);
418 } /* int conn_init */
419
420 static int conn_read (void)
421 {
422   int errors_num = 0;
423
424   conn_reset_port_entry ();
425
426   if (conn_read_file ("/proc/net/tcp") != 0)
427     errors_num++;
428   if (conn_read_file ("/proc/net/tcp6") != 0)
429     errors_num++;
430
431   if (errors_num < 2)
432   {
433     conn_submit_all ();
434   }
435   else
436   {
437     ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
438         "coult be read.");
439     return (-1);
440   }
441
442   return (0);
443 } /* int conn_read */
444 /* #endif KERNEL_LINUX */
445
446 #elif HAVE_SYSCTLBYNAME
447 static int conn_read (void)
448 {
449   int status;
450   char *buffer;
451   size_t buffer_len;;
452
453   struct xinpgen *in_orig;
454   struct xinpgen *in_ptr;
455
456   conn_reset_port_entry ();
457
458   buffer_len = 0;
459   status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
460   if (status < 0)
461   {
462     ERROR ("tcpconns plugin: sysctlbyname failed.");
463     return (-1);
464   }
465
466   buffer = (char *) malloc (buffer_len);
467   if (buffer == NULL)
468   {
469     ERROR ("tcpconns plugin: malloc failed.");
470     return (-1);
471   }
472
473   status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
474   if (status < 0)
475   {
476     ERROR ("tcpconns plugin: sysctlbyname failed.");
477     sfree (buffer);
478     return (-1);
479   }
480
481   if (buffer_len <= sizeof (struct xinpgen))
482   {
483     ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
484     sfree (buffer);
485     return (-1);
486   }
487
488   in_orig = (struct xinpgen *) buffer;
489   for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
490       in_ptr->xig_len > sizeof (struct xinpgen);
491       in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
492   {
493     struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
494     struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
495     struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
496
497     /* Ignore non-TCP sockets */
498     if (so->xso_protocol != IPPROTO_TCP)
499       continue;
500
501     /* Ignore PCBs which were freed during copyout. */
502     if (inp->inp_gencnt > in_orig->xig_gen)
503       continue;
504
505     if (((inp->inp_vflag & INP_IPV4) == 0)
506         && ((inp->inp_vflag & INP_IPV6) == 0))
507       continue;
508
509     conn_handle_ports (inp->inp_lport, inp->inp_fport, tp->t_state);
510   } /* for (in_ptr) */
511
512   in_orig = NULL;
513   in_ptr = NULL;
514   sfree (buffer);
515
516   conn_submit_all ();
517
518   return (0);
519 } /* int conn_read */
520 #endif /* HAVE_SYSCTLBYNAME */
521
522 void module_register (void)
523 {
524         plugin_register_config ("tcpconns", conn_config,
525                         config_keys, config_keys_num);
526 #if KERNEL_LINUX
527         plugin_register_init ("tcpconns", conn_init);
528 #endif
529         plugin_register_read ("tcpconns", conn_read);
530 } /* void module_register */
531
532 /*
533  * vim: set shiftwidth=2 softtabstop=2 tabstop=8 :
534  */