Merge branch 'collectd-5.7'
[collectd.git] / src / openldap.c
1 /**
2  * collectd - src/openldap.c
3  * Copyright (C) 2011       Kimo Rosenbaum
4  * Copyright (C) 2014-2015  Marc Fournier
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *   Kimo Rosenbaum <kimor79 at yahoo.com>
26  *   Marc Fournier <marc.fournier at camptocamp.com>
27  **/
28
29 #include "collectd.h"
30
31 #include "common.h"
32 #include "plugin.h"
33
34 #if defined(__APPLE__)
35 #pragma clang diagnostic push
36 #pragma clang diagnostic warning "-Wdeprecated-declarations"
37 #endif
38
39 #include <lber.h>
40 #include <ldap.h>
41
42 struct cldap_s /* {{{ */
43 {
44   char *name;
45
46   char *binddn;
47   char *password;
48   char *cacert;
49   char *host;
50   int state;
51   _Bool starttls;
52   int timeout;
53   char *url;
54   _Bool verifyhost;
55   int version;
56
57   LDAP *ld;
58 };
59 typedef struct cldap_s cldap_t; /* }}} */
60
61 static cldap_t **databases = NULL;
62 static size_t databases_num = 0;
63
64 static void cldap_free(cldap_t *st) /* {{{ */
65 {
66   if (st == NULL)
67     return;
68
69   sfree(st->binddn);
70   sfree(st->password);
71   sfree(st->cacert);
72   sfree(st->host);
73   sfree(st->name);
74   sfree(st->url);
75   if (st->ld)
76     ldap_memfree(st->ld);
77   sfree(st);
78 } /* }}} void cldap_free */
79
80 /* initialize ldap for each host */
81 static int cldap_init_host(cldap_t *st) /* {{{ */
82 {
83   LDAP *ld;
84   int rc;
85
86   if (st->state && st->ld) {
87     DEBUG("openldap plugin: Already connected to %s", st->url);
88     return 0;
89   }
90
91   rc = ldap_initialize(&ld, st->url);
92   if (rc != LDAP_SUCCESS) {
93     ERROR("openldap plugin: ldap_initialize failed: %s", ldap_err2string(rc));
94     st->state = 0;
95     if (ld != NULL)
96       ldap_unbind_ext_s(ld, NULL, NULL);
97     return (-1);
98   }
99
100   st->ld = ld;
101
102   ldap_set_option(st->ld, LDAP_OPT_PROTOCOL_VERSION, &st->version);
103
104   ldap_set_option(st->ld, LDAP_OPT_TIMEOUT,
105                   &(const struct timeval){st->timeout, 0});
106
107   ldap_set_option(st->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
108
109   if (st->cacert != NULL)
110     ldap_set_option(st->ld, LDAP_OPT_X_TLS_CACERTFILE, st->cacert);
111
112   if (st->verifyhost == 0) {
113     int never = LDAP_OPT_X_TLS_NEVER;
114     ldap_set_option(st->ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &never);
115   }
116
117   if (st->starttls != 0) {
118     rc = ldap_start_tls_s(ld, NULL, NULL);
119     if (rc != LDAP_SUCCESS) {
120       ERROR("openldap plugin: Failed to start tls on %s: %s", st->url,
121             ldap_err2string(rc));
122       st->state = 0;
123 <<<<<<< HEAD
124       ldap_unbind_ext_s(st->ld, NULL, NULL);
125       return -1;
126 =======
127       if (st->ld != NULL)
128         ldap_unbind_ext_s(st->ld, NULL, NULL);
129       return (-1);
130 >>>>>>> collectd-5.7
131     }
132   }
133
134   struct berval cred;
135   if (st->password != NULL) {
136     cred.bv_val = st->password;
137     cred.bv_len = strlen(st->password);
138   } else {
139     cred.bv_val = "";
140     cred.bv_len = 0;
141   }
142
143   rc = ldap_sasl_bind_s(st->ld, st->binddn, LDAP_SASL_SIMPLE, &cred, NULL, NULL,
144                         NULL);
145   if (rc != LDAP_SUCCESS) {
146     ERROR("openldap plugin: Failed to bind to %s: %s", st->url,
147           ldap_err2string(rc));
148     st->state = 0;
149 <<<<<<< HEAD
150     ldap_unbind_ext_s(st->ld, NULL, NULL);
151     return -1;
152 =======
153     if (st->ld != NULL)
154       ldap_unbind_ext_s(st->ld, NULL, NULL);
155     return (-1);
156 >>>>>>> collectd-5.7
157   } else {
158     DEBUG("openldap plugin: Successfully connected to %s", st->url);
159     st->state = 1;
160     return 0;
161   }
162 } /* }}} static cldap_init_host */
163
164 static void cldap_submit_value(const char *type,
165                                const char *type_instance, /* {{{ */
166                                value_t value, cldap_t *st) {
167   value_list_t vl = VALUE_LIST_INIT;
168
169   vl.values = &value;
170   vl.values_len = 1;
171
172   if ((st->host != NULL) && (strcmp("localhost", st->host) != 0))
173     sstrncpy(vl.host, st->host, sizeof(vl.host));
174
175   sstrncpy(vl.plugin, "openldap", sizeof(vl.plugin));
176   if (st->name != NULL)
177     sstrncpy(vl.plugin_instance, st->name, sizeof(vl.plugin_instance));
178
179   sstrncpy(vl.type, type, sizeof(vl.type));
180   if (type_instance != NULL)
181     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
182
183   plugin_dispatch_values(&vl);
184 } /* }}} void cldap_submit_value */
185
186 static void cldap_submit_derive(const char *type,
187                                 const char *type_instance, /* {{{ */
188                                 derive_t d, cldap_t *st) {
189   cldap_submit_value(type, type_instance, (value_t){.derive = d}, st);
190 } /* }}} void cldap_submit_derive */
191
192 static void cldap_submit_gauge(const char *type,
193                                const char *type_instance, /* {{{ */
194                                gauge_t g, cldap_t *st) {
195   cldap_submit_value(type, type_instance, (value_t){.gauge = g}, st);
196 } /* }}} void cldap_submit_gauge */
197
198 static int cldap_read_host(user_data_t *ud) /* {{{ */
199 {
200   cldap_t *st;
201   LDAPMessage *result;
202   char *dn;
203   int rc;
204   int status;
205
206   char *attrs[9] = {
207       "monitorCounter", "monitorOpCompleted", "monitorOpInitiated",
208       "monitoredInfo",  "olmBDBEntryCache",   "olmBDBDNCache",
209       "olmBDBIDLCache", "namingContexts",     NULL};
210
211   if ((ud == NULL) || (ud->data == NULL)) {
212     ERROR("openldap plugin: cldap_read_host: Invalid user data.");
213     return -1;
214   }
215
216   st = (cldap_t *)ud->data;
217
218   status = cldap_init_host(st);
219   if (status != 0)
220     return -1;
221
222   rc = ldap_search_ext_s(st->ld, "cn=Monitor", LDAP_SCOPE_SUBTREE,
223                          "(|(!(cn=* *))(cn=Database*))", attrs, 0, NULL, NULL,
224                          NULL, 0, &result);
225
226   if (rc != LDAP_SUCCESS) {
227     ERROR("openldap plugin: Failed to execute search: %s", ldap_err2string(rc));
228     ldap_msgfree(result);
229     st->state = 0;
230 <<<<<<< HEAD
231     ldap_unbind_ext_s(st->ld, NULL, NULL);
232     return -1;
233 =======
234     if (st->ld != NULL)
235       ldap_unbind_ext_s(st->ld, NULL, NULL);
236     return (-1);
237 >>>>>>> collectd-5.7
238   }
239
240   for (LDAPMessage *e = ldap_first_entry(st->ld, result); e != NULL;
241        e = ldap_next_entry(st->ld, e)) {
242     if ((dn = ldap_get_dn(st->ld, e)) != NULL) {
243       unsigned long long counter = 0;
244       unsigned long long opc = 0;
245       unsigned long long opi = 0;
246       unsigned long long info = 0;
247
248       struct berval counter_data;
249       struct berval opc_data;
250       struct berval opi_data;
251       struct berval info_data;
252       struct berval olmbdb_data;
253       struct berval nc_data;
254
255       struct berval **counter_list;
256       struct berval **opc_list;
257       struct berval **opi_list;
258       struct berval **info_list;
259       struct berval **olmbdb_list;
260       struct berval **nc_list;
261
262       if ((counter_list = ldap_get_values_len(st->ld, e, "monitorCounter")) !=
263           NULL) {
264         counter_data = *counter_list[0];
265         counter = atoll(counter_data.bv_val);
266       }
267
268       if ((opc_list = ldap_get_values_len(st->ld, e, "monitorOpCompleted")) !=
269           NULL) {
270         opc_data = *opc_list[0];
271         opc = atoll(opc_data.bv_val);
272       }
273
274       if ((opi_list = ldap_get_values_len(st->ld, e, "monitorOpInitiated")) !=
275           NULL) {
276         opi_data = *opi_list[0];
277         opi = atoll(opi_data.bv_val);
278       }
279
280       if ((info_list = ldap_get_values_len(st->ld, e, "monitoredInfo")) !=
281           NULL) {
282         info_data = *info_list[0];
283         info = atoll(info_data.bv_val);
284       }
285
286       if (strcmp(dn, "cn=Total,cn=Connections,cn=Monitor") == 0) {
287         cldap_submit_derive("total_connections", NULL, counter, st);
288       } else if (strcmp(dn, "cn=Current,cn=Connections,cn=Monitor") == 0) {
289         cldap_submit_gauge("current_connections", NULL, counter, st);
290       } else if (strcmp(dn, "cn=Operations,cn=Monitor") == 0) {
291         cldap_submit_derive("operations", "completed", opc, st);
292         cldap_submit_derive("operations", "initiated", opi, st);
293       } else if (strcmp(dn, "cn=Bind,cn=Operations,cn=Monitor") == 0) {
294         cldap_submit_derive("operations", "bind-completed", opc, st);
295         cldap_submit_derive("operations", "bind-initiated", opi, st);
296       } else if (strcmp(dn, "cn=UnBind,cn=Operations,cn=Monitor") == 0) {
297         cldap_submit_derive("operations", "unbind-completed", opc, st);
298         cldap_submit_derive("operations", "unbind-initiated", opi, st);
299       } else if (strcmp(dn, "cn=Search,cn=Operations,cn=Monitor") == 0) {
300         cldap_submit_derive("operations", "search-completed", opc, st);
301         cldap_submit_derive("operations", "search-initiated", opi, st);
302       } else if (strcmp(dn, "cn=Compare,cn=Operations,cn=Monitor") == 0) {
303         cldap_submit_derive("operations", "compare-completed", opc, st);
304         cldap_submit_derive("operations", "compare-initiated", opi, st);
305       } else if (strcmp(dn, "cn=Modify,cn=Operations,cn=Monitor") == 0) {
306         cldap_submit_derive("operations", "modify-completed", opc, st);
307         cldap_submit_derive("operations", "modify-initiated", opi, st);
308       } else if (strcmp(dn, "cn=Modrdn,cn=Operations,cn=Monitor") == 0) {
309         cldap_submit_derive("operations", "modrdn-completed", opc, st);
310         cldap_submit_derive("operations", "modrdn-initiated", opi, st);
311       } else if (strcmp(dn, "cn=Add,cn=Operations,cn=Monitor") == 0) {
312         cldap_submit_derive("operations", "add-completed", opc, st);
313         cldap_submit_derive("operations", "add-initiated", opi, st);
314       } else if (strcmp(dn, "cn=Delete,cn=Operations,cn=Monitor") == 0) {
315         cldap_submit_derive("operations", "delete-completed", opc, st);
316         cldap_submit_derive("operations", "delete-initiated", opi, st);
317       } else if (strcmp(dn, "cn=Abandon,cn=Operations,cn=Monitor") == 0) {
318         cldap_submit_derive("operations", "abandon-completed", opc, st);
319         cldap_submit_derive("operations", "abandon-initiated", opi, st);
320       } else if (strcmp(dn, "cn=Extended,cn=Operations,cn=Monitor") == 0) {
321         cldap_submit_derive("operations", "extended-completed", opc, st);
322         cldap_submit_derive("operations", "extended-initiated", opi, st);
323       } else if ((strncmp(dn, "cn=Database", 11) == 0) &&
324                  ((nc_list = ldap_get_values_len(st->ld, e,
325                                                  "namingContexts")) != NULL)) {
326         nc_data = *nc_list[0];
327         char typeinst[DATA_MAX_NAME_LEN];
328
329         if ((olmbdb_list =
330                  ldap_get_values_len(st->ld, e, "olmBDBEntryCache")) != NULL) {
331           olmbdb_data = *olmbdb_list[0];
332           ssnprintf(typeinst, sizeof(typeinst), "bdbentrycache-%s",
333                     nc_data.bv_val);
334           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
335                              st);
336           ldap_value_free_len(olmbdb_list);
337         }
338
339         if ((olmbdb_list = ldap_get_values_len(st->ld, e, "olmBDBDNCache")) !=
340             NULL) {
341           olmbdb_data = *olmbdb_list[0];
342           ssnprintf(typeinst, sizeof(typeinst), "bdbdncache-%s",
343                     nc_data.bv_val);
344           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
345                              st);
346           ldap_value_free_len(olmbdb_list);
347         }
348
349         if ((olmbdb_list = ldap_get_values_len(st->ld, e, "olmBDBIDLCache")) !=
350             NULL) {
351           olmbdb_data = *olmbdb_list[0];
352           ssnprintf(typeinst, sizeof(typeinst), "bdbidlcache-%s",
353                     nc_data.bv_val);
354           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
355                              st);
356           ldap_value_free_len(olmbdb_list);
357         }
358
359         ldap_value_free_len(nc_list);
360       } else if (strcmp(dn, "cn=Bytes,cn=Statistics,cn=Monitor") == 0) {
361         cldap_submit_derive("derive", "statistics-bytes", counter, st);
362       } else if (strcmp(dn, "cn=PDU,cn=Statistics,cn=Monitor") == 0) {
363         cldap_submit_derive("derive", "statistics-pdu", counter, st);
364       } else if (strcmp(dn, "cn=Entries,cn=Statistics,cn=Monitor") == 0) {
365         cldap_submit_derive("derive", "statistics-entries", counter, st);
366       } else if (strcmp(dn, "cn=Referrals,cn=Statistics,cn=Monitor") == 0) {
367         cldap_submit_derive("derive", "statistics-referrals", counter, st);
368       } else if (strcmp(dn, "cn=Open,cn=Threads,cn=Monitor") == 0) {
369         cldap_submit_gauge("threads", "threads-open", info, st);
370       } else if (strcmp(dn, "cn=Starting,cn=Threads,cn=Monitor") == 0) {
371         cldap_submit_gauge("threads", "threads-starting", info, st);
372       } else if (strcmp(dn, "cn=Active,cn=Threads,cn=Monitor") == 0) {
373         cldap_submit_gauge("threads", "threads-active", info, st);
374       } else if (strcmp(dn, "cn=Pending,cn=Threads,cn=Monitor") == 0) {
375         cldap_submit_gauge("threads", "threads-pending", info, st);
376       } else if (strcmp(dn, "cn=Backload,cn=Threads,cn=Monitor") == 0) {
377         cldap_submit_gauge("threads", "threads-backload", info, st);
378       } else if (strcmp(dn, "cn=Read,cn=Waiters,cn=Monitor") == 0) {
379         cldap_submit_derive("derive", "waiters-read", counter, st);
380       } else if (strcmp(dn, "cn=Write,cn=Waiters,cn=Monitor") == 0) {
381         cldap_submit_derive("derive", "waiters-write", counter, st);
382       }
383
384       ldap_value_free_len(counter_list);
385       ldap_value_free_len(opc_list);
386       ldap_value_free_len(opi_list);
387       ldap_value_free_len(info_list);
388     }
389
390     ldap_memfree(dn);
391   }
392
393   ldap_msgfree(result);
394   return 0;
395 } /* }}} int cldap_read_host */
396
397 /* Configuration handling functions {{{
398  *
399  * <Plugin ldap>
400  *   <Instance "plugin_instance1">
401  *     URL "ldap://localhost"
402  *     ...
403  *   </Instance>
404  * </Plugin>
405  */
406
407 static int cldap_config_add(oconfig_item_t *ci) /* {{{ */
408 {
409   cldap_t *st;
410   int status;
411
412   st = calloc(1, sizeof(*st));
413   if (st == NULL) {
414     ERROR("openldap plugin: calloc failed.");
415     return -1;
416   }
417
418   status = cf_util_get_string(ci, &st->name);
419   if (status != 0) {
420     sfree(st);
421     return status;
422   }
423
424   st->starttls = 0;
425   st->timeout = (long)CDTIME_T_TO_TIME_T(plugin_get_interval());
426   st->verifyhost = 1;
427   st->version = LDAP_VERSION3;
428
429   for (int i = 0; i < ci->children_num; i++) {
430     oconfig_item_t *child = ci->children + i;
431
432     if (strcasecmp("BindDN", child->key) == 0)
433       status = cf_util_get_string(child, &st->binddn);
434     else if (strcasecmp("Password", child->key) == 0)
435       status = cf_util_get_string(child, &st->password);
436     else if (strcasecmp("CACert", child->key) == 0)
437       status = cf_util_get_string(child, &st->cacert);
438     else if (strcasecmp("StartTLS", child->key) == 0)
439       status = cf_util_get_boolean(child, &st->starttls);
440     else if (strcasecmp("Timeout", child->key) == 0)
441       status = cf_util_get_int(child, &st->timeout);
442     else if (strcasecmp("URL", child->key) == 0)
443       status = cf_util_get_string(child, &st->url);
444     else if (strcasecmp("VerifyHost", child->key) == 0)
445       status = cf_util_get_boolean(child, &st->verifyhost);
446     else if (strcasecmp("Version", child->key) == 0)
447       status = cf_util_get_int(child, &st->version);
448     else {
449       WARNING("openldap plugin: Option `%s' not allowed here.", child->key);
450       status = -1;
451     }
452
453     if (status != 0)
454       break;
455   }
456
457   /* Check if struct is complete.. */
458   if ((status == 0) && (st->url == NULL)) {
459     ERROR("openldap plugin: Instance `%s': "
460           "No URL has been configured.",
461           st->name);
462     status = -1;
463   }
464
465   /* Check if URL is valid */
466   if ((status == 0) && (st->url != NULL)) {
467     LDAPURLDesc *ludpp;
468
469     if (ldap_url_parse(st->url, &ludpp) != 0) {
470       ERROR("openldap plugin: Instance `%s': "
471             "Invalid URL: `%s'",
472             st->name, st->url);
473       status = -1;
474     }
475
476     if ((status == 0) && (ludpp->lud_host != NULL))
477       st->host = strdup(ludpp->lud_host);
478
479     ldap_free_urldesc(ludpp);
480   }
481
482   if (status == 0) {
483     cldap_t **temp;
484
485     temp = (cldap_t **)realloc(databases,
486                                sizeof(*databases) * (databases_num + 1));
487
488     if (temp == NULL) {
489       ERROR("openldap plugin: realloc failed");
490       status = -1;
491     } else {
492       char callback_name[3 * DATA_MAX_NAME_LEN] = {0};
493
494       databases = temp;
495       databases[databases_num] = st;
496       databases_num++;
497
498       ssnprintf(callback_name, sizeof(callback_name), "openldap/%s/%s",
499                 (st->host != NULL) ? st->host : hostname_g,
500                 (st->name != NULL) ? st->name : "default");
501
502       status = plugin_register_complex_read(/* group = */ NULL,
503                                             /* name      = */ callback_name,
504                                             /* callback  = */ cldap_read_host,
505                                             /* interval  = */ 0, &(user_data_t){
506                                                                      .data = st,
507                                                                  });
508     }
509   }
510
511   if (status != 0) {
512     cldap_free(st);
513     return -1;
514   }
515
516   return 0;
517 } /* }}} int cldap_config_add */
518
519 static int cldap_config(oconfig_item_t *ci) /* {{{ */
520 {
521   int status = 0;
522
523   for (int i = 0; i < ci->children_num; i++) {
524     oconfig_item_t *child = ci->children + i;
525
526     if (strcasecmp("Instance", child->key) == 0)
527       cldap_config_add(child);
528     else
529       WARNING("openldap plugin: The configuration option "
530               "\"%s\" is not allowed here. Did you "
531               "forget to add an <Instance /> block "
532               "around the configuration?",
533               child->key);
534   } /* for (ci->children) */
535
536   return status;
537 } /* }}} int cldap_config */
538
539 /* }}} End of configuration handling functions */
540
541 static int cldap_init(void) /* {{{ */
542 {
543   /* Initialize LDAP library while still single-threaded as recommended in
544    * ldap_initialize(3) */
545   int debug_level;
546   ldap_get_option(NULL, LDAP_OPT_DEBUG_LEVEL, &debug_level);
547   return 0;
548 } /* }}} int cldap_init */
549
550 static int cldap_shutdown(void) /* {{{ */
551 {
552   for (size_t i = 0; i < databases_num; i++)
553     if (databases[i]->ld != NULL)
554       ldap_unbind_ext_s(databases[i]->ld, NULL, NULL);
555   sfree(databases);
556   databases_num = 0;
557
558   return 0;
559 } /* }}} int cldap_shutdown */
560
561 void module_register(void) /* {{{ */
562 {
563   plugin_register_complex_config("openldap", cldap_config);
564   plugin_register_init("openldap", cldap_init);
565   plugin_register_shutdown("openldap", cldap_shutdown);
566 } /* }}} void module_register */
567
568 #if defined(__APPLE__)
569 #pragma clang diagnostic pop
570 #endif