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
21 /// $PackageInfo: require_system("ubuntu") libldap2-dev
24 #include "modules/ldap.h"
26 // Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
28 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
34 # pragma comment(lib, "libldap_r.lib")
35 # pragma comment(lib, "liblber.lib")
45 LDAPMessage* message; /* message returned by ldap_ */
46 LDAPResult* result; /* final result */
50 LDAPRequest(LDAPService* s, LDAPInterface* i)
61 virtual ~LDAPRequest()
65 ldap_msgfree(message);
68 virtual int run() = 0;
71 class LDAPBind : public LDAPRequest
73 std::string who, pass;
76 LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
84 int run() CXX11_OVERRIDE;
87 class LDAPSearch : public LDAPRequest
94 LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
103 int run() CXX11_OVERRIDE;
106 class LDAPAdd : public LDAPRequest
112 LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
120 int run() CXX11_OVERRIDE;
123 class LDAPDel : public LDAPRequest
128 LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
135 int run() CXX11_OVERRIDE;
138 class LDAPModify : public LDAPRequest
144 LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
152 int run() CXX11_OVERRIDE;
155 class LDAPCompare : public LDAPRequest
157 std::string dn, attr, val;
160 LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
166 type = QUERY_COMPARE;
169 int run() CXX11_OVERRIDE;
172 class LDAPService : public LDAPProvider, public SocketThread
175 reference<ConfigTag> config;
181 static LDAPMod** BuildMods(const LDAPMods& attributes)
183 LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
184 memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
185 for (unsigned int x = 0; x < attributes.size(); ++x)
187 const LDAPModification& l = attributes[x];
188 LDAPMod* mod = new LDAPMod;
191 if (l.op == LDAPModification::LDAP_ADD)
192 mod->mod_op = LDAP_MOD_ADD;
193 else if (l.op == LDAPModification::LDAP_DEL)
194 mod->mod_op = LDAP_MOD_DELETE;
195 else if (l.op == LDAPModification::LDAP_REPLACE)
196 mod->mod_op = LDAP_MOD_REPLACE;
200 throw LDAPException("Unknown LDAP operation");
202 mod->mod_type = strdup(l.name.c_str());
203 mod->mod_values = new char*[l.values.size() + 1];
204 memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
205 for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
206 if (!l.values[j].empty())
207 mod->mod_values[c++] = strdup(l.values[j].c_str());
212 static void FreeMods(LDAPMod** mods)
214 for (unsigned int i = 0; mods[i] != NULL; ++i)
216 LDAPMod* mod = mods[i];
217 if (mod->mod_type != NULL)
219 if (mod->mod_values != NULL)
221 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
222 free(mod->mod_values[j]);
223 delete[] mod->mod_values;
232 // Only try one connect a minute. It is an expensive blocking operation
233 if (last_connect > ServerInstance->Time() - 60)
234 throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
235 last_connect = ServerInstance->Time();
237 ldap_unbind_ext(this->con, NULL, NULL);
241 void QueueRequest(LDAPRequest* r)
244 this->queries.push_back(r);
245 this->UnlockQueueWakeup();
249 typedef std::vector<LDAPRequest*> query_queue;
250 query_queue queries, results;
251 Mutex process_mutex; /* held when processing requests not in either queue */
253 LDAPService(Module* c, ConfigTag* tag)
254 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
255 , con(NULL), config(tag), last_connect(0)
257 std::string scope = config->getString("searchscope");
259 searchscope = LDAP_SCOPE_BASE;
260 else if (scope == "onelevel")
261 searchscope = LDAP_SCOPE_ONELEVEL;
263 searchscope = LDAP_SCOPE_SUBTREE;
264 timeout = config->getInt("timeout", 5);
273 for (unsigned int i = 0; i < this->queries.size(); ++i)
275 LDAPRequest* req = this->queries[i];
277 /* queries have no results yet */
278 req->result = new LDAPResult();
279 req->result->type = req->type;
280 req->result->error = "LDAP Interface is going away";
281 req->inter->OnError(*req->result);
285 this->queries.clear();
287 for (unsigned int i = 0; i < this->results.size(); ++i)
289 LDAPRequest* req = this->results[i];
291 /* even though this may have already finished successfully we return that it didn't */
292 req->result->error = "LDAP Interface is going away";
293 req->inter->OnError(*req->result);
297 this->results.clear();
301 ldap_unbind_ext(this->con, NULL, NULL);
306 std::string server = config->getString("server");
307 int i = ldap_initialize(&this->con, server.c_str());
308 if (i != LDAP_SUCCESS)
309 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
311 const int version = LDAP_VERSION3;
312 i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
313 if (i != LDAP_OPT_SUCCESS)
315 ldap_unbind_ext(this->con, NULL, NULL);
317 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
320 const struct timeval tv = { 0, 0 };
321 i = ldap_set_option(this->con, LDAP_OPT_NETWORK_TIMEOUT, &tv);
322 if (i != LDAP_OPT_SUCCESS)
324 ldap_unbind_ext(this->con, NULL, NULL);
326 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
330 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
332 std::string binddn = config->getString("binddn");
333 std::string bindauth = config->getString("bindauth");
334 this->Bind(i, binddn, bindauth);
337 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
339 LDAPBind* b = new LDAPBind(this, i, who, pass);
343 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
346 throw LDAPException("No interface");
348 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
352 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
354 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
358 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
360 LDAPDel* del = new LDAPDel(this, i, dn);
364 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
366 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
370 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
372 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
377 void BuildReply(int res, LDAPRequest* req)
379 LDAPResult* ldap_result = req->result = new LDAPResult();
380 req->result->type = req->type;
382 if (res != LDAP_SUCCESS)
384 ldap_result->error = ldap_err2string(res);
388 if (req->message == NULL)
393 /* a search result */
395 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
397 LDAPAttributes attributes;
399 char* dn = ldap_get_dn(this->con, cur);
402 attributes["dn"].push_back(dn);
407 BerElement* ber = NULL;
409 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
411 berval** vals = ldap_get_values_len(this->con, cur, attr);
412 int count = ldap_count_values_len(vals);
414 std::vector<std::string> attrs;
415 for (int j = 0; j < count; ++j)
416 attrs.push_back(vals[j]->bv_val);
417 attributes[attr] = attrs;
419 ldap_value_free_len(vals);
425 ldap_result->messages.push_back(attributes);
431 process_mutex.Lock();
440 process_mutex.Unlock();
444 for (unsigned int i = 0; i < q.size(); ++i)
446 LDAPRequest* req = q[i];
447 int ret = req->run();
449 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
456 catch (const LDAPException &)
463 BuildReply(ret, req);
466 this->results.push_back(req);
470 this->NotifyParent();
472 process_mutex.Unlock();
476 void Run() CXX11_OVERRIDE
478 while (!this->GetExitFlag())
481 if (this->queries.empty())
482 this->WaitForQueue();
489 void OnNotify() CXX11_OVERRIDE
494 this->results.swap(r);
497 for (unsigned int i = 0; i < r.size(); ++i)
499 LDAPRequest* req = r[i];
500 LDAPInterface* li = req->inter;
501 LDAPResult* res = req->result;
503 if (!res->error.empty())
512 LDAP* GetConnection()
518 class ModuleLDAP : public Module
520 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
521 ServiceMap LDAPServices;
524 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
528 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
529 for (ConfigIter i = tags.first; i != tags.second; i++)
531 const reference<ConfigTag>& tag = i->second;
533 if (tag->getString("module") != "ldap")
536 std::string id = tag->getString("id");
538 ServiceMap::iterator curr = LDAPServices.find(id);
539 if (curr == LDAPServices.end())
541 LDAPService* conn = new LDAPService(this, tag);
544 ServerInstance->Modules->AddService(*conn);
545 ServerInstance->Threads.Start(conn);
550 LDAPServices.erase(curr);
554 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
556 LDAPService* conn = i->second;
557 ServerInstance->Modules->DelService(*conn);
563 LDAPServices.swap(conns);
566 void OnUnloadModule(Module* m) CXX11_OVERRIDE
568 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
570 LDAPService* s = it->second;
572 s->process_mutex.Lock();
575 for (unsigned int i = s->queries.size(); i > 0; --i)
577 LDAPRequest* req = s->queries[i - 1];
578 LDAPInterface* li = req->inter;
580 if (li->creator == m)
582 s->queries.erase(s->queries.begin() + i - 1);
587 for (unsigned int i = s->results.size(); i > 0; --i)
589 LDAPRequest* req = s->results[i - 1];
590 LDAPInterface* li = req->inter;
592 if (li->creator == m)
594 s->results.erase(s->results.begin() + i - 1);
600 s->process_mutex.Unlock();
606 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
608 LDAPService* conn = i->second;
615 Version GetVersion() CXX11_OVERRIDE
617 return Version("LDAP support", VF_VENDOR);
624 cred.bv_val = strdup(pass.c_str());
625 cred.bv_len = pass.length();
627 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
634 int LDAPSearch::run()
636 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
641 LDAPMod** mods = LDAPService::BuildMods(attributes);
642 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
643 LDAPService::FreeMods(mods);
649 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
652 int LDAPModify::run()
654 LDAPMod** mods = LDAPService::BuildMods(attributes);
655 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
656 LDAPService::FreeMods(mods);
660 int LDAPCompare::run()
663 cred.bv_val = strdup(val.c_str());
664 cred.bv_len = val.length();
666 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
674 MODULE_INIT(ModuleLDAP)