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 void QueueRequest(LDAPRequest* r)
253 this->queries.push_back(r);
254 this->UnlockQueueWakeup();
258 typedef std::vector<LDAPRequest*> query_queue;
259 query_queue queries, results;
260 Mutex process_mutex; /* held when processing requests not in either queue */
262 LDAPService(Module* c, ConfigTag* tag)
263 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
264 , con(NULL), config(tag), last_connect(0)
266 std::string scope = config->getString("searchscope");
267 if (stdalgo::string::equalsci(scope, "base"))
268 searchscope = LDAP_SCOPE_BASE;
269 else if (stdalgo::string::equalsci(scope, "onelevel"))
270 searchscope = LDAP_SCOPE_ONELEVEL;
272 searchscope = LDAP_SCOPE_SUBTREE;
273 timeout = config->getDuration("timeout", 5);
282 for (unsigned int i = 0; i < this->queries.size(); ++i)
284 LDAPRequest* req = this->queries[i];
286 /* queries have no results yet */
287 req->result = new LDAPResult();
288 req->result->type = req->type;
289 req->result->error = "LDAP Interface is going away";
290 req->inter->OnError(*req->result);
294 this->queries.clear();
296 for (unsigned int i = 0; i < this->results.size(); ++i)
298 LDAPRequest* req = this->results[i];
300 /* even though this may have already finished successfully we return that it didn't */
301 req->result->error = "LDAP Interface is going away";
302 req->inter->OnError(*req->result);
306 this->results.clear();
310 ldap_unbind_ext(this->con, NULL, NULL);
315 std::string server = config->getString("server");
316 int i = ldap_initialize(&this->con, server.c_str());
317 if (i != LDAP_SUCCESS)
318 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
320 const int version = LDAP_VERSION3;
321 i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
322 if (i != LDAP_OPT_SUCCESS)
324 ldap_unbind_ext(this->con, NULL, NULL);
326 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
329 const struct timeval tv = { 0, 0 };
330 i = ldap_set_option(this->con, LDAP_OPT_NETWORK_TIMEOUT, &tv);
331 if (i != LDAP_OPT_SUCCESS)
333 ldap_unbind_ext(this->con, NULL, NULL);
335 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
339 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
341 std::string binddn = config->getString("binddn");
342 std::string bindauth = config->getString("bindauth");
343 this->Bind(i, binddn, bindauth);
346 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
348 LDAPBind* b = new LDAPBind(this, i, who, pass);
352 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
355 throw LDAPException("No interface");
357 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
361 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
363 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
367 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
369 LDAPDel* del = new LDAPDel(this, i, dn);
373 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
375 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
379 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
381 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
386 void BuildReply(int res, LDAPRequest* req)
388 LDAPResult* ldap_result = req->result = new LDAPResult();
389 req->result->type = req->type;
391 if (res != LDAP_SUCCESS)
393 ldap_result->error = ldap_err2string(res);
397 if (req->message == NULL)
402 /* a search result */
404 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
406 LDAPAttributes attributes;
408 char* dn = ldap_get_dn(this->con, cur);
411 attributes["dn"].push_back(dn);
416 BerElement* ber = NULL;
418 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
420 berval** vals = ldap_get_values_len(this->con, cur, attr);
421 int count = ldap_count_values_len(vals);
423 std::vector<std::string> attrs;
424 for (int j = 0; j < count; ++j)
425 attrs.push_back(vals[j]->bv_val);
426 attributes[attr] = attrs;
428 ldap_value_free_len(vals);
434 ldap_result->messages.push_back(attributes);
440 process_mutex.Lock();
449 process_mutex.Unlock();
453 for (unsigned int i = 0; i < q.size(); ++i)
455 LDAPRequest* req = q[i];
456 int ret = req->run();
458 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
465 catch (const LDAPException &)
472 BuildReply(ret, req);
475 this->results.push_back(req);
479 this->NotifyParent();
481 process_mutex.Unlock();
485 void Run() CXX11_OVERRIDE
487 while (!this->GetExitFlag())
490 if (this->queries.empty())
491 this->WaitForQueue();
498 void OnNotify() CXX11_OVERRIDE
503 this->results.swap(r);
506 for (unsigned int i = 0; i < r.size(); ++i)
508 LDAPRequest* req = r[i];
509 LDAPInterface* li = req->inter;
510 LDAPResult* res = req->result;
512 if (!res->error.empty())
521 LDAP* GetConnection()
527 class ModuleLDAP : public Module
529 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
530 ServiceMap LDAPServices;
533 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
537 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
538 for (ConfigIter i = tags.first; i != tags.second; i++)
540 const reference<ConfigTag>& tag = i->second;
542 if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
545 std::string id = tag->getString("id");
547 ServiceMap::iterator curr = LDAPServices.find(id);
548 if (curr == LDAPServices.end())
550 LDAPService* conn = new LDAPService(this, tag);
553 ServerInstance->Modules->AddService(*conn);
554 ServerInstance->Threads.Start(conn);
559 LDAPServices.erase(curr);
563 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
565 LDAPService* conn = i->second;
566 ServerInstance->Modules->DelService(*conn);
572 LDAPServices.swap(conns);
575 void OnUnloadModule(Module* m) CXX11_OVERRIDE
577 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
579 LDAPService* s = it->second;
581 s->process_mutex.Lock();
584 for (unsigned int i = s->queries.size(); i > 0; --i)
586 LDAPRequest* req = s->queries[i - 1];
587 LDAPInterface* li = req->inter;
589 if (li->creator == m)
591 s->queries.erase(s->queries.begin() + i - 1);
596 for (unsigned int i = s->results.size(); i > 0; --i)
598 LDAPRequest* req = s->results[i - 1];
599 LDAPInterface* li = req->inter;
601 if (li->creator == m)
603 s->results.erase(s->results.begin() + i - 1);
609 s->process_mutex.Unlock();
615 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
617 LDAPService* conn = i->second;
624 Version GetVersion() CXX11_OVERRIDE
626 return Version("Provides LDAP support", VF_VENDOR);
633 cred.bv_val = strdup(pass.c_str());
634 cred.bv_len = pass.length();
636 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
643 int LDAPSearch::run()
645 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
650 LDAPMod** mods = LDAPService::BuildMods(attributes);
651 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
652 LDAPService::FreeMods(mods);
658 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
661 int LDAPModify::run()
663 LDAPMod** mods = LDAPService::BuildMods(attributes);
664 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
665 LDAPService::FreeMods(mods);
669 int LDAPCompare::run()
672 cred.bv_val = strdup(val.c_str());
673 cred.bv_len = val.length();
675 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
683 MODULE_INIT(ModuleLDAP)