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