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("arch") libldap
23 /// $PackageInfo: require_system("centos") openldap-devel
24 /// $PackageInfo: require_system("debian") libldap2-dev
25 /// $PackageInfo: require_system("ubuntu") libldap2-dev
28 #include "modules/ldap.h"
30 // Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
32 # pragma GCC diagnostic push
33 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
39 # pragma GCC diagnostic pop
43 # pragma comment(lib, "libldap_r.lib")
44 # pragma comment(lib, "liblber.lib")
54 LDAPMessage* message; /* message returned by ldap_ */
55 LDAPResult* result; /* final result */
59 LDAPRequest(LDAPService* s, LDAPInterface* i)
70 virtual ~LDAPRequest()
74 ldap_msgfree(message);
77 virtual int run() = 0;
80 class LDAPBind : public LDAPRequest
82 std::string who, pass;
85 LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
93 int run() CXX11_OVERRIDE;
96 class LDAPSearch : public LDAPRequest
103 LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
112 int run() CXX11_OVERRIDE;
115 class LDAPAdd : public LDAPRequest
121 LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
129 int run() CXX11_OVERRIDE;
132 class LDAPDel : public LDAPRequest
137 LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
144 int run() CXX11_OVERRIDE;
147 class LDAPModify : public LDAPRequest
153 LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
161 int run() CXX11_OVERRIDE;
164 class LDAPCompare : public LDAPRequest
166 std::string dn, attr, val;
169 LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
175 type = QUERY_COMPARE;
178 int run() CXX11_OVERRIDE;
181 class LDAPService : public LDAPProvider, public SocketThread
184 reference<ConfigTag> config;
190 static LDAPMod** BuildMods(const LDAPMods& attributes)
192 LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
193 memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
194 for (unsigned int x = 0; x < attributes.size(); ++x)
196 const LDAPModification& l = attributes[x];
197 LDAPMod* mod = new LDAPMod;
200 if (l.op == LDAPModification::LDAP_ADD)
201 mod->mod_op = LDAP_MOD_ADD;
202 else if (l.op == LDAPModification::LDAP_DEL)
203 mod->mod_op = LDAP_MOD_DELETE;
204 else if (l.op == LDAPModification::LDAP_REPLACE)
205 mod->mod_op = LDAP_MOD_REPLACE;
209 throw LDAPException("Unknown LDAP operation");
211 mod->mod_type = strdup(l.name.c_str());
212 mod->mod_values = new char*[l.values.size() + 1];
213 memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
214 for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
215 if (!l.values[j].empty())
216 mod->mod_values[c++] = strdup(l.values[j].c_str());
221 static void FreeMods(LDAPMod** mods)
223 for (unsigned int i = 0; mods[i] != NULL; ++i)
225 LDAPMod* mod = mods[i];
226 if (mod->mod_type != NULL)
228 if (mod->mod_values != NULL)
230 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
231 free(mod->mod_values[j]);
232 delete[] mod->mod_values;
241 // Only try one connect a minute. It is an expensive blocking operation
242 if (last_connect > ServerInstance->Time() - 60)
243 throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
244 last_connect = ServerInstance->Time();
246 ldap_unbind_ext(this->con, NULL, NULL);
250 int SetOption(int option, const void* value)
252 int ret = ldap_set_option(this->con, option, value);
253 if (ret != LDAP_OPT_SUCCESS)
255 ldap_unbind_ext(this->con, NULL, NULL);
261 void QueueRequest(LDAPRequest* r)
264 this->queries.push_back(r);
265 this->UnlockQueueWakeup();
269 typedef std::vector<LDAPRequest*> query_queue;
270 query_queue queries, results;
271 Mutex process_mutex; /* held when processing requests not in either queue */
273 LDAPService(Module* c, ConfigTag* tag)
274 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
275 , con(NULL), config(tag), last_connect(0)
277 std::string scope = config->getString("searchscope");
278 if (stdalgo::string::equalsci(scope, "base"))
279 searchscope = LDAP_SCOPE_BASE;
280 else if (stdalgo::string::equalsci(scope, "onelevel"))
281 searchscope = LDAP_SCOPE_ONELEVEL;
283 searchscope = LDAP_SCOPE_SUBTREE;
284 timeout = config->getDuration("timeout", 5);
293 for (unsigned int i = 0; i < this->queries.size(); ++i)
295 LDAPRequest* req = this->queries[i];
297 /* queries have no results yet */
298 req->result = new LDAPResult();
299 req->result->type = req->type;
300 req->result->error = "LDAP Interface is going away";
301 req->inter->OnError(*req->result);
305 this->queries.clear();
307 for (unsigned int i = 0; i < this->results.size(); ++i)
309 LDAPRequest* req = this->results[i];
311 /* even though this may have already finished successfully we return that it didn't */
312 req->result->error = "LDAP Interface is going away";
313 req->inter->OnError(*req->result);
317 this->results.clear();
321 ldap_unbind_ext(this->con, NULL, NULL);
326 std::string server = config->getString("server");
327 int i = ldap_initialize(&this->con, server.c_str());
328 if (i != LDAP_SUCCESS)
329 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
331 const int version = LDAP_VERSION3;
332 i = SetOption(LDAP_OPT_PROTOCOL_VERSION, &version);
333 if (i != LDAP_OPT_SUCCESS)
334 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
336 const struct timeval tv = { 0, 0 };
337 i = SetOption(LDAP_OPT_NETWORK_TIMEOUT, &tv);
338 if (i != LDAP_OPT_SUCCESS)
339 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
342 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
344 std::string binddn = config->getString("binddn");
345 std::string bindauth = config->getString("bindauth");
346 this->Bind(i, binddn, bindauth);
349 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
351 LDAPBind* b = new LDAPBind(this, i, who, pass);
355 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
358 throw LDAPException("No interface");
360 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
364 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
366 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
370 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
372 LDAPDel* del = new LDAPDel(this, i, dn);
376 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
378 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
382 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
384 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
389 void BuildReply(int res, LDAPRequest* req)
391 LDAPResult* ldap_result = req->result = new LDAPResult();
392 req->result->type = req->type;
394 if (res != LDAP_SUCCESS)
396 ldap_result->error = ldap_err2string(res);
400 if (req->message == NULL)
405 /* a search result */
407 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
409 LDAPAttributes attributes;
411 char* dn = ldap_get_dn(this->con, cur);
414 attributes["dn"].push_back(dn);
419 BerElement* ber = NULL;
421 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
423 berval** vals = ldap_get_values_len(this->con, cur, attr);
424 int count = ldap_count_values_len(vals);
426 std::vector<std::string> attrs;
427 for (int j = 0; j < count; ++j)
428 attrs.push_back(vals[j]->bv_val);
429 attributes[attr] = attrs;
431 ldap_value_free_len(vals);
437 ldap_result->messages.push_back(attributes);
443 process_mutex.Lock();
452 process_mutex.Unlock();
456 for (unsigned int i = 0; i < q.size(); ++i)
458 LDAPRequest* req = q[i];
459 int ret = req->run();
461 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
468 catch (const LDAPException &)
475 BuildReply(ret, req);
478 this->results.push_back(req);
482 this->NotifyParent();
484 process_mutex.Unlock();
488 void Run() CXX11_OVERRIDE
490 while (!this->GetExitFlag())
493 if (this->queries.empty())
494 this->WaitForQueue();
501 void OnNotify() CXX11_OVERRIDE
506 this->results.swap(r);
509 for (unsigned int i = 0; i < r.size(); ++i)
511 LDAPRequest* req = r[i];
512 LDAPInterface* li = req->inter;
513 LDAPResult* res = req->result;
515 if (!res->error.empty())
524 LDAP* GetConnection()
530 class ModuleLDAP : public Module
532 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
533 ServiceMap LDAPServices;
536 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
540 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
541 for (ConfigIter i = tags.first; i != tags.second; i++)
543 const reference<ConfigTag>& tag = i->second;
545 if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
548 std::string id = tag->getString("id");
550 ServiceMap::iterator curr = LDAPServices.find(id);
551 if (curr == LDAPServices.end())
553 LDAPService* conn = new LDAPService(this, tag);
556 ServerInstance->Modules->AddService(*conn);
557 ServerInstance->Threads.Start(conn);
562 LDAPServices.erase(curr);
566 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
568 LDAPService* conn = i->second;
569 ServerInstance->Modules->DelService(*conn);
575 LDAPServices.swap(conns);
578 void OnUnloadModule(Module* m) CXX11_OVERRIDE
580 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
582 LDAPService* s = it->second;
584 s->process_mutex.Lock();
587 for (unsigned int i = s->queries.size(); i > 0; --i)
589 LDAPRequest* req = s->queries[i - 1];
590 LDAPInterface* li = req->inter;
592 if (li->creator == m)
594 s->queries.erase(s->queries.begin() + i - 1);
599 for (unsigned int i = s->results.size(); i > 0; --i)
601 LDAPRequest* req = s->results[i - 1];
602 LDAPInterface* li = req->inter;
604 if (li->creator == m)
606 s->results.erase(s->results.begin() + i - 1);
612 s->process_mutex.Unlock();
618 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
620 LDAPService* conn = i->second;
627 Version GetVersion() CXX11_OVERRIDE
629 return Version("Provides LDAP support", VF_VENDOR);
636 cred.bv_val = strdup(pass.c_str());
637 cred.bv_len = pass.length();
639 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
646 int LDAPSearch::run()
648 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
653 LDAPMod** mods = LDAPService::BuildMods(attributes);
654 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
655 LDAPService::FreeMods(mods);
661 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
664 int LDAPModify::run()
666 LDAPMod** mods = LDAPService::BuildMods(attributes);
667 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
668 LDAPService::FreeMods(mods);
672 int LDAPCompare::run()
675 cred.bv_val = strdup(val.c_str());
676 cred.bv_len = val.length();
678 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
686 MODULE_INIT(ModuleLDAP)