Merge branch 'collectd-4.3'
[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   strcpy (vl.host, hostname_g);
139   strcpy (vl.plugin, "tcpconns");
140   strcpy (vl.type, "tcp_connections");
141
142   if (((port_collect_listening != 0) && (pe->flags & PORT_IS_LISTENING))
143       || (pe->flags & PORT_COLLECT_LOCAL))
144   {
145     ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
146         "%hu-local", pe->port);
147
148     for (i = 1; i <= TCP_STATE_MAX; i++)
149     {
150       vl.values[0].gauge = pe->count_local[i];
151
152       sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
153
154       plugin_dispatch_values (&vl);
155     }
156   }
157
158   if (pe->flags & PORT_COLLECT_REMOTE)
159   {
160     ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance),
161         "%hu-remote", pe->port);
162
163     for (i = 1; i <= TCP_STATE_MAX; i++)
164     {
165       vl.values[0].gauge = pe->count_remote[i];
166
167       sstrncpy (vl.type_instance, tcp_state[i], sizeof (vl.type_instance));
168
169       plugin_dispatch_values (&vl);
170     }
171   }
172 } /* void conn_submit */
173
174 static void conn_submit_all (void)
175 {
176   port_entry_t *pe;
177
178   for (pe = port_list_head; pe != NULL; pe = pe->next)
179     conn_submit_port_entry (pe);
180 } /* void conn_submit_all */
181
182 static port_entry_t *conn_get_port_entry (uint16_t port, int create)
183 {
184   port_entry_t *ret;
185
186   ret = port_list_head;
187   while (ret != NULL)
188   {
189     if (ret->port == port)
190       break;
191     ret = ret->next;
192   }
193
194   if ((ret == NULL) && (create != 0))
195   {
196     ret = (port_entry_t *) malloc (sizeof (port_entry_t));
197     if (ret == NULL)
198       return (NULL);
199     memset (ret, '\0', sizeof (port_entry_t));
200
201     ret->port = port;
202     ret->next = port_list_head;
203     port_list_head = ret;
204   }
205
206   return (ret);
207 } /* port_entry_t *conn_get_port_entry */
208
209 /* Removes ports that were added automatically due to the `ListeningPorts'
210  * setting but which are no longer listening. */
211 static void conn_reset_port_entry (void)
212 {
213   port_entry_t *prev = NULL;
214   port_entry_t *pe = port_list_head;
215
216   while (pe != NULL)
217   {
218     /* If this entry was created while reading the files (ant not when handling
219      * the configuration) remove it now. */
220     if ((pe->flags & (PORT_COLLECT_LOCAL
221             | PORT_COLLECT_REMOTE
222             | PORT_IS_LISTENING)) == 0)
223     {
224       port_entry_t *next = pe->next;
225
226       DEBUG ("tcpconns plugin: Removing temporary entry "
227           "for listening port %hu", pe->port);
228
229       if (prev == NULL)
230         port_list_head = next;
231       else
232         prev->next = next;
233
234       sfree (pe);
235       pe = next;
236
237       continue;
238     }
239
240     memset (pe->count_local, '\0', sizeof (pe->count_local));
241     memset (pe->count_remote, '\0', sizeof (pe->count_remote));
242     pe->flags &= ~PORT_IS_LISTENING;
243
244     pe = pe->next;
245   }
246 } /* void conn_reset_port_entry */
247
248 static int conn_handle_ports (uint16_t port_local, uint16_t port_remote, uint8_t state)
249 {
250   port_entry_t *pe = NULL;
251
252   if ((state > TCP_STATE_MAX)
253 #if TCP_STATE_MIN > 0
254       || (state < TCP_STATE_MIN)
255 #endif
256      )
257   {
258     NOTICE ("tcpconns plugin: Ignoring connection with unknown state 0x%02x.",
259         state);
260     return (-1);
261   }
262
263   /* Listening sockets */
264   if ((state == TCP_STATE_LISTEN) && (port_collect_listening != 0))
265   {
266     pe = conn_get_port_entry (port_local, 1 /* create */);
267     if (pe != NULL)
268       pe->flags |= PORT_IS_LISTENING;
269   }
270
271   DEBUG ("tcpconns plugin: Connection %hu <-> %hu (%s)",
272       port_local, port_remote, tcp_state[state]);
273
274   pe = conn_get_port_entry (port_local, 0 /* no create */);
275   if (pe != NULL)
276     pe->count_local[state]++;
277
278   pe = conn_get_port_entry (port_remote, 0 /* no create */);
279   if (pe != NULL)
280     pe->count_remote[state]++;
281
282   return (0);
283 } /* int conn_handle_ports */
284
285 #if KERNEL_LINUX
286 static int conn_handle_line (char *buffer)
287 {
288   char *fields[32];
289   int   fields_len;
290
291   char *endptr;
292
293   char *port_local_str;
294   char *port_remote_str;
295   uint16_t port_local;
296   uint16_t port_remote;
297
298   uint8_t state;
299
300   int buffer_len = strlen (buffer);
301
302   while ((buffer_len > 0) && (buffer[buffer_len - 1] < 32))
303     buffer[--buffer_len] = '\0';
304   if (buffer_len <= 0)
305     return (-1);
306
307   fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
308   if (fields_len < 12)
309   {
310     DEBUG ("tcpconns plugin: Got %i fields, expected at least 12.", fields_len);
311     return (-1);
312   }
313
314   port_local_str  = strchr (fields[1], ':');
315   port_remote_str = strchr (fields[2], ':');
316
317   if ((port_local_str == NULL) || (port_remote_str == NULL))
318     return (-1);
319   port_local_str++;
320   port_remote_str++;
321   if ((*port_local_str == '\0') || (*port_remote_str == '\0'))
322     return (-1);
323
324   endptr = NULL;
325   port_local = (uint16_t) strtol (port_local_str, &endptr, 16);
326   if ((endptr == NULL) || (*endptr != '\0'))
327     return (-1);
328
329   endptr = NULL;
330   port_remote = (uint16_t) strtol (port_remote_str, &endptr, 16);
331   if ((endptr == NULL) || (*endptr != '\0'))
332     return (-1);
333
334   endptr = NULL;
335   state = (uint8_t) strtol (fields[3], &endptr, 16);
336   if ((endptr == NULL) || (*endptr != '\0'))
337     return (-1);
338
339   return (conn_handle_ports (port_local, port_remote, state));
340 } /* int conn_handle_line */
341
342 static int conn_read_file (const char *file)
343 {
344   FILE *fh;
345   char buffer[1024];
346
347   fh = fopen (file, "r");
348   if (fh == NULL)
349     return (-1);
350
351   while (fgets (buffer, sizeof (buffer), fh) != NULL)
352   {
353     conn_handle_line (buffer);
354   } /* while (fgets) */
355
356   fclose (fh);
357
358   return (0);
359 } /* int conn_read_file */
360 /* #endif KERNEL_LINUX */
361
362 #elif HAVE_SYSCTLBYNAME
363 #endif /* HAVE_SYSCTLBYNAME */
364
365 static int conn_config (const char *key, const char *value)
366 {
367   if (strcasecmp (key, "ListeningPorts") == 0)
368   {
369     if ((strcasecmp (value, "Yes") == 0)
370         || (strcasecmp (value, "True") == 0)
371         || (strcasecmp (value, "On") == 0))
372       port_collect_listening = 1;
373     else
374       port_collect_listening = 0;
375   }
376   else if ((strcasecmp (key, "LocalPort") == 0)
377       || (strcasecmp (key, "RemotePort") == 0))
378   {
379       port_entry_t *pe;
380       int port = atoi (value);
381
382       if ((port < 1) || (port > 65535))
383       {
384         ERROR ("tcpconns plugin: Invalid port: %i", port);
385         return (1);
386       }
387
388       pe = conn_get_port_entry ((uint16_t) port, 1 /* create */);
389       if (pe == NULL)
390       {
391         ERROR ("tcpconns plugin: conn_get_port_entry failed.");
392         return (1);
393       }
394
395       if (strcasecmp (key, "LocalPort") == 0)
396         pe->flags |= PORT_COLLECT_LOCAL;
397       else
398         pe->flags |= PORT_COLLECT_REMOTE;
399   }
400   else
401   {
402     return (-1);
403   }
404
405   return (0);
406 } /* int conn_config */
407
408 #if KERNEL_LINUX
409 static int conn_init (void)
410 {
411   if (port_list_head == NULL)
412     port_collect_listening = 1;
413
414   return (0);
415 } /* int conn_init */
416
417 static int conn_read (void)
418 {
419   int errors_num = 0;
420
421   conn_reset_port_entry ();
422
423   if (conn_read_file ("/proc/net/tcp") != 0)
424     errors_num++;
425   if (conn_read_file ("/proc/net/tcp6") != 0)
426     errors_num++;
427
428   if (errors_num < 2)
429   {
430     conn_submit_all ();
431   }
432   else
433   {
434     ERROR ("tcpconns plugin: Neither /proc/net/tcp nor /proc/net/tcp6 "
435         "coult be read.");
436     return (-1);
437   }
438
439   return (0);
440 } /* int conn_read */
441 /* #endif KERNEL_LINUX */
442
443 #elif HAVE_SYSCTLBYNAME
444 static int conn_read (void)
445 {
446   int status;
447   char *buffer;
448   size_t buffer_len;;
449
450   struct xinpgen *in_orig;
451   struct xinpgen *in_ptr;
452
453   conn_reset_port_entry ();
454
455   buffer_len = 0;
456   status = sysctlbyname ("net.inet.tcp.pcblist", NULL, &buffer_len, 0, 0);
457   if (status < 0)
458   {
459     ERROR ("tcpconns plugin: sysctlbyname failed.");
460     return (-1);
461   }
462
463   buffer = (char *) malloc (buffer_len);
464   if (buffer == NULL)
465   {
466     ERROR ("tcpconns plugin: malloc failed.");
467     return (-1);
468   }
469
470   status = sysctlbyname ("net.inet.tcp.pcblist", buffer, &buffer_len, 0, 0);
471   if (status < 0)
472   {
473     ERROR ("tcpconns plugin: sysctlbyname failed.");
474     sfree (buffer);
475     return (-1);
476   }
477
478   if (buffer_len <= sizeof (struct xinpgen))
479   {
480     ERROR ("tcpconns plugin: (buffer_len <= sizeof (struct xinpgen))");
481     sfree (buffer);
482     return (-1);
483   }
484
485   in_orig = (struct xinpgen *) buffer;
486   for (in_ptr = (struct xinpgen *) (((char *) in_orig) + in_orig->xig_len);
487       in_ptr->xig_len > sizeof (struct xinpgen);
488       in_ptr = (struct xinpgen *) (((char *) in_ptr) + in_ptr->xig_len))
489   {
490     struct tcpcb *tp = &((struct xtcpcb *) in_ptr)->xt_tp;
491     struct inpcb *inp = &((struct xtcpcb *) in_ptr)->xt_inp;
492     struct xsocket *so = &((struct xtcpcb *) in_ptr)->xt_socket;
493
494     /* Ignore non-TCP sockets */
495     if (so->xso_protocol != IPPROTO_TCP)
496       continue;
497
498     /* Ignore PCBs which were freed during copyout. */
499     if (inp->inp_gencnt > in_orig->xig_gen)
500       continue;
501
502     if (((inp->inp_vflag & INP_IPV4) == 0)
503         && ((inp->inp_vflag & INP_IPV6) == 0))
504       continue;
505
506     conn_handle_ports (inp->inp_lport, inp->inp_fport, tp->t_state);
507   } /* for (in_ptr) */
508
509   in_orig = NULL;
510   in_ptr = NULL;
511   sfree (buffer);
512
513   conn_submit_all ();
514
515   return (0);
516 } /* int conn_read */
517 #endif /* HAVE_SYSCTLBYNAME */
518
519 void module_register (void)
520 {
521         plugin_register_config ("tcpconns", conn_config,
522                         config_keys, config_keys_num);
523 #if KERNEL_LINUX
524         plugin_register_init ("tcpconns", conn_init);
525 #endif
526         plugin_register_read ("tcpconns", conn_read);
527 } /* void module_register */
528
529 /*
530  * vim: set shiftwidth=2 softtabstop=2 tabstop=8 :
531  */