61eb62e3577eb508e0dd613bfd92570d374e4b42
[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     ldap_unbind_ext_s(ld, NULL, NULL);
96     return (-1);
97   }
98
99   st->ld = ld;
100
101   ldap_set_option(st->ld, LDAP_OPT_PROTOCOL_VERSION, &st->version);
102
103   ldap_set_option(st->ld, LDAP_OPT_TIMEOUT,
104                   &(const struct timeval){st->timeout, 0});
105
106   ldap_set_option(st->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
107
108   if (st->cacert != NULL)
109     ldap_set_option(st->ld, LDAP_OPT_X_TLS_CACERTFILE, st->cacert);
110
111   if (st->verifyhost == 0) {
112     int never = LDAP_OPT_X_TLS_NEVER;
113     ldap_set_option(st->ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &never);
114   }
115
116   if (st->starttls != 0) {
117     rc = ldap_start_tls_s(ld, NULL, NULL);
118     if (rc != LDAP_SUCCESS) {
119       ERROR("openldap plugin: Failed to start tls on %s: %s", st->url,
120             ldap_err2string(rc));
121       st->state = 0;
122       ldap_unbind_ext_s(st->ld, NULL, NULL);
123       return (-1);
124     }
125   }
126
127   struct berval cred;
128   if (st->password != NULL) {
129     cred.bv_val = st->password;
130     cred.bv_len = strlen(st->password);
131   } else {
132     cred.bv_val = "";
133     cred.bv_len = 0;
134   }
135
136   rc = ldap_sasl_bind_s(st->ld, st->binddn, LDAP_SASL_SIMPLE, &cred, NULL, NULL,
137                         NULL);
138   if (rc != LDAP_SUCCESS) {
139     ERROR("openldap plugin: Failed to bind to %s: %s", st->url,
140           ldap_err2string(rc));
141     st->state = 0;
142     ldap_unbind_ext_s(st->ld, NULL, NULL);
143     return (-1);
144   } else {
145     DEBUG("openldap plugin: Successfully connected to %s", st->url);
146     st->state = 1;
147     return (0);
148   }
149 } /* }}} static cldap_init_host */
150
151 static void cldap_submit_value(const char *type,
152                                const char *type_instance, /* {{{ */
153                                value_t value, cldap_t *st) {
154   value_list_t vl = VALUE_LIST_INIT;
155
156   vl.values = &value;
157   vl.values_len = 1;
158
159   if ((st->host == NULL) || (strcmp("", st->host) == 0) ||
160       (strcmp("localhost", st->host) == 0))
161     sstrncpy(vl.host, hostname_g, sizeof(vl.host));
162   else
163     sstrncpy(vl.host, st->host, sizeof(vl.host));
164
165   sstrncpy(vl.plugin, "openldap", sizeof(vl.plugin));
166   if (st->name != NULL)
167     sstrncpy(vl.plugin_instance, st->name, sizeof(vl.plugin_instance));
168
169   sstrncpy(vl.type, type, sizeof(vl.type));
170   if (type_instance != NULL)
171     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
172
173   plugin_dispatch_values(&vl);
174 } /* }}} void cldap_submit_value */
175
176 static void cldap_submit_derive(const char *type,
177                                 const char *type_instance, /* {{{ */
178                                 derive_t d, cldap_t *st) {
179   value_t v;
180   v.derive = d;
181   cldap_submit_value(type, type_instance, v, st);
182 } /* }}} void cldap_submit_derive */
183
184 static void cldap_submit_gauge(const char *type,
185                                const char *type_instance, /* {{{ */
186                                gauge_t g, cldap_t *st) {
187   value_t v;
188   v.gauge = g;
189   cldap_submit_value(type, type_instance, v, st);
190 } /* }}} void cldap_submit_gauge */
191
192 static int cldap_read_host(user_data_t *ud) /* {{{ */
193 {
194   cldap_t *st;
195   LDAPMessage *result;
196   char *dn;
197   int rc;
198   int status;
199
200   char *attrs[9] = {
201       "monitorCounter", "monitorOpCompleted", "monitorOpInitiated",
202       "monitoredInfo",  "olmBDBEntryCache",   "olmBDBDNCache",
203       "olmBDBIDLCache", "namingContexts",     NULL};
204
205   if ((ud == NULL) || (ud->data == NULL)) {
206     ERROR("openldap plugin: cldap_read_host: Invalid user data.");
207     return (-1);
208   }
209
210   st = (cldap_t *)ud->data;
211
212   status = cldap_init_host(st);
213   if (status != 0)
214     return (-1);
215
216   rc = ldap_search_ext_s(st->ld, "cn=Monitor", LDAP_SCOPE_SUBTREE,
217                          "(|(!(cn=* *))(cn=Database*))", attrs, 0, NULL, NULL,
218                          NULL, 0, &result);
219
220   if (rc != LDAP_SUCCESS) {
221     ERROR("openldap plugin: Failed to execute search: %s", ldap_err2string(rc));
222     ldap_msgfree(result);
223     st->state = 0;
224     ldap_unbind_ext_s(st->ld, NULL, NULL);
225     return (-1);
226   }
227
228   for (LDAPMessage *e = ldap_first_entry(st->ld, result); e != NULL;
229        e = ldap_next_entry(st->ld, e)) {
230     if ((dn = ldap_get_dn(st->ld, e)) != NULL) {
231       unsigned long long counter = 0;
232       unsigned long long opc = 0;
233       unsigned long long opi = 0;
234       unsigned long long info = 0;
235
236       struct berval counter_data;
237       struct berval opc_data;
238       struct berval opi_data;
239       struct berval info_data;
240       struct berval olmbdb_data;
241       struct berval nc_data;
242
243       struct berval **counter_list;
244       struct berval **opc_list;
245       struct berval **opi_list;
246       struct berval **info_list;
247       struct berval **olmbdb_list;
248       struct berval **nc_list;
249
250       if ((counter_list = ldap_get_values_len(st->ld, e, "monitorCounter")) !=
251           NULL) {
252         counter_data = *counter_list[0];
253         counter = atoll(counter_data.bv_val);
254       }
255
256       if ((opc_list = ldap_get_values_len(st->ld, e, "monitorOpCompleted")) !=
257           NULL) {
258         opc_data = *opc_list[0];
259         opc = atoll(opc_data.bv_val);
260       }
261
262       if ((opi_list = ldap_get_values_len(st->ld, e, "monitorOpInitiated")) !=
263           NULL) {
264         opi_data = *opi_list[0];
265         opi = atoll(opi_data.bv_val);
266       }
267
268       if ((info_list = ldap_get_values_len(st->ld, e, "monitoredInfo")) !=
269           NULL) {
270         info_data = *info_list[0];
271         info = atoll(info_data.bv_val);
272       }
273
274       if (strcmp(dn, "cn=Total,cn=Connections,cn=Monitor") == 0) {
275         cldap_submit_derive("total_connections", NULL, counter, st);
276       } else if (strcmp(dn, "cn=Current,cn=Connections,cn=Monitor") == 0) {
277         cldap_submit_gauge("current_connections", NULL, counter, st);
278       } else if (strcmp(dn, "cn=Operations,cn=Monitor") == 0) {
279         cldap_submit_derive("operations", "completed", opc, st);
280         cldap_submit_derive("operations", "initiated", opi, st);
281       } else if (strcmp(dn, "cn=Bind,cn=Operations,cn=Monitor") == 0) {
282         cldap_submit_derive("operations", "bind-completed", opc, st);
283         cldap_submit_derive("operations", "bind-initiated", opi, st);
284       } else if (strcmp(dn, "cn=UnBind,cn=Operations,cn=Monitor") == 0) {
285         cldap_submit_derive("operations", "unbind-completed", opc, st);
286         cldap_submit_derive("operations", "unbind-initiated", opi, st);
287       } else if (strcmp(dn, "cn=Search,cn=Operations,cn=Monitor") == 0) {
288         cldap_submit_derive("operations", "search-completed", opc, st);
289         cldap_submit_derive("operations", "search-initiated", opi, st);
290       } else if (strcmp(dn, "cn=Compare,cn=Operations,cn=Monitor") == 0) {
291         cldap_submit_derive("operations", "compare-completed", opc, st);
292         cldap_submit_derive("operations", "compare-initiated", opi, st);
293       } else if (strcmp(dn, "cn=Modify,cn=Operations,cn=Monitor") == 0) {
294         cldap_submit_derive("operations", "modify-completed", opc, st);
295         cldap_submit_derive("operations", "modify-initiated", opi, st);
296       } else if (strcmp(dn, "cn=Modrdn,cn=Operations,cn=Monitor") == 0) {
297         cldap_submit_derive("operations", "modrdn-completed", opc, st);
298         cldap_submit_derive("operations", "modrdn-initiated", opi, st);
299       } else if (strcmp(dn, "cn=Add,cn=Operations,cn=Monitor") == 0) {
300         cldap_submit_derive("operations", "add-completed", opc, st);
301         cldap_submit_derive("operations", "add-initiated", opi, st);
302       } else if (strcmp(dn, "cn=Delete,cn=Operations,cn=Monitor") == 0) {
303         cldap_submit_derive("operations", "delete-completed", opc, st);
304         cldap_submit_derive("operations", "delete-initiated", opi, st);
305       } else if (strcmp(dn, "cn=Abandon,cn=Operations,cn=Monitor") == 0) {
306         cldap_submit_derive("operations", "abandon-completed", opc, st);
307         cldap_submit_derive("operations", "abandon-initiated", opi, st);
308       } else if (strcmp(dn, "cn=Extended,cn=Operations,cn=Monitor") == 0) {
309         cldap_submit_derive("operations", "extended-completed", opc, st);
310         cldap_submit_derive("operations", "extended-initiated", opi, st);
311       } else if ((strncmp(dn, "cn=Database", 11) == 0) &&
312                  ((nc_list = ldap_get_values_len(st->ld, e,
313                                                  "namingContexts")) != NULL)) {
314         nc_data = *nc_list[0];
315         char typeinst[DATA_MAX_NAME_LEN];
316
317         if ((olmbdb_list =
318                  ldap_get_values_len(st->ld, e, "olmBDBEntryCache")) != NULL) {
319           olmbdb_data = *olmbdb_list[0];
320           ssnprintf(typeinst, sizeof(typeinst), "bdbentrycache-%s",
321                     nc_data.bv_val);
322           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
323                              st);
324           ldap_value_free_len(olmbdb_list);
325         }
326
327         if ((olmbdb_list = ldap_get_values_len(st->ld, e, "olmBDBDNCache")) !=
328             NULL) {
329           olmbdb_data = *olmbdb_list[0];
330           ssnprintf(typeinst, sizeof(typeinst), "bdbdncache-%s",
331                     nc_data.bv_val);
332           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
333                              st);
334           ldap_value_free_len(olmbdb_list);
335         }
336
337         if ((olmbdb_list = ldap_get_values_len(st->ld, e, "olmBDBIDLCache")) !=
338             NULL) {
339           olmbdb_data = *olmbdb_list[0];
340           ssnprintf(typeinst, sizeof(typeinst), "bdbidlcache-%s",
341                     nc_data.bv_val);
342           cldap_submit_gauge("cache_size", typeinst, atoll(olmbdb_data.bv_val),
343                              st);
344           ldap_value_free_len(olmbdb_list);
345         }
346
347         ldap_value_free_len(nc_list);
348       } else if (strcmp(dn, "cn=Bytes,cn=Statistics,cn=Monitor") == 0) {
349         cldap_submit_derive("derive", "statistics-bytes", counter, st);
350       } else if (strcmp(dn, "cn=PDU,cn=Statistics,cn=Monitor") == 0) {
351         cldap_submit_derive("derive", "statistics-pdu", counter, st);
352       } else if (strcmp(dn, "cn=Entries,cn=Statistics,cn=Monitor") == 0) {
353         cldap_submit_derive("derive", "statistics-entries", counter, st);
354       } else if (strcmp(dn, "cn=Referrals,cn=Statistics,cn=Monitor") == 0) {
355         cldap_submit_derive("derive", "statistics-referrals", counter, st);
356       } else if (strcmp(dn, "cn=Open,cn=Threads,cn=Monitor") == 0) {
357         cldap_submit_gauge("threads", "threads-open", info, st);
358       } else if (strcmp(dn, "cn=Starting,cn=Threads,cn=Monitor") == 0) {
359         cldap_submit_gauge("threads", "threads-starting", info, st);
360       } else if (strcmp(dn, "cn=Active,cn=Threads,cn=Monitor") == 0) {
361         cldap_submit_gauge("threads", "threads-active", info, st);
362       } else if (strcmp(dn, "cn=Pending,cn=Threads,cn=Monitor") == 0) {
363         cldap_submit_gauge("threads", "threads-pending", info, st);
364       } else if (strcmp(dn, "cn=Backload,cn=Threads,cn=Monitor") == 0) {
365         cldap_submit_gauge("threads", "threads-backload", info, st);
366       } else if (strcmp(dn, "cn=Read,cn=Waiters,cn=Monitor") == 0) {
367         cldap_submit_derive("derive", "waiters-read", counter, st);
368       } else if (strcmp(dn, "cn=Write,cn=Waiters,cn=Monitor") == 0) {
369         cldap_submit_derive("derive", "waiters-write", counter, st);
370       }
371
372       ldap_value_free_len(counter_list);
373       ldap_value_free_len(opc_list);
374       ldap_value_free_len(opi_list);
375       ldap_value_free_len(info_list);
376     }
377
378     ldap_memfree(dn);
379   }
380
381   ldap_msgfree(result);
382   return (0);
383 } /* }}} int cldap_read_host */
384
385 /* Configuration handling functions {{{
386  *
387  * <Plugin ldap>
388  *   <Instance "plugin_instance1">
389  *     URL "ldap://localhost"
390  *     ...
391  *   </Instance>
392  * </Plugin>
393  */
394
395 static int cldap_config_add(oconfig_item_t *ci) /* {{{ */
396 {
397   cldap_t *st;
398   int status;
399
400   st = calloc(1, sizeof(*st));
401   if (st == NULL) {
402     ERROR("openldap plugin: calloc failed.");
403     return (-1);
404   }
405
406   status = cf_util_get_string(ci, &st->name);
407   if (status != 0) {
408     sfree(st);
409     return (status);
410   }
411
412   st->starttls = 0;
413   st->timeout = (long)(CDTIME_T_TO_MS(plugin_get_interval()) / 1000);
414   st->verifyhost = 1;
415   st->version = LDAP_VERSION3;
416
417   for (int i = 0; i < ci->children_num; i++) {
418     oconfig_item_t *child = ci->children + i;
419
420     if (strcasecmp("BindDN", child->key) == 0)
421       status = cf_util_get_string(child, &st->binddn);
422     else if (strcasecmp("Password", child->key) == 0)
423       status = cf_util_get_string(child, &st->password);
424     else if (strcasecmp("CACert", child->key) == 0)
425       status = cf_util_get_string(child, &st->cacert);
426     else if (strcasecmp("StartTLS", child->key) == 0)
427       status = cf_util_get_boolean(child, &st->starttls);
428     else if (strcasecmp("Timeout", child->key) == 0)
429       status = cf_util_get_int(child, &st->timeout);
430     else if (strcasecmp("URL", child->key) == 0)
431       status = cf_util_get_string(child, &st->url);
432     else if (strcasecmp("VerifyHost", child->key) == 0)
433       status = cf_util_get_boolean(child, &st->verifyhost);
434     else if (strcasecmp("Version", child->key) == 0)
435       status = cf_util_get_int(child, &st->version);
436     else {
437       WARNING("openldap plugin: Option `%s' not allowed here.", child->key);
438       status = -1;
439     }
440
441     if (status != 0)
442       break;
443   }
444
445   /* Check if struct is complete.. */
446   if ((status == 0) && (st->url == NULL)) {
447     ERROR("openldap plugin: Instance `%s': "
448           "No URL has been configured.",
449           st->name);
450     status = -1;
451   }
452
453   /* Check if URL is valid */
454   if ((status == 0) && (st->url != NULL)) {
455     LDAPURLDesc *ludpp;
456
457     if (ldap_url_parse(st->url, &ludpp) != 0) {
458       ERROR("openldap plugin: Instance `%s': "
459             "Invalid URL: `%s'",
460             st->name, st->url);
461       status = -1;
462     }
463
464     if ((status == 0) && (ludpp->lud_host != NULL))
465       st->host = strdup(ludpp->lud_host);
466
467     ldap_free_urldesc(ludpp);
468   }
469
470   if (status == 0) {
471     cldap_t **temp;
472
473     temp = (cldap_t **)realloc(databases,
474                                sizeof(*databases) * (databases_num + 1));
475
476     if (temp == NULL) {
477       ERROR("openldap plugin: realloc failed");
478       status = -1;
479     } else {
480       char callback_name[3 * DATA_MAX_NAME_LEN] = {0};
481
482       databases = temp;
483       databases[databases_num] = st;
484       databases_num++;
485
486       ssnprintf(callback_name, sizeof(callback_name), "openldap/%s/%s",
487                 (st->host != NULL) ? st->host : hostname_g,
488                 (st->name != NULL) ? st->name : "default");
489
490       user_data_t ud = {.data = st};
491
492       status = plugin_register_complex_read(/* group = */ NULL,
493                                             /* name      = */ callback_name,
494                                             /* callback  = */ cldap_read_host,
495                                             /* interval  = */ 0,
496                                             /* user_data = */ &ud);
497     }
498   }
499
500   if (status != 0) {
501     cldap_free(st);
502     return (-1);
503   }
504
505   return (0);
506 } /* }}} int cldap_config_add */
507
508 static int cldap_config(oconfig_item_t *ci) /* {{{ */
509 {
510   int status = 0;
511
512   for (int i = 0; i < ci->children_num; i++) {
513     oconfig_item_t *child = ci->children + i;
514
515     if (strcasecmp("Instance", child->key) == 0)
516       cldap_config_add(child);
517     else
518       WARNING("openldap plugin: The configuration option "
519               "\"%s\" is not allowed here. Did you "
520               "forget to add an <Instance /> block "
521               "around the configuration?",
522               child->key);
523   } /* for (ci->children) */
524
525   return (status);
526 } /* }}} int cldap_config */
527
528 /* }}} End of configuration handling functions */
529
530 static int cldap_init(void) /* {{{ */
531 {
532   /* Initialize LDAP library while still single-threaded as recommended in
533    * ldap_initialize(3) */
534   int debug_level;
535   ldap_get_option(NULL, LDAP_OPT_DEBUG_LEVEL, &debug_level);
536   return (0);
537 } /* }}} int cldap_init */
538
539 static int cldap_shutdown(void) /* {{{ */
540 {
541   for (size_t i = 0; i < databases_num; i++)
542     if (databases[i]->ld != NULL)
543       ldap_unbind_ext_s(databases[i]->ld, NULL, NULL);
544   sfree(databases);
545   databases_num = 0;
546
547   return (0);
548 } /* }}} int cldap_shutdown */
549
550 void module_register(void) /* {{{ */
551 {
552   plugin_register_complex_config("openldap", cldap_config);
553   plugin_register_init("openldap", cldap_init);
554   plugin_register_shutdown("openldap", cldap_shutdown);
555 } /* }}} void module_register */
556
557 #if defined(__APPLE__)
558 #pragma clang diagnostic pop
559 #endif