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