Merge pull request #3329 from efuss/fix-3311
[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 "plugin.h"
32 #include "utils/common/common.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;
84 static bool collect_compression = true;
85 static bool collect_user_count;
86 static bool collect_individual_users = true;
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 = 0;
98   char *ptr = string;
99   char *saveptr = NULL;
100
101   while ((fields[i] = strtok_r(ptr, ",\t", &saveptr)) != NULL) {
102     ptr = NULL;
103     i++;
104
105     if (i >= size)
106       break;
107   }
108
109   return i;
110 } /* int openvpn_strsplit */
111
112 static void openvpn_free(void *arg) {
113   vpn_status_t *st = arg;
114
115   sfree(st->file);
116   sfree(st);
117 } /* void openvpn_free */
118
119 /* dispatches number of users */
120 static void numusers_submit(const char *pinst, const char *tinst,
121                             gauge_t value) {
122   value_list_t vl = VALUE_LIST_INIT;
123
124   vl.values = &(value_t){.gauge = value};
125   vl.values_len = 1;
126   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
127   sstrncpy(vl.type, "users", sizeof(vl.type));
128   if (pinst != NULL)
129     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
130   if (tinst != NULL)
131     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
132
133   plugin_dispatch_values(&vl);
134 } /* void numusers_submit */
135
136 /* dispatches stats about traffic (TCP or UDP) generated by the tunnel
137  * per single endpoint */
138 static void iostats_submit(const char *pinst, const char *tinst, derive_t rx,
139                            derive_t tx) {
140   value_list_t vl = VALUE_LIST_INIT;
141   value_t values[] = {
142       {.derive = rx},
143       {.derive = tx},
144   };
145
146   /* NOTE ON THE NEW NAMING SCHEMA:
147    *       using plugin_instance to identify each vpn config (and
148    *       status) file; using type_instance to identify the endpoint
149    *       host when in multimode, traffic or overhead when in single.
150    */
151
152   vl.values = values;
153   vl.values_len = STATIC_ARRAY_SIZE(values);
154   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
155   if (pinst != NULL)
156     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
157   sstrncpy(vl.type, "if_octets", sizeof(vl.type));
158   if (tinst != NULL)
159     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
160
161   plugin_dispatch_values(&vl);
162 } /* void traffic_submit */
163
164 /* dispatches stats about data compression shown when in single mode */
165 static void compression_submit(const char *pinst, const char *tinst,
166                                derive_t uncompressed, derive_t compressed) {
167   value_list_t vl = VALUE_LIST_INIT;
168   value_t values[] = {
169       {.derive = uncompressed},
170       {.derive = compressed},
171   };
172
173   vl.values = values;
174   vl.values_len = STATIC_ARRAY_SIZE(values);
175   sstrncpy(vl.plugin, "openvpn", sizeof(vl.plugin));
176   if (pinst != NULL)
177     sstrncpy(vl.plugin_instance, pinst, sizeof(vl.plugin_instance));
178   sstrncpy(vl.type, "compression", sizeof(vl.type));
179   if (tinst != NULL)
180     sstrncpy(vl.type_instance, tinst, sizeof(vl.type_instance));
181
182   plugin_dispatch_values(&vl);
183 } /* void compression_submit */
184
185 static int single_read(const char *name, FILE *fh) {
186   char buffer[1024];
187   char *fields[4];
188   const int max_fields = STATIC_ARRAY_SIZE(fields);
189
190   derive_t link_rx = 0, link_tx = 0;
191   derive_t tun_rx = 0, tun_tx = 0;
192   derive_t pre_compress = 0, post_compress = 0;
193   derive_t pre_decompress = 0, post_decompress = 0;
194
195   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
196     int fields_num = openvpn_strsplit(buffer, fields, max_fields);
197
198     /* status file is generated by openvpn/sig.c:print_status()
199      * http://svn.openvpn.net/projects/openvpn/trunk/openvpn/sig.c
200      *
201      * The line we're expecting has 2 fields. We ignore all lines
202      *  with more or less fields.
203      */
204     if (fields_num != 2) {
205       continue;
206     }
207
208     if (strcmp(fields[0], "TUN/TAP read bytes") == 0) {
209       /* read from the system and sent over the tunnel */
210       tun_tx = atoll(fields[1]);
211     } else if (strcmp(fields[0], "TUN/TAP write bytes") == 0) {
212       /* read from the tunnel and written in the system */
213       tun_rx = atoll(fields[1]);
214     } else if (strcmp(fields[0], "TCP/UDP read bytes") == 0) {
215       link_rx = atoll(fields[1]);
216     } else if (strcmp(fields[0], "TCP/UDP write bytes") == 0) {
217       link_tx = atoll(fields[1]);
218     } else if (strcmp(fields[0], "pre-compress bytes") == 0) {
219       pre_compress = atoll(fields[1]);
220     } else if (strcmp(fields[0], "post-compress bytes") == 0) {
221       post_compress = atoll(fields[1]);
222     } else if (strcmp(fields[0], "pre-decompress bytes") == 0) {
223       pre_decompress = atoll(fields[1]);
224     } else if (strcmp(fields[0], "post-decompress bytes") == 0) {
225       post_decompress = atoll(fields[1]);
226     }
227   }
228
229   iostats_submit(name, "traffic", link_rx, link_tx);
230
231   /* we need to force this order to avoid negative values with these unsigned */
232   derive_t overhead_rx =
233       (((link_rx - pre_decompress) + post_decompress) - tun_rx);
234   derive_t overhead_tx = (((link_tx - post_compress) + pre_compress) - tun_tx);
235
236   iostats_submit(name, "overhead", overhead_rx, overhead_tx);
237
238   if (collect_compression) {
239     compression_submit(name, "data_in", post_decompress, pre_decompress);
240     compression_submit(name, "data_out", pre_compress, post_compress);
241   }
242
243   return 0;
244 } /* int single_read */
245
246 /* for reading status version 1 */
247 static int multi1_read(const char *name, FILE *fh) {
248   char buffer[1024];
249   char *fields[10];
250   const int max_fields = STATIC_ARRAY_SIZE(fields);
251   long long sum_users = 0;
252   bool found_header = false;
253
254   /* read the file until the "ROUTING TABLE" line is found (no more info after)
255    */
256   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
257     if (strcmp(buffer, "ROUTING TABLE\n") == 0)
258       break;
259
260     if (strcmp(buffer, V1HEADER) == 0) {
261       found_header = true;
262       continue;
263     }
264
265     /* skip the first lines until the client list section is found */
266     if (found_header == false)
267       /* we can't start reading data until this string is found */
268       continue;
269
270     int fields_num = openvpn_strsplit(buffer, fields, max_fields);
271     if (fields_num < 4)
272       continue;
273
274     if (collect_user_count)
275     /* If so, sum all users, ignore the individuals*/
276     {
277       sum_users += 1;
278     }
279     if (collect_individual_users) {
280       if (new_naming_schema) {
281         iostats_submit(name,              /* vpn instance */
282                        fields[0],         /* "Common Name" */
283                        atoll(fields[2]),  /* "Bytes Received" */
284                        atoll(fields[3])); /* "Bytes Sent" */
285       } else {
286         iostats_submit(fields[0],         /* "Common Name" */
287                        NULL,              /* unused when in multimode */
288                        atoll(fields[2]),  /* "Bytes Received" */
289                        atoll(fields[3])); /* "Bytes Sent" */
290       }
291     }
292   }
293
294   if (ferror(fh))
295     return -1;
296
297   if (found_header == false) {
298     NOTICE("openvpn plugin: Unknown file format in instance %s, please "
299            "report this as bug. Make sure to include "
300            "your status file, so the plugin can "
301            "be adapted.",
302            name);
303     return -1;
304   }
305
306   if (collect_user_count)
307     numusers_submit(name, name, sum_users);
308
309   return 0;
310 } /* int multi1_read */
311
312 /* for reading status version 2 / version 3
313  * status file is generated by openvpn/multi.c:multi_print_status()
314  * http://svn.openvpn.net/projects/openvpn/trunk/openvpn/multi.c
315  */
316 static int multi2_read(const char *name, FILE *fh) {
317   char buffer[1024];
318   /* OpenVPN-2.4 has 11 fields of data + 2 fields for "HEADER" and "CLIENT_LIST"
319    * So, set array size to 20 elements, to support future extensions.
320    */
321   char *fields[20];
322   const int max_fields = STATIC_ARRAY_SIZE(fields);
323   long long sum_users = 0;
324
325   bool found_header = false;
326   int idx_cname = 0;
327   int idx_bytes_recv = 0;
328   int idx_bytes_sent = 0;
329   int columns = 0;
330
331   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
332     int fields_num = openvpn_strsplit(buffer, fields, max_fields);
333
334     /* Try to find section header */
335     if (found_header == false) {
336       if (fields_num < 2)
337         continue;
338       if (strcmp(fields[0], "HEADER") != 0)
339         continue;
340       if (strcmp(fields[1], "CLIENT_LIST") != 0)
341         continue;
342
343       for (int i = 2; i < fields_num; i++) {
344         if (strcmp(fields[i], "Common Name") == 0) {
345           idx_cname = i - 1;
346         } else if (strcmp(fields[i], "Bytes Received") == 0) {
347           idx_bytes_recv = i - 1;
348         } else if (strcmp(fields[i], "Bytes Sent") == 0) {
349           idx_bytes_sent = i - 1;
350         }
351       }
352
353       DEBUG("openvpn plugin: found MULTI v2/v3 HEADER. "
354             "Column idx: cname: %d, bytes_recv: %d, bytes_sent: %d",
355             idx_cname, idx_bytes_recv, idx_bytes_sent);
356
357       if (idx_cname == 0 || idx_bytes_recv == 0 || idx_bytes_sent == 0)
358         break;
359
360       /* Data row has 1 field ("HEADER") less than header row */
361       columns = fields_num - 1;
362
363       found_header = true;
364       continue;
365     }
366
367     /* Header already found. Check if the line is the section data.
368      * If no match, then section was finished and there is no more data.
369      * Empty section is OK too.
370      */
371     if (fields_num == 0 || strcmp(fields[0], "CLIENT_LIST") != 0)
372       break;
373
374     /* Check if the data line fields count matches header line. */
375     if (fields_num != columns) {
376       ERROR("openvpn plugin: File format error in instance %s: Fields count "
377             "mismatch.",
378             name);
379       return -1;
380     }
381
382     DEBUG("openvpn plugin: found MULTI v2/v3 CLIENT_LIST. "
383           "Columns: cname: %s, bytes_recv: %s, bytes_sent: %s",
384           fields[idx_cname], fields[idx_bytes_recv], fields[idx_bytes_sent]);
385
386     if (collect_user_count)
387       sum_users += 1;
388
389     if (collect_individual_users) {
390       if (new_naming_schema) {
391         /* plugin inst = file name, type inst = fields[1] */
392         iostats_submit(name,                           /* vpn instance     */
393                        fields[idx_cname],              /* "Common Name"    */
394                        atoll(fields[idx_bytes_recv]),  /* "Bytes Received" */
395                        atoll(fields[idx_bytes_sent])); /* "Bytes Sent"     */
396       } else {
397         /* plugin inst = fields[idx_cname], type inst = "" */
398         iostats_submit(fields[idx_cname], /*              "Common Name"    */
399                        NULL,              /* unused when in multimode      */
400                        atoll(fields[idx_bytes_recv]),  /* "Bytes Received" */
401                        atoll(fields[idx_bytes_sent])); /* "Bytes Sent"     */
402       }
403     }
404   }
405
406   if (ferror(fh))
407     return -1;
408
409   if (found_header == false) {
410     NOTICE("openvpn plugin: Unknown file format in instance %s, please "
411            "report this as bug. Make sure to include "
412            "your status file, so the plugin can "
413            "be adapted.",
414            name);
415     return -1;
416   }
417
418   if (collect_user_count) {
419     numusers_submit(name, name, sum_users);
420   }
421
422   return 0;
423 } /* int multi2_read */
424
425 /* read callback */
426 static int openvpn_read(user_data_t *user_data) {
427   char buffer[1024];
428   int read = 0;
429
430   vpn_status_t *st = user_data->data;
431
432   FILE *fh = fopen(st->file, "r");
433   if (fh == NULL) {
434     WARNING("openvpn plugin: fopen(%s) failed: %s", st->file, STRERRNO);
435
436     return -1;
437   }
438
439   // Try to detect file format by its first line
440   if ((fgets(buffer, sizeof(buffer), fh)) == NULL) {
441     WARNING("openvpn plugin: failed to get data from: %s", st->file);
442     fclose(fh);
443     return -1;
444   }
445
446   if (strcmp(buffer, TITLE_SINGLE) == 0) { // OpenVPN STATISTICS
447     DEBUG("openvpn plugin: found status file SINGLE");
448     read = single_read(st->name, fh);
449   } else if (strcmp(buffer, TITLE_V1) == 0) { // OpenVPN CLIENT LIST
450     DEBUG("openvpn plugin: found status file MULTI version 1");
451     read = multi1_read(st->name, fh);
452   } else if (strncmp(buffer, TITLE_V2, strlen(TITLE_V2)) == 0) { // TITLE
453     DEBUG("openvpn plugin: found status file MULTI version 2/3");
454     read = multi2_read(st->name, fh);
455   } else {
456     NOTICE("openvpn plugin: %s: Unknown file format, please "
457            "report this as bug. Make sure to include "
458            "your status file, so the plugin can "
459            "be adapted.",
460            st->file);
461     read = -1;
462   }
463   fclose(fh);
464   return read;
465 } /* int openvpn_read */
466
467 static int openvpn_config(const char *key, const char *value) {
468   if (strcasecmp("StatusFile", key) == 0) {
469     char callback_name[3 * DATA_MAX_NAME_LEN];
470     char *status_name;
471
472     char *status_file = strdup(value);
473     if (status_file == NULL) {
474       ERROR("openvpn plugin: strdup failed: %s", STRERRNO);
475       return 1;
476     }
477
478     /* it determines the file name as string starting at location filename + 1
479      */
480     char *filename = strrchr(status_file, (int)'/');
481     if (filename == NULL) {
482       /* status_file is already the file name only */
483       status_name = status_file;
484     } else {
485       /* doesn't waste memory, uses status_file starting at filename + 1 */
486       status_name = filename + 1;
487     }
488
489     /* create a new vpn element */
490     vpn_status_t *instance = calloc(1, sizeof(*instance));
491     if (instance == NULL) {
492       ERROR("openvpn plugin: malloc failed: %s", STRERRNO);
493       sfree(status_file);
494       return 1;
495     }
496     instance->file = status_file;
497     instance->name = status_name;
498
499     snprintf(callback_name, sizeof(callback_name), "openvpn/%s", status_name);
500
501     int status = plugin_register_complex_read(
502         /* group = */ "openvpn",
503         /* name      = */ callback_name,
504         /* callback  = */ openvpn_read,
505         /* interval  = */ 0,
506         &(user_data_t){
507             .data = instance,
508             .free_func = openvpn_free,
509         });
510
511     if (status == EINVAL) {
512       ERROR("openvpn plugin: status filename \"%s\" "
513             "already used, please choose a "
514             "different one.",
515             status_name);
516       return -1;
517     }
518
519     DEBUG("openvpn plugin: status file \"%s\" added", instance->file);
520   } /* if (strcasecmp ("StatusFile", key) == 0) */
521   else if ((strcasecmp("CollectCompression", key) == 0) ||
522            (strcasecmp("Compression", key) == 0)) /* old, deprecated name */
523   {
524     if (IS_FALSE(value))
525       collect_compression = false;
526     else
527       collect_compression = true;
528   } /* if (strcasecmp ("CollectCompression", key) == 0) */
529   else if (strcasecmp("ImprovedNamingSchema", key) == 0) {
530     if (IS_TRUE(value)) {
531       DEBUG("openvpn plugin: using the new naming schema");
532       new_naming_schema = true;
533     } else {
534       new_naming_schema = false;
535     }
536   } /* if (strcasecmp ("ImprovedNamingSchema", key) == 0) */
537   else if (strcasecmp("CollectUserCount", key) == 0) {
538     if (IS_TRUE(value))
539       collect_user_count = true;
540     else
541       collect_user_count = false;
542   } /* if (strcasecmp("CollectUserCount", key) == 0) */
543   else if (strcasecmp("CollectIndividualUsers", key) == 0) {
544     if (IS_FALSE(value))
545       collect_individual_users = false;
546     else
547       collect_individual_users = true;
548   } /* if (strcasecmp("CollectIndividualUsers", key) == 0) */
549   else {
550     return -1;
551   }
552
553   return 0;
554 } /* int openvpn_config */
555
556 static int openvpn_init(void) {
557   if (!collect_individual_users && !collect_compression &&
558       !collect_user_count) {
559     WARNING("OpenVPN plugin: Neither `CollectIndividualUsers', "
560             "`CollectCompression', nor `CollectUserCount' is true. There's no "
561             "data left to collect.");
562     return -1;
563   }
564
565   return 0;
566 } /* int openvpn_init */
567
568 void module_register(void) {
569   plugin_register_config("openvpn", openvpn_config, config_keys,
570                          config_keys_num);
571   plugin_register_init("openvpn", openvpn_init);
572 } /* void module_register */