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