f6d5b99f4814e460598ec64c268b3f4212bc098b
[collectd.git] / src / openvpn.c
1 /**
2  * collectd - src/openvpn.c
3  * Copyright (C) 2008       Doug MacEachern
4  * Copyright (C) 2009,2010  Florian octo Forster
5  * Copyright (C) 2009       Marco Chiappero
6  * Copyright (C) 2009       Fabian Schuh
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by the
10  * Free Software Foundation; only version 2 of the License is applicable.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
20  *
21  * Authors:
22  *   Doug MacEachern <dougm at hyperic.com>
23  *   Florian octo Forster <octo at collectd.org>
24  *   Marco Chiappero <marco at absence.it>
25  *   Fabian Schuh <mail at xeroc.org>
26  *   Pavel Rochnyak <pavel2000 ngs.ru>
27  **/
28
29 #include "collectd.h"
30
31 #include "common.h"
32 #include "plugin.h"
33
34 /**
35  * There is two main kinds of OpenVPN status file:
36  * - for 'single' mode (point-to-point or client mode)
37  * - for 'multi' mode  (server with multiple clients)
38  *
39  * For 'multi' there is 3 versions of status file format:
40  * - version 1 - First version of status file: without line type tokens,
41  *   comma delimited for easy machine parsing. Currently used by default.
42  *   Added in openvpn-2.0-beta3.
43  * - version 2 - with line type tokens, with 'HEADER' line type, uses comma
44  *   as a delimiter.
45  *   Added in openvpn-2.0-beta15.
46  * - version 3 - The only difference from version 2 is delimiter: in version 3
47  *   tabs are used instead of commas. Set of fields is the same.
48  *   Added in openvpn-2.1_rc14.
49  *
50  * For versions 2/3 there may be different sets of fields in different
51  * OpenVPN versions.
52  *
53  * Versions 2.0, 2.1, 2.2:
54  * Common Name,Real Address,Virtual Address,
55  * Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t)
56  *
57  * Version 2.3:
58  * Common Name,Real Address,Virtual Address,
59  * Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username
60  *
61  * Version 2.4:
62  * Common Name,Real Address,Virtual Address,Virtual IPv6 Address,
63  * Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,
64  * Client ID,Peer ID
65  *
66  * Current Collectd code tries to handle changes in this field set,
67  * if they are backward-compatible.
68  **/
69
70 #define TITLE_SINGLE "OpenVPN STATISTICS\n"
71 #define TITLE_V1     "OpenVPN CLIENT LIST\n"
72 #define TITLE_V2     "TITLE"
73
74 #define V1HEADER                                                               \
75   "Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since\n"
76
77 struct vpn_status_s {
78   char *file;
79   char *name;
80 };
81 typedef struct vpn_status_s vpn_status_t;
82
83 static _Bool new_naming_schema = 0;
84 static _Bool collect_compression = 1;
85 static _Bool collect_user_count = 0;
86 static _Bool collect_individual_users = 1;
87
88 static const char *config_keys[] = {
89     "StatusFile",           "Compression", /* old, deprecated name */
90     "ImprovedNamingSchema", "CollectCompression",
91     "CollectUserCount",     "CollectIndividualUsers"};
92 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
93
94 /* Helper function
95  * copy-n-pasted from common.c - changed delim to ",\t"  */
96 static int openvpn_strsplit(char *string, char **fields, size_t size) {
97   size_t i;
98   char *ptr;
99   char *saveptr;
100
101   i = 0;
102   ptr = string;
103   saveptr = NULL;
104   while ((fields[i] = strtok_r(ptr, ",\t", &saveptr)) != NULL) {
105     ptr = NULL;
106     i++;
107
108     if (i >= size)
109       break;
110   }
111
112   return i;
113 } /* int openvpn_strsplit */
114
115 static void openvpn_free(void *arg) {
116   vpn_status_t *st = arg;
117   
118   sfree(st->file);
119   sfree(st);
120 } /* void openvpn_free */
121
122 /* dispatches number of users */
123 static void numusers_submit(const char *pinst, const char *tinst,
124                             gauge_t value) {
125   value_list_t vl = VALUE_LIST_INIT;
126
127   vl.values = &(value_t){.gauge = value};
128   vl.values_len = 1;
129   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
130   sstrncpy(vl.type, "users", sizeof(vl.type));
131   if (pinst != NULL)
132     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
133   if (tinst != NULL)
134     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
135
136   plugin_dispatch_values(&vl);
137 } /* void numusers_submit */
138
139 /* dispatches stats about traffic (TCP or UDP) generated by the tunnel
140  * per single endpoint */
141 static void iostats_submit(const char *pinst, const char *tinst, derive_t rx,
142                            derive_t tx) {
143   value_list_t vl = VALUE_LIST_INIT;
144   value_t values[] = {
145       {.derive = rx}, {.derive = tx},
146   };
147
148   /* NOTE ON THE NEW NAMING SCHEMA:
149    *       using plugin_instance to identify each vpn config (and
150    *       status) file; using type_instance to identify the endpoint
151    *       host when in multimode, traffic or overhead when in single.
152    */
153
154   vl.values = values;
155   vl.values_len = STATIC_ARRAY_SIZE(values);
156   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
157   if (pinst != NULL)
158     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
159   sstrncpy(vl.type, "if_octets", sizeof(vl.type));
160   if (tinst != NULL)
161     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
162
163   plugin_dispatch_values(&vl);
164 } /* void traffic_submit */
165
166 /* dispatches stats about data compression shown when in single mode */
167 static void compression_submit(const char *pinst, const char *tinst,
168                                derive_t uncompressed, derive_t compressed) {
169   value_list_t vl = VALUE_LIST_INIT;
170   value_t values[] = {
171       {.derive = uncompressed}, {.derive = compressed},
172   };
173
174   vl.values = values;
175   vl.values_len = STATIC_ARRAY_SIZE(values);
176   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
177   if (pinst != NULL)
178     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
179   sstrncpy(vl.type, "compression", sizeof(vl.type));
180   if (tinst != NULL)
181     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
182
183   plugin_dispatch_values(&vl);
184 } /* void compression_submit */
185
186 static int single_read(const char *name, FILE *fh) {
187   char buffer[1024];
188   char *fields[4];
189   const int max_fields = STATIC_ARRAY_SIZE(fields);
190   int fields_num;
191
192   derive_t link_rx, link_tx;
193   derive_t tun_rx, tun_tx;
194   derive_t pre_compress, post_compress;
195   derive_t pre_decompress, post_decompress;
196   derive_t overhead_rx, overhead_tx;
197
198   link_rx = 0;
199   link_tx = 0;
200   tun_rx = 0;
201   tun_tx = 0;
202   pre_compress = 0;
203   post_compress = 0;
204   pre_decompress = 0;
205   post_decompress = 0;
206
207   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
208     fields_num = openvpn_strsplit(buffer, fields, max_fields);
209
210     /* status file is generated by openvpn/sig.c:print_status()
211      * http://svn.openvpn.net/projects/openvpn/trunk/openvpn/sig.c
212      *
213      * The line we're expecting has 2 fields. We ignore all lines
214      *  with more or less fields.
215      */
216     if (fields_num != 2) {
217       continue;
218     }
219
220     if (strcmp(fields[0], "TUN/TAP read bytes") == 0) {
221       /* read from the system and sent over the tunnel */
222       tun_tx = atoll(fields[1]);
223     } else if (strcmp(fields[0], "TUN/TAP write bytes") == 0) {
224       /* read from the tunnel and written in the system */
225       tun_rx = atoll(fields[1]);
226     } else if (strcmp(fields[0], "TCP/UDP read bytes") == 0) {
227       link_rx = atoll(fields[1]);
228     } else if (strcmp(fields[0], "TCP/UDP write bytes") == 0) {
229       link_tx = atoll(fields[1]);
230     } else if (strcmp(fields[0], "pre-compress bytes") == 0) {
231       pre_compress = atoll(fields[1]);
232     } else if (strcmp(fields[0], "post-compress bytes") == 0) {
233       post_compress = atoll(fields[1]);
234     } else if (strcmp(fields[0], "pre-decompress bytes") == 0) {
235       pre_decompress = atoll(fields[1]);
236     } else if (strcmp(fields[0], "post-decompress bytes") == 0) {
237       post_decompress = atoll(fields[1]);
238     }
239   }
240
241   iostats_submit(name, "traffic", link_rx, link_tx);
242
243   /* we need to force this order to avoid negative values with these unsigned */
244   overhead_rx = (((link_rx - pre_decompress) + post_decompress) - tun_rx);
245   overhead_tx = (((link_tx - post_compress) + pre_compress) - tun_tx);
246
247   iostats_submit(name, "overhead", overhead_rx, overhead_tx);
248
249   if (collect_compression) {
250     compression_submit(name, "data_in", post_decompress, pre_decompress);
251     compression_submit(name, "data_out", pre_compress, post_compress);
252   }
253
254   return 0;
255 } /* int single_read */
256
257 /* for reading status version 1 */
258 static int multi1_read(const char *name, FILE *fh) {
259   char buffer[1024];
260   char *fields[10];
261   int fields_num, found_header = 0;
262   long long sum_users = 0;
263
264   /* read the file until the "ROUTING TABLE" line is found (no more info after)
265    */
266   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
267     if (strcmp(buffer, "ROUTING TABLE\n") == 0)
268       break;
269
270     if (strcmp(buffer, V1HEADER) == 0) {
271       found_header = 1;
272       continue;
273     }
274
275     /* skip the first lines until the client list section is found */
276     if (found_header == 0)
277       /* we can't start reading data until this string is found */
278       continue;
279
280     fields_num = openvpn_strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
281     if (fields_num < 4)
282       continue;
283
284     if (collect_user_count)
285     /* If so, sum all users, ignore the individuals*/
286     {
287       sum_users += 1;
288     }
289     if (collect_individual_users) {
290       if (new_naming_schema) {
291         iostats_submit(name,              /* vpn instance */
292                        fields[0],         /* "Common Name" */
293                        atoll(fields[2]),  /* "Bytes Received" */
294                        atoll(fields[3])); /* "Bytes Sent" */
295       } else {
296         iostats_submit(fields[0],         /* "Common Name" */
297                        NULL,              /* unused when in multimode */
298                        atoll(fields[2]),  /* "Bytes Received" */
299                        atoll(fields[3])); /* "Bytes Sent" */
300       }
301     }
302   }
303
304   if (ferror(fh))
305     return -1;
306
307   if (found_header == 0) {
308     NOTICE("openvpn plugin: Unknown file format in instance %s, please "
309            "report this as bug. Make sure to include "
310            "your status file, so the plugin can "
311            "be adapted.",
312            name);
313     return -1;
314   }
315
316   if (collect_user_count)
317     numusers_submit(name, name, sum_users);
318
319   return 0;
320 } /* int multi1_read */
321
322 /* for reading status version 2 / version 3
323  * status file is generated by openvpn/multi.c:multi_print_status()
324  * http://svn.openvpn.net/projects/openvpn/trunk/openvpn/multi.c
325  */
326 static int multi2_read(const char *name, FILE *fh) {
327   char buffer[1024];
328   /* OpenVPN-2.4 has 11 fields of data + 2 fields for "HEADER" and "CLIENT_LIST"
329    * So, set array size to 20 elements, to support future extensions.
330    */
331   char *fields[20];
332   const int max_fields = STATIC_ARRAY_SIZE(fields);
333   int fields_num;
334   long long sum_users = 0;
335   
336   int found_header = 0;
337   int idx_cname = 0;
338   int idx_bytes_recv = 0;
339   int idx_bytes_sent = 0;
340   int columns = 0;
341
342   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
343     fields_num = openvpn_strsplit(buffer, fields, max_fields);
344
345     /* Try to find section header */
346     if (found_header == 0) {
347       if (fields_num < 2)
348         continue;
349       if (strcmp(fields[0], "HEADER") != 0)
350         continue;
351       if (strcmp(fields[1], "CLIENT_LIST") != 0)
352         continue;
353
354       for (int i = 2; i < fields_num; i++) {
355         if (strcmp(fields[i], "Common Name") == 0) {
356           idx_cname = i - 1;
357         }
358         else if (strcmp(fields[i], "Bytes Received") == 0) {
359           idx_bytes_recv = i - 1;
360         }
361         else if (strcmp(fields[i], "Bytes Sent") == 0) {
362           idx_bytes_sent = i - 1;
363         }
364       }
365
366       DEBUG("openvpn plugin: found MULTI v2/v3 HEADER. "
367             "Column idx: cname: %d, bytes_recv: %d, bytes_sent: %d",
368             idx_cname, idx_bytes_recv, idx_bytes_sent);
369
370       if (idx_cname == 0 || idx_bytes_recv == 0 || idx_bytes_sent == 0)
371         break;
372
373       /* Data row has 1 field ("HEADER") less than header row */
374       columns = fields_num - 1;
375
376       found_header = 1;
377       continue;
378     }
379
380     /* Header already found. Check if the line is the section data.
381      * If no match, then section was finished and there is no more data.
382      * Empty section is OK too.
383      */
384     if (fields_num == 0 || strcmp(fields[0], "CLIENT_LIST") != 0)
385       break;
386
387     /* Check if the data line fields count matches header line. */
388     if (fields_num != columns) {
389       ERROR("openvpn plugin: File format error in instance %s: Fields count "
390             "mismatch.", name);
391       return -1;
392     }
393
394     DEBUG("openvpn plugin: found MULTI v2/v3 CLIENT_LIST. "
395           "Columns: cname: %s, bytes_recv: %s, bytes_sent: %s",
396           fields[idx_cname], fields[idx_bytes_recv], fields[idx_bytes_sent]);
397
398     if (collect_user_count)
399       sum_users += 1;
400
401     if (collect_individual_users) {
402       if (new_naming_schema) {
403         /* plugin inst = file name, type inst = fields[1] */
404         iostats_submit(name,                           /* vpn instance     */
405                        fields[idx_cname],              /* "Common Name"    */
406                        atoll(fields[idx_bytes_recv]),  /* "Bytes Received" */
407                        atoll(fields[idx_bytes_sent])); /* "Bytes Sent"     */
408       } else {
409         /* plugin inst = fields[idx_cname], type inst = "" */
410         iostats_submit(fields[idx_cname],              /* "Common Name"    */
411                        NULL,              /* unused when in multimode      */
412                        atoll(fields[idx_bytes_recv]),  /* "Bytes Received" */
413                        atoll(fields[idx_bytes_sent])); /* "Bytes Sent"     */
414       }
415     }
416   }
417
418   if (ferror(fh))
419     return -1;
420
421   if (found_header == 0) {
422     NOTICE("openvpn plugin: Unknown file format in instance %s, please "
423            "report this as bug. Make sure to include "
424            "your status file, so the plugin can "
425            "be adapted.",
426            name);
427     return -1;
428   }
429
430   if (collect_user_count) {
431     numusers_submit(name, name, sum_users);
432   }
433
434   return 0;
435 } /* int multi2_read */
436
437 /* read callback */
438 static int openvpn_read(user_data_t *user_data) {
439   FILE *fh;
440   char buffer[1024];
441   int read = 0;
442
443   vpn_status_t *st;
444   st = user_data->data;
445
446   fh = fopen(st->file, "r");
447   if (fh == NULL) {
448     char errbuf[1024];
449     WARNING("openvpn plugin: fopen(%s) failed: %s", st->file,
450             sstrerror(errno, errbuf, sizeof(errbuf)));
451
452     return -1;
453   }
454
455   //Try to detect file format by its first line
456   if ((fgets(buffer, sizeof(buffer), fh)) == NULL) {
457     WARNING("openvpn plugin: failed to get data from: %s", st->file);
458     fclose(fh);
459     return -1;
460   }
461
462   if (strcmp(buffer, TITLE_SINGLE) == 0) { //OpenVPN STATISTICS
463     DEBUG("openvpn plugin: found status file SINGLE");
464     read = single_read(st->name, fh);
465   }
466   else if (strcmp(buffer, TITLE_V1) == 0) { //OpenVPN CLIENT LIST
467     DEBUG("openvpn plugin: found status file MULTI version 1");
468     read = multi1_read(st->name, fh);
469   }
470   else if (strncmp(buffer, TITLE_V2, strlen(TITLE_V2)) == 0) { //TITLE
471     DEBUG("openvpn plugin: found status file MULTI version 2/3");
472     read = multi2_read(st->name, fh);
473   }
474   else {
475     NOTICE("openvpn plugin: %s: Unknown file format, please "
476            "report this as bug. Make sure to include "
477            "your status file, so the plugin can "
478            "be adapted. BUF %s",
479            st->file, buffer);
480     read = -1;
481   }
482   fclose(fh);
483   return read;
484 } /* int openvpn_read */
485
486 static int openvpn_config(const char *key, const char *value) {
487   if (strcasecmp("StatusFile", key) == 0) {
488     char callback_name[3 * DATA_MAX_NAME_LEN];
489     char *status_file, *status_name, *filename;
490     vpn_status_t *instance;
491
492     status_file = sstrdup(value);
493     if (status_file == NULL) {
494       char errbuf[1024];
495       ERROR("openvpn plugin: sstrdup failed: %s",
496             sstrerror(errno, errbuf, sizeof(errbuf)));
497       return 1;
498     }
499
500     /* it determines the file name as string starting at location filename + 1
501      */
502     filename = strrchr(status_file, (int)'/');
503     if (filename == NULL) {
504       /* status_file is already the file name only */
505       status_name = status_file;
506     } else {
507       /* doesn't waste memory, uses status_file starting at filename + 1 */
508       status_name = filename + 1;
509     }
510
511     /* create a new vpn element */
512     instance = malloc(sizeof(*instance));
513     if (instance == NULL) {
514       char errbuf[1024];
515       ERROR("openvpn plugin: malloc failed: %s",
516             sstrerror(errno, errbuf, sizeof(errbuf)));
517       sfree(status_file);
518       return 1;
519     }
520     instance->file = status_file;
521     instance->name = status_name;
522
523     int status;
524
525     ssnprintf(callback_name, sizeof(callback_name), "openvpn/%s", status_name);
526
527     status = plugin_register_complex_read(
528       /* group = */ "openvpn",
529       /* name      = */ callback_name,
530       /* callback  = */ openvpn_read,
531       /* interval  = */ 0, &(user_data_t){
532                                .data = instance, .free_func = openvpn_free,
533                            });
534
535     if (status == EINVAL) {
536       WARNING("openvpn plugin: status filename \"%s\" "
537               "already used, please choose a "
538               "different one.",
539               status_name);
540       return -1;
541     }
542
543     DEBUG("openvpn plugin: status file \"%s\" added", instance->file);
544   } /* if (strcasecmp ("StatusFile", key) == 0) */
545   else if ((strcasecmp("CollectCompression", key) == 0) ||
546            (strcasecmp("Compression", key) == 0)) /* old, deprecated name */
547   {
548     if (IS_FALSE(value))
549       collect_compression = 0;
550     else
551       collect_compression = 1;
552   } /* if (strcasecmp ("CollectCompression", key) == 0) */
553   else if (strcasecmp("ImprovedNamingSchema", key) == 0) {
554     if (IS_TRUE(value)) {
555       DEBUG("openvpn plugin: using the new naming schema");
556       new_naming_schema = 1;
557     } else {
558       new_naming_schema = 0;
559     }
560   } /* if (strcasecmp ("ImprovedNamingSchema", key) == 0) */
561   else if (strcasecmp("CollectUserCount", key) == 0) {
562     if (IS_TRUE(value))
563       collect_user_count = 1;
564     else
565       collect_user_count = 0;
566   } /* if (strcasecmp("CollectUserCount", key) == 0) */
567   else if (strcasecmp("CollectIndividualUsers", key) == 0) {
568     if (IS_FALSE(value))
569       collect_individual_users = 0;
570     else
571       collect_individual_users = 1;
572   } /* if (strcasecmp("CollectIndividualUsers", key) == 0) */
573   else {
574     return -1;
575   }
576
577   return 0;
578 } /* int openvpn_config */
579
580 static int openvpn_init(void) {
581   if (!collect_individual_users && !collect_compression &&
582       !collect_user_count) {
583     WARNING("OpenVPN plugin: Neither `CollectIndividualUsers', "
584             "`CollectCompression', nor `CollectUserCount' is true. There's no "
585             "data left to collect.");
586     return -1;
587   }
588
589   return 0;
590 } /* int openvpn_init */
591
592 void module_register(void) {
593   plugin_register_config("openvpn", openvpn_config, config_keys,
594                          config_keys_num);
595   plugin_register_init("openvpn", openvpn_init);
596 } /* void module_register */