+#include "modules/cap.h"
+#include "modules/account.h"
+#include "modules/sasl.h"
+#include "modules/ssl.h"
+
+/* $ModDesc: Provides support for IRC Authentication Layer (aka: atheme SASL) via AUTHENTICATE. */
+
+enum SaslState { SASL_INIT, SASL_COMM, SASL_DONE };
+enum SaslResult { SASL_OK, SASL_FAIL, SASL_ABORT };
+
+static std::string sasl_target = "*";
+
+static void SendSASL(const parameterlist& params)
+{
+ if (!ServerInstance->PI->SendEncapsulatedData(params))
+ {
+ SASLFallback(NULL, params);
+ }
+}
+
+/**
+ * Tracks SASL authentication state like charybdis does. --nenolod
+ */
+class SaslAuthenticator
+{
+ private:
+ std::string agent;
+ User *user;
+ SaslState state;
+ SaslResult result;
+ bool state_announced;
+
+ public:
+ SaslAuthenticator(User *user_, std::string method, Module *ctor)
+ : user(user_), state(SASL_INIT), state_announced(false)
+ {
+ parameterlist params;
+ params.push_back(sasl_target);
+ params.push_back("SASL");
+ params.push_back(user->uuid);
+ params.push_back("*");
+ params.push_back("S");
+ params.push_back(method);
+
+ if (method == "EXTERNAL" && IS_LOCAL(user_))
+ {
+ SocketCertificateRequest req(&((LocalUser*)user_)->eh, ServerInstance->Modules->Find("m_sasl.so"));
+ std::string fp = req.GetFingerprint();
+
+ if (fp.size())
+ params.push_back(fp);
+ }
+
+ SendSASL(params);
+ }
+
+ SaslResult GetSaslResult(const std::string &result_)
+ {
+ if (result_ == "F")
+ return SASL_FAIL;
+
+ if (result_ == "A")
+ return SASL_ABORT;
+
+ return SASL_OK;
+ }
+
+ /* checks for and deals with a state change. */
+ SaslState ProcessInboundMessage(const std::vector<std::string> &msg)
+ {
+ switch (this->state)
+ {
+ case SASL_INIT:
+ this->agent = msg[0];
+ this->user->Write("AUTHENTICATE %s", msg[3].c_str());
+ this->state = SASL_COMM;
+ break;
+ case SASL_COMM:
+ if (msg[0] != this->agent)
+ return this->state;
+
+ if (msg[2] != "D")
+ this->user->Write("AUTHENTICATE %s", msg[3].c_str());
+ else
+ {
+ this->state = SASL_DONE;
+ this->result = this->GetSaslResult(msg[3]);
+ }
+
+ break;
+ case SASL_DONE:
+ break;
+ default:
+ ServerInstance->Logs->Log("m_sasl", LOG_DEFAULT, "WTF: SaslState is not a known state (%d)", this->state);
+ break;
+ }
+
+ return this->state;
+ }
+
+ void Abort(void)
+ {
+ this->state = SASL_DONE;
+ this->result = SASL_ABORT;
+ }
+
+ bool SendClientMessage(const std::vector<std::string>& parameters)
+ {
+ if (this->state != SASL_COMM)
+ return true;
+
+ parameterlist params;
+ params.push_back(sasl_target);
+ params.push_back("SASL");
+ params.push_back(this->user->uuid);
+ params.push_back(this->agent);
+ params.push_back("C");
+
+ params.insert(params.end(), parameters.begin(), parameters.end());
+
+ SendSASL(params);
+
+ if (parameters[0][0] == '*')
+ {
+ this->Abort();
+ return false;
+ }
+
+ return true;
+ }
+
+ void AnnounceState(void)
+ {
+ if (this->state_announced)
+ return;