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 push
32 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
38 # pragma GCC diagnostic pop
42 # pragma comment(lib, "libldap_r.lib")
43 # pragma comment(lib, "liblber.lib")
53 LDAPMessage* message; /* message returned by ldap_ */
54 LDAPResult* result; /* final result */
58 LDAPRequest(LDAPService* s, LDAPInterface* i)
69 virtual ~LDAPRequest()
73 ldap_msgfree(message);
76 virtual int run() = 0;
79 class LDAPBind : public LDAPRequest
81 std::string who, pass;
84 LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
92 int run() CXX11_OVERRIDE;
95 class LDAPSearch : public LDAPRequest
102 LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
111 int run() CXX11_OVERRIDE;
114 class LDAPAdd : public LDAPRequest
120 LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
128 int run() CXX11_OVERRIDE;
131 class LDAPDel : public LDAPRequest
136 LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
143 int run() CXX11_OVERRIDE;
146 class LDAPModify : public LDAPRequest
152 LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
160 int run() CXX11_OVERRIDE;
163 class LDAPCompare : public LDAPRequest
165 std::string dn, attr, val;
168 LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
174 type = QUERY_COMPARE;
177 int run() CXX11_OVERRIDE;
180 class LDAPService : public LDAPProvider, public SocketThread
183 reference<ConfigTag> config;
189 static LDAPMod** BuildMods(const LDAPMods& attributes)
191 LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
192 memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
193 for (unsigned int x = 0; x < attributes.size(); ++x)
195 const LDAPModification& l = attributes[x];
196 LDAPMod* mod = new LDAPMod;
199 if (l.op == LDAPModification::LDAP_ADD)
200 mod->mod_op = LDAP_MOD_ADD;
201 else if (l.op == LDAPModification::LDAP_DEL)
202 mod->mod_op = LDAP_MOD_DELETE;
203 else if (l.op == LDAPModification::LDAP_REPLACE)
204 mod->mod_op = LDAP_MOD_REPLACE;
208 throw LDAPException("Unknown LDAP operation");
210 mod->mod_type = strdup(l.name.c_str());
211 mod->mod_values = new char*[l.values.size() + 1];
212 memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
213 for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
214 if (!l.values[j].empty())
215 mod->mod_values[c++] = strdup(l.values[j].c_str());
220 static void FreeMods(LDAPMod** mods)
222 for (unsigned int i = 0; mods[i] != NULL; ++i)
224 LDAPMod* mod = mods[i];
225 if (mod->mod_type != NULL)
227 if (mod->mod_values != NULL)
229 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
230 free(mod->mod_values[j]);
231 delete[] mod->mod_values;
240 // Only try one connect a minute. It is an expensive blocking operation
241 if (last_connect > ServerInstance->Time() - 60)
242 throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
243 last_connect = ServerInstance->Time();
245 ldap_unbind_ext(this->con, NULL, NULL);
249 void QueueRequest(LDAPRequest* r)
252 this->queries.push_back(r);
253 this->UnlockQueueWakeup();
257 typedef std::vector<LDAPRequest*> query_queue;
258 query_queue queries, results;
259 Mutex process_mutex; /* held when processing requests not in either queue */
261 LDAPService(Module* c, ConfigTag* tag)
262 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
263 , con(NULL), config(tag), last_connect(0)
265 std::string scope = config->getString("searchscope");
266 if (stdalgo::string::equalsci(scope, "base"))
267 searchscope = LDAP_SCOPE_BASE;
268 else if (stdalgo::string::equalsci(scope, "onelevel"))
269 searchscope = LDAP_SCOPE_ONELEVEL;
271 searchscope = LDAP_SCOPE_SUBTREE;
272 timeout = config->getDuration("timeout", 5);
281 for (unsigned int i = 0; i < this->queries.size(); ++i)
283 LDAPRequest* req = this->queries[i];
285 /* queries have no results yet */
286 req->result = new LDAPResult();
287 req->result->type = req->type;
288 req->result->error = "LDAP Interface is going away";
289 req->inter->OnError(*req->result);
293 this->queries.clear();
295 for (unsigned int i = 0; i < this->results.size(); ++i)
297 LDAPRequest* req = this->results[i];
299 /* even though this may have already finished successfully we return that it didn't */
300 req->result->error = "LDAP Interface is going away";
301 req->inter->OnError(*req->result);
305 this->results.clear();
309 ldap_unbind_ext(this->con, NULL, NULL);
314 std::string server = config->getString("server");
315 int i = ldap_initialize(&this->con, server.c_str());
316 if (i != LDAP_SUCCESS)
317 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
319 const int version = LDAP_VERSION3;
320 i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
321 if (i != LDAP_OPT_SUCCESS)
323 ldap_unbind_ext(this->con, NULL, NULL);
325 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
328 const struct timeval tv = { 0, 0 };
329 i = ldap_set_option(this->con, LDAP_OPT_NETWORK_TIMEOUT, &tv);
330 if (i != LDAP_OPT_SUCCESS)
332 ldap_unbind_ext(this->con, NULL, NULL);
334 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
338 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
340 std::string binddn = config->getString("binddn");
341 std::string bindauth = config->getString("bindauth");
342 this->Bind(i, binddn, bindauth);
345 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
347 LDAPBind* b = new LDAPBind(this, i, who, pass);
351 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
354 throw LDAPException("No interface");
356 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
360 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
362 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
366 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
368 LDAPDel* del = new LDAPDel(this, i, dn);
372 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
374 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
378 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
380 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
385 void BuildReply(int res, LDAPRequest* req)
387 LDAPResult* ldap_result = req->result = new LDAPResult();
388 req->result->type = req->type;
390 if (res != LDAP_SUCCESS)
392 ldap_result->error = ldap_err2string(res);
396 if (req->message == NULL)
401 /* a search result */
403 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
405 LDAPAttributes attributes;
407 char* dn = ldap_get_dn(this->con, cur);
410 attributes["dn"].push_back(dn);
415 BerElement* ber = NULL;
417 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
419 berval** vals = ldap_get_values_len(this->con, cur, attr);
420 int count = ldap_count_values_len(vals);
422 std::vector<std::string> attrs;
423 for (int j = 0; j < count; ++j)
424 attrs.push_back(vals[j]->bv_val);
425 attributes[attr] = attrs;
427 ldap_value_free_len(vals);
433 ldap_result->messages.push_back(attributes);
439 process_mutex.Lock();
448 process_mutex.Unlock();
452 for (unsigned int i = 0; i < q.size(); ++i)
454 LDAPRequest* req = q[i];
455 int ret = req->run();
457 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
464 catch (const LDAPException &)
471 BuildReply(ret, req);
474 this->results.push_back(req);
478 this->NotifyParent();
480 process_mutex.Unlock();
484 void Run() CXX11_OVERRIDE
486 while (!this->GetExitFlag())
489 if (this->queries.empty())
490 this->WaitForQueue();
497 void OnNotify() CXX11_OVERRIDE
502 this->results.swap(r);
505 for (unsigned int i = 0; i < r.size(); ++i)
507 LDAPRequest* req = r[i];
508 LDAPInterface* li = req->inter;
509 LDAPResult* res = req->result;
511 if (!res->error.empty())
520 LDAP* GetConnection()
526 class ModuleLDAP : public Module
528 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
529 ServiceMap LDAPServices;
532 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
536 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
537 for (ConfigIter i = tags.first; i != tags.second; i++)
539 const reference<ConfigTag>& tag = i->second;
541 if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
544 std::string id = tag->getString("id");
546 ServiceMap::iterator curr = LDAPServices.find(id);
547 if (curr == LDAPServices.end())
549 LDAPService* conn = new LDAPService(this, tag);
552 ServerInstance->Modules->AddService(*conn);
553 ServerInstance->Threads.Start(conn);
558 LDAPServices.erase(curr);
562 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
564 LDAPService* conn = i->second;
565 ServerInstance->Modules->DelService(*conn);
571 LDAPServices.swap(conns);
574 void OnUnloadModule(Module* m) CXX11_OVERRIDE
576 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
578 LDAPService* s = it->second;
580 s->process_mutex.Lock();
583 for (unsigned int i = s->queries.size(); i > 0; --i)
585 LDAPRequest* req = s->queries[i - 1];
586 LDAPInterface* li = req->inter;
588 if (li->creator == m)
590 s->queries.erase(s->queries.begin() + i - 1);
595 for (unsigned int i = s->results.size(); i > 0; --i)
597 LDAPRequest* req = s->results[i - 1];
598 LDAPInterface* li = req->inter;
600 if (li->creator == m)
602 s->results.erase(s->results.begin() + i - 1);
608 s->process_mutex.Unlock();
614 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
616 LDAPService* conn = i->second;
623 Version GetVersion() CXX11_OVERRIDE
625 return Version("Provides LDAP support", VF_VENDOR);
632 cred.bv_val = strdup(pass.c_str());
633 cred.bv_len = pass.length();
635 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
642 int LDAPSearch::run()
644 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
649 LDAPMod** mods = LDAPService::BuildMods(attributes);
650 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
651 LDAPService::FreeMods(mods);
657 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
660 int LDAPModify::run()
662 LDAPMod** mods = LDAPService::BuildMods(attributes);
663 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
664 LDAPService::FreeMods(mods);
668 int LDAPCompare::run()
671 cred.bv_val = strdup(val.c_str());
672 cred.bv_len = val.length();
674 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
682 MODULE_INIT(ModuleLDAP)