2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2019 Robby <robby@chatbelgie.be>
6 * Copyright (C) 2016-2019 Sadie Powell <sadie@witchery.services>
7 * Copyright (C) 2014, 2016 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2013-2016 Adam <Adam@anope.org>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 /// $LinkerFlags: -llber -lldap_r
25 /// $PackageInfo: require_system("arch") libldap
26 /// $PackageInfo: require_system("centos") openldap-devel
27 /// $PackageInfo: require_system("debian") libldap2-dev
28 /// $PackageInfo: require_system("ubuntu") libldap2-dev
31 #include "modules/ldap.h"
33 // Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
35 # pragma GCC diagnostic push
36 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
42 # pragma GCC diagnostic pop
46 # pragma comment(lib, "libldap_r.lib")
47 # pragma comment(lib, "liblber.lib")
57 LDAPMessage* message; /* message returned by ldap_ */
58 LDAPResult* result; /* final result */
62 LDAPRequest(LDAPService* s, LDAPInterface* i)
73 virtual ~LDAPRequest()
77 ldap_msgfree(message);
80 virtual int run() = 0;
83 class LDAPBind : public LDAPRequest
85 std::string who, pass;
88 LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
96 int run() CXX11_OVERRIDE;
99 class LDAPSearch : public LDAPRequest
106 LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
115 int run() CXX11_OVERRIDE;
118 class LDAPAdd : public LDAPRequest
124 LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
132 int run() CXX11_OVERRIDE;
135 class LDAPDel : public LDAPRequest
140 LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
147 int run() CXX11_OVERRIDE;
150 class LDAPModify : public LDAPRequest
156 LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
164 int run() CXX11_OVERRIDE;
167 class LDAPCompare : public LDAPRequest
169 std::string dn, attr, val;
172 LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
178 type = QUERY_COMPARE;
181 int run() CXX11_OVERRIDE;
184 class LDAPService : public LDAPProvider, public SocketThread
187 reference<ConfigTag> config;
193 static LDAPMod** BuildMods(const LDAPMods& attributes)
195 LDAPMod** mods = new LDAPMod*[attributes.size() + 1];
196 memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
197 for (unsigned int x = 0; x < attributes.size(); ++x)
199 const LDAPModification& l = attributes[x];
200 LDAPMod* mod = new LDAPMod;
203 if (l.op == LDAPModification::LDAP_ADD)
204 mod->mod_op = LDAP_MOD_ADD;
205 else if (l.op == LDAPModification::LDAP_DEL)
206 mod->mod_op = LDAP_MOD_DELETE;
207 else if (l.op == LDAPModification::LDAP_REPLACE)
208 mod->mod_op = LDAP_MOD_REPLACE;
212 throw LDAPException("Unknown LDAP operation");
214 mod->mod_type = strdup(l.name.c_str());
215 mod->mod_values = new char*[l.values.size() + 1];
216 memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1));
217 for (unsigned int j = 0, c = 0; j < l.values.size(); ++j)
218 if (!l.values[j].empty())
219 mod->mod_values[c++] = strdup(l.values[j].c_str());
224 static void FreeMods(LDAPMod** mods)
226 for (unsigned int i = 0; mods[i] != NULL; ++i)
228 LDAPMod* mod = mods[i];
229 if (mod->mod_type != NULL)
231 if (mod->mod_values != NULL)
233 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
234 free(mod->mod_values[j]);
235 delete[] mod->mod_values;
244 // Only try one connect a minute. It is an expensive blocking operation
245 if (last_connect > ServerInstance->Time() - 60)
246 throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
247 last_connect = ServerInstance->Time();
249 ldap_unbind_ext(this->con, NULL, NULL);
253 int SetOption(int option, const void* value)
255 int ret = ldap_set_option(this->con, option, value);
256 if (ret != LDAP_OPT_SUCCESS)
258 ldap_unbind_ext(this->con, NULL, NULL);
264 void QueueRequest(LDAPRequest* r)
267 this->queries.push_back(r);
268 this->UnlockQueueWakeup();
272 typedef std::vector<LDAPRequest*> query_queue;
273 query_queue queries, results;
274 Mutex process_mutex; /* held when processing requests not in either queue */
276 LDAPService(Module* c, ConfigTag* tag)
277 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
278 , con(NULL), config(tag), last_connect(0)
280 std::string scope = config->getString("searchscope");
281 if (stdalgo::string::equalsci(scope, "base"))
282 searchscope = LDAP_SCOPE_BASE;
283 else if (stdalgo::string::equalsci(scope, "onelevel"))
284 searchscope = LDAP_SCOPE_ONELEVEL;
286 searchscope = LDAP_SCOPE_SUBTREE;
287 timeout = config->getDuration("timeout", 5);
296 for (unsigned int i = 0; i < this->queries.size(); ++i)
298 LDAPRequest* req = this->queries[i];
300 /* queries have no results yet */
301 req->result = new LDAPResult();
302 req->result->type = req->type;
303 req->result->error = "LDAP Interface is going away";
304 req->inter->OnError(*req->result);
308 this->queries.clear();
310 for (unsigned int i = 0; i < this->results.size(); ++i)
312 LDAPRequest* req = this->results[i];
314 /* even though this may have already finished successfully we return that it didn't */
315 req->result->error = "LDAP Interface is going away";
316 req->inter->OnError(*req->result);
320 this->results.clear();
324 ldap_unbind_ext(this->con, NULL, NULL);
329 std::string server = config->getString("server");
330 int i = ldap_initialize(&this->con, server.c_str());
331 if (i != LDAP_SUCCESS)
332 throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
334 const int version = LDAP_VERSION3;
335 i = SetOption(LDAP_OPT_PROTOCOL_VERSION, &version);
336 if (i != LDAP_OPT_SUCCESS)
337 throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
339 const struct timeval tv = { 0, 0 };
340 i = SetOption(LDAP_OPT_NETWORK_TIMEOUT, &tv);
341 if (i != LDAP_OPT_SUCCESS)
342 throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
345 void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
347 std::string binddn = config->getString("binddn");
348 std::string bindauth = config->getString("bindauth");
349 this->Bind(i, binddn, bindauth);
352 void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
354 LDAPBind* b = new LDAPBind(this, i, who, pass);
358 void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
361 throw LDAPException("No interface");
363 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
367 void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
369 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
373 void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
375 LDAPDel* del = new LDAPDel(this, i, dn);
379 void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
381 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
385 void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
387 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
392 void BuildReply(int res, LDAPRequest* req)
394 LDAPResult* ldap_result = req->result = new LDAPResult();
395 req->result->type = req->type;
397 if (res != LDAP_SUCCESS)
399 ldap_result->error = ldap_err2string(res);
403 if (req->message == NULL)
408 /* a search result */
410 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
412 LDAPAttributes attributes;
414 char* dn = ldap_get_dn(this->con, cur);
417 attributes["dn"].push_back(dn);
422 BerElement* ber = NULL;
424 for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
426 berval** vals = ldap_get_values_len(this->con, cur, attr);
427 int count = ldap_count_values_len(vals);
429 std::vector<std::string> attrs;
430 for (int j = 0; j < count; ++j)
431 attrs.push_back(vals[j]->bv_val);
432 attributes[attr] = attrs;
434 ldap_value_free_len(vals);
440 ldap_result->messages.push_back(attributes);
446 process_mutex.Lock();
455 process_mutex.Unlock();
459 for (unsigned int i = 0; i < q.size(); ++i)
461 LDAPRequest* req = q[i];
462 int ret = req->run();
464 if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
471 catch (const LDAPException &)
478 BuildReply(ret, req);
481 this->results.push_back(req);
485 this->NotifyParent();
487 process_mutex.Unlock();
491 void Run() CXX11_OVERRIDE
493 while (!this->GetExitFlag())
496 if (this->queries.empty())
497 this->WaitForQueue();
504 void OnNotify() CXX11_OVERRIDE
509 this->results.swap(r);
512 for (unsigned int i = 0; i < r.size(); ++i)
514 LDAPRequest* req = r[i];
515 LDAPInterface* li = req->inter;
516 LDAPResult* res = req->result;
518 if (!res->error.empty())
527 LDAP* GetConnection()
533 class ModuleLDAP : public Module
535 typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
536 ServiceMap LDAPServices;
539 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
543 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
544 for (ConfigIter i = tags.first; i != tags.second; i++)
546 const reference<ConfigTag>& tag = i->second;
548 if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
551 std::string id = tag->getString("id");
553 ServiceMap::iterator curr = LDAPServices.find(id);
554 if (curr == LDAPServices.end())
556 LDAPService* conn = new LDAPService(this, tag);
559 ServerInstance->Modules->AddService(*conn);
560 ServerInstance->Threads.Start(conn);
565 LDAPServices.erase(curr);
569 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
571 LDAPService* conn = i->second;
572 ServerInstance->Modules->DelService(*conn);
578 LDAPServices.swap(conns);
581 void OnUnloadModule(Module* m) CXX11_OVERRIDE
583 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
585 LDAPService* s = it->second;
587 s->process_mutex.Lock();
590 for (unsigned int i = s->queries.size(); i > 0; --i)
592 LDAPRequest* req = s->queries[i - 1];
593 LDAPInterface* li = req->inter;
595 if (li->creator == m)
597 s->queries.erase(s->queries.begin() + i - 1);
602 for (unsigned int i = s->results.size(); i > 0; --i)
604 LDAPRequest* req = s->results[i - 1];
605 LDAPInterface* li = req->inter;
607 if (li->creator == m)
609 s->results.erase(s->results.begin() + i - 1);
615 s->process_mutex.Unlock();
621 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
623 LDAPService* conn = i->second;
630 Version GetVersion() CXX11_OVERRIDE
632 return Version("Provides LDAP support", VF_VENDOR);
639 cred.bv_val = strdup(pass.c_str());
640 cred.bv_len = pass.length();
642 int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
649 int LDAPSearch::run()
651 return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
656 LDAPMod** mods = LDAPService::BuildMods(attributes);
657 int i = ldap_add_ext_s(service->GetConnection(), dn.c_str(), mods, NULL, NULL);
658 LDAPService::FreeMods(mods);
664 return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
667 int LDAPModify::run()
669 LDAPMod** mods = LDAPService::BuildMods(attributes);
670 int i = ldap_modify_ext_s(service->GetConnection(), base.c_str(), mods, NULL, NULL);
671 LDAPService::FreeMods(mods);
675 int LDAPCompare::run()
678 cred.bv_val = strdup(val.c_str());
679 cred.bv_len = val.length();
681 int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
689 MODULE_INIT(ModuleLDAP)