2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013-2015 Adam <Adam@anope.org>
5 * Copyright (C) 2003-2015 Anope Team <team@anope.org>
7 * This file is part of InspIRCd. InspIRCd is free software: you can
8 * redistribute it and/or modify it under the terms of the GNU General Public
9 * License as published by the Free Software Foundation, version 2.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /// $LinkerFlags: -llber -lldap_r
22 /// $PackageInfo: require_system("centos") openldap-devel
23 /// $PackageInfo: require_system("debian") libldap2-dev
24 /// $PackageInfo: require_system("ubuntu") libldap2-dev
27 #include "modules/ldap.h"
29 // Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
31 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
37 # pragma comment(lib, "libldap_r.lib")
38 # pragma comment(lib, "liblber.lib")
48 LDAPMessage* message; /* message returned by ldap_ */
49 LDAPResult* result; /* final result */
53 LDAPRequest(LDAPService* s, LDAPInterface* i)
64 virtual ~LDAPRequest()
68 ldap_msgfree(message);
71 virtual int run() = 0;
74 class LDAPBind : public LDAPRequest
76 std::string who, pass;
79 LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
87 int run() CXX11_OVERRIDE;
90 class LDAPSearch : public LDAPRequest
97 LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
106 int run() CXX11_OVERRIDE;
109 class LDAPAdd : public LDAPRequest
115 LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
123 int run() CXX11_OVERRIDE;
126 class LDAPDel : public LDAPRequest
131 LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
138 int run() CXX11_OVERRIDE;
141 class LDAPModify : public LDAPRequest
147 LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
155 int run() CXX11_OVERRIDE;
158 class LDAPCompare : public LDAPRequest
160 std::string dn, attr, val;
163 LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
169 type = QUERY_COMPARE;
172 int run() CXX11_OVERRIDE;
175 class LDAPService : public LDAPProvider, public SocketThread
178 reference<ConfigTag> config;
184 static LDAPMod** BuildMods(const LDAPMods& attributes)
186 LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
187 memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
188 for (unsigned int x = 0; x < attributes.size(); ++x)
190 const LDAPModification& l = attributes[x];
191 LDAPMod* mod = new LDAPMod;
194 if (l.op == LDAPModification::LDAP_ADD)
195 mod->mod_op = LDAP_MOD_ADD;
196 else if (l.op == LDAPModification::LDAP_DEL)
197 mod->mod_op = LDAP_MOD_DELETE;
198 else if (l.op == LDAPModification::LDAP_REPLACE)
199 mod->mod_op = LDAP_MOD_REPLACE;
203 throw LDAPException("Unknown LDAP operation");
205 mod->mod_type = strdup(l.name.c_str());
206 mod->mod_values = new char*[l.values.size() + 1];
207 memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
208 for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
209 if (!l.values[j].empty())
210 mod->mod_values[c++] = strdup(l.values[j].c_str());
215 static void FreeMods(LDAPMod** mods)
217 for (unsigned int i = 0; mods[i] != NULL; ++i)
219 LDAPMod* mod = mods[i];
220 if (mod->mod_type != NULL)
222 if (mod->mod_values != NULL)
224 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
225 free(mod->mod_values[j]);
226 delete[] mod->mod_values;
235 // Only try one connect a minute. It is an expensive blocking operation
236 if (last_connect > ServerInstance->Time() - 60)
237 throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
238 last_connect = ServerInstance->Time();
240 ldap_unbind_ext(this->con, NULL, NULL);
244 void QueueRequest(LDAPRequest* r)
247 this->queries.push_back(r);
248 this->UnlockQueueWakeup();
252 typedef std::vector<LDAPRequest*> query_queue;
253 query_queue queries, results;
254 Mutex process_mutex; /* held when processing requests not in either queue */
256 LDAPService(Module* c, ConfigTag* tag)
257 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
258 , con(NULL), config(tag), last_connect(0)
260 std::string scope = config->getString("searchscope");
262 searchscope = LDAP_SCOPE_BASE;
263 else if (scope == "onelevel")
264 searchscope = LDAP_SCOPE_ONELEVEL;
266 searchscope = LDAP_SCOPE_SUBTREE;
267 timeout = config->getDuration("timeout", 5);
276 for (unsigned int i = 0; i < this->queries.size(); ++i)
278 LDAPRequest* req = this->queries[i];
280 /* queries have no results yet */
281 req->result = new LDAPResult();
282 req->result->type = req->type;
283 req->result->error = "LDAP Interface is going away";
284 req->inter->OnError(*req->result);
288 this->queries.clear();
290 for (unsigned int i = 0; i < this->results.size(); ++i)
292 LDAPRequest* req = this->results[i];
294 /* even though this may have already finished successfully we return that it didn't */
295 req->result->error = "LDAP Interface is going away";
296 req->inter->OnError(*req->result);
300 this->results.clear();
304 ldap_unbind_ext(this->con, NULL, NULL);
309 std::string server = config->getString("server");
310 int i = ldap_initialize(&this->con, server.c_str());
311 if (i != LDAP_SUCCESS)
312 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
314 const int version = LDAP_VERSION3;
315 i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
316 if (i != LDAP_OPT_SUCCESS)
318 ldap_unbind_ext(this->con, NULL, NULL);
320 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
323 const struct timeval tv = { 0, 0 };
324 i = ldap_set_option(this->con, LDAP_OPT_NETWORK_TIMEOUT, &tv);
325 if (i != LDAP_OPT_SUCCESS)
327 ldap_unbind_ext(this->con, NULL, NULL);
329 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
333 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
335 std::string binddn = config->getString("binddn");
336 std::string bindauth = config->getString("bindauth");
337 this->Bind(i, binddn, bindauth);
340 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
342 LDAPBind* b = new LDAPBind(this, i, who, pass);
346 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
349 throw LDAPException("No interface");
351 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
355 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
357 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
361 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
363 LDAPDel* del = new LDAPDel(this, i, dn);
367 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
369 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
373 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
375 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
380 void BuildReply(int res, LDAPRequest* req)
382 LDAPResult* ldap_result = req->result = new LDAPResult();
383 req->result->type = req->type;
385 if (res != LDAP_SUCCESS)
387 ldap_result->error = ldap_err2string(res);
391 if (req->message == NULL)
396 /* a search result */
398 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
400 LDAPAttributes attributes;
402 char* dn = ldap_get_dn(this->con, cur);
405 attributes["dn"].push_back(dn);
410 BerElement* ber = NULL;
412 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
414 berval** vals = ldap_get_values_len(this->con, cur, attr);
415 int count = ldap_count_values_len(vals);
417 std::vector<std::string> attrs;
418 for (int j = 0; j < count; ++j)
419 attrs.push_back(vals[j]->bv_val);
420 attributes[attr] = attrs;
422 ldap_value_free_len(vals);
428 ldap_result->messages.push_back(attributes);
434 process_mutex.Lock();
443 process_mutex.Unlock();
447 for (unsigned int i = 0; i < q.size(); ++i)
449 LDAPRequest* req = q[i];
450 int ret = req->run();
452 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
459 catch (const LDAPException &)
466 BuildReply(ret, req);
469 this->results.push_back(req);
473 this->NotifyParent();
475 process_mutex.Unlock();
479 void Run() CXX11_OVERRIDE
481 while (!this->GetExitFlag())
484 if (this->queries.empty())
485 this->WaitForQueue();
492 void OnNotify() CXX11_OVERRIDE
497 this->results.swap(r);
500 for (unsigned int i = 0; i < r.size(); ++i)
502 LDAPRequest* req = r[i];
503 LDAPInterface* li = req->inter;
504 LDAPResult* res = req->result;
506 if (!res->error.empty())
515 LDAP* GetConnection()
521 class ModuleLDAP : public Module
523 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
524 ServiceMap LDAPServices;
527 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
531 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
532 for (ConfigIter i = tags.first; i != tags.second; i++)
534 const reference<ConfigTag>& tag = i->second;
536 if (tag->getString("module") != "ldap")
539 std::string id = tag->getString("id");
541 ServiceMap::iterator curr = LDAPServices.find(id);
542 if (curr == LDAPServices.end())
544 LDAPService* conn = new LDAPService(this, tag);
547 ServerInstance->Modules->AddService(*conn);
548 ServerInstance->Threads.Start(conn);
553 LDAPServices.erase(curr);
557 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
559 LDAPService* conn = i->second;
560 ServerInstance->Modules->DelService(*conn);
566 LDAPServices.swap(conns);
569 void OnUnloadModule(Module* m) CXX11_OVERRIDE
571 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
573 LDAPService* s = it->second;
575 s->process_mutex.Lock();
578 for (unsigned int i = s->queries.size(); i > 0; --i)
580 LDAPRequest* req = s->queries[i - 1];
581 LDAPInterface* li = req->inter;
583 if (li->creator == m)
585 s->queries.erase(s->queries.begin() + i - 1);
590 for (unsigned int i = s->results.size(); i > 0; --i)
592 LDAPRequest* req = s->results[i - 1];
593 LDAPInterface* li = req->inter;
595 if (li->creator == m)
597 s->results.erase(s->results.begin() + i - 1);
603 s->process_mutex.Unlock();
609 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
611 LDAPService* conn = i->second;
618 Version GetVersion() CXX11_OVERRIDE
620 return Version("LDAP support", VF_VENDOR);
627 cred.bv_val = strdup(pass.c_str());
628 cred.bv_len = pass.length();
630 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
637 int LDAPSearch::run()
639 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
644 LDAPMod** mods = LDAPService::BuildMods(attributes);
645 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
646 LDAPService::FreeMods(mods);
652 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
655 int LDAPModify::run()
657 LDAPMod** mods = LDAPService::BuildMods(attributes);
658 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
659 LDAPService::FreeMods(mods);
663 int LDAPCompare::run()
666 cred.bv_val = strdup(val.c_str());
667 cred.bv_len = val.length();
669 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
677 MODULE_INIT(ModuleLDAP)