- LDAPMessage *msg, *entry;
- std::string what = (attribute + "=" + user->nick);
- if ((res = ldap_search_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, &msg)) != LDAP_SUCCESS)
+
+ int res;
+ // bind anonymously if no bind DN and authentication are given in the config
+ struct berval cred;
+ cred.bv_val = const_cast<char*>(password.c_str());
+ cred.bv_len = password.length();
+
+ if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
+ {
+ if (res == LDAP_SERVER_DOWN)
+ {
+ // Attempt to reconnect if the connection dropped
+ if (verbose)
+ ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
+ Connect();
+ res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
+ }
+
+ if (res != LDAP_SUCCESS)
+ {
+ if (verbose)
+ ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
+ ldap_unbind_ext(conn, NULL, NULL);
+ conn = NULL;
+ return false;
+ }
+ }
+
+ RAIILDAPMessage msg;
+ std::string what;
+ std::string::size_type pos = user->password.find(':');
+ // If a username is provided in PASS, use it, othewrise user their nick or ident
+ if (pos != std::string::npos)
+ {
+ what = (attribute + "=" + user->password.substr(0, pos));
+
+ // Trim the user: prefix, leaving just 'pass' for later password check
+ user->password = user->password.substr(pos + 1);
+ }
+ else
+ {
+ what = (attribute + "=" + (useusername ? user->ident : user->nick));
+ }
+ if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)