1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
|
/*
*
* (C) 2011-2024 Anope Team
* Contact us at team@anope.org
*
* Please read COPYING and README for further details.
*
* Based on the original code of Epona by Lara.
* Based on the original code of Services by Andy Church.
*/
/* RequiredLibraries: ldap_r|ldap,lber */
#include "module.h"
#include "modules/ldap.h"
#ifdef _WIN32
# include <Winldap.h>
# include <WinBer.h>
# include <wininet.h>
# define LDAP_OPT_SUCCESS LDAP_SUCCESS
# define LDAP_OPT_NETWORK_TIMEOUT LDAP_OPT_SEND_TIMEOUT
# define LDAP_STR(X) const_cast<PSTR>((X).c_str())
# define LDAP_SASL_SIMPLE static_cast<PSTR>(0)
# define LDAP_TIME(X) reinterpret_cast<PLDAP_TIMEVAL>(&(X))
# define ldap_first_message ldap_first_entry
# define ldap_next_message ldap_next_entry
# define ldap_unbind_ext(LDAP, UNUSED1, UNUSED2) ldap_unbind(LDAP)
# pragma comment(lib, "Wldap32.lib")
# pragma comment(lib, "Wininet.lib")
#else
# include <ldap.h>
# define LDAP_STR(X) ((X).c_str())
# define LDAP_TIME(X) (&(X))
#endif
#if defined LDAP_API_FEATURE_X_OPENLDAP_REENTRANT && !LDAP_API_FEATURE_X_OPENLDAP_REENTRANT
# error Anope requires OpenLDAP to be built as reentrant.
#endif
class LDAPService;
static Pipe *me;
class LDAPRequest
{
public:
LDAPService *service;
LDAPInterface *inter;
LDAPMessage *message; /* message returned by ldap_ */
LDAPResult *result; /* final result */
struct timeval tv;
QueryType type;
LDAPRequest(LDAPService *s, LDAPInterface *i)
: service(s)
, inter(i)
, message(NULL)
, result(NULL)
{
type = QUERY_UNKNOWN;
tv.tv_sec = 0;
tv.tv_usec = 100000;
}
virtual ~LDAPRequest()
{
delete result;
if (inter != NULL)
inter->OnDelete();
if (message != NULL)
ldap_msgfree(message);
}
virtual int run() = 0;
};
class LDAPBind : public LDAPRequest
{
Anope::string who, pass;
public:
LDAPBind(LDAPService *s, LDAPInterface *i, const Anope::string &w, const Anope::string &p)
: LDAPRequest(s, i)
, who(w)
, pass(p)
{
type = QUERY_BIND;
}
int run() anope_override;
};
class LDAPSearchRequest : public LDAPRequest
{
Anope::string base;
Anope::string filter;
public:
LDAPSearchRequest(LDAPService *s, LDAPInterface *i, const Anope::string &b, const Anope::string &f)
: LDAPRequest(s, i)
, base(b)
, filter(f)
{
type = QUERY_SEARCH;
}
int run() anope_override;
};
class LDAPAdd : public LDAPRequest
{
Anope::string dn;
LDAPMods attributes;
public:
LDAPAdd(LDAPService *s, LDAPInterface *i, const Anope::string &d, const LDAPMods &attr)
: LDAPRequest(s, i)
, dn(d)
, attributes(attr)
{
type = QUERY_ADD;
}
int run() anope_override;
};
class LDAPDel : public LDAPRequest
{
Anope::string dn;
public:
LDAPDel(LDAPService *s, LDAPInterface *i, const Anope::string &d)
: LDAPRequest(s, i)
, dn(d)
{
type = QUERY_DELETE;
}
int run() anope_override;
};
class LDAPModify : public LDAPRequest
{
Anope::string base;
LDAPMods attributes;
public:
LDAPModify(LDAPService *s, LDAPInterface *i, const Anope::string &b, const LDAPMods &attr)
: LDAPRequest(s, i)
, base(b)
, attributes(attr)
{
type = QUERY_MODIFY;
}
int run() anope_override;
};
class LDAPService : public LDAPProvider, public Thread, public Condition
{
Anope::string server;
Anope::string admin_binddn;
Anope::string admin_pass;
LDAP *con;
time_t last_connect;
public:
static LDAPMod **BuildMods(const LDAPMods &attributes)
{
LDAPMod **mods = new LDAPMod*[attributes.size() + 1];
memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1));
for (unsigned x = 0; x < attributes.size(); ++x)
{
const LDAPModification &l = attributes[x];
mods[x] = new LDAPMod();
if (l.op == LDAPModification::LDAP_ADD)
mods[x]->mod_op = LDAP_MOD_ADD;
else if (l.op == LDAPModification::LDAP_DEL)
mods[x]->mod_op = LDAP_MOD_DELETE;
else if (l.op == LDAPModification::LDAP_REPLACE)
mods[x]->mod_op = LDAP_MOD_REPLACE;
else if (l.op != 0)
throw LDAPException("Unknown LDAP operation");
mods[x]->mod_type = strdup(l.name.c_str());
mods[x]->mod_values = new char*[l.values.size() + 1];
memset(mods[x]->mod_values, 0, sizeof(char *) * (l.values.size() + 1));
for (unsigned j = 0, c = 0; j < l.values.size(); ++j)
if (!l.values[j].empty())
mods[x]->mod_values[c++] = strdup(l.values[j].c_str());
}
return mods;
}
static void FreeMods(LDAPMod **mods)
{
for (int i = 0; mods[i] != NULL; ++i)
{
free(mods[i]->mod_type);
for (int j = 0; mods[i]->mod_values[j] != NULL; ++j)
free(mods[i]->mod_values[j]);
delete [] mods[i]->mod_values;
}
delete [] mods;
}
private:
#ifdef _WIN32
// Windows LDAP does not implement this so we need to do it.
int ldap_initialize(LDAP** ldap, const char* url)
{
URL_COMPONENTS urlComponents;
memset(&urlComponents, 0, sizeof(urlComponents));
urlComponents.dwStructSize = sizeof(urlComponents);
urlComponents.lpszScheme = new char[8];
urlComponents.dwSchemeLength = 8;
urlComponents.lpszHostName = new char[1024];
urlComponents.dwHostNameLength = 1024;
if (!InternetCrackUrlA(url, 0, 0, &urlComponents))
{
delete[] urlComponents.lpszScheme;
delete[] urlComponents.lpszHostName;
return LDAP_CONNECT_ERROR; // Malformed url.
}
unsigned long port = 389; // Default plaintext port.
bool secure = false; // LDAP defaults to plaintext.
if (urlComponents.dwSchemeLength > 0)
{
const Anope::string scheme(urlComponents.lpszScheme);
if (scheme.equals_ci("ldaps"))
{
port = 636; // Default encrypted port.
secure = true;
}
else if (!scheme.equals_ci("ldap"))
{
delete[] urlComponents.lpszScheme;
delete[] urlComponents.lpszHostName;
return LDAP_CONNECT_ERROR; // Invalid protocol.
}
}
if (urlComponents.nPort > 0)
{
port = urlComponents.nPort;
}
*ldap = ldap_sslinit(urlComponents.lpszHostName, port, secure);
delete[] urlComponents.lpszScheme;
delete[] urlComponents.lpszHostName;
if (!*ldap)
{
return LdapGetLastError(); // Something went wrong, find out what.
}
// We're connected to the LDAP server!
return LDAP_SUCCESS;
}
#endif
void Connect()
{
int i = ldap_initialize(&this->con, this->server.c_str());
if (i != LDAP_SUCCESS)
throw LDAPException("Unable to connect to LDAP service " + this->name + ": " + ldap_err2string(i));
const int version = LDAP_VERSION3;
i = ldap_set_option(this->con, LDAP_OPT_PROTOCOL_VERSION, &version);
if (i != LDAP_OPT_SUCCESS)
throw LDAPException("Unable to set protocol version for " + this->name + ": " + ldap_err2string(i));
const struct timeval tv = { 0, 0 };
i = ldap_set_option(this->con, LDAP_OPT_NETWORK_TIMEOUT, &tv);
if (i != LDAP_OPT_SUCCESS)
throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i));
}
void Reconnect()
{
/* Only try one connect a minute. It is an expensive blocking operation */
if (last_connect > Anope::CurTime - 60)
throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast");
last_connect = Anope::CurTime;
ldap_unbind_ext(this->con, NULL, NULL);
Connect();
}
void QueueRequest(LDAPRequest *r)
{
this->Lock();
this->queries.push_back(r);
this->Wakeup();
this->Unlock();
}
public:
typedef std::vector<LDAPRequest *> query_queue;
query_queue queries, results;
Mutex process_mutex; /* held when processing requests not in either queue */
LDAPService(Module *o, const Anope::string &n, const Anope::string &s, const Anope::string &b, const Anope::string &p) : LDAPProvider(o, n), server(s), admin_binddn(b), admin_pass(p), last_connect(0)
{
Connect();
}
~LDAPService()
{
/* At this point the thread has stopped so we don't need to hold process_mutex */
this->Lock();
for (unsigned int i = 0; i < this->queries.size(); ++i)
{
LDAPRequest *req = this->queries[i];
/* queries have no results yet */
req->result = new LDAPResult();
req->result->type = req->type;
req->result->error = "LDAP Interface is going away";
if (req->inter)
req->inter->OnError(*req->result);
delete req;
}
this->queries.clear();
for (unsigned int i = 0; i < this->results.size(); ++i)
{
LDAPRequest *req = this->results[i];
/* even though this may have already finished successfully we return that it didn't */
req->result->error = "LDAP Interface is going away";
if (req->inter)
req->inter->OnError(*req->result);
delete req;
}
this->Unlock();
ldap_unbind_ext(this->con, NULL, NULL);
}
void BindAsAdmin(LDAPInterface *i) anope_override
{
this->Bind(i, this->admin_binddn, this->admin_pass);
}
void Bind(LDAPInterface *i, const Anope::string &who, const Anope::string &pass) anope_override
{
LDAPBind *b = new LDAPBind(this, i, who, pass);
QueueRequest(b);
}
void Search(LDAPInterface *i, const Anope::string &base, const Anope::string &filter) anope_override
{
if (i == NULL)
throw LDAPException("No interface");
LDAPSearchRequest *s = new LDAPSearchRequest(this, i, base, filter);
QueueRequest(s);
}
void Add(LDAPInterface *i, const Anope::string &dn, LDAPMods &attributes) anope_override
{
LDAPAdd *add = new LDAPAdd(this, i, dn, attributes);
QueueRequest(add);
}
void Del(LDAPInterface *i, const Anope::string &dn) anope_override
{
LDAPDel *del = new LDAPDel(this, i, dn);
QueueRequest(del);
}
void Modify(LDAPInterface *i, const Anope::string &base, LDAPMods &attributes) anope_override
{
LDAPModify *mod = new LDAPModify(this, i, base, attributes);
QueueRequest(mod);
}
private:
void BuildReply(int res, LDAPRequest *req)
{
LDAPResult *ldap_result = req->result = new LDAPResult();
req->result->type = req->type;
if (res != LDAP_SUCCESS)
{
ldap_result->error = ldap_err2string(res);
return;
}
if (req->message == NULL)
{
return;
}
/* a search result */
for (LDAPMessage *cur = ldap_first_message(this->con, req->message); cur; cur = ldap_next_message(this->con, cur))
{
LDAPAttributes attributes;
char *dn = ldap_get_dn(this->con, cur);
if (dn != NULL)
{
attributes["dn"].push_back(dn);
ldap_memfree(dn);
dn = NULL;
}
BerElement *ber = NULL;
for (char *attr = ldap_first_attribute(this->con, cur, &ber); attr; attr = ldap_next_attribute(this->con, cur, ber))
{
berval **vals = ldap_get_values_len(this->con, cur, attr);
int count = ldap_count_values_len(vals);
std::vector<Anope::string> attrs;
for (int j = 0; j < count; ++j)
attrs.push_back(vals[j]->bv_val);
attributes[attr] = attrs;
ldap_value_free_len(vals);
ldap_memfree(attr);
}
if (ber != NULL)
ber_free(ber, 0);
ldap_result->messages.push_back(attributes);
}
}
void SendRequests()
{
process_mutex.Lock();
query_queue q;
this->Lock();
queries.swap(q);
this->Unlock();
if (q.empty())
{
process_mutex.Unlock();
return;
}
for (unsigned int i = 0; i < q.size(); ++i)
{
LDAPRequest *req = q[i];
int ret = req->run();
if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT)
{
/* try again */
try
{
Reconnect();
}
catch (const LDAPException &)
{
}
ret = req->run();
}
BuildReply(ret, req);
this->Lock();
results.push_back(req);
this->Unlock();
}
me->Notify();
process_mutex.Unlock();
}
public:
void Run() anope_override
{
while (!this->GetExitState())
{
this->Lock();
/* Queries can be non empty if one is pushed during SendRequests() */
if (queries.empty())
this->Wait();
this->Unlock();
SendRequests();
}
}
LDAP* GetConnection()
{
return con;
}
};
class ModuleLDAP : public Module, public Pipe
{
std::map<Anope::string, LDAPService *> LDAPServices;
public:
ModuleLDAP(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, EXTRA | VENDOR)
{
me = this;
}
~ModuleLDAP()
{
for (std::map<Anope::string, LDAPService *>::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
{
it->second->SetExitState();
it->second->Wakeup();
it->second->Join();
delete it->second;
}
LDAPServices.clear();
}
void OnReload(Configuration::Conf *config) anope_override
{
Configuration::Block *conf = config->GetModule(this);
for (std::map<Anope::string, LDAPService *>::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end();)
{
const Anope::string &cname = it->first;
LDAPService *s = it->second;
int i;
++it;
for (i = 0; i < conf->CountBlock("ldap"); ++i)
if (conf->GetBlock("ldap", i)->Get<const Anope::string>("name", "ldap/main") == cname)
break;
if (i == conf->CountBlock("ldap"))
{
Log(LOG_NORMAL, "ldap") << "LDAP: Removing server connection " << cname;
s->SetExitState();
s->Wakeup();
s->Join();
delete s;
this->LDAPServices.erase(cname);
}
}
for (int i = 0; i < conf->CountBlock("ldap"); ++i)
{
Configuration::Block *ldap = conf->GetBlock("ldap", i);
const Anope::string &connname = ldap->Get<const Anope::string>("name", "ldap/main");
if (this->LDAPServices.find(connname) == this->LDAPServices.end())
{
const Anope::string &server = ldap->Get<const Anope::string>("server", "127.0.0.1");
const Anope::string &admin_binddn = ldap->Get<const Anope::string>("admin_binddn");
const Anope::string &admin_password = ldap->Get<const Anope::string>("admin_password");
try
{
LDAPService *ss = new LDAPService(this, connname, server, admin_binddn, admin_password);
ss->Start();
this->LDAPServices.insert(std::make_pair(connname, ss));
Log(LOG_NORMAL, "ldap") << "LDAP: Successfully initialized server " << connname << " (" << server << ")";
}
catch (const LDAPException &ex)
{
Log(LOG_NORMAL, "ldap") << "LDAP: " << ex.GetReason();
}
}
}
}
void OnModuleUnload(User *, Module *m) anope_override
{
for (std::map<Anope::string, LDAPService *>::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
{
LDAPService *s = it->second;
s->process_mutex.Lock();
s->Lock();
for (unsigned int i = s->queries.size(); i > 0; --i)
{
LDAPRequest *req = s->queries[i - 1];
LDAPInterface *li = req->inter;
if (li && li->owner == m)
{
s->queries.erase(s->queries.begin() + i - 1);
delete req;
}
}
for (unsigned int i = s->results.size(); i > 0; --i)
{
LDAPRequest *req = s->results[i - 1];
LDAPInterface *li = req->inter;
if (li && li->owner == m)
{
s->results.erase(s->results.begin() + i - 1);
delete req;
}
}
s->Unlock();
s->process_mutex.Unlock();
}
}
void OnNotify() anope_override
{
for (std::map<Anope::string, LDAPService *>::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it)
{
LDAPService *s = it->second;
LDAPService::query_queue results;
s->Lock();
results.swap(s->results);
s->Unlock();
for (unsigned int i = 0; i < results.size(); ++i)
{
LDAPRequest *req = results[i];
LDAPInterface *li = req->inter;
LDAPResult *r = req->result;
if (li != NULL)
{
if (!r->getError().empty())
{
Log(this) << "Error running LDAP query: " << r->getError();
li->OnError(*r);
}
else
li->OnResult(*r);
}
delete req;
}
}
}
};
int LDAPBind::run()
{
berval cred;
cred.bv_val = strdup(pass.c_str());
cred.bv_len = pass.length();
int i = ldap_sasl_bind_s(service->GetConnection(), LDAP_STR(who), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
free(cred.bv_val);
return i;
}
int LDAPSearchRequest::run()
{
return ldap_search_ext_s(service->GetConnection(), LDAP_STR(base), LDAP_SCOPE_SUBTREE, LDAP_STR(filter), NULL, 0, NULL, NULL, LDAP_TIME(tv), 0, &message);
}
int LDAPAdd::run()
{
LDAPMod **mods = LDAPService::BuildMods(attributes);
int i = ldap_add_ext_s(service->GetConnection(), LDAP_STR(dn), mods, NULL, NULL);
LDAPService::FreeMods(mods);
return i;
}
int LDAPDel::run()
{
return ldap_delete_ext_s(service->GetConnection(), LDAP_STR(dn), NULL, NULL);
}
int LDAPModify::run()
{
LDAPMod **mods = LDAPService::BuildMods(attributes);
int i = ldap_modify_ext_s(service->GetConnection(), LDAP_STR(base), mods, NULL, NULL);
LDAPService::FreeMods(mods);
return i;
}
MODULE_INIT(ModuleLDAP)
|