]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldap.cpp
m_chanfilter: Apply filters to part messages (#1702)
[user/henk/code/inspircd.git] / src / modules / extra / m_ldap.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2013-2015 Adam <Adam@anope.org>
5  *   Copyright (C) 2003-2015 Anope Team <team@anope.org>
6  *
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.
10  *
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
14  * details.
15  *
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/>.
18  */
19
20 /// $LinkerFlags: -llber -lldap_r
21
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
26
27 #include "inspircd.h"
28 #include "modules/ldap.h"
29
30 // Ignore OpenLDAP deprecation warnings on OS X Yosemite and newer.
31 #if defined __APPLE__
32 # pragma GCC diagnostic push
33 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
34 #endif
35
36 #include <ldap.h>
37
38 #ifdef __APPLE__
39 # pragma GCC diagnostic pop
40 #endif
41
42 #ifdef _WIN32
43 # pragma comment(lib, "libldap_r.lib")
44 # pragma comment(lib, "liblber.lib")
45 #endif
46
47 class LDAPService;
48
49 class LDAPRequest
50 {
51  public:
52         LDAPService* service;
53         LDAPInterface* inter;
54         LDAPMessage* message; /* message returned by ldap_ */
55         LDAPResult* result; /* final result */
56         struct timeval tv;
57         QueryType type;
58
59         LDAPRequest(LDAPService* s, LDAPInterface* i)
60                 : service(s)
61                 , inter(i)
62                 , message(NULL)
63                 , result(NULL)
64         {
65                 type = QUERY_UNKNOWN;
66                 tv.tv_sec = 0;
67                 tv.tv_usec = 100000;
68         }
69
70         virtual ~LDAPRequest()
71         {
72                 delete result;
73                 if (message != NULL)
74                         ldap_msgfree(message);
75         }
76
77         virtual int run() = 0;
78 };
79
80 class LDAPBind : public LDAPRequest
81 {
82         std::string who, pass;
83
84  public:
85         LDAPBind(LDAPService* s, LDAPInterface* i, const std::string& w, const std::string& p)
86                 : LDAPRequest(s, i)
87                 , who(w)
88                 , pass(p)
89         {
90                 type = QUERY_BIND;
91         }
92
93         int run() CXX11_OVERRIDE;
94 };
95
96 class LDAPSearch : public LDAPRequest
97 {
98         std::string base;
99         int searchscope;
100         std::string filter;
101
102  public:
103         LDAPSearch(LDAPService* s, LDAPInterface* i, const std::string& b, int se, const std::string& f)
104                 : LDAPRequest(s, i)
105                 , base(b)
106                 , searchscope(se)
107                 , filter(f)
108         {
109                 type = QUERY_SEARCH;
110         }
111
112         int run() CXX11_OVERRIDE;
113 };
114
115 class LDAPAdd : public LDAPRequest
116 {
117         std::string dn;
118         LDAPMods attributes;
119
120  public:
121         LDAPAdd(LDAPService* s, LDAPInterface* i, const std::string& d, const LDAPMods& attr)
122                 : LDAPRequest(s, i)
123                 , dn(d)
124                 , attributes(attr)
125         {
126                 type = QUERY_ADD;
127         }
128
129         int run() CXX11_OVERRIDE;
130 };
131
132 class LDAPDel : public LDAPRequest
133 {
134         std::string dn;
135
136  public:
137         LDAPDel(LDAPService* s, LDAPInterface* i, const std::string& d)
138                 : LDAPRequest(s, i)
139                 , dn(d)
140         {
141                 type = QUERY_DELETE;
142         }
143
144         int run() CXX11_OVERRIDE;
145 };
146
147 class LDAPModify : public LDAPRequest
148 {
149         std::string base;
150         LDAPMods attributes;
151
152  public:
153         LDAPModify(LDAPService* s, LDAPInterface* i, const std::string& b, const LDAPMods& attr)
154                 : LDAPRequest(s, i)
155                 , base(b)
156                 , attributes(attr)
157         {
158                 type = QUERY_MODIFY;
159         }
160
161         int run() CXX11_OVERRIDE;
162 };
163
164 class LDAPCompare : public LDAPRequest
165 {
166         std::string dn, attr, val;
167
168  public:
169         LDAPCompare(LDAPService* s, LDAPInterface* i, const std::string& d, const std::string& a, const std::string& v)
170                 : LDAPRequest(s, i)
171                 , dn(d)
172                 , attr(a)
173                 , val(v)
174         {
175                 type = QUERY_COMPARE;
176         }
177
178         int run() CXX11_OVERRIDE;
179 };
180
181 class LDAPService : public LDAPProvider, public SocketThread
182 {
183         LDAP* con;
184         reference<ConfigTag> config;
185         time_t last_connect;
186         int searchscope;
187         time_t timeout;
188
189  public:
190         static LDAPMod** BuildMods(const LDAPMods& attributes)
191         {
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)
195                 {
196                         const LDAPModification& l = attributes[x];
197                         LDAPMod* mod = new LDAPMod;
198                         mods[x] = mod;
199
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;
206                         else if (l.op != 0)
207                         {
208                                 FreeMods(mods);
209                                 throw LDAPException("Unknown LDAP operation");
210                         }
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());
217                 }
218                 return mods;
219         }
220
221         static void FreeMods(LDAPMod** mods)
222         {
223                 for (unsigned int i = 0; mods[i] != NULL; ++i)
224                 {
225                         LDAPMod* mod = mods[i];
226                         if (mod->mod_type != NULL)
227                                 free(mod->mod_type);
228                         if (mod->mod_values != NULL)
229                         {
230                                 for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j)
231                                         free(mod->mod_values[j]);
232                                 delete[] mod->mod_values;
233                         }
234                 }
235                 delete[] mods;
236         }
237
238  private:
239         void Reconnect()
240         {
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();
245
246                 ldap_unbind_ext(this->con, NULL, NULL);
247                 Connect();
248         }
249
250         void QueueRequest(LDAPRequest* r)
251         {
252                 this->LockQueue();
253                 this->queries.push_back(r);
254                 this->UnlockQueueWakeup();
255         }
256
257  public:
258         typedef std::vector<LDAPRequest*> query_queue;
259         query_queue queries, results;
260         Mutex process_mutex; /* held when processing requests not in either queue */
261
262         LDAPService(Module* c, ConfigTag* tag)
263                 : LDAPProvider(c, "LDAP/" + tag->getString("id"))
264                 , con(NULL), config(tag), last_connect(0)
265         {
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;
271                 else
272                         searchscope = LDAP_SCOPE_SUBTREE;
273                 timeout = config->getDuration("timeout", 5);
274
275                 Connect();
276         }
277
278         ~LDAPService()
279         {
280                 this->LockQueue();
281
282                 for (unsigned int i = 0; i < this->queries.size(); ++i)
283                 {
284                         LDAPRequest* req = this->queries[i];
285
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);
291
292                         delete req;
293                 }
294                 this->queries.clear();
295
296                 for (unsigned int i = 0; i < this->results.size(); ++i)
297                 {
298                         LDAPRequest* req = this->results[i];
299
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);
303
304                         delete req;
305                 }
306                 this->results.clear();
307
308                 this->UnlockQueue();
309
310                 ldap_unbind_ext(this->con, NULL, NULL);
311         }
312
313         void Connect()
314         {
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));
319
320                 const int version = LDAP_VERSION3;
321                 i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
322                 if (i != LDAP_OPT_SUCCESS)
323                 {
324                         ldap_unbind_ext(this->con, NULL, NULL);
325                         this->con = NULL;
326                         throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
327                 }
328
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)
332                 {
333                         ldap_unbind_ext(this->con, NULL, NULL);
334                         this->con = NULL;
335                         throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
336                 }
337         }
338
339         void BindAsManager(LDAPInterface* i) CXX11_OVERRIDE
340         {
341                 std::string binddn = config->getString("binddn");
342                 std::string bindauth = config->getString("bindauth");
343                 this->Bind(i, binddn, bindauth);
344         }
345
346         void Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE
347         {
348                 LDAPBind* b = new LDAPBind(this, i, who, pass);
349                 QueueRequest(b);
350         }
351
352         void Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE
353         {
354                 if (i == NULL)
355                         throw LDAPException("No interface");
356
357                 LDAPSearch* s = new LDAPSearch(this, i, base, searchscope, filter);
358                 QueueRequest(s);
359         }
360
361         void Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE
362         {
363                 LDAPAdd* add = new LDAPAdd(this, i, dn, attributes);
364                 QueueRequest(add);
365         }
366
367         void Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE
368         {
369                 LDAPDel* del = new LDAPDel(this, i, dn);
370                 QueueRequest(del);
371         }
372
373         void Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE
374         {
375                 LDAPModify* mod = new LDAPModify(this, i, base, attributes);
376                 QueueRequest(mod);
377         }
378
379         void Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE
380         {
381                 LDAPCompare* comp = new LDAPCompare(this, i, dn, attr, val);
382                 QueueRequest(comp);
383         }
384
385  private:
386         void BuildReply(int res, LDAPRequest* req)
387         {
388                 LDAPResult* ldap_result = req->result = new LDAPResult();
389                 req->result->type = req->type;
390
391                 if (res != LDAP_SUCCESS)
392                 {
393                         ldap_result->error = ldap_err2string(res);
394                         return;
395                 }
396
397                 if (req->message == NULL)
398                 {
399                         return;
400                 }
401
402                 /* a search result */
403
404                 for (LDAPMessage* cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
405                 {
406                         LDAPAttributes attributes;
407
408                         char* dn = ldap_get_dn(this->con, cur);
409                         if (dn != NULL)
410                         {
411                                 attributes["dn"].push_back(dn);
412                                 ldap_memfree(dn);
413                                 dn = NULL;
414                         }
415
416                         BerElement* ber = NULL;
417
418                         for (char* attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
419                         {
420                                 berval** vals = ldap_get_values_len(this->con, cur, attr);
421                                 int count = ldap_count_values_len(vals);
422
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;
427
428                                 ldap_value_free_len(vals);
429                                 ldap_memfree(attr);
430                         }
431                         if (ber != NULL)
432                                 ber_free(ber, 0);
433
434                         ldap_result->messages.push_back(attributes);
435                 }
436         }
437
438         void SendRequests()
439         {
440                 process_mutex.Lock();
441
442                 query_queue q;
443                 this->LockQueue();
444                 queries.swap(q);
445                 this->UnlockQueue();
446
447                 if (q.empty())
448                 {
449                         process_mutex.Unlock();
450                         return;
451                 }
452
453                 for (unsigned int i = 0; i < q.size(); ++i)
454                 {
455                         LDAPRequest* req = q[i];
456                         int ret = req->run();
457
458                         if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
459                         {
460                                 /* try again */
461                                 try
462                                 {
463                                         Reconnect();
464                                 }
465                                 catch (const LDAPException &)
466                                 {
467                                 }
468
469                                 ret = req->run();
470                         }
471
472                         BuildReply(ret, req);
473
474                         this->LockQueue();
475                         this->results.push_back(req);
476                         this->UnlockQueue();
477                 }
478
479                 this->NotifyParent();
480
481                 process_mutex.Unlock();
482         }
483
484  public:
485         void Run() CXX11_OVERRIDE
486         {
487                 while (!this->GetExitFlag())
488                 {
489                         this->LockQueue();
490                         if (this->queries.empty())
491                                 this->WaitForQueue();
492                         this->UnlockQueue();
493
494                         SendRequests();
495                 }
496         }
497
498         void OnNotify() CXX11_OVERRIDE
499         {
500                 query_queue r;
501
502                 this->LockQueue();
503                 this->results.swap(r);
504                 this->UnlockQueue();
505
506                 for (unsigned int i = 0; i < r.size(); ++i)
507                 {
508                         LDAPRequest* req = r[i];
509                         LDAPInterface* li = req->inter;
510                         LDAPResult* res = req->result;
511
512                         if (!res->error.empty())
513                                 li->OnError(*res);
514                         else
515                                 li->OnResult(*res);
516
517                         delete req;
518                 }
519         }
520
521         LDAP* GetConnection()
522         {
523                 return con;
524         }
525 };
526
527 class ModuleLDAP : public Module
528 {
529         typedef insp::flat_map<std::string, LDAPService*> ServiceMap;
530         ServiceMap LDAPServices;
531
532  public:
533         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
534         {
535                 ServiceMap conns;
536
537                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
538                 for (ConfigIter i = tags.first; i != tags.second; i++)
539                 {
540                         const reference<ConfigTag>& tag = i->second;
541
542                         if (!stdalgo::string::equalsci(tag->getString("module"), "ldap"))
543                                 continue;
544
545                         std::string id = tag->getString("id");
546
547                         ServiceMap::iterator curr = LDAPServices.find(id);
548                         if (curr == LDAPServices.end())
549                         {
550                                 LDAPService* conn = new LDAPService(this, tag);
551                                 conns[id] = conn;
552
553                                 ServerInstance->Modules->AddService(*conn);
554                                 ServerInstance->Threads.Start(conn);
555                         }
556                         else
557                         {
558                                 conns.insert(*curr);
559                                 LDAPServices.erase(curr);
560                         }
561                 }
562
563                 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
564                 {
565                         LDAPService* conn = i->second;
566                         ServerInstance->Modules->DelService(*conn);
567                         conn->join();
568                         conn->OnNotify();
569                         delete conn;
570                 }
571
572                 LDAPServices.swap(conns);
573         }
574
575         void OnUnloadModule(Module* m) CXX11_OVERRIDE
576         {
577                 for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
578                 {
579                         LDAPService* s = it->second;
580
581                         s->process_mutex.Lock();
582                         s->LockQueue();
583
584                         for (unsigned int i = s->queries.size(); i > 0; --i)
585                         {
586                                 LDAPRequest* req = s->queries[i - 1];
587                                 LDAPInterface* li = req->inter;
588
589                                 if (li->creator == m)
590                                 {
591                                         s->queries.erase(s->queries.begin() + i - 1);
592                                         delete req;
593                                 }
594                         }
595
596                         for (unsigned int i = s->results.size(); i > 0; --i)
597                         {
598                                 LDAPRequest* req = s->results[i - 1];
599                                 LDAPInterface* li = req->inter;
600
601                                 if (li->creator == m)
602                                 {
603                                         s->results.erase(s->results.begin() + i - 1);
604                                         delete req;
605                                 }
606                         }
607
608                         s->UnlockQueue();
609                         s->process_mutex.Unlock();
610                 }
611         }
612
613         ~ModuleLDAP()
614         {
615                 for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i)
616                 {
617                         LDAPService* conn = i->second;
618                         conn->join();
619                         conn->OnNotify();
620                         delete conn;
621                 }
622         }
623
624         Version GetVersion() CXX11_OVERRIDE
625         {
626                 return Version("Provides LDAP support", VF_VENDOR);
627         }
628 };
629
630 int LDAPBind::run()
631 {
632         berval cred;
633         cred.bv_val = strdup(pass.c_str());
634         cred.bv_len = pass.length();
635
636         int i = ldap_sasl_bind_s(service->GetConnection(), who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
637
638         free(cred.bv_val);
639
640         return i;
641 }
642
643 int LDAPSearch::run()
644 {
645         return ldap_search_ext_s(service->GetConnection(), base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, &tv, 0, &message);
646 }
647
648 int LDAPAdd::run()
649 {
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);
653         return i;
654 }
655
656 int LDAPDel::run()
657 {
658         return ldap_delete_ext_s(service->GetConnection(), dn.c_str(), NULL, NULL);
659 }
660
661 int LDAPModify::run()
662 {
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);
666         return i;
667 }
668
669 int LDAPCompare::run()
670 {
671         berval cred;
672         cred.bv_val = strdup(val.c_str());
673         cred.bv_len = val.length();
674
675         int ret = ldap_compare_ext_s(service->GetConnection(), dn.c_str(), attr.c_str(), &cred, NULL, NULL);
676
677         free(cred.bv_val);
678
679         return ret;
680
681 }
682
683 MODULE_INIT(ModuleLDAP)