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