diff options
Diffstat (limited to 'src/modules')
241 files changed, 13075 insertions, 13854 deletions
diff --git a/src/modules/account.h b/src/modules/account.h deleted file mode 100644 index ba671ba0b..000000000 --- a/src/modules/account.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef ACCOUNT_H -#define ACCOUNT_H - -#include <map> -#include <string> - -class AccountEvent : public Event -{ - public: - User* const user; - const std::string account; - AccountEvent(Module* me, User* u, const std::string& name) - : Event(me, "account_login"), user(u), account(name) - { - } -}; - -typedef StringExtItem AccountExtItem; - -inline AccountExtItem* GetAccountExtItem() -{ - return static_cast<AccountExtItem*>(ServerInstance->Extensions.GetItem("accountname")); -} - -#endif diff --git a/src/modules/extra/m_geoip.cpp b/src/modules/extra/m_geoip.cpp index a36c39bc8..d21a82149 100644 --- a/src/modules/extra/m_geoip.cpp +++ b/src/modules/extra/m_geoip.cpp @@ -27,7 +27,6 @@ # pragma comment(lib, "GeoIP.lib") #endif -/* $ModDesc: Provides a way to restrict users by country using GeoIP lookup */ /* $LinkerFlags: -lGeoIP */ class ModuleGeoIP : public Module @@ -37,7 +36,7 @@ class ModuleGeoIP : public Module std::string* SetExt(LocalUser* user) { - const char* c = GeoIP_country_code_by_addr(gi, user->GetIPString()); + const char* c = GeoIP_country_code_by_addr(gi, user->GetIPString().c_str()); if (!c) c = "UNK"; @@ -47,21 +46,20 @@ class ModuleGeoIP : public Module } public: - ModuleGeoIP() : ext("geoip_cc", this), gi(NULL) + ModuleGeoIP() + : ext("geoip_cc", ExtensionItem::EXT_USER, this) + , gi(NULL) { } - void init() + void init() CXX11_OVERRIDE { gi = GeoIP_new(GEOIP_STANDARD); if (gi == NULL) throw ModuleException("Unable to initialize geoip, are you missing GeoIP.dat?"); - ServerInstance->Modules->AddService(ext); - Implementation eventlist[] = { I_OnSetConnectClass, I_OnStats }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - for (LocalUserList::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); ++i) + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i) { LocalUser* user = *i; if ((user->registered == REG_ALL) && (!ext.get(user))) @@ -77,12 +75,12 @@ class ModuleGeoIP : public Module GeoIP_delete(gi); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides a way to assign users to connect classes by country using GeoIP lookup", VF_VENDOR); } - ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) + ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE { std::string* cc = ext.get(user); if (!cc) @@ -99,14 +97,16 @@ class ModuleGeoIP : public Module return MOD_RES_DENY; } - ModResult OnStats(char symbol, User* user, string_list &out) + ModResult OnStats(char symbol, User* user, string_list &out) CXX11_OVERRIDE { if (symbol != 'G') return MOD_RES_PASSTHRU; unsigned int unknown = 0; std::map<std::string, unsigned int> results; - for (LocalUserList::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); ++i) + + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i) { std::string* cc = ext.get(*i); if (cc) @@ -115,7 +115,7 @@ class ModuleGeoIP : public Module unknown++; } - std::string p = ServerInstance->Config->ServerName + " 801 " + user->nick + " :GeoIPSTATS "; + std::string p = "801 " + user->nick + " :GeoIPSTATS "; for (std::map<std::string, unsigned int>::const_iterator i = results.begin(); i != results.end(); ++i) { out.push_back(p + i->first + " " + ConvToStr(i->second)); @@ -129,4 +129,3 @@ class ModuleGeoIP : public Module }; MODULE_INIT(ModuleGeoIP) - diff --git a/src/modules/extra/m_ldap.cpp b/src/modules/extra/m_ldap.cpp new file mode 100644 index 000000000..10469f370 --- /dev/null +++ b/src/modules/extra/m_ldap.cpp @@ -0,0 +1,628 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013-2014 Adam <Adam@anope.org> + * Copyright (C) 2003-2014 Anope Team <team@anope.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "inspircd.h" +#include "modules/ldap.h" + +#include <ldap.h> + +#ifdef _WIN32 +# pragma comment(lib, "libldap_r.lib") +# pragma comment(lib, "liblber.lib") +#endif + +/* $LinkerFlags: -lldap_r */ + +class LDAPService : public LDAPProvider, public SocketThread +{ + LDAP* con; + reference<ConfigTag> config; + time_t last_connect; + int searchscope; + time_t timeout; + time_t last_timeout_check; + + LDAPMod** BuildMods(const LDAPMods& attributes) + { + LDAPMod** mods = new LDAPMod*[attributes.size() + 1]; + memset(mods, 0, sizeof(LDAPMod*) * (attributes.size() + 1)); + for (unsigned int x = 0; x < attributes.size(); ++x) + { + const LDAPModification& l = attributes[x]; + LDAPMod* mod = new LDAPMod; + mods[x] = mod; + + if (l.op == LDAPModification::LDAP_ADD) + mod->mod_op = LDAP_MOD_ADD; + else if (l.op == LDAPModification::LDAP_DEL) + mod->mod_op = LDAP_MOD_DELETE; + else if (l.op == LDAPModification::LDAP_REPLACE) + mod->mod_op = LDAP_MOD_REPLACE; + else if (l.op != 0) + { + FreeMods(mods); + throw LDAPException("Unknown LDAP operation"); + } + mod->mod_type = strdup(l.name.c_str()); + mod->mod_values = new char*[l.values.size() + 1]; + memset(mod->mod_values, 0, sizeof(char*) * (l.values.size() + 1)); + for (unsigned int j = 0, c = 0; j < l.values.size(); ++j) + if (!l.values[j].empty()) + mod->mod_values[c++] = strdup(l.values[j].c_str()); + } + return mods; + } + + void FreeMods(LDAPMod** mods) + { + for (unsigned int i = 0; mods[i] != NULL; ++i) + { + LDAPMod* mod = mods[i]; + if (mod->mod_type != NULL) + free(mod->mod_type); + if (mod->mod_values != NULL) + { + for (unsigned int j = 0; mod->mod_values[j] != NULL; ++j) + free(mod->mod_values[j]); + delete[] mod->mod_values; + } + } + delete[] mods; + } + + void Reconnect() + { + // Only try one connect a minute. It is an expensive blocking operation + if (last_connect > ServerInstance->Time() - 60) + throw LDAPException("Unable to connect to LDAP service " + this->name + ": reconnecting too fast"); + last_connect = ServerInstance->Time(); + + ldap_unbind_ext(this->con, NULL, NULL); + Connect(); + } + + void SaveInterface(LDAPInterface* i, LDAPQuery msgid) + { + if (i != NULL) + { + this->LockQueue(); + this->queries[msgid] = std::make_pair(ServerInstance->Time(), i); + this->UnlockQueueWakeup(); + } + } + + void Timeout() + { + if (last_timeout_check == ServerInstance->Time()) + return; + last_timeout_check = ServerInstance->Time(); + + for (query_queue::iterator it = this->queries.begin(); it != this->queries.end(); ) + { + LDAPQuery msgid = it->first; + time_t created = it->second.first; + LDAPInterface* i = it->second.second; + ++it; + + if (ServerInstance->Time() > created + timeout) + { + LDAPResult* ldap_result = new LDAPResult(); + ldap_result->id = msgid; + ldap_result->error = "Query timed out"; + + this->queries.erase(msgid); + this->results.push_back(std::make_pair(i, ldap_result)); + + this->NotifyParent(); + } + } + } + + public: + typedef std::map<LDAPQuery, std::pair<time_t, LDAPInterface*> > query_queue; + typedef std::vector<std::pair<LDAPInterface*, LDAPResult*> > result_queue; + query_queue queries; + result_queue results; + + LDAPService(Module* c, ConfigTag* tag) + : LDAPProvider(c, "LDAP/" + tag->getString("id")) + , con(NULL), config(tag), last_connect(0), last_timeout_check(0) + { + std::string scope = config->getString("searchscope"); + if (scope == "base") + searchscope = LDAP_SCOPE_BASE; + else if (scope == "onelevel") + searchscope = LDAP_SCOPE_ONELEVEL; + else + searchscope = LDAP_SCOPE_SUBTREE; + timeout = config->getInt("timeout", 5); + + Connect(); + } + + ~LDAPService() + { + this->LockQueue(); + + for (query_queue::iterator i = this->queries.begin(); i != this->queries.end(); ++i) + { + LDAPQuery msgid = i->first; + LDAPInterface* inter = i->second.second; + + ldap_abandon_ext(this->con, msgid, NULL, NULL); + + if (inter) + { + LDAPResult r; + r.error = "LDAP Interface is going away"; + inter->OnError(r); + } + } + this->queries.clear(); + + for (result_queue::iterator i = this->results.begin(); i != this->results.end(); ++i) + { + LDAPInterface* inter = i->first; + LDAPResult* r = i->second; + + r->error = "LDAP Interface is going away"; + if (inter) + inter->OnError(*r); + } + this->results.clear(); + + this->UnlockQueue(); + + ldap_unbind_ext(this->con, NULL, NULL); + } + + void Connect() + { + std::string server = config->getString("server"); + int i = ldap_initialize(&this->con, 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) + { + ldap_unbind_ext(this->con, NULL, NULL); + this->con = NULL; + 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) + { + ldap_unbind_ext(this->con, NULL, NULL); + this->con = NULL; + throw LDAPException("Unable to set timeout for " + this->name + ": " + ldap_err2string(i)); + } + } + + LDAPQuery BindAsManager(LDAPInterface* i) CXX11_OVERRIDE + { + std::string binddn = config->getString("binddn"); + std::string bindauth = config->getString("bindauth"); + return this->Bind(i, binddn, bindauth); + } + + LDAPQuery Bind(LDAPInterface* i, const std::string& who, const std::string& pass) CXX11_OVERRIDE + { + berval cred; + cred.bv_val = strdup(pass.c_str()); + cred.bv_len = pass.length(); + + LDAPQuery msgid; + int ret = ldap_sasl_bind(con, who.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, &msgid); + free(cred.bv_val); + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Bind(i, who, pass); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + LDAPQuery Search(LDAPInterface* i, const std::string& base, const std::string& filter) CXX11_OVERRIDE + { + if (i == NULL) + throw LDAPException("No interface"); + + LDAPQuery msgid; + int ret = ldap_search_ext(this->con, base.c_str(), searchscope, filter.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msgid); + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Search(i, base, filter); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + LDAPQuery Add(LDAPInterface* i, const std::string& dn, LDAPMods& attributes) CXX11_OVERRIDE + { + LDAPMod** mods = this->BuildMods(attributes); + LDAPQuery msgid; + int ret = ldap_add_ext(this->con, dn.c_str(), mods, NULL, NULL, &msgid); + this->FreeMods(mods); + + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Add(i, dn, attributes); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + LDAPQuery Del(LDAPInterface* i, const std::string& dn) CXX11_OVERRIDE + { + LDAPQuery msgid; + int ret = ldap_delete_ext(this->con, dn.c_str(), NULL, NULL, &msgid); + + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Del(i, dn); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + LDAPQuery Modify(LDAPInterface* i, const std::string& base, LDAPMods& attributes) CXX11_OVERRIDE + { + LDAPMod** mods = this->BuildMods(attributes); + LDAPQuery msgid; + int ret = ldap_modify_ext(this->con, base.c_str(), mods, NULL, NULL, &msgid); + this->FreeMods(mods); + + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Modify(i, base, attributes); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + LDAPQuery Compare(LDAPInterface* i, const std::string& dn, const std::string& attr, const std::string& val) CXX11_OVERRIDE + { + berval cred; + cred.bv_val = strdup(val.c_str()); + cred.bv_len = val.length(); + + LDAPQuery msgid; + int ret = ldap_compare_ext(con, dn.c_str(), attr.c_str(), &cred, NULL, NULL, &msgid); + free(cred.bv_val); + + if (ret != LDAP_SUCCESS) + { + if (ret == LDAP_SERVER_DOWN || ret == LDAP_TIMEOUT) + { + this->Reconnect(); + return this->Compare(i, dn, attr, val); + } + else + throw LDAPException(ldap_err2string(ret)); + } + + SaveInterface(i, msgid); + return msgid; + } + + void Run() CXX11_OVERRIDE + { + while (!this->GetExitFlag()) + { + this->LockQueue(); + if (this->queries.empty()) + { + this->WaitForQueue(); + this->UnlockQueue(); + continue; + } + this->Timeout(); + this->UnlockQueue(); + + struct timeval tv = { 1, 0 }; + LDAPMessage* result; + int rtype = ldap_result(this->con, LDAP_RES_ANY, 1, &tv, &result); + if (rtype <= 0 || this->GetExitFlag()) + continue; + + int cur_id = ldap_msgid(result); + + this->LockQueue(); + + query_queue::iterator it = this->queries.find(cur_id); + if (it == this->queries.end()) + { + this->UnlockQueue(); + ldap_msgfree(result); + continue; + } + LDAPInterface* i = it->second.second; + this->queries.erase(it); + + this->UnlockQueue(); + + LDAPResult* ldap_result = new LDAPResult(); + ldap_result->id = cur_id; + + for (LDAPMessage* cur = ldap_first_message(this->con, result); cur; cur = ldap_next_message(this->con, cur)) + { + int cur_type = ldap_msgtype(cur); + + LDAPAttributes attributes; + + { + char* dn = ldap_get_dn(this->con, cur); + if (dn != NULL) + { + attributes["dn"].push_back(dn); + ldap_memfree(dn); + } + } + + switch (cur_type) + { + case LDAP_RES_BIND: + ldap_result->type = LDAPResult::QUERY_BIND; + break; + case LDAP_RES_SEARCH_ENTRY: + ldap_result->type = LDAPResult::QUERY_SEARCH; + break; + case LDAP_RES_ADD: + ldap_result->type = LDAPResult::QUERY_ADD; + break; + case LDAP_RES_DELETE: + ldap_result->type = LDAPResult::QUERY_DELETE; + break; + case LDAP_RES_MODIFY: + ldap_result->type = LDAPResult::QUERY_MODIFY; + break; + case LDAP_RES_SEARCH_RESULT: + // If we get here and ldap_result->type is LDAPResult::QUERY_UNKNOWN + // then the result set is empty + ldap_result->type = LDAPResult::QUERY_SEARCH; + break; + case LDAP_RES_COMPARE: + ldap_result->type = LDAPResult::QUERY_COMPARE; + break; + default: + continue; + } + + switch (cur_type) + { + case LDAP_RES_SEARCH_ENTRY: + { + 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<std::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); + + break; + } + case LDAP_RES_BIND: + case LDAP_RES_ADD: + case LDAP_RES_DELETE: + case LDAP_RES_MODIFY: + case LDAP_RES_COMPARE: + { + int errcode = -1; + int parse_result = ldap_parse_result(this->con, cur, &errcode, NULL, NULL, NULL, NULL, 0); + if (parse_result != LDAP_SUCCESS) + { + ldap_result->error = ldap_err2string(parse_result); + } + else + { + if (cur_type == LDAP_RES_COMPARE) + { + if (errcode != LDAP_COMPARE_TRUE) + ldap_result->error = ldap_err2string(errcode); + } + else if (errcode != LDAP_SUCCESS) + ldap_result->error = ldap_err2string(errcode); + } + break; + } + default: + continue; + } + + ldap_result->messages.push_back(attributes); + } + + ldap_msgfree(result); + + this->LockQueue(); + this->results.push_back(std::make_pair(i, ldap_result)); + this->UnlockQueueWakeup(); + + this->NotifyParent(); + } + } + + void OnNotify() CXX11_OVERRIDE + { + LDAPService::result_queue r; + + this->LockQueue(); + this->results.swap(r); + this->UnlockQueue(); + + for (LDAPService::result_queue::iterator i = r.begin(); i != r.end(); ++i) + { + LDAPInterface* li = i->first; + LDAPResult* res = i->second; + + if (!res->error.empty()) + li->OnError(*res); + else + li->OnResult(*res); + + delete res; + } + } +}; + +class ModuleLDAP : public Module +{ + typedef insp::flat_map<std::string, LDAPService*> ServiceMap; + ServiceMap LDAPServices; + + public: + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ServiceMap conns; + + ConfigTagList tags = ServerInstance->Config->ConfTags("database"); + for (ConfigIter i = tags.first; i != tags.second; i++) + { + const reference<ConfigTag>& tag = i->second; + + if (tag->getString("module") != "ldap") + continue; + + std::string id = tag->getString("id"); + + ServiceMap::iterator curr = LDAPServices.find(id); + if (curr == LDAPServices.end()) + { + LDAPService* conn = new LDAPService(this, tag); + conns[id] = conn; + + ServerInstance->Modules->AddService(*conn); + ServerInstance->Threads.Start(conn); + } + else + { + conns.insert(*curr); + LDAPServices.erase(curr); + } + } + + for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i) + { + LDAPService* conn = i->second; + ServerInstance->Modules->DelService(*conn); + conn->join(); + conn->OnNotify(); + delete conn; + } + + LDAPServices.swap(conns); + } + + void OnUnloadModule(Module* m) CXX11_OVERRIDE + { + for (ServiceMap::iterator it = this->LDAPServices.begin(); it != this->LDAPServices.end(); ++it) + { + LDAPService* s = it->second; + s->LockQueue(); + for (LDAPService::query_queue::iterator it2 = s->queries.begin(); it2 != s->queries.end();) + { + int msgid = it2->first; + LDAPInterface* i = it2->second.second; + ++it2; + + if (i->creator == m) + s->queries.erase(msgid); + } + for (unsigned int i = s->results.size(); i > 0; --i) + { + LDAPInterface* li = s->results[i - 1].first; + LDAPResult* r = s->results[i - 1].second; + + if (li->creator == m) + { + s->results.erase(s->results.begin() + i - 1); + delete r; + } + } + s->UnlockQueue(); + } + } + + ~ModuleLDAP() + { + for (ServiceMap::iterator i = LDAPServices.begin(); i != LDAPServices.end(); ++i) + { + LDAPService* conn = i->second; + conn->join(); + conn->OnNotify(); + delete conn; + } + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("LDAP support", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleLDAP) diff --git a/src/modules/extra/m_ldapauth.cpp b/src/modules/extra/m_ldapauth.cpp deleted file mode 100644 index 6c765fb2e..000000000 --- a/src/modules/extra/m_ldapauth.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2011 Pierre Carrier <pierre@spotify.com> - * Copyright (C) 2009-2010 Robin Burchell <robin+git@viroteck.net> - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> - * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> - * Copyright (C) 2008 Dennis Friis <peavey@inspircd.org> - * Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "inspircd.h" -#include "users.h" -#include "channels.h" -#include "modules.h" - -#include <ldap.h> - -#ifdef _WIN32 -# pragma comment(lib, "libldap.lib") -# pragma comment(lib, "liblber.lib") -#endif - -/* $ModDesc: Allow/Deny connections based upon answer from LDAP server */ -/* $LinkerFlags: -lldap */ - -struct RAIILDAPString -{ - char *str; - - RAIILDAPString(char *Str) - : str(Str) - { - } - - ~RAIILDAPString() - { - ldap_memfree(str); - } - - operator char*() - { - return str; - } - - operator std::string() - { - return str; - } -}; - -struct RAIILDAPMessage -{ - RAIILDAPMessage() - { - } - - ~RAIILDAPMessage() - { - dealloc(); - } - - void dealloc() - { - ldap_msgfree(msg); - } - - operator LDAPMessage*() - { - return msg; - } - - LDAPMessage **operator &() - { - return &msg; - } - - LDAPMessage *msg; -}; - -class ModuleLDAPAuth : public Module -{ - LocalIntExt ldapAuthed; - LocalStringExt ldapVhost; - std::string base; - std::string attribute; - std::string ldapserver; - std::string allowpattern; - std::string killreason; - std::string username; - std::string password; - std::string vhost; - std::vector<std::string> whitelistedcidrs; - std::vector<std::pair<std::string, std::string> > requiredattributes; - int searchscope; - bool verbose; - bool useusername; - LDAP *conn; - -public: - ModuleLDAPAuth() - : ldapAuthed("ldapauth", this) - , ldapVhost("ldapauth_vhost", this) - { - conn = NULL; - } - - void init() - { - ServerInstance->Modules->AddService(ldapAuthed); - ServerInstance->Modules->AddService(ldapVhost); - Implementation eventlist[] = { I_OnCheckReady, I_OnRehash,I_OnUserRegister, I_OnUserConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - - ~ModuleLDAPAuth() - { - if (conn) - ldap_unbind_ext(conn, NULL, NULL); - } - - void OnRehash(User* user) - { - ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth"); - whitelistedcidrs.clear(); - requiredattributes.clear(); - - base = tag->getString("baserdn"); - attribute = tag->getString("attribute"); - ldapserver = tag->getString("server"); - allowpattern = tag->getString("allowpattern"); - killreason = tag->getString("killreason"); - std::string scope = tag->getString("searchscope"); - username = tag->getString("binddn"); - password = tag->getString("bindauth"); - vhost = tag->getString("host"); - verbose = tag->getBool("verbose"); /* Set to true if failed connects should be reported to operators */ - useusername = tag->getBool("userfield"); - - ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist"); - - for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i) - { - std::string cidr = i->second->getString("cidr"); - if (!cidr.empty()) { - whitelistedcidrs.push_back(cidr); - } - } - - ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire"); - - for (ConfigIter i = attributetags.first; i != attributetags.second; ++i) - { - const std::string attr = i->second->getString("attribute"); - const std::string val = i->second->getString("value"); - - if (!attr.empty() && !val.empty()) - requiredattributes.push_back(make_pair(attr, val)); - } - - if (scope == "base") - searchscope = LDAP_SCOPE_BASE; - else if (scope == "onelevel") - searchscope = LDAP_SCOPE_ONELEVEL; - else searchscope = LDAP_SCOPE_SUBTREE; - - Connect(); - } - - bool Connect() - { - if (conn != NULL) - ldap_unbind_ext(conn, NULL, NULL); - int res, v = LDAP_VERSION3; - res = ldap_initialize(&conn, ldapserver.c_str()); - if (res != LDAP_SUCCESS) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res)); - conn = NULL; - return false; - } - - res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v); - if (res != LDAP_SUCCESS) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res)); - ldap_unbind_ext(conn, NULL, NULL); - conn = NULL; - return false; - } - return true; - } - - std::string SafeReplace(const std::string &text, std::map<std::string, - std::string> &replacements) - { - std::string result; - result.reserve(MAXBUF); - - for (unsigned int i = 0; i < text.length(); ++i) { - char c = text[i]; - if (c == '$') { - // find the first nonalpha - i++; - unsigned int start = i; - - while (i < text.length() - 1 && isalpha(text[i + 1])) - ++i; - - std::string key = text.substr(start, (i - start) + 1); - result.append(replacements[key]); - } else { - result.push_back(c); - } - } - - return result; - } - - virtual void OnUserConnect(LocalUser *user) - { - std::string* cc = ldapVhost.get(user); - if (cc) - { - user->ChangeDisplayedHost(cc->c_str()); - ldapVhost.unset(user); - } - } - - ModResult OnUserRegister(LocalUser* user) - { - if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern))) - { - ldapAuthed.set(user,1); - return MOD_RES_PASSTHRU; - } - - for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++) - { - if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map)) - { - ldapAuthed.set(user,1); - return MOD_RES_PASSTHRU; - } - } - - if (!CheckCredentials(user)) - { - ServerInstance->Users->QuitUser(user, killreason); - return MOD_RES_DENY; - } - return MOD_RES_PASSTHRU; - } - - bool CheckCredentials(LocalUser* user) - { - if (conn == NULL) - if (!Connect()) - return false; - - if (user->password.empty()) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str()); - return false; - } - - 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 = (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) - { - // Do a second search, based on password, if it contains a : - // That is, PASS <user>:<password> will work. - size_t pos = user->password.find(":"); - if (pos != std::string::npos) - { - // manpage says we must deallocate regardless of success or failure - // since we're about to do another query (and reset msg), first - // free the old one. - msg.dealloc(); - - std::string cutpassword = user->password.substr(0, pos); - res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg); - - if (res == LDAP_SUCCESS) - { - // Trim the user: prefix, leaving just 'pass' for later password check - user->password = user->password.substr(pos + 1); - } - } - - // It may have found based on user:pass check above. - if (res != LDAP_SUCCESS) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res)); - return false; - } - } - if (ldap_count_entries(conn, msg) > 1) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res)); - return false; - } - - LDAPMessage *entry; - if ((entry = ldap_first_entry(conn, msg)) == NULL) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res)); - return false; - } - cred.bv_val = (char*)user->password.data(); - cred.bv_len = user->password.length(); - RAIILDAPString DN(ldap_get_dn(conn, entry)); - if ((res = ldap_sasl_bind_s(conn, DN, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res)); - return false; - } - - if (!requiredattributes.empty()) - { - bool authed = false; - - for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it) - { - const std::string &attr = it->first; - const std::string &val = it->second; - - struct berval attr_value; - attr_value.bv_val = const_cast<char*>(val.c_str()); - attr_value.bv_len = val.length(); - - ServerInstance->Logs->Log("m_ldapauth", DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str()); - - authed = (ldap_compare_ext_s(conn, DN, attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE); - - if (authed) - break; - } - - if (!authed) - { - if (verbose) - ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str()); - return false; - } - } - - if (!vhost.empty()) - { - irc::commasepstream stream(DN); - - // mashed map of key:value parts of the DN - std::map<std::string, std::string> dnParts; - - std::string dnPart; - while (stream.GetToken(dnPart)) - { - std::string::size_type pos = dnPart.find('='); - if (pos == std::string::npos) // malformed - continue; - - std::string key = dnPart.substr(0, pos); - std::string value = dnPart.substr(pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself - dnParts[key] = value; - } - - // change host according to config key - ldapVhost.set(user, SafeReplace(vhost, dnParts)); - } - - ldapAuthed.set(user,1); - return true; - } - - ModResult OnCheckReady(LocalUser* user) - { - return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY; - } - - Version GetVersion() - { - return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR); - } - -}; - -MODULE_INIT(ModuleLDAPAuth) diff --git a/src/modules/extra/m_ldapoper.cpp b/src/modules/extra/m_ldapoper.cpp deleted file mode 100644 index 1f46361d4..000000000 --- a/src/modules/extra/m_ldapoper.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Robin Burchell <robin+git@viroteck.net> - * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> - * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> - * Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "inspircd.h" -#include "users.h" -#include "channels.h" -#include "modules.h" - -#include <ldap.h> - -#ifdef _WIN32 -# pragma comment(lib, "libldap.lib") -# pragma comment(lib, "liblber.lib") -#endif - -/* $ModDesc: Adds the ability to authenticate opers via LDAP */ -/* $LinkerFlags: -lldap */ - -// Duplicated code, also found in cmd_oper and m_sqloper -static bool OneOfMatches(const char* host, const char* ip, const std::string& hostlist) -{ - std::stringstream hl(hostlist); - std::string xhost; - while (hl >> xhost) - { - if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map)) - { - return true; - } - } - return false; -} - -struct RAIILDAPString -{ - char *str; - - RAIILDAPString(char *Str) - : str(Str) - { - } - - ~RAIILDAPString() - { - ldap_memfree(str); - } - - operator char*() - { - return str; - } - - operator std::string() - { - return str; - } -}; - -class ModuleLDAPAuth : public Module -{ - std::string base; - std::string ldapserver; - std::string username; - std::string password; - std::string attribute; - int searchscope; - LDAP *conn; - - bool HandleOper(LocalUser* user, const std::string& opername, const std::string& inputpass) - { - OperIndex::iterator it = ServerInstance->Config->oper_blocks.find(opername); - if (it == ServerInstance->Config->oper_blocks.end()) - return false; - - ConfigTag* tag = it->second->oper_block; - if (!tag) - return false; - - std::string acceptedhosts = tag->getString("host"); - std::string hostname = user->ident + "@" + user->host; - if (!OneOfMatches(hostname.c_str(), user->GetIPString(), acceptedhosts)) - return false; - - if (!LookupOper(opername, inputpass)) - return false; - - user->Oper(it->second); - return true; - } - -public: - ModuleLDAPAuth() - : conn(NULL) - { - } - - void init() - { - Implementation eventlist[] = { I_OnRehash, I_OnPreCommand }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - - virtual ~ModuleLDAPAuth() - { - if (conn) - ldap_unbind_ext(conn, NULL, NULL); - } - - virtual void OnRehash(User* user) - { - ConfigTag* tag = ServerInstance->Config->ConfValue("ldapoper"); - - base = tag->getString("baserdn"); - ldapserver = tag->getString("server"); - std::string scope = tag->getString("searchscope"); - username = tag->getString("binddn"); - password = tag->getString("bindauth"); - attribute = tag->getString("attribute"); - - if (scope == "base") - searchscope = LDAP_SCOPE_BASE; - else if (scope == "onelevel") - searchscope = LDAP_SCOPE_ONELEVEL; - else searchscope = LDAP_SCOPE_SUBTREE; - - Connect(); - } - - bool Connect() - { - if (conn != NULL) - ldap_unbind_ext(conn, NULL, NULL); - int res, v = LDAP_VERSION3; - res = ldap_initialize(&conn, ldapserver.c_str()); - if (res != LDAP_SUCCESS) - { - conn = NULL; - return false; - } - - res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v); - if (res != LDAP_SUCCESS) - { - ldap_unbind_ext(conn, NULL, NULL); - conn = NULL; - return false; - } - return true; - } - - ModResult OnPreCommand(std::string& command, std::vector<std::string>& parameters, LocalUser* user, bool validated, const std::string& original_line) - { - if (validated && command == "OPER" && parameters.size() >= 2) - { - if (HandleOper(user, parameters[0], parameters[1])) - return MOD_RES_DENY; - } - return MOD_RES_PASSTHRU; - } - - bool LookupOper(const std::string& opername, const std::string& opassword) - { - if (conn == NULL) - if (!Connect()) - return false; - - int res; - char* authpass = strdup(password.c_str()); - // bind anonymously if no bind DN and authentication are given in the config - struct berval cred; - cred.bv_val = authpass; - 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 - 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) - { - free(authpass); - ldap_unbind_ext(conn, NULL, NULL); - conn = NULL; - return false; - } - } - free(authpass); - - LDAPMessage *msg, *entry; - std::string what = attribute + "=" + opername; - if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS) - { - return false; - } - if (ldap_count_entries(conn, msg) > 1) - { - ldap_msgfree(msg); - return false; - } - if ((entry = ldap_first_entry(conn, msg)) == NULL) - { - ldap_msgfree(msg); - return false; - } - authpass = strdup(opassword.c_str()); - cred.bv_val = authpass; - cred.bv_len = opassword.length(); - RAIILDAPString DN(ldap_get_dn(conn, entry)); - if ((res = ldap_sasl_bind_s(conn, DN, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) == LDAP_SUCCESS) - { - free(authpass); - ldap_msgfree(msg); - return true; - } - else - { - free(authpass); - ldap_msgfree(msg); - return false; - } - } - - virtual Version GetVersion() - { - return Version("Adds the ability to authenticate opers via LDAP", VF_VENDOR); - } - -}; - -MODULE_INIT(ModuleLDAPAuth) diff --git a/src/modules/extra/m_mssql.cpp b/src/modules/extra/m_mssql.cpp index 598f9aac9..0e8c8cf55 100644 --- a/src/modules/extra/m_mssql.cpp +++ b/src/modules/extra/m_mssql.cpp @@ -24,22 +24,17 @@ #include "inspircd.h" #include <tds.h> #include <tdsconvert.h> -#include "users.h" -#include "channels.h" -#include "modules.h" #include "m_sqlv2.h" -/* $ModDesc: MsSQL provider */ /* $CompileFlags: exec("grep VERSION_NO /usr/include/tdsver.h 2>/dev/null | perl -e 'print "-D_TDSVER=".((<> =~ /freetds v(\d+\.\d+)/i) ? $1*100 : 0);'") */ /* $LinkerFlags: -ltds */ -/* $ModDep: m_sqlv2.h */ class SQLConn; class MsSQLResult; class ModuleMsSQL; -typedef std::map<std::string, SQLConn*> ConnMap; +typedef insp::flat_map<std::string, SQLConn*> ConnMap; typedef std::deque<MsSQLResult*> ResultQueue; unsigned long count(const char * const str, char a) @@ -64,8 +59,8 @@ class QueryThread : public SocketThread public: QueryThread(ModuleMsSQL* mod) : Parent(mod) { } ~QueryThread() { } - virtual void Run(); - virtual void OnNotify(); + void Run(); + void OnNotify(); }; class MsSQLResult : public SQLresult @@ -88,10 +83,6 @@ class MsSQLResult : public SQLresult { } - ~MsSQLResult() - { - } - void AddRow(int colsnum, char **dat, char **colname) { colnames.clear(); @@ -111,17 +102,17 @@ class MsSQLResult : public SQLresult rows++; } - virtual int Rows() + int Rows() { return rows; } - virtual int Cols() + int Cols() { return cols; } - virtual std::string ColName(int column) + std::string ColName(int column) { if (column < (int)colnames.size()) { @@ -134,7 +125,7 @@ class MsSQLResult : public SQLresult return ""; } - virtual int ColNum(const std::string &column) + int ColNum(const std::string &column) { for (unsigned int i = 0; i < colnames.size(); i++) { @@ -145,7 +136,7 @@ class MsSQLResult : public SQLresult return 0; } - virtual SQLfield GetValue(int row, int column) + SQLfield GetValue(int row, int column) { if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) { @@ -158,7 +149,7 @@ class MsSQLResult : public SQLresult return SQLfield("",true); } - virtual SQLfieldList& GetRow() + SQLfieldList& GetRow() { if (currentrow < rows) return fieldlists[currentrow]; @@ -166,7 +157,7 @@ class MsSQLResult : public SQLresult return emptyfieldlist; } - virtual SQLfieldMap& GetRowMap() + SQLfieldMap& GetRowMap() { /* In an effort to reduce overhead we don't actually allocate the map * until the first time it's needed...so... @@ -192,7 +183,7 @@ class MsSQLResult : public SQLresult return *fieldmap; } - virtual SQLfieldList* GetRowPtr() + SQLfieldList* GetRowPtr() { fieldlist = new SQLfieldList(); @@ -207,7 +198,7 @@ class MsSQLResult : public SQLresult return fieldlist; } - virtual SQLfieldMap* GetRowMapPtr() + SQLfieldMap* GetRowMapPtr() { fieldmap = new SQLfieldMap(); @@ -223,12 +214,12 @@ class MsSQLResult : public SQLresult return fieldmap; } - virtual void Free(SQLfieldMap* fm) + void Free(SQLfieldMap* fm) { delete fm; } - virtual void Free(SQLfieldList* fl) + void Free(SQLfieldList* fl) { delete fl; } @@ -258,7 +249,7 @@ class SQLConn : public classbase if (tds_process_simple_query(sock) != TDS_SUCCEED) { LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id); LoggingMutex->Unlock(); CloseDB(); } @@ -266,7 +257,7 @@ class SQLConn : public classbase else { LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not select database " + host.name + " for DB with id: " + host.id); LoggingMutex->Unlock(); CloseDB(); } @@ -274,7 +265,7 @@ class SQLConn : public classbase else { LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: Could not connect to DB with id: " + host.id); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to DB with id: " + host.id); LoggingMutex->Unlock(); CloseDB(); } @@ -433,7 +424,7 @@ class SQLConn : public classbase char* msquery = strdup(req->query.q.data()); LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql",DEBUG,"doing Query: %s",msquery); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "doing Query: %s",msquery); LoggingMutex->Unlock(); if (tds_submit_query(sock, msquery) != TDS_SUCCEED) { @@ -449,8 +440,8 @@ class SQLConn : public classbase int tds_res; while (tds_process_tokens(sock, &tds_res, NULL, TDS_TOKEN_RESULTS) == TDS_SUCCEED) { - //ServerInstance->Logs->Log("m_mssql",DEBUG,"<******> result type: %d", tds_res); - //ServerInstance->Logs->Log("m_mssql",DEBUG,"AFFECTED ROWS: %d", sock->rows_affected); + //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "<******> result type: %d", tds_res); + //ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "AFFECTED ROWS: %d", sock->rows_affected); switch (tds_res) { case TDS_ROWFMT_RESULT: @@ -476,8 +467,8 @@ class SQLConn : public classbase if (sock->res_info->row_count > 0) { int cols = sock->res_info->num_cols; - char** name = new char*[MAXBUF]; - char** data = new char*[MAXBUF]; + char** name = new char*[512]; + char** data = new char*[512]; for (int j=0; j<cols; j++) { TDSCOLUMN* col = sock->current_results->columns[j]; @@ -516,7 +507,7 @@ class SQLConn : public classbase { SQLConn* sc = (SQLConn*)pContext->parent; LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql", DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Message for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message); LoggingMutex->Unlock(); return 0; } @@ -525,7 +516,7 @@ class SQLConn : public classbase { SQLConn* sc = (SQLConn*)pContext->parent; LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql", DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error for DB with id: %s -> %s", sc->host.id.c_str(), pMessage->message); LoggingMutex->Unlock(); return 0; } @@ -657,18 +648,14 @@ class ModuleMsSQL : public Module queryDispatcher = new QueryThread(this); } - void init() + void init() CXX11_OVERRIDE { ReadConf(); - ServerInstance->Threads->Start(queryDispatcher); - - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - ServerInstance->Modules->AddService(sqlserv); + ServerInstance->Threads.Start(queryDispatcher); } - virtual ~ModuleMsSQL() + ~ModuleMsSQL() { queryDispatcher->join(); delete queryDispatcher; @@ -753,7 +740,7 @@ class ModuleMsSQL : public Module if (HasHost(hi)) { LoggingMutex->Lock(); - ServerInstance->Logs->Log("m_mssql",DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: A MsSQL connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str()); LoggingMutex->Unlock(); return; } @@ -787,14 +774,14 @@ class ModuleMsSQL : public Module connections.clear(); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { queryDispatcher->LockQueue(); ReadConf(); queryDispatcher->UnlockQueueWakeup(); } - void OnRequest(Request& request) + void OnRequest(Request& request) CXX11_OVERRIDE { if(strcmp(SQLREQID, request.id) == 0) { @@ -825,7 +812,7 @@ class ModuleMsSQL : public Module return ++currid; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("MsSQL provider", VF_VENDOR); } diff --git a/src/modules/extra/m_mysql.cpp b/src/modules/extra/m_mysql.cpp index 01b1553b0..d8dda27a4 100644 --- a/src/modules/extra/m_mysql.cpp +++ b/src/modules/extra/m_mysql.cpp @@ -25,7 +25,7 @@ #include "inspircd.h" #include <mysql.h> -#include "sql.h" +#include "modules/sql.h" #ifdef _WIN32 # pragma comment(lib, "libmysql.lib") @@ -33,7 +33,6 @@ /* VERSION 3 API: With nonblocking (threaded) requests */ -/* $ModDesc: SQL Service Provider module for all other m_sql* modules */ /* $CompileFlags: exec("mysql_config --include") */ /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */ @@ -90,7 +89,7 @@ struct RQueueItem RQueueItem(SQLQuery* Q, MySQLresult* R) : q(Q), r(R) {} }; -typedef std::map<std::string, SQLConnection*> ConnMap; +typedef insp::flat_map<std::string, SQLConnection*> ConnMap; typedef std::deque<QQueueItem> QueryQueue; typedef std::deque<RQueueItem> ResultQueue; @@ -105,11 +104,11 @@ class ModuleSQL : public Module ConnMap connections; // main thread only ModuleSQL(); - void init(); + void init() CXX11_OVERRIDE; ~ModuleSQL(); - void OnRehash(User* user); - void OnUnloadModule(Module* mod); - Version GetVersion(); + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE; + void OnUnloadModule(Module* mod) CXX11_OVERRIDE; + Version GetVersion() CXX11_OVERRIDE; }; class DispatcherThread : public SocketThread @@ -119,8 +118,8 @@ class DispatcherThread : public SocketThread public: DispatcherThread(ModuleSQL* CreatorModule) : Parent(CreatorModule) { } ~DispatcherThread() { } - virtual void Run(); - virtual void OnNotify(); + void Run(); + void OnNotify(); }; #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224 @@ -186,21 +185,17 @@ class MySQLresult : public SQLResult } - ~MySQLresult() - { - } - - virtual int Rows() + int Rows() { return rows; } - virtual void GetCols(std::vector<std::string>& result) + void GetCols(std::vector<std::string>& result) { result.assign(colnames.begin(), colnames.end()); } - virtual SQLEntry GetValue(int row, int column) + SQLEntry GetValue(int row, int column) { if ((row >= 0) && (row < rows) && (column >= 0) && (column < (int)fieldlists[row].size())) { @@ -209,7 +204,7 @@ class MySQLresult : public SQLResult return SQLEntry(); } - virtual bool GetRow(SQLEntries& result) + bool GetRow(SQLEntries& result) { if (currentrow < rows) { @@ -260,6 +255,12 @@ class SQLConnection : public SQLProvider bool rv = mysql_real_connect(connection, host.c_str(), user.c_str(), pass.c_str(), dbname.c_str(), port, NULL, 0); if (!rv) return rv; + + // Enable character set settings + std::string charset = config->getString("charset"); + if ((!charset.empty()) && (mysql_set_character_set(connection, charset.c_str()))) + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not set character set to \"%s\"", charset.c_str()); + std::string initquery; if (config->readString("initialquery", initquery)) { @@ -383,12 +384,7 @@ ModuleSQL::ModuleSQL() void ModuleSQL::init() { Dispatcher = new DispatcherThread(this); - ServerInstance->Threads->Start(Dispatcher); - - Implementation eventlist[] = { I_OnRehash, I_OnUnloadModule }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - OnRehash(NULL); + ServerInstance->Threads.Start(Dispatcher); } ModuleSQL::~ModuleSQL() @@ -405,7 +401,7 @@ ModuleSQL::~ModuleSQL() } } -void ModuleSQL::OnRehash(User* user) +void ModuleSQL::ReadConfig(ConfigStatus& status) { ConnMap conns; ConfigTagList tags = ServerInstance->Config->ConfTags("database"); diff --git a/src/modules/extra/m_pgsql.cpp b/src/modules/extra/m_pgsql.cpp index ac247548a..ff8c1174c 100644 --- a/src/modules/extra/m_pgsql.cpp +++ b/src/modules/extra/m_pgsql.cpp @@ -24,11 +24,9 @@ #include "inspircd.h" #include <cstdlib> -#include <sstream> #include <libpq-fe.h> -#include "sql.h" +#include "modules/sql.h" -/* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */ /* $CompileFlags: -Iexec("pg_config --includedir") eval("my $s = `pg_config --version`;$s =~ /^.*?(\d+)\.(\d+)\.(\d+).*?$/;my $v = hex(sprintf("0x%02x%02x%02x", $1, $2, $3));print "-DPGSQL_HAS_ESCAPECONN" if(($v >= 0x080104) || ($v >= 0x07030F && $v < 0x070400) || ($v >= 0x07040D && $v < 0x080000) || ($v >= 0x080008 && $v < 0x080100));") */ /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */ @@ -43,7 +41,7 @@ class SQLConn; class ModulePgSQL; -typedef std::map<std::string, SQLConn*> ConnMap; +typedef insp::flat_map<std::string, SQLConn*> ConnMap; /* CREAD, Connecting and wants read event * CWRITE, Connecting and wants write event @@ -59,10 +57,10 @@ class ReconnectTimer : public Timer private: ModulePgSQL* mod; public: - ReconnectTimer(ModulePgSQL* m) : Timer(5, ServerInstance->Time(), false), mod(m) + ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m) { } - virtual void Tick(time_t TIME); + bool Tick(time_t TIME); }; struct QueueItem @@ -97,12 +95,12 @@ class PgSQLresult : public SQLResult PQclear(res); } - virtual int Rows() + int Rows() { return rows; } - virtual void GetCols(std::vector<std::string>& result) + void GetCols(std::vector<std::string>& result) { result.resize(PQnfields(res)); for(unsigned int i=0; i < result.size(); i++) @@ -111,7 +109,7 @@ class PgSQLresult : public SQLResult } } - virtual SQLEntry GetValue(int row, int column) + SQLEntry GetValue(int row, int column) { char* v = PQgetvalue(res, row, column); if (!v || PQgetisnull(res, row, column)) @@ -120,7 +118,7 @@ class PgSQLresult : public SQLResult return SQLEntry(std::string(v, PQgetlength(res, row, column))); } - virtual bool GetRow(SQLEntries& result) + bool GetRow(SQLEntries& result) { if (currentrow >= PQntuples(res)) return false; @@ -152,7 +150,7 @@ class SQLConn : public SQLProvider, public EventHandler { if (!DoConnect()) { - ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database " + tag->getString("id")); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id")); DelayReconnect(); } } @@ -180,18 +178,19 @@ class SQLConn : public SQLProvider, public EventHandler } } - virtual void HandleEvent(EventType et, int errornum) + void OnEventHandlerRead() CXX11_OVERRIDE { - switch (et) - { - case EVENT_READ: - case EVENT_WRITE: - DoEvent(); - break; + DoEvent(); + } - case EVENT_ERROR: - DelayReconnect(); - } + void OnEventHandlerWrite() CXX11_OVERRIDE + { + DoEvent(); + } + + void OnEventHandlerError(int errornum) CXX11_OVERRIDE + { + DelayReconnect(); } std::string GetDSN() @@ -242,9 +241,9 @@ class SQLConn : public SQLProvider, public EventHandler if(this->fd <= -1) return false; - if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ)) + if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ)) { - ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine"); return false; } @@ -257,17 +256,17 @@ class SQLConn : public SQLProvider, public EventHandler switch(PQconnectPoll(sql)) { case PGRES_POLLING_WRITING: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ); status = CWRITE; return true; case PGRES_POLLING_READING: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); status = CREAD; return true; case PGRES_POLLING_FAILED: return false; case PGRES_POLLING_OK: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); status = WWRITE; DoConnectedPoll(); default: @@ -350,17 +349,17 @@ restart: switch(PQresetPoll(sql)) { case PGRES_POLLING_WRITING: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ); status = CWRITE; return DoPoll(); case PGRES_POLLING_READING: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); status = CREAD; return true; case PGRES_POLLING_FAILED: return false; case PGRES_POLLING_OK: - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); status = WWRITE; DoConnectedPoll(); default: @@ -417,7 +416,7 @@ restart: int error; size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error); if (error) - ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed"); #else size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length()); #endif @@ -452,7 +451,7 @@ restart: int error; size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error); if (error) - ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed"); #else size_t escapedsize = PQescapeString(&buffer[0], parm.data(), parm.length()); #endif @@ -488,7 +487,7 @@ restart: void Close() { - ServerInstance->SE->DelFd(this); + SocketEngine::DelFd(this); if(sql) { @@ -505,25 +504,17 @@ class ModulePgSQL : public Module ReconnectTimer* retimer; ModulePgSQL() + : retimer(NULL) { } - void init() - { - ReadConf(); - - Implementation eventlist[] = { I_OnUnloadModule, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModulePgSQL() + ~ModulePgSQL() { - if (retimer) - ServerInstance->Timers->DelTimer(retimer); + delete retimer; ClearAllConnections(); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ReadConf(); } @@ -564,7 +555,7 @@ class ModulePgSQL : public Module connections.clear(); } - void OnUnloadModule(Module* mod) + void OnUnloadModule(Module* mod) CXX11_OVERRIDE { SQLerror err(SQL_BAD_DBID); for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++) @@ -592,16 +583,18 @@ class ModulePgSQL : public Module } } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR); } }; -void ReconnectTimer::Tick(time_t time) +bool ReconnectTimer::Tick(time_t time) { mod->retimer = NULL; mod->ReadConf(); + delete this; + return false; } void SQLConn::DelayReconnect() @@ -615,7 +608,7 @@ void SQLConn::DelayReconnect() if (!mod->retimer) { mod->retimer = new ReconnectTimer(mod); - ServerInstance->Timers->AddTimer(mod->retimer); + ServerInstance->Timers.AddTimer(mod->retimer); } } } diff --git a/src/modules/extra/m_regex_pcre.cpp b/src/modules/extra/m_regex_pcre.cpp index cba234c8c..9ae6719ba 100644 --- a/src/modules/extra/m_regex_pcre.cpp +++ b/src/modules/extra/m_regex_pcre.cpp @@ -20,10 +20,8 @@ #include "inspircd.h" #include <pcre.h> -#include "m_regex.h" +#include "modules/regex.h" -/* $ModDesc: Regex Provider Module for PCRE */ -/* $ModDep: m_regex.h */ /* $CompileFlags: exec("pcre-config --cflags") */ /* $LinkerFlags: exec("pcre-config --libs") rpath("pcre-config --libs") -lpcre */ @@ -31,21 +29,11 @@ # pragma comment(lib, "libpcre.lib") #endif -class PCREException : public ModuleException -{ -public: - PCREException(const std::string& rx, const std::string& error, int erroffset) - : ModuleException("Error in regex " + rx + " at offset " + ConvToStr(erroffset) + ": " + error) - { - } -}; - class PCRERegex : public Regex { -private: pcre* regex; -public: + public: PCRERegex(const std::string& rx) : Regex(rx) { const char* error; @@ -53,24 +41,19 @@ public: regex = pcre_compile(rx.c_str(), 0, &error, &erroffset, NULL); if (!regex) { - ServerInstance->Logs->Log("REGEX", DEBUG, "pcre_compile failed: /%s/ [%d] %s", rx.c_str(), erroffset, error); - throw PCREException(rx, error, erroffset); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "pcre_compile failed: /%s/ [%d] %s", rx.c_str(), erroffset, error); + throw RegexException(rx, error, erroffset); } } - virtual ~PCRERegex() + ~PCRERegex() { pcre_free(regex); } - virtual bool Matches(const std::string& text) + bool Matches(const std::string& text) CXX11_OVERRIDE { - if (pcre_exec(regex, NULL, text.c_str(), text.length(), 0, 0, NULL, 0) > -1) - { - // Bang. :D - return true; - } - return false; + return (pcre_exec(regex, NULL, text.c_str(), text.length(), 0, 0, NULL, 0) >= 0); } }; @@ -78,7 +61,7 @@ class PCREFactory : public RegexFactory { public: PCREFactory(Module* m) : RegexFactory(m, "regex/pcre") {} - Regex* Create(const std::string& expr) + Regex* Create(const std::string& expr) CXX11_OVERRIDE { return new PCRERegex(expr); } @@ -86,13 +69,13 @@ class PCREFactory : public RegexFactory class ModuleRegexPCRE : public Module { -public: + public: PCREFactory ref; - ModuleRegexPCRE() : ref(this) { - ServerInstance->Modules->AddService(ref); + ModuleRegexPCRE() : ref(this) + { } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Regex Provider Module for PCRE", VF_VENDOR); } diff --git a/src/modules/extra/m_regex_posix.cpp b/src/modules/extra/m_regex_posix.cpp index b3afd60c8..b5fddfab8 100644 --- a/src/modules/extra/m_regex_posix.cpp +++ b/src/modules/extra/m_regex_posix.cpp @@ -19,28 +19,15 @@ #include "inspircd.h" -#include "m_regex.h" +#include "modules/regex.h" #include <sys/types.h> #include <regex.h> -/* $ModDesc: Regex Provider Module for POSIX Regular Expressions */ -/* $ModDep: m_regex.h */ - -class POSIXRegexException : public ModuleException -{ -public: - POSIXRegexException(const std::string& rx, const std::string& error) - : ModuleException("Error in regex " + rx + ": " + error) - { - } -}; - class POSIXRegex : public Regex { -private: regex_t regbuf; -public: + public: POSIXRegex(const std::string& rx, bool extended) : Regex(rx) { int flags = (extended ? REG_EXTENDED : 0) | REG_NOSUB; @@ -58,23 +45,18 @@ public: error = errbuf; delete[] errbuf; regfree(®buf); - throw POSIXRegexException(rx, error); + throw RegexException(rx, error); } } - virtual ~POSIXRegex() + ~POSIXRegex() { regfree(®buf); } - virtual bool Matches(const std::string& text) + bool Matches(const std::string& text) CXX11_OVERRIDE { - if (regexec(®buf, text.c_str(), 0, NULL, 0) == 0) - { - // Bang. :D - return true; - } - return false; + return (regexec(®buf, text.c_str(), 0, NULL, 0) == 0); } }; @@ -83,7 +65,7 @@ class PosixFactory : public RegexFactory public: bool extended; PosixFactory(Module* m) : RegexFactory(m, "regex/posix") {} - Regex* Create(const std::string& expr) + Regex* Create(const std::string& expr) CXX11_OVERRIDE { return new POSIXRegex(expr, extended); } @@ -92,20 +74,18 @@ class PosixFactory : public RegexFactory class ModuleRegexPOSIX : public Module { PosixFactory ref; -public: - ModuleRegexPOSIX() : ref(this) { - ServerInstance->Modules->AddService(ref); - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); + + public: + ModuleRegexPOSIX() : ref(this) + { } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Regex Provider Module for POSIX Regular Expressions", VF_VENDOR); } - void OnRehash(User* u) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ref.extended = ServerInstance->Config->ConfValue("posix")->getBool("extended"); } diff --git a/src/modules/extra/m_regex_re2.cpp b/src/modules/extra/m_regex_re2.cpp new file mode 100644 index 000000000..c4657bf8b --- /dev/null +++ b/src/modules/extra/m_regex_re2.cpp @@ -0,0 +1,81 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Peter Powell <petpow@saberuk.com> + * Copyright (C) 2012 ChrisTX <chris@rev-crew.info> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "modules/regex.h" + +// Fix warnings about the use of `long long` on C++03 and +// shadowing on GCC. +#if defined __clang__ +# pragma clang diagnostic ignored "-Wc++11-long-long" +#elif defined __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +# pragma GCC diagnostic ignored "-Wshadow" +#endif + +#include <re2/re2.h> + +/* $LinkerFlags: -lre2 */ + +class RE2Regex : public Regex +{ + RE2 regexcl; + + public: + RE2Regex(const std::string& rx) : Regex(rx), regexcl(rx, RE2::Quiet) + { + if (!regexcl.ok()) + { + throw RegexException(rx, regexcl.error()); + } + } + + bool Matches(const std::string& text) CXX11_OVERRIDE + { + return RE2::FullMatch(text, regexcl); + } +}; + +class RE2Factory : public RegexFactory +{ + public: + RE2Factory(Module* m) : RegexFactory(m, "regex/re2") { } + Regex* Create(const std::string& expr) CXX11_OVERRIDE + { + return new RE2Regex(expr); + } +}; + +class ModuleRegexRE2 : public Module +{ + RE2Factory ref; + + public: + ModuleRegexRE2() : ref(this) + { + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Regex Provider Module for RE2", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleRegexRE2) diff --git a/src/modules/extra/m_regex_stdlib.cpp b/src/modules/extra/m_regex_stdlib.cpp index 204728b65..8e7bd0da2 100644 --- a/src/modules/extra/m_regex_stdlib.cpp +++ b/src/modules/extra/m_regex_stdlib.cpp @@ -15,32 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - + #include "inspircd.h" -#include "m_regex.h" +#include "modules/regex.h" #include <regex> -/* $ModDesc: Regex Provider Module for std::regex Regular Expressions */ -/* $ModConfig: <stdregex type="ecmascript"> - * Specify the Regular Expression engine to use here. Valid settings are - * bre, ere, awk, grep, egrep, ecmascript (default if not specified)*/ /* $CompileFlags: -std=c++11 */ -/* $ModDep: m_regex.h */ - -class StdRegexException : public ModuleException -{ -public: - StdRegexException(const std::string& rx, const std::string& error) - : ModuleException(std::string("Error in regex ") + rx + ": " + error) - { - } -}; class StdRegex : public Regex { -private: std::regex regexcl; -public: + + public: StdRegex(const std::string& rx, std::regex::flag_type fltype) : Regex(rx) { try{ @@ -48,11 +34,11 @@ public: } catch(std::regex_error rxerr) { - throw StdRegexException(rx, rxerr.what()); + throw RegexException(rx, rxerr.what()); } } - - virtual bool Matches(const std::string& text) + + bool Matches(const std::string& text) CXX11_OVERRIDE { return std::regex_search(text, regexcl); } @@ -63,7 +49,7 @@ class StdRegexFactory : public RegexFactory public: std::regex::flag_type regextype; StdRegexFactory(Module* m) : RegexFactory(m, "regex/stdregex") {} - Regex* Create(const std::string& expr) + Regex* Create(const std::string& expr) CXX11_OVERRIDE { return new StdRegex(expr, regextype); } @@ -73,23 +59,20 @@ class ModuleRegexStd : public Module { public: StdRegexFactory ref; - ModuleRegexStd() : ref(this) { - ServerInstance->Modules->AddService(ref); - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); + ModuleRegexStd() : ref(this) + { } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Regex Provider Module for std::regex", VF_VENDOR); } - - void OnRehash(User* u) + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* Conf = ServerInstance->Config->ConfValue("stdregex"); std::string regextype = Conf->getString("type", "ecmascript"); - + if(regextype == "bre") ref.regextype = std::regex::basic; else if(regextype == "ere") diff --git a/src/modules/extra/m_regex_tre.cpp b/src/modules/extra/m_regex_tre.cpp index 4b9eab472..8a1d54248 100644 --- a/src/modules/extra/m_regex_tre.cpp +++ b/src/modules/extra/m_regex_tre.cpp @@ -19,27 +19,15 @@ #include "inspircd.h" -#include "m_regex.h" +#include "modules/regex.h" #include <sys/types.h> #include <tre/regex.h> -/* $ModDesc: Regex Provider Module for TRE Regular Expressions */ /* $CompileFlags: pkgconfincludes("tre","tre/regex.h","") */ /* $LinkerFlags: pkgconflibs("tre","/libtre.so","-ltre") rpath("pkg-config --libs tre") */ -/* $ModDep: m_regex.h */ - -class TRERegexException : public ModuleException -{ -public: - TRERegexException(const std::string& rx, const std::string& error) - : ModuleException("Error in regex " + rx + ": " + error) - { - } -}; class TRERegex : public Regex { -private: regex_t regbuf; public: @@ -60,30 +48,26 @@ public: error = errbuf; delete[] errbuf; regfree(®buf); - throw TRERegexException(rx, error); + throw RegexException(rx, error); } } - virtual ~TRERegex() + ~TRERegex() { regfree(®buf); } - virtual bool Matches(const std::string& text) + bool Matches(const std::string& text) CXX11_OVERRIDE { - if (regexec(®buf, text.c_str(), 0, NULL, 0) == 0) - { - // Bang. :D - return true; - } - return false; + return (regexec(®buf, text.c_str(), 0, NULL, 0) == 0); } }; -class TREFactory : public RegexFactory { +class TREFactory : public RegexFactory +{ public: TREFactory(Module* m) : RegexFactory(m, "regex/tre") {} - Regex* Create(const std::string& expr) + Regex* Create(const std::string& expr) CXX11_OVERRIDE { return new TRERegex(expr); } @@ -92,18 +76,15 @@ class TREFactory : public RegexFactory { class ModuleRegexTRE : public Module { TREFactory trf; -public: - ModuleRegexTRE() : trf(this) { - ServerInstance->Modules->AddService(trf); - } - Version GetVersion() + public: + ModuleRegexTRE() : trf(this) { - return Version("Regex Provider Module for TRE Regular Expressions", VF_VENDOR); } - ~ModuleRegexTRE() + Version GetVersion() CXX11_OVERRIDE { + return Version("Regex Provider Module for TRE Regular Expressions", VF_VENDOR); } }; diff --git a/src/modules/extra/m_sqlite3.cpp b/src/modules/extra/m_sqlite3.cpp index 1e3a65a18..05203da39 100644 --- a/src/modules/extra/m_sqlite3.cpp +++ b/src/modules/extra/m_sqlite3.cpp @@ -21,20 +21,26 @@ #include "inspircd.h" +#include "modules/sql.h" + +// Fix warnings about the use of `long long` on C++03. +#if defined __clang__ +# pragma clang diagnostic ignored "-Wc++11-long-long" +#elif defined __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +#endif + #include <sqlite3.h> -#include "sql.h" #ifdef _WIN32 # pragma comment(lib, "sqlite3.lib") #endif -/* $ModDesc: sqlite3 provider */ /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */ /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */ -/* $NoPedantic */ class SQLConn; -typedef std::map<std::string, SQLConn*> ConnMap; +typedef insp::flat_map<std::string, SQLConn*> ConnMap; class SQLite3Result : public SQLResult { @@ -48,16 +54,12 @@ class SQLite3Result : public SQLResult { } - ~SQLite3Result() - { - } - - virtual int Rows() + int Rows() { return rows; } - virtual bool GetRow(SQLEntries& result) + bool GetRow(SQLEntries& result) { if (currentrow < rows) { @@ -72,7 +74,7 @@ class SQLite3Result : public SQLResult } } - virtual void GetCols(std::vector<std::string>& result) + void GetCols(std::vector<std::string>& result) { result.assign(columns.begin(), columns.end()); } @@ -80,7 +82,6 @@ class SQLite3Result : public SQLResult class SQLConn : public SQLProvider { - private: sqlite3* conn; reference<ConfigTag> config; @@ -90,7 +91,7 @@ class SQLConn : public SQLProvider std::string host = tag->getString("hostname"); if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK) { - ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id")); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id")); conn = NULL; } } @@ -152,13 +153,13 @@ class SQLConn : public SQLProvider sqlite3_finalize(stmt); } - virtual void submit(SQLQuery* query, const std::string& q) + void submit(SQLQuery* query, const std::string& q) { Query(query, q); delete query; } - virtual void submit(SQLQuery* query, const std::string& q, const ParamL& p) + void submit(SQLQuery* query, const std::string& q, const ParamL& p) { std::string res; unsigned int param = 0; @@ -179,7 +180,7 @@ class SQLConn : public SQLProvider submit(query, res); } - virtual void submit(SQLQuery* query, const std::string& q, const ParamM& p) + void submit(SQLQuery* query, const std::string& q, const ParamM& p) { std::string res; for(std::string::size_type i = 0; i < q.length(); i++) @@ -209,23 +210,10 @@ class SQLConn : public SQLProvider class ModuleSQLite3 : public Module { - private: ConnMap conns; public: - ModuleSQLite3() - { - } - - void init() - { - ReadConf(); - - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleSQLite3() + ~ModuleSQLite3() { ClearConns(); } @@ -241,7 +229,7 @@ class ModuleSQLite3 : public Module conns.clear(); } - void ReadConf() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ClearConns(); ConfigTagList tags = ServerInstance->Config->ConfTags("database"); @@ -255,12 +243,7 @@ class ModuleSQLite3 : public Module } } - void OnRehash(User* user) - { - ReadConf(); - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("sqlite3 provider", VF_VENDOR); } diff --git a/src/modules/extra/m_ssl_gnutls.cpp b/src/modules/extra/m_ssl_gnutls.cpp index 59ac1acb3..d33403aba 100644 --- a/src/modules/extra/m_ssl_gnutls.cpp +++ b/src/modules/extra/m_ssl_gnutls.cpp @@ -22,117 +22,79 @@ #include "inspircd.h" -#include <gnutls/gnutls.h> -#include <gnutls/x509.h> -#include "ssl.h" -#include "m_cap.h" - -#ifdef _WIN32 -# pragma comment(lib, "libgnutls-28.lib") +#include "modules/ssl.h" +#include <memory> + +// Fix warnings about the use of commas at end of enumerator lists on C++03. +#if defined __clang__ +# pragma clang diagnostic ignored "-Wc++11-extensions" +#elif defined __GNUC__ +# pragma GCC diagnostic ignored "-pedantic" #endif -/* $ModDesc: Provides SSL support for clients */ -/* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --cflags") */ -/* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") iflt("pkg-config --modversion gnutls","2.12") exec("libgcrypt-config --libs") */ -/* $NoPedantic */ +#include <gnutls/gnutls.h> +#include <gnutls/x509.h> -#ifndef GNUTLS_VERSION_MAJOR -#define GNUTLS_VERSION_MAJOR LIBGNUTLS_VERSION_MAJOR -#define GNUTLS_VERSION_MINOR LIBGNUTLS_VERSION_MINOR -#define GNUTLS_VERSION_PATCH LIBGNUTLS_VERSION_PATCH +#ifndef GNUTLS_VERSION_NUMBER +#define GNUTLS_VERSION_NUMBER LIBGNUTLS_VERSION_NUMBER #endif -// These don't exist in older GnuTLS versions -#if ((GNUTLS_VERSION_MAJOR > 2) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR > 1) || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR == 1 && GNUTLS_VERSION_PATCH >= 7)) -#define GNUTLS_NEW_PRIO_API -#endif +// Check if the GnuTLS library is at least version major.minor.patch +#define INSPIRCD_GNUTLS_HAS_VERSION(major, minor, patch) (GNUTLS_VERSION_NUMBER >= ((major << 16) | (minor << 8) | patch)) -#if(GNUTLS_VERSION_MAJOR < 2) -typedef gnutls_certificate_credentials_t gnutls_certificate_credentials; -typedef gnutls_dh_params_t gnutls_dh_params; +#if INSPIRCD_GNUTLS_HAS_VERSION(2, 9, 8) +#define GNUTLS_HAS_MAC_GET_ID +#include <gnutls/crypto.h> #endif -#if (GNUTLS_VERSION_MAJOR > 2 || (GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR >= 12)) +#if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0) # define GNUTLS_HAS_RND -# include <gnutls/crypto.h> #else # include <gcrypt.h> #endif -enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED }; - -struct SSLConfig : public refcountbase -{ - gnutls_certificate_credentials_t x509_cred; - std::vector<gnutls_x509_crt_t> x509_certs; - gnutls_x509_privkey_t x509_key; - gnutls_dh_params_t dh_params; -#ifdef GNUTLS_NEW_PRIO_API - gnutls_priority_t priority; +#ifdef _WIN32 +# pragma comment(lib, "libgnutls-28.lib") #endif - SSLConfig() - : x509_cred(NULL) - , x509_key(NULL) - , dh_params(NULL) -#ifdef GNUTLS_NEW_PRIO_API - , priority(NULL) -#endif - { - } - - ~SSLConfig() - { - ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Destroying SSLConfig %p", (void*)this); - - if (x509_cred) - gnutls_certificate_free_credentials(x509_cred); - - for (unsigned int i = 0; i < x509_certs.size(); i++) - gnutls_x509_crt_deinit(x509_certs[i]); +/* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") eval("print `libgcrypt-config --cflags | tr -d \r` if `pkg-config --modversion gnutls 2>/dev/null | tr -d \r` lt '2.12'") */ +/* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") eval("print `libgcrypt-config --libs | tr -d \r` if `pkg-config --modversion gnutls 2>/dev/null | tr -d \r` lt '2.12'") */ - if (x509_key) - gnutls_x509_privkey_deinit(x509_key); - - if (dh_params) - gnutls_dh_params_deinit(dh_params); +// These don't exist in older GnuTLS versions +#if INSPIRCD_GNUTLS_HAS_VERSION(2, 1, 7) +#define GNUTLS_NEW_PRIO_API +#endif -#ifdef GNUTLS_NEW_PRIO_API - if (priority) - gnutls_priority_deinit(priority); +#if (!INSPIRCD_GNUTLS_HAS_VERSION(2, 0, 0)) +typedef gnutls_certificate_credentials_t gnutls_certificate_credentials; +typedef gnutls_dh_params_t gnutls_dh_params; #endif - } -}; -static reference<SSLConfig> currconf; +enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_HANDSHAKEN }; -static SSLConfig* GetSessionConfig(gnutls_session_t session); +#if INSPIRCD_GNUTLS_HAS_VERSION(2, 12, 0) +#define INSPIRCD_GNUTLS_HAS_VECTOR_PUSH +#define GNUTLS_NEW_CERT_CALLBACK_API +typedef gnutls_retr2_st cert_cb_last_param_type; +#else +typedef gnutls_retr_st cert_cb_last_param_type; +#endif -#if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) ) -static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs, - const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) { +#if INSPIRCD_GNUTLS_HAS_VERSION(3, 3, 5) +#define INSPIRCD_GNUTLS_HAS_RECV_PACKET +#endif - st->type = GNUTLS_CRT_X509; +#if INSPIRCD_GNUTLS_HAS_VERSION(2, 99, 0) +// The second parameter of gnutls_init() has changed in 2.99.0 from gnutls_connection_end_t to unsigned int +// (it became a general flags parameter) and the enum has been deprecated and generates a warning on use. +typedef unsigned int inspircd_gnutls_session_init_flags_t; #else -static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs, - const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) { - st->cert_type = GNUTLS_CRT_X509; - st->key_type = GNUTLS_PRIVKEY_X509; +typedef gnutls_connection_end_t inspircd_gnutls_session_init_flags_t; #endif - SSLConfig* conf = GetSessionConfig(session); - std::vector<gnutls_x509_crt_t>& x509_certs = conf->x509_certs; - st->ncerts = x509_certs.size(); - st->cert.x509 = &x509_certs[0]; - st->key.x509 = conf->x509_key; - st->deinit_all = 0; - - return 0; -} class RandGen : public HandlerBase2<void, char*, size_t> { public: - RandGen() {} void Call(char* buffer, size_t len) { #ifdef GNUTLS_HAS_RND @@ -143,746 +105,592 @@ class RandGen : public HandlerBase2<void, char*, size_t> } }; -/** Represents an SSL user's extra data - */ -class issl_session -{ -public: - StreamSocket* socket; - gnutls_session_t sess; - issl_status status; - reference<ssl_cert> cert; - reference<SSLConfig> config; - - issl_session() : socket(NULL), sess(NULL), status(ISSL_NONE) {} -}; - -static SSLConfig* GetSessionConfig(gnutls_session_t sess) -{ - issl_session* session = reinterpret_cast<issl_session*>(gnutls_transport_get_ptr(sess)); - return session->config; -} - -class CommandStartTLS : public SplitCommand +namespace GnuTLS { - public: - bool enabled; - CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS") + class Init { - enabled = true; - works_before_reg = true; - } + public: + Init() { gnutls_global_init(); } + ~Init() { gnutls_global_deinit(); } + }; - CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser *user) + class Exception : public ModuleException { - if (!enabled) - { - user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str()); - return CMD_FAILURE; - } + public: + Exception(const std::string& reason) + : ModuleException(reason) { } + }; - if (user->registered == REG_ALL) - { - user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str()); - } - else + void ThrowOnError(int errcode, const char* msg) + { + if (errcode < 0) { - if (!user->eh.GetIOHook()) - { - user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str()); - /* We need to flush the write buffer prior to adding the IOHook, - * otherwise we'll be sending this line inside the SSL session - which - * won't start its handshake until the client gets this line. Currently, - * we assume the write will not block here; this is usually safe, as - * STARTTLS is sent very early on in the registration phase, where the - * user hasn't built up much sendq. Handling a blocked write here would - * be very annoying. - */ - user->eh.DoWrite(); - user->eh.AddIOHook(creator); - creator->OnStreamSocketAccept(&user->eh, NULL, NULL); - } - else - user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str()); + std::string reason = msg; + reason.append(" :").append(gnutls_strerror(errcode)); + throw Exception(reason); } - - return CMD_FAILURE; } -}; -class ModuleSSLGnuTLS : public Module -{ - issl_session* sessions; - - gnutls_digest_algorithm_t hash; - - std::string sslports; - int dh_bits; + /** Used to create a gnutls_datum_t* from a std::string + */ + class Datum + { + gnutls_datum_t datum; - RandGen randhandler; - CommandStartTLS starttls; + public: + Datum(const std::string& dat) + { + datum.data = (unsigned char*)dat.data(); + datum.size = static_cast<unsigned int>(dat.length()); + } - GenericCap capHandler; - ServiceProvider iohook; + const gnutls_datum_t* get() const { return &datum; } + }; - inline static const char* UnknownIfNULL(const char* str) + class Hash { - return str ? str : "UNKNOWN"; - } + gnutls_digest_algorithm_t hash; - static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size) - { - issl_session* session = reinterpret_cast<issl_session*>(session_wrap); - if (session->socket->GetEventMask() & FD_READ_WILL_BLOCK) + public: + // Nothing to deallocate, constructor may throw freely + Hash(const std::string& hashname) { -#ifdef _WIN32 - gnutls_transport_set_errno(session->sess, EAGAIN); + // As older versions of gnutls can't do this, let's disable it where needed. +#ifdef GNUTLS_HAS_MAC_GET_ID + // As gnutls_digest_algorithm_t and gnutls_mac_algorithm_t are mapped 1:1, we can do this + // There is no gnutls_dig_get_id() at the moment, but it may come later + hash = (gnutls_digest_algorithm_t)gnutls_mac_get_id(hashname.c_str()); + if (hash == GNUTLS_DIG_UNKNOWN) + throw Exception("Unknown hash type " + hashname); + + // Check if the user is giving us something that is a valid MAC but not digest + gnutls_hash_hd_t is_digest; + if (gnutls_hash_init(&is_digest, hash) < 0) + throw Exception("Unknown hash type " + hashname); + gnutls_hash_deinit(is_digest, NULL); #else - errno = EAGAIN; + if (hashname == "md5") + hash = GNUTLS_DIG_MD5; + else if (hashname == "sha1") + hash = GNUTLS_DIG_SHA1; +#ifdef INSPIRCD_GNUTLS_ENABLE_SHA256_FINGERPRINT + else if (hashname == "sha256") + hash = GNUTLS_DIG_SHA256; +#endif + else + throw Exception("Unknown hash type " + hashname); #endif - return -1; } - int rv = ServerInstance->SE->Recv(session->socket, reinterpret_cast<char *>(buffer), size, 0); + gnutls_digest_algorithm_t get() const { return hash; } + }; -#ifdef _WIN32 - if (rv < 0) + class DHParams + { + gnutls_dh_params_t dh_params; + + DHParams() { - /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError() - * and then set errno appropriately. - * The gnutls library may also have a different errno variable than us, see - * gnutls_transport_set_errno(3). - */ - gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno); + ThrowOnError(gnutls_dh_params_init(&dh_params), "gnutls_dh_params_init() failed"); } -#endif - - if (rv < (int)size) - ServerInstance->SE->ChangeEventMask(session->socket, FD_READ_WILL_BLOCK); - return rv; - } - static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size) - { - issl_session* session = reinterpret_cast<issl_session*>(session_wrap); - if (session->socket->GetEventMask() & FD_WRITE_WILL_BLOCK) + public: + /** Import */ + static std::auto_ptr<DHParams> Import(const std::string& dhstr) { -#ifdef _WIN32 - gnutls_transport_set_errno(session->sess, EAGAIN); -#else - errno = EAGAIN; -#endif - return -1; + std::auto_ptr<DHParams> dh(new DHParams); + int ret = gnutls_dh_params_import_pkcs3(dh->dh_params, Datum(dhstr).get(), GNUTLS_X509_FMT_PEM); + ThrowOnError(ret, "Unable to import DH params"); + return dh; } - int rv = ServerInstance->SE->Send(session->socket, reinterpret_cast<const char *>(buffer), size, 0); - -#ifdef _WIN32 - if (rv < 0) + /** Generate */ + static std::auto_ptr<DHParams> Generate(unsigned int bits) { - /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError() - * and then set errno appropriately. - * The gnutls library may also have a different errno variable than us, see - * gnutls_transport_set_errno(3). - */ - gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno); + std::auto_ptr<DHParams> dh(new DHParams); + ThrowOnError(gnutls_dh_params_generate2(dh->dh_params, bits), "Unable to generate DH params"); + return dh; } -#endif - if (rv < (int)size) - ServerInstance->SE->ChangeEventMask(session->socket, FD_WRITE_WILL_BLOCK); - return rv; - } + ~DHParams() + { + gnutls_dh_params_deinit(dh_params); + } - public: + const gnutls_dh_params_t& get() const { return dh_params; } + }; - ModuleSSLGnuTLS() - : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK) + class X509Key { -#ifndef GNUTLS_HAS_RND - gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); -#endif - - sessions = new issl_session[ServerInstance->SE->GetMaxFds()]; - - gnutls_global_init(); // This must be called once in the program - } + /** Ensure that the key is deinited in case the constructor of X509Key throws + */ + class RAIIKey + { + public: + gnutls_x509_privkey_t key; - void init() - { - currconf = new SSLConfig; - InitSSLConfig(currconf); + RAIIKey() + { + ThrowOnError(gnutls_x509_privkey_init(&key), "gnutls_x509_privkey_init() failed"); + } - ServerInstance->GenRandom = &randhandler; + ~RAIIKey() + { + gnutls_x509_privkey_deinit(key); + } + } key; - Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect, - I_OnEvent, I_OnHookIO, I_OnCheckReady }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + public: + /** Import */ + X509Key(const std::string& keystr) + { + int ret = gnutls_x509_privkey_import(key.key, Datum(keystr).get(), GNUTLS_X509_FMT_PEM); + ThrowOnError(ret, "Unable to import private key"); + } - ServerInstance->Modules->AddService(iohook); - ServerInstance->Modules->AddService(starttls); - } + gnutls_x509_privkey_t& get() { return key.key; } + }; - void OnRehash(User* user) + class X509CertList { - sslports.clear(); + std::vector<gnutls_x509_crt_t> certs; - ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls"); - starttls.enabled = Conf->getBool("starttls", true); - - if (Conf->getBool("showports", true)) + public: + /** Import */ + X509CertList(const std::string& certstr) { - sslports = Conf->getString("advertisedports"); - if (!sslports.empty()) - return; + unsigned int certcount = 3; + certs.resize(certcount); + Datum datum(certstr); - for (size_t i = 0; i < ServerInstance->ports.size(); i++) + int ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED); + if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) { - ListenSocket* port = ServerInstance->ports[i]; - if (port->bind_tag->getString("ssl") != "gnutls") - continue; - - const std::string& portid = port->bind_desc; - ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str()); - - if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1") - { - /* - * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display - * the IP:port in ISUPPORT. - * - * We used to advertise all ports seperated by a ';' char that matched the above criteria, - * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed. - * To solve this by default we now only display the first IP:port found and let the user - * configure the exact value for the 005 token, if necessary. - */ - sslports = portid; - break; - } + // the buffer wasn't big enough to hold all certs but gnutls changed certcount to the number of available certs, + // try again with a bigger buffer + certs.resize(certcount); + ret = gnutls_x509_crt_list_import(raw(), &certcount, datum.get(), GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED); } - } - } - void OnModuleRehash(User* user, const std::string ¶m) - { - if(param != "ssl") - return; + ThrowOnError(ret, "Unable to load certificates"); - reference<SSLConfig> newconf = new SSLConfig; - try - { - InitSSLConfig(newconf); + // Resize the vector to the actual number of certs because we rely on its size being correct + // when deallocating the certs + certs.resize(certcount); } - catch (ModuleException& ex) + + ~X509CertList() { - ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Not applying new config. %s", ex.GetReason()); - return; + for (std::vector<gnutls_x509_crt_t>::iterator i = certs.begin(); i != certs.end(); ++i) + gnutls_x509_crt_deinit(*i); } - ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls: Applying new config, old config is in use by %d connection(s)", currconf->GetReferenceCount()-1); - currconf = newconf; - } + gnutls_x509_crt_t* raw() { return &certs[0]; } + unsigned int size() const { return certs.size(); } + }; - void InitSSLConfig(SSLConfig* config) + class X509CRL : public refcountbase { - ServerInstance->Logs->Log("m_ssl_gnutls", DEBUG, "Initializing new SSLConfig %p", (void*)config); - - std::string keyfile; - std::string certfile; - std::string cafile; - std::string crlfile; - OnRehash(NULL); - - ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls"); - - cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem"); - crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem"); - certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem"); - keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem"); - dh_bits = Conf->getInt("dhbits"); - std::string hashname = Conf->getString("hash", "md5"); - - // The GnuTLS manual states that the gnutls_set_default_priority() - // call we used previously when initializing the session is the same - // as setting the "NORMAL" priority string. - // Thus if the setting below is not in the config we will behave exactly - // the same as before, when the priority setting wasn't available. - std::string priorities = Conf->getString("priority", "NORMAL"); - - if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096)) - dh_bits = 1024; - - if (hashname == "md5") - hash = GNUTLS_DIG_MD5; - else if (hashname == "sha1") - hash = GNUTLS_DIG_SHA1; -#ifdef INSPIRCD_GNUTLS_ENABLE_SHA256_FINGERPRINT - else if (hashname == "sha256") - hash = GNUTLS_DIG_SHA256; -#endif - else - throw ModuleException("Unknown hash type " + hashname); - + class RAIICRL + { + public: + gnutls_x509_crl_t crl; - int ret; + RAIICRL() + { + ThrowOnError(gnutls_x509_crl_init(&crl), "gnutls_x509_crl_init() failed"); + } - gnutls_certificate_credentials_t& x509_cred = config->x509_cred; + ~RAIICRL() + { + gnutls_x509_crl_deinit(crl); + } + } crl; - ret = gnutls_certificate_allocate_credentials(&x509_cred); - if (ret < 0) + public: + /** Import */ + X509CRL(const std::string& crlstr) { - // Set to NULL because we can't be sure what value is in it and we must not try to - // deallocate it in case of an error - x509_cred = NULL; - throw ModuleException("Failed to allocate certificate credentials: " + std::string(gnutls_strerror(ret))); + int ret = gnutls_x509_crl_import(get(), Datum(crlstr).get(), GNUTLS_X509_FMT_PEM); + ThrowOnError(ret, "Unable to load certificate revocation list"); } - if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) - ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret)); - - if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) - ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret)); + gnutls_x509_crl_t& get() { return crl.crl; } + }; - FileReader reader; - - reader.LoadFile(certfile); - std::string cert_string = reader.Contents(); - gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) }; +#ifdef GNUTLS_NEW_PRIO_API + class Priority + { + gnutls_priority_t priority; - reader.LoadFile(keyfile); - std::string key_string = reader.Contents(); - gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) }; + public: + Priority(const std::string& priorities) + { + // Try to set the priorities for ciphers, kex methods etc. to the user supplied string + // If the user did not supply anything then the string is already set to "NORMAL" + const char* priocstr = priorities.c_str(); + const char* prioerror; - std::vector<gnutls_x509_crt_t>& x509_certs = config->x509_certs; + int ret = gnutls_priority_init(&priority, priocstr, &prioerror); + if (ret < 0) + { + // gnutls did not understand the user supplied string + throw Exception("Unable to initialize priorities to \"" + priorities + "\": " + gnutls_strerror(ret) + " Syntax error at position " + ConvToStr((unsigned int) (prioerror - priocstr))); + } + } - // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException - unsigned int certcount = 3; - x509_certs.resize(certcount); - ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED); - if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) + ~Priority() { - // the buffer wasn't big enough to hold all certs but gnutls updated certcount to the number of available certs, try again with a bigger buffer - x509_certs.resize(certcount); - ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED); + gnutls_priority_deinit(priority); } - if (ret <= 0) + void SetupSession(gnutls_session_t sess) { - // clear the vector so we won't call gnutls_x509_crt_deinit() on the (uninited) certs later - x509_certs.clear(); - throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + ((ret < 0) ? (std::string(gnutls_strerror(ret))) : "No certs could be read")); + gnutls_priority_set(sess, priority); } - x509_certs.resize(ret); - - gnutls_x509_privkey_t& x509_key = config->x509_key; - if (gnutls_x509_privkey_init(&x509_key) < 0) + }; +#else + /** Dummy class, used when gnutls_priority_set() is not available + */ + class Priority + { + public: + Priority(const std::string& priorities) { - // Make sure the destructor does not try to deallocate this, see above - x509_key = NULL; - throw ModuleException("Unable to initialize private key"); + if (priorities != "NORMAL") + throw Exception("You've set a non-default priority string, but GnuTLS lacks support for it"); } - if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0) - throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret))); - - if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0) - throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret))); - - #ifdef GNUTLS_NEW_PRIO_API - // Try to set the priorities for ciphers, kex methods etc. to the user supplied string - // If the user did not supply anything then the string is already set to "NORMAL" - const char* priocstr = priorities.c_str(); - const char* prioerror; - - gnutls_priority_t& priority = config->priority; - if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0) + static void SetupSession(gnutls_session_t sess) { - // gnutls did not understand the user supplied string, log and fall back to the default priorities - ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %u, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (unsigned int) (prioerror - priocstr)); - gnutls_priority_init(&priority, "NORMAL", NULL); + // Always set the default priorities + gnutls_set_default_priority(sess); } + }; +#endif - #else - if (priorities != "NORMAL") - ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: You've set <gnutls:priority> to a value other than the default, but this is only supported with GnuTLS v2.1.7 or newer. Your GnuTLS version is older than that so the option will have no effect."); - #endif + class CertCredentials + { + /** DH parameters associated with these credentials + */ + std::auto_ptr<DHParams> dh; - #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) ) - gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback); - #else - gnutls_certificate_set_retrieve_function (x509_cred, cert_callback); - #endif + protected: + gnutls_certificate_credentials_t cred; - gnutls_dh_params_t& dh_params = config->dh_params; - ret = gnutls_dh_params_init(&dh_params); - if (ret < 0) + public: + CertCredentials() { - // Make sure the destructor does not try to deallocate this, see above - dh_params = NULL; - ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret)); - return; + ThrowOnError(gnutls_certificate_allocate_credentials(&cred), "Cannot allocate certificate credentials"); } - std::string dhfile = Conf->getString("dhfile"); - if (!dhfile.empty()) + ~CertCredentials() { - // Try to load DH params from file - reader.LoadFile(dhfile); - std::string dhstring = reader.Contents(); - gnutls_datum_t dh_datum = { (unsigned char*)dhstring.data(), static_cast<unsigned int>(dhstring.length()) }; - - if ((ret = gnutls_dh_params_import_pkcs3(dh_params, &dh_datum, GNUTLS_X509_FMT_PEM)) < 0) - { - // File unreadable or GnuTLS was unhappy with the contents, generate the DH primes now - ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Generating DH parameters because I failed to load them from file '%s': %s", dhfile.c_str(), gnutls_strerror(ret)); - GenerateDHParams(dh_params); - } + gnutls_certificate_free_credentials(cred); } - else + + /** Associates these credentials with the session + */ + void SetupSession(gnutls_session_t sess) { - GenerateDHParams(dh_params); + gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, cred); } - gnutls_certificate_set_dh_params(x509_cred, dh_params); - } + /** Set the given DH parameters to be used with these credentials + */ + void SetDH(std::auto_ptr<DHParams>& DH) + { + dh = DH; + gnutls_certificate_set_dh_params(cred, dh->get()); + } + }; - void GenerateDHParams(gnutls_dh_params_t dh_params) + class X509Credentials : public CertCredentials { - // Generate Diffie Hellman parameters - for use with DHE - // kx algorithms. These should be discarded and regenerated - // once a day, once a week or once a month. Depending on the - // security requirements. + /** Private key + */ + X509Key key; - int ret; + /** Certificate list, presented to the peer + */ + X509CertList certs; - if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0) - ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret)); - } + /** Trusted CA, may be NULL + */ + std::auto_ptr<X509CertList> trustedca; - ~ModuleSSLGnuTLS() - { - currconf = NULL; + /** Certificate revocation list, may be NULL + */ + std::auto_ptr<X509CRL> crl; - gnutls_global_deinit(); - delete[] sessions; - ServerInstance->GenRandom = &ServerInstance->HandleGenRandom; - } + static int cert_callback(gnutls_session_t session, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st); - void OnCleanup(int target_type, void* item) - { - if(target_type == TYPE_USER) + public: + X509Credentials(const std::string& certstr, const std::string& keystr) + : key(keystr) + , certs(certstr) { - LocalUser* user = IS_LOCAL(static_cast<User*>(item)); + // Throwing is ok here, the destructor of Credentials is called in that case + int ret = gnutls_certificate_set_x509_key(cred, certs.raw(), certs.size(), key.get()); + ThrowOnError(ret, "Unable to set cert/key pair"); - if (user && user->eh.GetIOHook() == this) - { - // User is using SSL, they're a local user, and they're using one of *our* SSL ports. - // Potentially there could be multiple SSL modules loaded at once on different ports. - ServerInstance->Users->QuitUser(user, "SSL module unloading"); - } +#ifdef GNUTLS_NEW_CERT_CALLBACK_API + gnutls_certificate_set_retrieve_function(cred, cert_callback); +#else + gnutls_certificate_client_set_retrieve_function(cred, cert_callback); +#endif } - } - Version GetVersion() - { - return Version("Provides SSL support for clients", VF_VENDOR); - } + /** Sets the trusted CA and the certificate revocation list + * to use when verifying certificates + */ + void SetCA(std::auto_ptr<X509CertList>& certlist, std::auto_ptr<X509CRL>& CRL) + { + // Do nothing if certlist is NULL + if (certlist.get()) + { + int ret = gnutls_certificate_set_x509_trust(cred, certlist->raw(), certlist->size()); + ThrowOnError(ret, "gnutls_certificate_set_x509_trust() failed"); + if (CRL.get()) + { + ret = gnutls_certificate_set_x509_crl(cred, &CRL->get(), 1); + ThrowOnError(ret, "gnutls_certificate_set_x509_crl() failed"); + } - void On005Numeric(std::string &output) - { - if (!sslports.empty()) - output.append(" SSL=" + sslports); - if (starttls.enabled) - output.append(" STARTTLS"); - } + trustedca = certlist; + crl = CRL; + } + } + }; - void OnHookIO(StreamSocket* user, ListenSocket* lsb) + class DataReader { - if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls") + int retval; +#ifdef INSPIRCD_GNUTLS_HAS_RECV_PACKET + gnutls_packet_t packet; + + public: + DataReader(gnutls_session_t sess) { - /* Hook the user with our module */ - user->AddIOHook(this); + // Using the packet API avoids the final copy of the data which GnuTLS does if we supply + // our own buffer. Instead, we get the buffer containing the data from GnuTLS and copy it + // to the recvq directly from there in appendto(). + retval = gnutls_record_recv_packet(sess, &packet); } - } - void OnRequest(Request& request) - { - if (strcmp("GET_SSL_CERT", request.id) == 0) + void appendto(std::string& recvq) { - SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request); - int fd = req.sock->GetFd(); - issl_session* session = &sessions[fd]; + // Copy data from GnuTLS buffers to recvq + gnutls_datum_t datum; + gnutls_packet_get(packet, &datum, NULL); + recvq.append(reinterpret_cast<const char*>(datum.data), datum.size); - req.cert = session->cert; + gnutls_packet_deinit(packet); } - else if (!strcmp("GET_RAW_SSL_SESSION", request.id)) +#else + char* const buffer; + + public: + DataReader(gnutls_session_t sess) + : buffer(ServerInstance->GetReadBuffer()) { - SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request); - if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds())) - req.data = reinterpret_cast<void*>(sessions[req.fd].sess); + // Read data from GnuTLS buffers into ReadBuffer + retval = gnutls_record_recv(sess, buffer, ServerInstance->Config->NetBufferSize); } - } - - void InitSession(StreamSocket* user, bool me_server) - { - issl_session* session = &sessions[user->GetFd()]; - - gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT); - session->socket = user; - session->config = currconf; - - #ifdef GNUTLS_NEW_PRIO_API - gnutls_priority_set(session->sess, currconf->priority); - #else - gnutls_set_default_priority(session->sess); - #endif - gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, currconf->x509_cred); - gnutls_dh_set_prime_bits(session->sess, dh_bits); - gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(session)); - gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper); - gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper); - if (me_server) - gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any. + void appendto(std::string& recvq) + { + // Copy data from ReadBuffer to recvq + recvq.append(buffer, retval); + } +#endif - Handshake(session, user); - } + int ret() const { return retval; } + }; - void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) + class Profile : public refcountbase { - issl_session* session = &sessions[user->GetFd()]; - - /* For STARTTLS: Don't try and init a session on a socket that already has a session */ - if (session->sess) - return; - - InitSession(user, true); - } + /** Name of this profile + */ + const std::string name; - void OnStreamSocketConnect(StreamSocket* user) - { - InitSession(user, false); - } + /** X509 certificate(s) and key + */ + X509Credentials x509cred; - void OnStreamSocketClose(StreamSocket* user) - { - CloseSession(&sessions[user->GetFd()]); - } + /** The minimum length in bits for the DH prime to be accepted as a client + */ + unsigned int min_dh_bits; - int OnStreamSocketRead(StreamSocket* user, std::string& recvq) - { - issl_session* session = &sessions[user->GetFd()]; + /** Hashing algorithm to use when generating certificate fingerprints + */ + Hash hash; - if (!session->sess) + /** Priorities for ciphers, compression methods, etc. + */ + Priority priority; + + Profile(const std::string& profilename, const std::string& certstr, const std::string& keystr, + std::auto_ptr<DHParams>& DH, unsigned int mindh, const std::string& hashstr, + const std::string& priostr, std::auto_ptr<X509CertList>& CA, std::auto_ptr<X509CRL>& CRL) + : name(profilename) + , x509cred(certstr, keystr) + , min_dh_bits(mindh) + , hash(hashstr) + , priority(priostr) { - CloseSession(session); - user->SetError("No SSL session"); - return -1; + x509cred.SetDH(DH); + x509cred.SetCA(CA, CRL); } - if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) + static std::string ReadFile(const std::string& filename) { - // The handshake isn't finished, try to finish it. - - if(!Handshake(session, user)) - { - if (session->status != ISSL_CLOSING) - return 0; - return -1; - } + FileReader reader(filename); + std::string ret = reader.GetString(); + if (ret.empty()) + throw Exception("Cannot read file " + filename); + return ret; } - // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN. - - if (session->status == ISSL_HANDSHAKEN) + public: + static reference<Profile> Create(const std::string& profilename, ConfigTag* tag) { - char* buffer = ServerInstance->GetReadBuffer(); - size_t bufsiz = ServerInstance->Config->NetBufferSize; - int ret = gnutls_record_recv(session->sess, buffer, bufsiz); - if (ret > 0) - { - recvq.append(buffer, ret); - return 1; - } - else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) + std::string certstr = ReadFile(tag->getString("certfile", "cert.pem")); + std::string keystr = ReadFile(tag->getString("keyfile", "key.pem")); + + std::auto_ptr<DHParams> dh; + int gendh = tag->getInt("gendh"); + if (gendh) { - return 0; - } - else if (ret == 0) - { - user->SetError("Connection closed"); - CloseSession(session); - return -1; + gendh = (gendh < 1024 ? 1024 : gendh); + dh = DHParams::Generate(gendh); } else + dh = DHParams::Import(ReadFile(tag->getString("dhfile", "dhparams.pem"))); + + // Use default priority string if this tag does not specify one + std::string priostr = tag->getString("priority", "NORMAL"); + unsigned int mindh = tag->getInt("mindhbits", 1024); + std::string hashstr = tag->getString("hash", "md5"); + + // Load trusted CA and revocation list, if set + std::auto_ptr<X509CertList> ca; + std::auto_ptr<X509CRL> crl; + std::string filename = tag->getString("cafile"); + if (!filename.empty()) { - user->SetError(gnutls_strerror(ret)); - CloseSession(session); - return -1; - } - } - else if (session->status == ISSL_CLOSING) - return -1; - - return 0; - } + ca.reset(new X509CertList(ReadFile(filename))); - int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) - { - issl_session* session = &sessions[user->GetFd()]; + filename = tag->getString("crlfile"); + if (!filename.empty()) + crl.reset(new X509CRL(ReadFile(filename))); + } - if (!session->sess) - { - CloseSession(session); - user->SetError("No SSL session"); - return -1; + return new Profile(profilename, certstr, keystr, dh, mindh, hashstr, priostr, ca, crl); } - if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ) + /** Set up the given session with the settings in this profile + */ + void SetupSession(gnutls_session_t sess) { - // The handshake isn't finished, try to finish it. - Handshake(session, user); - if (session->status != ISSL_CLOSING) - return 0; - return -1; + priority.SetupSession(sess); + x509cred.SetupSession(sess); + gnutls_dh_set_prime_bits(sess, min_dh_bits); + + // Request client certificate if we are a server, no-op if we're a client + gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST); } - int ret = 0; + const std::string& GetName() const { return name; } + X509Credentials& GetX509Credentials() { return x509cred; } + gnutls_digest_algorithm_t GetHash() const { return hash.get(); } + }; +} - if (session->status == ISSL_HANDSHAKEN) - { - ret = gnutls_record_send(session->sess, sendq.data(), sendq.length()); +class GnuTLSIOHook : public SSLIOHook +{ + private: + gnutls_session_t sess; + issl_status status; + reference<GnuTLS::Profile> profile; - if (ret == (int)sendq.length()) - { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE); - return 1; - } - else if (ret > 0) - { - sendq = sendq.substr(ret); - ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE); - return 0; - } - else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0) - { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE); - return 0; - } - else // (ret < 0) - { - user->SetError(gnutls_strerror(ret)); - CloseSession(session); - return -1; - } + void CloseSession() + { + if (this->sess) + { + gnutls_bye(this->sess, GNUTLS_SHUT_WR); + gnutls_deinit(this->sess); } - - return 0; + sess = NULL; + certificate = NULL; + status = ISSL_NONE; } - bool Handshake(issl_session* session, StreamSocket* user) + // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed + int Handshake(StreamSocket* user) { - int ret = gnutls_handshake(session->sess); + int ret = gnutls_handshake(this->sess); if (ret < 0) { if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { // Handshake needs resuming later, read() or write() would have blocked. + this->status = ISSL_HANDSHAKING; - if(gnutls_record_get_direction(session->sess) == 0) + if (gnutls_record_get_direction(this->sess) == 0) { // gnutls_handshake() wants to read() again. - session->status = ISSL_HANDSHAKING_READ; - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); } else { // gnutls_handshake() wants to write() again. - session->status = ISSL_HANDSHAKING_WRITE; - ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); + SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); } + + return 0; } else { user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret))); - CloseSession(session); - session->status = ISSL_CLOSING; + CloseSession(); + return -1; } - - return false; } else { // Change the seesion state - session->status = ISSL_HANDSHAKEN; + this->status = ISSL_HANDSHAKEN; - VerifyCertificate(session,user); + VerifyCertificate(); // Finish writing, if any left - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE); + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE); - return true; + return 1; } } - void OnUserConnect(LocalUser* user) + void VerifyCertificate() { - if (user->eh.GetIOHook() == this) - { - if (sessions[user->eh.GetFd()].sess) - { - const gnutls_session_t& sess = sessions[user->eh.GetFd()].sess; - std::string cipher = UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess))); - cipher.append("-").append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).append("-"); - cipher.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess)))); - - ssl_cert* cert = sessions[user->eh.GetFd()].cert; - if (cert->fingerprint.empty()) - user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str()); - else - user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"" - " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str()); - } - } - } - - void CloseSession(issl_session* session) - { - if (session->sess) - { - gnutls_bye(session->sess, GNUTLS_SHUT_WR); - gnutls_deinit(session->sess); - } - session->socket = NULL; - session->sess = NULL; - session->cert = NULL; - session->status = ISSL_NONE; - session->config = NULL; - } - - void VerifyCertificate(issl_session* session, StreamSocket* user) - { - if (!session->sess || !user) - return; - - unsigned int status; + unsigned int certstatus; const gnutls_datum_t* cert_list; int ret; unsigned int cert_list_size; gnutls_x509_crt_t cert; - char name[MAXBUF]; - unsigned char digest[MAXBUF]; + char str[512]; + unsigned char digest[512]; size_t digest_size = sizeof(digest); - size_t name_size = sizeof(name); + size_t name_size = sizeof(str); ssl_cert* certinfo = new ssl_cert; - session->cert = certinfo; + this->certificate = certinfo; /* This verification function uses the trusted CAs in the credentials * structure. So you must have installed one or more CA certificates. */ - ret = gnutls_certificate_verify_peers2(session->sess, &status); + ret = gnutls_certificate_verify_peers2(this->sess, &certstatus); if (ret < 0) { @@ -890,16 +698,16 @@ class ModuleSSLGnuTLS : public Module return; } - certinfo->invalid = (status & GNUTLS_CERT_INVALID); - certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND); - certinfo->revoked = (status & GNUTLS_CERT_REVOKED); - certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA); + certinfo->invalid = (certstatus & GNUTLS_CERT_INVALID); + certinfo->unknownsigner = (certstatus & GNUTLS_CERT_SIGNER_NOT_FOUND); + certinfo->revoked = (certstatus & GNUTLS_CERT_REVOKED); + certinfo->trusted = !(certstatus & GNUTLS_CERT_SIGNER_NOT_CA); /* Up to here the process is the same for X.509 certificates and * OpenPGP keys. From now on X.509 certificates are assumed. This can * be easily extended to work with openpgp keys as well. */ - if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509) + if (gnutls_certificate_type_get(this->sess) != GNUTLS_CRT_X509) { certinfo->error = "No X509 keys sent"; return; @@ -913,7 +721,7 @@ class ModuleSSLGnuTLS : public Module } cert_list_size = 0; - cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size); + cert_list = gnutls_certificate_get_peers(this->sess, &cert_list_size); if (cert_list == NULL) { certinfo->error = "No certificate was found"; @@ -931,31 +739,31 @@ class ModuleSSLGnuTLS : public Module goto info_done_dealloc; } - if (gnutls_x509_crt_get_dn(cert, name, &name_size) == 0) + if (gnutls_x509_crt_get_dn(cert, str, &name_size) == 0) { std::string& dn = certinfo->dn; - dn = name; + dn = str; // Make sure there are no chars in the string that we consider invalid if (dn.find_first_of("\r\n") != std::string::npos) dn.clear(); } - name_size = sizeof(name); - if (gnutls_x509_crt_get_issuer_dn(cert, name, &name_size) == 0) + name_size = sizeof(str); + if (gnutls_x509_crt_get_issuer_dn(cert, str, &name_size) == 0) { std::string& issuer = certinfo->issuer; - issuer = name; + issuer = str; if (issuer.find_first_of("\r\n") != std::string::npos) issuer.clear(); } - if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0) + if ((ret = gnutls_x509_crt_get_fingerprint(cert, profile->GetHash(), digest, &digest_size)) < 0) { certinfo->error = gnutls_strerror(ret); } else { - certinfo->fingerprint = irc::hex(digest, digest_size); + certinfo->fingerprint = BinToHex(digest, digest_size); } /* Beware here we do not check for errors. @@ -969,16 +777,444 @@ info_done_dealloc: gnutls_x509_crt_deinit(cert); } - void OnEvent(Event& ev) + // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error + int PrepareIO(StreamSocket* sock) { - if (starttls.enabled) - capHandler.HandleEvent(ev); + if (status == ISSL_HANDSHAKEN) + return 1; + else if (status == ISSL_HANDSHAKING) + { + // The handshake isn't finished, try to finish it + return Handshake(sock); + } + + CloseSession(); + sock->SetError("No SSL session"); + return -1; + } + + static const char* UnknownIfNULL(const char* str) + { + return str ? str : "UNKNOWN"; } - ModResult OnCheckReady(LocalUser* user) + static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t session_wrap, void* buffer, size_t size) { - if ((user->eh.GetIOHook() == this) && (sessions[user->eh.GetFd()].status != ISSL_HANDSHAKEN)) - return MOD_RES_DENY; + StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap); +#ifdef _WIN32 + GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook()); +#endif + + if (sock->GetEventMask() & FD_READ_WILL_BLOCK) + { +#ifdef _WIN32 + gnutls_transport_set_errno(session->sess, EAGAIN); +#else + errno = EAGAIN; +#endif + return -1; + } + + int rv = SocketEngine::Recv(sock, reinterpret_cast<char *>(buffer), size, 0); + +#ifdef _WIN32 + if (rv < 0) + { + /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError() + * and then set errno appropriately. + * The gnutls library may also have a different errno variable than us, see + * gnutls_transport_set_errno(3). + */ + gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno); + } +#endif + + if (rv < (int)size) + SocketEngine::ChangeEventMask(sock, FD_READ_WILL_BLOCK); + return rv; + } + +#ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH + static ssize_t VectorPush(gnutls_transport_ptr_t transportptr, const giovec_t* iov, int iovcnt) + { + StreamSocket* sock = reinterpret_cast<StreamSocket*>(transportptr); +#ifdef _WIN32 + GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook()); +#endif + + if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK) + { +#ifdef _WIN32 + gnutls_transport_set_errno(session->sess, EAGAIN); +#else + errno = EAGAIN; +#endif + return -1; + } + + // Cast the giovec_t to iovec not to IOVector so the correct function is called on Windows + int ret = SocketEngine::WriteV(sock, reinterpret_cast<const iovec*>(iov), iovcnt); +#ifdef _WIN32 + // See the function above for more info about the usage of gnutls_transport_set_errno() on Windows + if (ret < 0) + gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno); +#endif + + int size = 0; + for (int i = 0; i < iovcnt; i++) + size += iov[i].iov_len; + + if (ret < size) + SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK); + return ret; + } + +#else // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH + static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t session_wrap, const void* buffer, size_t size) + { + StreamSocket* sock = reinterpret_cast<StreamSocket*>(session_wrap); +#ifdef _WIN32 + GnuTLSIOHook* session = static_cast<GnuTLSIOHook*>(sock->GetIOHook()); +#endif + + if (sock->GetEventMask() & FD_WRITE_WILL_BLOCK) + { +#ifdef _WIN32 + gnutls_transport_set_errno(session->sess, EAGAIN); +#else + errno = EAGAIN; +#endif + return -1; + } + + int rv = SocketEngine::Send(sock, reinterpret_cast<const char *>(buffer), size, 0); + +#ifdef _WIN32 + if (rv < 0) + { + /* Windows doesn't use errno, but gnutls does, so check SocketEngine::IgnoreError() + * and then set errno appropriately. + * The gnutls library may also have a different errno variable than us, see + * gnutls_transport_set_errno(3). + */ + gnutls_transport_set_errno(session->sess, SocketEngine::IgnoreError() ? EAGAIN : errno); + } +#endif + + if (rv < (int)size) + SocketEngine::ChangeEventMask(sock, FD_WRITE_WILL_BLOCK); + return rv; + } +#endif // INSPIRCD_GNUTLS_HAS_VECTOR_PUSH + + public: + GnuTLSIOHook(IOHookProvider* hookprov, StreamSocket* sock, inspircd_gnutls_session_init_flags_t flags, const reference<GnuTLS::Profile>& sslprofile) + : SSLIOHook(hookprov) + , sess(NULL) + , status(ISSL_NONE) + , profile(sslprofile) + { + gnutls_init(&sess, flags); + gnutls_transport_set_ptr(sess, reinterpret_cast<gnutls_transport_ptr_t>(sock)); +#ifdef INSPIRCD_GNUTLS_HAS_VECTOR_PUSH + gnutls_transport_set_vec_push_function(sess, VectorPush); +#else + gnutls_transport_set_push_function(sess, gnutls_push_wrapper); +#endif + gnutls_transport_set_pull_function(sess, gnutls_pull_wrapper); + profile->SetupSession(sess); + + sock->AddIOHook(this); + Handshake(sock); + } + + void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE + { + CloseSession(); + } + + int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE + { + // Finish handshake if needed + int prepret = PrepareIO(user); + if (prepret <= 0) + return prepret; + + // If we resumed the handshake then this->status will be ISSL_HANDSHAKEN. + { + GnuTLS::DataReader reader(sess); + int ret = reader.ret(); + if (ret > 0) + { + reader.appendto(recvq); + return 1; + } + else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) + { + return 0; + } + else if (ret == 0) + { + user->SetError("Connection closed"); + CloseSession(); + return -1; + } + else + { + user->SetError(gnutls_strerror(ret)); + CloseSession(); + return -1; + } + } + } + + int OnStreamSocketWrite(StreamSocket* user, std::string& sendq) CXX11_OVERRIDE + { + // Finish handshake if needed + int prepret = PrepareIO(user); + if (prepret <= 0) + return prepret; + + // Session is ready for transferring application data + int ret = 0; + + { + ret = gnutls_record_send(this->sess, sendq.data(), sendq.length()); + + if (ret == (int)sendq.length()) + { + SocketEngine::ChangeEventMask(user, FD_WANT_NO_WRITE); + return 1; + } + else if (ret > 0) + { + sendq.erase(0, ret); + SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE); + return 0; + } + else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0) + { + SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE); + return 0; + } + else // (ret < 0) + { + user->SetError(gnutls_strerror(ret)); + CloseSession(); + return -1; + } + } + } + + void TellCiphersAndFingerprint(LocalUser* user) + { + if (sess) + { + std::string text = "*** You are connected using SSL cipher '"; + GetCiphersuite(text); + text += '\''; + if (!certificate->fingerprint.empty()) + text += " and your SSL certificate fingerprint is " + certificate->fingerprint; + + user->WriteNotice(text); + } + } + + void GetCiphersuite(std::string& out) const + { + out.append(UnknownIfNULL(gnutls_protocol_get_name(gnutls_protocol_get_version(sess)))).push_back('-'); + out.append(UnknownIfNULL(gnutls_kx_get_name(gnutls_kx_get(sess)))).push_back('-'); + out.append(UnknownIfNULL(gnutls_cipher_get_name(gnutls_cipher_get(sess)))).push_back('-'); + out.append(UnknownIfNULL(gnutls_mac_get_name(gnutls_mac_get(sess)))); + } + + GnuTLS::Profile* GetProfile() { return profile; } + bool IsHandshakeDone() const { return (status == ISSL_HANDSHAKEN); } +}; + +int GnuTLS::X509Credentials::cert_callback(gnutls_session_t sess, const gnutls_datum_t* req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t* sign_algos, int sign_algos_length, cert_cb_last_param_type* st) +{ +#ifndef GNUTLS_NEW_CERT_CALLBACK_API + st->type = GNUTLS_CRT_X509; +#else + st->cert_type = GNUTLS_CRT_X509; + st->key_type = GNUTLS_PRIVKEY_X509; +#endif + StreamSocket* sock = reinterpret_cast<StreamSocket*>(gnutls_transport_get_ptr(sess)); + GnuTLS::X509Credentials& cred = static_cast<GnuTLSIOHook*>(sock->GetIOHook())->GetProfile()->GetX509Credentials(); + + st->ncerts = cred.certs.size(); + st->cert.x509 = cred.certs.raw(); + st->key.x509 = cred.key.get(); + st->deinit_all = 0; + + return 0; +} + +class GnuTLSIOHookProvider : public refcountbase, public IOHookProvider +{ + reference<GnuTLS::Profile> profile; + + public: + GnuTLSIOHookProvider(Module* mod, reference<GnuTLS::Profile>& prof) + : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL) + , profile(prof) + { + ServerInstance->Modules->AddService(*this); + } + + ~GnuTLSIOHookProvider() + { + ServerInstance->Modules->DelService(*this); + } + + void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE + { + new GnuTLSIOHook(this, sock, GNUTLS_SERVER, profile); + } + + void OnConnect(StreamSocket* sock) CXX11_OVERRIDE + { + new GnuTLSIOHook(this, sock, GNUTLS_CLIENT, profile); + } +}; + +class ModuleSSLGnuTLS : public Module +{ + typedef std::vector<reference<GnuTLSIOHookProvider> > ProfileList; + + // First member of the class, gets constructed first and destructed last + GnuTLS::Init libinit; + RandGen randhandler; + ProfileList profiles; + + void ReadProfiles() + { + // First, store all profiles in a new, temporary container. If no problems occur, swap the two + // containers; this way if something goes wrong we can go back and continue using the current profiles, + // avoiding unpleasant situations where no new SSL connections are possible. + ProfileList newprofiles; + + ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile"); + if (tags.first == tags.second) + { + // No <sslprofile> tags found, create a profile named "gnutls" from settings in the <gnutls> block + const std::string defname = "gnutls"; + ConfigTag* tag = ServerInstance->Config->ConfValue(defname); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found; using settings from the <gnutls> tag"); + + try + { + reference<GnuTLS::Profile> profile(GnuTLS::Profile::Create(defname, tag)); + newprofiles.push_back(new GnuTLSIOHookProvider(this, profile)); + } + catch (CoreException& ex) + { + throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason()); + } + } + + for (ConfigIter i = tags.first; i != tags.second; ++i) + { + ConfigTag* tag = i->second; + if (tag->getString("provider") != "gnutls") + continue; + + std::string name = tag->getString("name"); + if (name.empty()) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation()); + continue; + } + + reference<GnuTLS::Profile> profile; + try + { + profile = GnuTLS::Profile::Create(name, tag); + } + catch (CoreException& ex) + { + throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason()); + } + + newprofiles.push_back(new GnuTLSIOHookProvider(this, profile)); + } + + // New profiles are ok, begin using them + // Old profiles are deleted when their refcount drops to zero + profiles.swap(newprofiles); + } + + public: + ModuleSSLGnuTLS() + { +#ifndef GNUTLS_HAS_RND + gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); +#endif + } + + void init() CXX11_OVERRIDE + { + ReadProfiles(); + ServerInstance->GenRandom = &randhandler; + } + + void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE + { + if(param != "ssl") + return; + + try + { + ReadProfiles(); + } + catch (ModuleException& ex) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings."); + } + } + + ~ModuleSSLGnuTLS() + { + ServerInstance->GenRandom = &ServerInstance->HandleGenRandom; + } + + void OnCleanup(int target_type, void* item) CXX11_OVERRIDE + { + if(target_type == TYPE_USER) + { + LocalUser* user = IS_LOCAL(static_cast<User*>(item)); + + if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this) + { + // User is using SSL, they're a local user, and they're using one of *our* SSL ports. + // Potentially there could be multiple SSL modules loaded at once on different ports. + ServerInstance->Users->QuitUser(user, "SSL module unloading"); + } + } + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides SSL support for clients", VF_VENDOR); + } + + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE + { + IOHook* hook = user->eh.GetIOHook(); + if (hook && hook->prov->creator == this) + static_cast<GnuTLSIOHook*>(hook)->TellCiphersAndFingerprint(user); + } + + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE + { + if ((user->eh.GetIOHook()) && (user->eh.GetIOHook()->prov->creator == this)) + { + GnuTLSIOHook* iohook = static_cast<GnuTLSIOHook*>(user->eh.GetIOHook()); + if (!iohook->IsHandshakeDone()) + return MOD_RES_DENY; + } + return MOD_RES_PASSTHRU; } }; diff --git a/src/modules/extra/m_ssl_openssl.cpp b/src/modules/extra/m_ssl_openssl.cpp index b21091d3f..c8a035fac 100644 --- a/src/modules/extra/m_ssl_openssl.cpp +++ b/src/modules/extra/m_ssl_openssl.cpp @@ -21,829 +21,834 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - /* HACK: This prevents OpenSSL on OS X 10.7 and later from spewing deprecation - * warnings for every single function call. As far as I (SaberUK) know, Apple - * have no plans to remove OpenSSL so this warning just causes needless spam. - */ -#ifdef __APPLE__ -# define __AVAILABILITYMACROS__ -# define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER -#endif - + #include "inspircd.h" +#include "iohook.h" +#include "modules/ssl.h" + +// Ignore OpenSSL deprecation warnings on OS X Lion and newer. +#if defined __APPLE__ +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + +// Fix warnings about the use of `long long` on C++03. +#if defined __clang__ +# pragma clang diagnostic ignored "-Wc++11-long-long" +#elif defined __GNUC__ +# pragma GCC diagnostic ignored "-Wlong-long" +#endif + #include <openssl/ssl.h> #include <openssl/err.h> -#include "ssl.h" #ifdef _WIN32 # pragma comment(lib, "ssleay32.lib") # pragma comment(lib, "libeay32.lib") -# undef MAX_DESCRIPTORS -# define MAX_DESCRIPTORS 10000 #endif -/* $ModDesc: Provides SSL support for clients */ - -/* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */ -/* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */ -/* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */ - -/* $NoPedantic */ - - -class ModuleSSLOpenSSL; +/* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */ +/* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto") */ enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN }; static bool SelfSigned = false; - -#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION -static ModuleSSLOpenSSL* opensslmod = NULL; -#endif +static int exdataindex; char* get_error() { return ERR_error_string(ERR_get_error(), NULL); } -static int error_callback(const char *str, size_t len, void *u); +static int OnVerify(int preverify_ok, X509_STORE_CTX* ctx); +static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc); -/** Represents an SSL user's extra data - */ -class issl_session +namespace OpenSSL { -public: - SSL* sess; - issl_status status; - reference<ssl_cert> cert; - - bool outbound; - bool data_to_write; - - issl_session() - : sess(NULL) - , status(ISSL_NONE) + class Exception : public ModuleException { - outbound = false; - data_to_write = false; - } -}; - -static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx) -{ - /* XXX: This will allow self signed certificates. - * In the future if we want an option to not allow this, - * we can just return preverify_ok here, and openssl - * will boot off self-signed and invalid peer certs. - */ - int ve = X509_STORE_CTX_get_error(ctx); + public: + Exception(const std::string& reason) + : ModuleException(reason) { } + }; - SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT); - - return 1; -} + class DHParams + { + DH* dh; -class ModuleSSLOpenSSL : public Module -{ - issl_session* sessions; + public: + DHParams(const std::string& filename) + { + BIO* dhpfile = BIO_new_file(filename.c_str(), "r"); + if (dhpfile == NULL) + throw Exception("Couldn't open DH file " + filename); - SSL_CTX* ctx; - SSL_CTX* clictx; + dh = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL); + BIO_free(dhpfile); - long ctx_options; - long clictx_options; + if (!dh) + throw Exception("Couldn't read DH params from file " + filename); + } - std::string sslports; - bool use_sha; + ~DHParams() + { + DH_free(dh); + } - ServiceProvider iohook; + DH* get() + { + return dh; + } + }; - static void SetContextOptions(SSL_CTX* ctx, long defoptions, const std::string& ctxname, ConfigTag* tag) + class Context { - long setoptions = tag->getInt(ctxname + "setoptions"); - // User-friendly config options for setting context options -#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE - if (tag->getBool("cipherserverpref")) - setoptions |= SSL_OP_CIPHER_SERVER_PREFERENCE; + SSL_CTX* const ctx; + long ctx_options; + + public: + Context(SSL_CTX* context) + : ctx(context) + { + // Sane default options for OpenSSL see https://www.openssl.org/docs/ssl/SSL_CTX_set_options.html + // and when choosing a cipher, use the server's preferences instead of the client preferences. + long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE; + // Only turn options on if they exist +#ifdef SSL_OP_SINGLE_ECDH_USE + opts |= SSL_OP_SINGLE_ECDH_USE; #endif -#ifdef SSL_OP_NO_COMPRESSION - if (!tag->getBool("compression", true)) - setoptions |= SSL_OP_NO_COMPRESSION; +#ifdef SSL_OP_NO_TICKET + opts |= SSL_OP_NO_TICKET; #endif - if (!tag->getBool("sslv3", true)) - setoptions |= SSL_OP_NO_SSLv3; - if (!tag->getBool("tlsv1", true)) - setoptions |= SSL_OP_NO_TLSv1; - long clearoptions = tag->getInt(ctxname + "clearoptions"); - ServerInstance->Logs->Log("m_ssl_openssl", DEBUG, "Setting OpenSSL %s context options, default: %ld set: %ld clear: %ld", ctxname.c_str(), defoptions, setoptions, clearoptions); + ctx_options = SSL_CTX_set_options(ctx, opts); + SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify); + SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); + SSL_CTX_set_info_callback(ctx, StaticSSLInfoCallback); + } - // Clear everything - SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx)); + ~Context() + { + SSL_CTX_free(ctx); + } - // Set the default options and what is in the conf - SSL_CTX_set_options(ctx, defoptions | setoptions); - long final = SSL_CTX_clear_options(ctx, clearoptions); - ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "OpenSSL %s context options: %ld", ctxname.c_str(), final); - } + bool SetDH(DHParams& dh) + { + ERR_clear_error(); + return (SSL_CTX_set_tmp_dh(ctx, dh.get()) >= 0); + } #ifdef INSPIRCD_OPENSSL_ENABLE_ECDH - void SetupECDH(ConfigTag* tag) - { - std::string curvename = tag->getString("ecdhcurve", "prime256v1"); - if (curvename.empty()) - return; - - int nid = OBJ_sn2nid(curvename.c_str()); - if (nid == 0) + void SetECDH(const std::string& curvename) { - ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Unknown curve: \"%s\"", curvename.c_str()); - return; + int nid = OBJ_sn2nid(curvename.c_str()); + if (nid == 0) + throw Exception("Unknown curve: " + curvename); + + EC_KEY* eckey = EC_KEY_new_by_curve_name(nid); + if (!eckey) + throw Exception("Unable to create EC key object"); + + ERR_clear_error(); + bool ret = (SSL_CTX_set_tmp_ecdh(ctx, eckey) >= 0); + EC_KEY_free(eckey); + if (!ret) + throw Exception("Couldn't set ECDH parameters"); } +#endif - EC_KEY* eckey = EC_KEY_new_by_curve_name(nid); - if (!eckey) + bool SetCiphers(const std::string& ciphers) { - ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Unable to create EC key object"); - return; + ERR_clear_error(); + return SSL_CTX_set_cipher_list(ctx, ciphers.c_str()); } - ERR_clear_error(); - if (SSL_CTX_set_tmp_ecdh(ctx, eckey) < 0) + bool SetCerts(const std::string& filename) { - ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Couldn't set ECDH parameters"); - ERR_print_errors_cb(error_callback, this); + ERR_clear_error(); + return SSL_CTX_use_certificate_chain_file(ctx, filename.c_str()); } - EC_KEY_free(eckey); - } -#endif - -#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION - static void SSLInfoCallback(const SSL* ssl, int where, int rc) - { - int fd = SSL_get_fd(const_cast<SSL*>(ssl)); - issl_session& session = opensslmod->sessions[fd]; + bool SetPrivateKey(const std::string& filename) + { + ERR_clear_error(); + return SSL_CTX_use_PrivateKey_file(ctx, filename.c_str(), SSL_FILETYPE_PEM); + } - if ((where & SSL_CB_HANDSHAKE_START) && (session.status == ISSL_OPEN)) + bool SetCA(const std::string& filename) { - // The other side is trying to renegotiate, kill the connection and change status - // to ISSL_NONE so CheckRenego() closes the session - session.status = ISSL_NONE; - ServerInstance->SE->Shutdown(fd, 2); + ERR_clear_error(); + return SSL_CTX_load_verify_locations(ctx, filename.c_str(), 0); } - } - bool CheckRenego(StreamSocket* sock, issl_session* session) - { - if (session->status != ISSL_NONE) - return true; + long GetDefaultContextOptions() const + { + return ctx_options; + } - ServerInstance->Logs->Log("m_ssl_openssl", DEBUG, "Session %p killed, attempted to renegotiate", (void*)session->sess); - CloseSession(session); - sock->SetError("Renegotiation is not allowed"); - return false; - } -#endif + long SetRawContextOptions(long setoptions, long clearoptions) + { + // Clear everything + SSL_CTX_clear_options(ctx, SSL_CTX_get_options(ctx)); - public: + // Set the default options and what is in the conf + SSL_CTX_set_options(ctx, ctx_options | setoptions); + return SSL_CTX_clear_options(ctx, clearoptions); + } - ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK) - { -#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION - opensslmod = this; -#endif - sessions = new issl_session[ServerInstance->SE->GetMaxFds()]; + SSL* CreateServerSession() + { + SSL* sess = SSL_new(ctx); + SSL_set_accept_state(sess); // Act as server + return sess; + } - /* Global SSL library initialization*/ - SSL_library_init(); - SSL_load_error_strings(); + SSL* CreateClientSession() + { + SSL* sess = SSL_new(ctx); + SSL_set_connect_state(sess); // Act as client + return sess; + } + }; - /* Build our SSL contexts: - * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK. + class Profile : public refcountbase + { + /** Name of this profile */ - ctx = SSL_CTX_new( SSLv23_server_method() ); - clictx = SSL_CTX_new( SSLv23_client_method() ); - - SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); - SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); + const std::string name; - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify); - SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify); + /** DH parameters in use + */ + DHParams dh; - SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); - SSL_CTX_set_session_cache_mode(clictx, SSL_SESS_CACHE_OFF); + /** OpenSSL makes us have two contexts, one for servers and one for clients + */ + Context ctx; + Context clictx; - long opts = SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE; - // Only turn options on if they exist -#ifdef SSL_OP_SINGLE_ECDH_USE - opts |= SSL_OP_SINGLE_ECDH_USE; -#endif -#ifdef SSL_OP_NO_TICKET - opts |= SSL_OP_NO_TICKET; -#endif + /** Digest to use when generating fingerprints + */ + const EVP_MD* digest; - ctx_options = SSL_CTX_set_options(ctx, opts); - clictx_options = SSL_CTX_set_options(clictx, opts); - } + /** Last error, set by error_callback() + */ + std::string lasterr; - void init() - { - // Needs the flag as it ignores a plain /rehash - OnModuleRehash(NULL,"ssl"); - Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - ServerInstance->Modules->AddService(iohook); - } + /** True if renegotiations are allowed, false if not + */ + const bool allowrenego; - void OnHookIO(StreamSocket* user, ListenSocket* lsb) - { - if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl") + static int error_callback(const char* str, size_t len, void* u) { - /* Hook the user with our module */ - user->AddIOHook(this); + Profile* profile = reinterpret_cast<Profile*>(u); + profile->lasterr = std::string(str, len - 1); + return 0; } - } - void OnRehash(User* user) - { - sslports.clear(); + /** Set raw OpenSSL context (SSL_CTX) options from a config tag + * @param ctxname Name of the context, client or server + * @param tag Config tag defining this profile + * @param context Context object to manipulate + */ + void SetContextOptions(const std::string& ctxname, ConfigTag* tag, Context& context) + { + long setoptions = tag->getInt(ctxname + "setoptions"); + long clearoptions = tag->getInt(ctxname + "clearoptions"); +#ifdef SSL_OP_NO_COMPRESSION + if (!tag->getBool("compression", true)) + setoptions |= SSL_OP_NO_COMPRESSION; +#endif + if (!tag->getBool("sslv3", true)) + setoptions |= SSL_OP_NO_SSLv3; + if (!tag->getBool("tlsv1", true)) + setoptions |= SSL_OP_NO_TLSv1; - ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl"); + if (!setoptions && !clearoptions) + return; // Nothing to do -#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION - // Set the callback if we are not allowing renegotiations, unset it if we do - if (Conf->getBool("renegotiation", true)) - { - SSL_CTX_set_info_callback(ctx, NULL); - SSL_CTX_set_info_callback(clictx, NULL); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Setting %s %s context options, default: %ld set: %ld clear: %ld", name.c_str(), ctxname.c_str(), ctx.GetDefaultContextOptions(), setoptions, clearoptions); + long final = context.SetRawContextOptions(setoptions, clearoptions); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "%s %s context options: %ld", name.c_str(), ctxname.c_str(), final); } - else - { - SSL_CTX_set_info_callback(ctx, SSLInfoCallback); - SSL_CTX_set_info_callback(clictx, SSLInfoCallback); - } -#endif - if (Conf->getBool("showports", true)) + public: + Profile(const std::string& profilename, ConfigTag* tag) + : name(profilename) + , dh(ServerInstance->Config->Paths.PrependConfig(tag->getString("dhfile", "dh.pem"))) + , ctx(SSL_CTX_new(SSLv23_server_method())) + , clictx(SSL_CTX_new(SSLv23_client_method())) + , allowrenego(tag->getBool("renegotiation", true)) { - sslports = Conf->getString("advertisedports"); - if (!sslports.empty()) - return; - - for (size_t i = 0; i < ServerInstance->ports.size(); i++) - { - ListenSocket* port = ServerInstance->ports[i]; - if (port->bind_tag->getString("ssl") != "openssl") - continue; + if ((!ctx.SetDH(dh)) || (!clictx.SetDH(dh))) + throw Exception("Couldn't set DH parameters"); - const std::string& portid = port->bind_desc; - ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str()); + std::string hash = tag->getString("hash", "md5"); + digest = EVP_get_digestbyname(hash.c_str()); + if (digest == NULL) + throw Exception("Unknown hash type " + hash); - if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1") + std::string ciphers = tag->getString("ciphers"); + if (!ciphers.empty()) + { + if ((!ctx.SetCiphers(ciphers)) || (!clictx.SetCiphers(ciphers))) { - /* - * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display - * the IP:port in ISUPPORT. - * - * We used to advertise all ports seperated by a ';' char that matched the above criteria, - * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed. - * To solve this by default we now only display the first IP:port found and let the user - * configure the exact value for the 005 token, if necessary. - */ - sslports = portid; - break; + ERR_print_errors_cb(error_callback, this); + throw Exception("Can't set cipher list to \"" + ciphers + "\" " + lasterr); } } - } - } - - void OnModuleRehash(User* user, const std::string ¶m) - { - if (param != "ssl") - return; - std::string keyfile; - std::string certfile; - std::string cafile; - std::string dhfile; - OnRehash(user); - - ConfigTag* conf = ServerInstance->Config->ConfValue("openssl"); +#ifdef INSPIRCD_OPENSSL_ENABLE_ECDH + std::string curvename = tag->getString("ecdhcurve", "prime256v1"); + if (!curvename.empty()) + ctx.SetECDH(curvename); +#endif - cafile = conf->getString("cafile", CONFIG_PATH "/ca.pem"); - certfile = conf->getString("certfile", CONFIG_PATH "/cert.pem"); - keyfile = conf->getString("keyfile", CONFIG_PATH "/key.pem"); - dhfile = conf->getString("dhfile", CONFIG_PATH "/dhparams.pem"); - std::string hash = conf->getString("hash", "md5"); - if (hash != "sha1" && hash != "md5") - throw ModuleException("Unknown hash type " + hash); - use_sha = (hash == "sha1"); + SetContextOptions("server", tag, ctx); + SetContextOptions("client", tag, clictx); - if (conf->getBool("customcontextoptions")) - { - SetContextOptions(ctx, ctx_options, "server", conf); - SetContextOptions(clictx, clictx_options, "client", conf); - } + /* Load our keys and certificates + * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck. + */ + std::string filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("certfile", "cert.pem")); + if ((!ctx.SetCerts(filename)) || (!clictx.SetCerts(filename))) + { + ERR_print_errors_cb(error_callback, this); + throw Exception("Can't read certificate file: " + lasterr); + } - std::string ciphers = conf->getString("ciphers", ""); + filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("keyfile", "key.pem")); + if ((!ctx.SetPrivateKey(filename)) || (!clictx.SetPrivateKey(filename))) + { + ERR_print_errors_cb(error_callback, this); + throw Exception("Can't read key file: " + lasterr); + } - if (!ciphers.empty()) - { - ERR_clear_error(); - if ((!SSL_CTX_set_cipher_list(ctx, ciphers.c_str())) || (!SSL_CTX_set_cipher_list(clictx, ciphers.c_str()))) + // Load the CAs we trust + filename = ServerInstance->Config->Paths.PrependConfig(tag->getString("cafile", "ca.pem")); + if ((!ctx.SetCA(filename)) || (!clictx.SetCA(filename))) { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't set cipher list to %s.", ciphers.c_str()); ERR_print_errors_cb(error_callback, this); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", filename.c_str(), lasterr.c_str()); } } - /* Load our keys and certificates - * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck. - */ - ERR_clear_error(); - if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str()))) - { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno)); - ERR_print_errors_cb(error_callback, this); - } + const std::string& GetName() const { return name; } + SSL* CreateServerSession() { return ctx.CreateServerSession(); } + SSL* CreateClientSession() { return clictx.CreateClientSession(); } + const EVP_MD* GetDigest() { return digest; } + bool AllowRenegotiation() const { return allowrenego; } + }; +} - ERR_clear_error(); - if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno)); - ERR_print_errors_cb(error_callback, this); - } +static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx) +{ + /* XXX: This will allow self signed certificates. + * In the future if we want an option to not allow this, + * we can just return preverify_ok here, and openssl + * will boot off self-signed and invalid peer certs. + */ + int ve = X509_STORE_CTX_get_error(ctx); - /* Load the CAs we trust*/ - ERR_clear_error(); - if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0))) - { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. This is only a problem if you want to verify client certificates, otherwise it's safe to ignore this message. Error: %s", cafile.c_str(), strerror(errno)); - ERR_print_errors_cb(error_callback, this); - } + SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT); -#ifdef _WIN32 - BIO* dhpfile = BIO_new_file(dhfile.c_str(), "r"); -#else - FILE* dhpfile = fopen(dhfile.c_str(), "r"); -#endif - DH* ret; + return 1; +} - if (dhpfile == NULL) - { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno)); - throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno)); - } - else +class OpenSSLIOHook : public SSLIOHook +{ + private: + SSL* sess; + issl_status status; + bool data_to_write; + reference<OpenSSL::Profile> profile; + + // Returns 1 if handshake succeeded, 0 if it is still in progress, -1 if it failed + int Handshake(StreamSocket* user) + { + ERR_clear_error(); + int ret = SSL_do_handshake(sess); + if (ret < 0) { -#ifdef _WIN32 - ret = PEM_read_bio_DHparams(dhpfile, NULL, NULL, NULL); - BIO_free(dhpfile); -#else - ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL); -#endif + int err = SSL_get_error(sess, ret); - ERR_clear_error(); - if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0)) + if (err == SSL_ERROR_WANT_READ) { - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str()); - ERR_print_errors_cb(error_callback, this); + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + this->status = ISSL_HANDSHAKING; + return 0; + } + else if (err == SSL_ERROR_WANT_WRITE) + { + SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); + this->status = ISSL_HANDSHAKING; + return 0; + } + else + { + CloseSession(); + return -1; } - DH_free(ret); } + else if (ret > 0) + { + // Handshake complete. + VerifyCertificate(); -#ifndef _WIN32 - fclose(dhpfile); -#endif - -#ifdef INSPIRCD_OPENSSL_ENABLE_ECDH - SetupECDH(conf); -#endif - } - - void On005Numeric(std::string &output) - { - if (!sslports.empty()) - output.append(" SSL=" + sslports); - } + status = ISSL_OPEN; - ~ModuleSSLOpenSSL() - { - SSL_CTX_free(ctx); - SSL_CTX_free(clictx); - delete[] sessions; - } + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE); - void OnUserConnect(LocalUser* user) - { - if (user->eh.GetIOHook() == this) + return 1; + } + else if (ret == 0) { - if (sessions[user->eh.GetFd()].sess) - { - if (!sessions[user->eh.GetFd()].cert->fingerprint.empty()) - user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"" - " and your SSL fingerprint is %s", user->nick.c_str(), SSL_get_cipher(sessions[user->eh.GetFd()].sess), sessions[user->eh.GetFd()].cert->fingerprint.c_str()); - else - user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->eh.GetFd()].sess)); - } + CloseSession(); } + return -1; } - void OnCleanup(int target_type, void* item) + void CloseSession() { - if (target_type == TYPE_USER) + if (sess) { - LocalUser* user = IS_LOCAL((User*)item); - - if (user && user->eh.GetIOHook() == this) - { - // User is using SSL, they're a local user, and they're using one of *our* SSL ports. - // Potentially there could be multiple SSL modules loaded at once on different ports. - ServerInstance->Users->QuitUser(user, "SSL module unloading"); - } + SSL_shutdown(sess); + SSL_free(sess); } + sess = NULL; + certificate = NULL; + status = ISSL_NONE; } - Version GetVersion() + void VerifyCertificate() { - return Version("Provides SSL support for clients", VF_VENDOR); - } + X509* cert; + ssl_cert* certinfo = new ssl_cert; + this->certificate = certinfo; + unsigned int n; + unsigned char md[EVP_MAX_MD_SIZE]; - void OnRequest(Request& request) - { - if (strcmp("GET_SSL_CERT", request.id) == 0) + cert = SSL_get_peer_certificate(sess); + + if (!cert) { - SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request); - int fd = req.sock->GetFd(); - issl_session* session = &sessions[fd]; + certinfo->error = "Could not get peer certificate: "+std::string(get_error()); + return; + } + + certinfo->invalid = (SSL_get_verify_result(sess) != X509_V_OK); - req.cert = session->cert; + if (!SelfSigned) + { + certinfo->unknownsigner = false; + certinfo->trusted = true; } - else if (!strcmp("GET_RAW_SSL_SESSION", request.id)) + else { - SSLRawSessionRequest& req = static_cast<SSLRawSessionRequest&>(request); - if ((req.fd >= 0) && (req.fd < ServerInstance->SE->GetMaxFds())) - req.data = reinterpret_cast<void*>(sessions[req.fd].sess); + certinfo->unknownsigner = true; + certinfo->trusted = false; } - } - - void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) - { - int fd = user->GetFd(); - issl_session* session = &sessions[fd]; + char buf[512]; + X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); + certinfo->dn = buf; + // Make sure there are no chars in the string that we consider invalid + if (certinfo->dn.find_first_of("\r\n") != std::string::npos) + certinfo->dn.clear(); - session->sess = SSL_new(ctx); - session->status = ISSL_NONE; - session->outbound = false; - session->data_to_write = false; + X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)); + certinfo->issuer = buf; + if (certinfo->issuer.find_first_of("\r\n") != std::string::npos) + certinfo->issuer.clear(); - if (session->sess == NULL) - return; + if (!X509_digest(cert, profile->GetDigest(), md, &n)) + { + certinfo->error = "Out of memory generating fingerprint"; + } + else + { + certinfo->fingerprint = BinToHex(md, n); + } - if (SSL_set_fd(session->sess, fd) == 0) + if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0)) { - ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); - return; + certinfo->error = "Not activated, or expired certificate"; } - Handshake(user, session); + X509_free(cert); } - void OnStreamSocketConnect(StreamSocket* user) +#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION + void SSLInfoCallback(int where, int rc) { - int fd = user->GetFd(); - /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */ - if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1)) - return; + if ((where & SSL_CB_HANDSHAKE_START) && (status == ISSL_OPEN)) + { + if (profile->AllowRenegotiation()) + return; - issl_session* session = &sessions[fd]; + // The other side is trying to renegotiate, kill the connection and change status + // to ISSL_NONE so CheckRenego() closes the session + status = ISSL_NONE; + SocketEngine::Shutdown(SSL_get_fd(sess), 2); + } + } - session->sess = SSL_new(clictx); - session->status = ISSL_NONE; - session->outbound = true; - session->data_to_write = false; + bool CheckRenego(StreamSocket* sock) + { + if (status != ISSL_NONE) + return true; - if (session->sess == NULL) - return; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Session %p killed, attempted to renegotiate", (void*)sess); + CloseSession(); + sock->SetError("Renegotiation is not allowed"); + return false; + } +#endif - if (SSL_set_fd(session->sess, fd) == 0) + // Returns 1 if application I/O should proceed, 0 if it must wait for the underlying protocol to progress, -1 on fatal error + int PrepareIO(StreamSocket* sock) + { + if (status == ISSL_OPEN) + return 1; + else if (status == ISSL_HANDSHAKING) { - ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); - return; + // The handshake isn't finished, try to finish it + return Handshake(sock); } - Handshake(user, session); + CloseSession(); + return -1; } - void OnStreamSocketClose(StreamSocket* user) + // Calls our private SSLInfoCallback() + friend void StaticSSLInfoCallback(const SSL* ssl, int where, int rc); + + public: + OpenSSLIOHook(IOHookProvider* hookprov, StreamSocket* sock, SSL* session, const reference<OpenSSL::Profile>& sslprofile) + : SSLIOHook(hookprov) + , sess(session) + , status(ISSL_NONE) + , data_to_write(false) + , profile(sslprofile) { - int fd = user->GetFd(); - /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */ - if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1)) + if (sess == NULL) return; + if (SSL_set_fd(sess, sock->GetFd()) == 0) + throw ModuleException("Can't set fd with SSL_set_fd: " + ConvToStr(sock->GetFd())); - CloseSession(&sessions[fd]); + SSL_set_ex_data(sess, exdataindex, this); + sock->AddIOHook(this); + Handshake(sock); } - int OnStreamSocketRead(StreamSocket* user, std::string& recvq) + void OnStreamSocketClose(StreamSocket* user) CXX11_OVERRIDE { - int fd = user->GetFd(); - /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */ - if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1)) - return -1; - - issl_session* session = &sessions[fd]; - - if (!session->sess) - { - CloseSession(session); - return -1; - } - - if (session->status == ISSL_HANDSHAKING) - { - // The handshake isn't finished and it wants to read, try to finish it. - if (!Handshake(user, session)) - { - // Couldn't resume handshake. - if (session->status == ISSL_NONE) - return -1; - return 0; - } - } + CloseSession(); + } - // If we resumed the handshake then session->status will be ISSL_OPEN + int OnStreamSocketRead(StreamSocket* user, std::string& recvq) CXX11_OVERRIDE + { + // Finish handshake if needed + int prepret = PrepareIO(user); + if (prepret <= 0) + return prepret; - if (session->status == ISSL_OPEN) + // If we resumed the handshake then this->status will be ISSL_OPEN { ERR_clear_error(); char* buffer = ServerInstance->GetReadBuffer(); size_t bufsiz = ServerInstance->Config->NetBufferSize; - int ret = SSL_read(session->sess, buffer, bufsiz); + int ret = SSL_read(sess, buffer, bufsiz); #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION - if (!CheckRenego(user, session)) + if (!CheckRenego(user)) return -1; #endif if (ret > 0) { recvq.append(buffer, ret); - if (session->data_to_write) - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE); + if (data_to_write) + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE); return 1; } else if (ret == 0) { // Client closed connection. - CloseSession(session); + CloseSession(); user->SetError("Connection closed"); return -1; } - else if (ret < 0) + else // if (ret < 0) { - int err = SSL_get_error(session->sess, ret); + int err = SSL_get_error(sess, ret); if (err == SSL_ERROR_WANT_READ) { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ); + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ); return 0; } else if (err == SSL_ERROR_WANT_WRITE) { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); + SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); return 0; } else { - CloseSession(session); + CloseSession(); return -1; } } } - - return 0; } - int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) + int OnStreamSocketWrite(StreamSocket* user, std::string& buffer) CXX11_OVERRIDE { - int fd = user->GetFd(); - - issl_session* session = &sessions[fd]; - - if (!session->sess) - { - CloseSession(session); - return -1; - } + // Finish handshake if needed + int prepret = PrepareIO(user); + if (prepret <= 0) + return prepret; - session->data_to_write = true; - - if (session->status == ISSL_HANDSHAKING) - { - if (!Handshake(user, session)) - { - // Couldn't resume handshake. - if (session->status == ISSL_NONE) - return -1; - return 0; - } - } + data_to_write = true; - if (session->status == ISSL_OPEN) + // Session is ready for transferring application data { ERR_clear_error(); - int ret = SSL_write(session->sess, buffer.data(), buffer.size()); + int ret = SSL_write(sess, buffer.data(), buffer.size()); #ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION - if (!CheckRenego(user, session)) + if (!CheckRenego(user)) return -1; #endif if (ret == (int)buffer.length()) { - session->data_to_write = false; - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + data_to_write = false; + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); return 1; } else if (ret > 0) { - buffer = buffer.substr(ret); - ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE); + buffer.erase(0, ret); + SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE); return 0; } else if (ret == 0) { - CloseSession(session); + CloseSession(); return -1; } - else if (ret < 0) + else // if (ret < 0) { - int err = SSL_get_error(session->sess, ret); + int err = SSL_get_error(sess, ret); if (err == SSL_ERROR_WANT_WRITE) { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE); + SocketEngine::ChangeEventMask(user, FD_WANT_SINGLE_WRITE); return 0; } else if (err == SSL_ERROR_WANT_READ) { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ); + SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ); return 0; } else { - CloseSession(session); + CloseSession(); return -1; } } } - return 0; } - bool Handshake(StreamSocket* user, issl_session* session) + void TellCiphersAndFingerprint(LocalUser* user) { - int ret; + if (sess) + { + std::string text = "*** You are connected using SSL cipher '"; + GetCiphersuite(text); + text += '\''; + const std::string& fingerprint = certificate->fingerprint; + if (!fingerprint.empty()) + text += " and your SSL certificate fingerprint is " + fingerprint; - ERR_clear_error(); - if (session->outbound) - ret = SSL_connect(session->sess); - else - ret = SSL_accept(session->sess); + user->WriteNotice(text); + } + } - if (ret < 0) + void GetCiphersuite(std::string& out) const + { + out.append(SSL_get_version(sess)).push_back('-'); + out.append(SSL_get_cipher(sess)); + } + + bool IsHandshakeDone() const { return (status == ISSL_OPEN); } +}; + +static void StaticSSLInfoCallback(const SSL* ssl, int where, int rc) +{ +#ifdef INSPIRCD_OPENSSL_ENABLE_RENEGO_DETECTION + OpenSSLIOHook* hook = static_cast<OpenSSLIOHook*>(SSL_get_ex_data(ssl, exdataindex)); + hook->SSLInfoCallback(where, rc); +#endif +} + +class OpenSSLIOHookProvider : public refcountbase, public IOHookProvider +{ + reference<OpenSSL::Profile> profile; + + public: + OpenSSLIOHookProvider(Module* mod, reference<OpenSSL::Profile>& prof) + : IOHookProvider(mod, "ssl/" + prof->GetName(), IOHookProvider::IOH_SSL) + , profile(prof) + { + ServerInstance->Modules->AddService(*this); + } + + ~OpenSSLIOHookProvider() + { + ServerInstance->Modules->DelService(*this); + } + + void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE + { + new OpenSSLIOHook(this, sock, profile->CreateServerSession(), profile); + } + + void OnConnect(StreamSocket* sock) CXX11_OVERRIDE + { + new OpenSSLIOHook(this, sock, profile->CreateClientSession(), profile); + } +}; + +class ModuleSSLOpenSSL : public Module +{ + typedef std::vector<reference<OpenSSLIOHookProvider> > ProfileList; + + ProfileList profiles; + + void ReadProfiles() + { + ProfileList newprofiles; + ConfigTagList tags = ServerInstance->Config->ConfTags("sslprofile"); + if (tags.first == tags.second) { - int err = SSL_get_error(session->sess, ret); + // Create a default profile named "openssl" + const std::string defname = "openssl"; + ConfigTag* tag = ServerInstance->Config->ConfValue(defname); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No <sslprofile> tags found, using settings from the <openssl> tag"); - if (err == SSL_ERROR_WANT_READ) + try { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); - session->status = ISSL_HANDSHAKING; - return true; + reference<OpenSSL::Profile> profile(new OpenSSL::Profile(defname, tag)); + newprofiles.push_back(new OpenSSLIOHookProvider(this, profile)); } - else if (err == SSL_ERROR_WANT_WRITE) + catch (OpenSSL::Exception& ex) { - ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE); - session->status = ISSL_HANDSHAKING; - return true; + throw ModuleException("Error while initializing the default SSL profile - " + ex.GetReason()); } - else - { - CloseSession(session); - } - - return false; } - else if (ret > 0) + + for (ConfigIter i = tags.first; i != tags.second; ++i) { - // Handshake complete. - VerifyCertificate(session, user); + ConfigTag* tag = i->second; + if (tag->getString("provider") != "openssl") + continue; - session->status = ISSL_OPEN; + std::string name = tag->getString("name"); + if (name.empty()) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring <sslprofile> tag without name at " + tag->getTagLocation()); + continue; + } - ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE); + reference<OpenSSL::Profile> profile; + try + { + profile = new OpenSSL::Profile(name, tag); + } + catch (CoreException& ex) + { + throw ModuleException("Error while initializing SSL profile \"" + name + "\" at " + tag->getTagLocation() + " - " + ex.GetReason()); + } - return true; + newprofiles.push_back(new OpenSSLIOHookProvider(this, profile)); } - else if (ret == 0) - { - CloseSession(session); - } - return false; + + profiles.swap(newprofiles); } - void CloseSession(issl_session* session) + public: + ModuleSSLOpenSSL() { - if (session->sess) - { - SSL_shutdown(session->sess); - SSL_free(session->sess); - } - - session->sess = NULL; - session->status = ISSL_NONE; - session->cert = NULL; + // Initialize OpenSSL + SSL_library_init(); + SSL_load_error_strings(); } - void VerifyCertificate(issl_session* session, StreamSocket* user) + void init() CXX11_OVERRIDE { - if (!session->sess || !user) - return; - - X509* cert; - ssl_cert* certinfo = new ssl_cert; - session->cert = certinfo; - unsigned int n; - unsigned char md[EVP_MAX_MD_SIZE]; - const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5(); + // Register application specific data + char exdatastr[] = "inspircd"; + exdataindex = SSL_get_ex_new_index(0, exdatastr, NULL, NULL, NULL); + if (exdataindex < 0) + throw ModuleException("Failed to register application specific data"); - cert = SSL_get_peer_certificate((SSL*)session->sess); + ReadProfiles(); + } - if (!cert) - { - certinfo->error = "Could not get peer certificate: "+std::string(get_error()); + void OnModuleRehash(User* user, const std::string ¶m) CXX11_OVERRIDE + { + if (param != "ssl") return; - } - certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK); - - if (!SelfSigned) + try { - certinfo->unknownsigner = false; - certinfo->trusted = true; + ReadProfiles(); } - else + catch (ModuleException& ex) { - certinfo->unknownsigner = true; - certinfo->trusted = false; + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason() + " Not applying settings."); } + } - char buf[512]; - X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); - certinfo->dn = buf; - // Make sure there are no chars in the string that we consider invalid - if (certinfo->dn.find_first_of("\r\n") != std::string::npos) - certinfo->dn.clear(); - - X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)); - certinfo->issuer = buf; - if (certinfo->issuer.find_first_of("\r\n") != std::string::npos) - certinfo->issuer.clear(); + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE + { + IOHook* hook = user->eh.GetIOHook(); + if (hook && hook->prov->creator == this) + static_cast<OpenSSLIOHook*>(hook)->TellCiphersAndFingerprint(user); + } - if (!X509_digest(cert, digest, md, &n)) - { - certinfo->error = "Out of memory generating fingerprint"; - } - else + void OnCleanup(int target_type, void* item) CXX11_OVERRIDE + { + if (target_type == TYPE_USER) { - certinfo->fingerprint = irc::hex(md, n); + LocalUser* user = IS_LOCAL((User*)item); + + if (user && user->eh.GetIOHook() && user->eh.GetIOHook()->prov->creator == this) + { + // User is using SSL, they're a local user, and they're using one of *our* SSL ports. + // Potentially there could be multiple SSL modules loaded at once on different ports. + ServerInstance->Users->QuitUser(user, "SSL module unloading"); + } } + } - if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0)) + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE + { + if ((user->eh.GetIOHook()) && (user->eh.GetIOHook()->prov->creator == this)) { - certinfo->error = "Not activated, or expired certificate"; + OpenSSLIOHook* iohook = static_cast<OpenSSLIOHook*>(user->eh.GetIOHook()); + if (!iohook->IsHandshakeDone()) + return MOD_RES_DENY; } - X509_free(cert); + return MOD_RES_PASSTHRU; } -}; -static int error_callback(const char *str, size_t len, void *u) -{ - ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1)); - - // - // XXX: Remove this line, it causes valgrind warnings... - // - // MD_update(&m, buf, j); - // - // - // ... ONLY JOKING! :-) - // - - return 0; -} + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides SSL support for clients", VF_VENDOR); + } +}; MODULE_INIT(ModuleSSLOpenSSL) diff --git a/src/modules/hash.h b/src/modules/hash.h deleted file mode 100644 index f7bf85e20..000000000 --- a/src/modules/hash.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef HASH_H -#define HASH_H - -#include "modules.h" - -class HashProvider : public DataProvider -{ - public: - const unsigned int out_size; - const unsigned int block_size; - HashProvider(Module* mod, const std::string& Name, int osiz, int bsiz) - : DataProvider(mod, Name), out_size(osiz), block_size(bsiz) {} - virtual std::string sum(const std::string& data) = 0; - inline std::string hexsum(const std::string& data) - { - return BinToHex(sum(data)); - } - - inline std::string b64sum(const std::string& data) - { - return BinToBase64(sum(data), NULL, 0); - } - - /** Allows the IVs for the hash to be specified. As the choice of initial IV is - * important for the security of a hash, this should not be used except to - * maintain backwards compatability. This also allows you to change the hex - * sequence from its default of "0123456789abcdef", which does not improve the - * strength of the output, but helps confuse those attempting to implement it. - * - * Example: - * \code - * unsigned int iv[] = { 0xFFFFFFFF, 0x00000000, 0xAAAAAAAA, 0xCCCCCCCC }; - * std::string result = Hash.sumIV(iv, "fedcba9876543210", "data"); - * \endcode - */ - virtual std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata) = 0; - - /** HMAC algorithm, RFC 2104 */ - std::string hmac(const std::string& key, const std::string& msg) - { - std::string hmac1, hmac2; - std::string kbuf = key.length() > block_size ? sum(key) : key; - kbuf.resize(block_size); - - for (size_t n = 0; n < block_size; n++) - { - hmac1.push_back(static_cast<char>(kbuf[n] ^ 0x5C)); - hmac2.push_back(static_cast<char>(kbuf[n] ^ 0x36)); - } - hmac2.append(msg); - hmac1.append(sum(hmac2)); - return sum(hmac1); - } -}; - -#endif - diff --git a/src/modules/httpd.h b/src/modules/httpd.h deleted file mode 100644 index 56fd22da0..000000000 --- a/src/modules/httpd.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> - * Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net> - * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org> - * Copyright (C) 2006 Craig Edwards <craigedwards@brainbox.cc> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "base.h" - -#ifndef HTTPD_H -#define HTTPD_H - -#include <string> -#include <sstream> -#include <map> - -/** A modifyable list of HTTP header fields - */ -class HTTPHeaders -{ - protected: - std::map<std::string,std::string> headers; - public: - - /** Set the value of a header - * Sets the value of the named header. If the header is already present, it will be replaced - */ - void SetHeader(const std::string &name, const std::string &data) - { - headers[name] = data; - } - - /** Set the value of a header, only if it doesn't exist already - * Sets the value of the named header. If the header is already present, it will NOT be updated - */ - void CreateHeader(const std::string &name, const std::string &data) - { - if (!IsSet(name)) - SetHeader(name, data); - } - - /** Remove the named header - */ - void RemoveHeader(const std::string &name) - { - headers.erase(name); - } - - /** Remove all headers - */ - void Clear() - { - headers.clear(); - } - - /** Get the value of a header - * @return The value of the header, or an empty string - */ - std::string GetHeader(const std::string &name) - { - std::map<std::string,std::string>::iterator it = headers.find(name); - if (it == headers.end()) - return std::string(); - - return it->second; - } - - /** Check if the given header is specified - * @return true if the header is specified - */ - bool IsSet(const std::string &name) - { - std::map<std::string,std::string>::iterator it = headers.find(name); - return (it != headers.end()); - } - - /** Get all headers, formatted by the HTTP protocol - * @return Returns all headers, formatted according to the HTTP protocol. There is no request terminator at the end - */ - std::string GetFormattedHeaders() - { - std::string re; - - for (std::map<std::string,std::string>::iterator i = headers.begin(); i != headers.end(); i++) - re += i->first + ": " + i->second + "\r\n"; - - return re; - } -}; - -class HttpServerSocket; - -/** This class represents a HTTP request. - */ -class HTTPRequest : public Event -{ - protected: - std::string type; - std::string document; - std::string ipaddr; - std::string postdata; - - public: - - HTTPHeaders *headers; - int errorcode; - - /** A socket pointer, which you must return in your HTTPDocument class - * if you reply to this request. - */ - HttpServerSocket* sock; - - /** Initialize HTTPRequest. - * This constructor is called by m_httpd.so to initialize the class. - * @param request_type The request type, e.g. GET, POST, HEAD - * @param uri The URI, e.g. /page - * @param hdr The headers sent with the request - * @param opaque An opaque pointer used internally by m_httpd, which you must pass back to the module in your reply. - * @param ip The IP address making the web request. - * @param pdata The post data (content after headers) received with the request, up to Content-Length in size - */ - HTTPRequest(Module* me, const std::string &eventid, const std::string &request_type, const std::string &uri, - HTTPHeaders* hdr, HttpServerSocket* socket, const std::string &ip, const std::string &pdata) - : Event(me, eventid), type(request_type), document(uri), ipaddr(ip), postdata(pdata), headers(hdr), sock(socket) - { - } - - /** Get the post data (request content). - * All post data will be returned, including carriage returns and linefeeds. - * @return The postdata - */ - std::string& GetPostData() - { - return postdata; - } - - /** Get the request type. - * Any request type can be intercepted, even ones which are invalid in the HTTP/1.1 spec. - * @return The request type, e.g. GET, POST, HEAD - */ - std::string& GetType() - { - return type; - } - - /** Get URI. - * The URI string (URL minus hostname and scheme) will be provided by this function. - * @return The URI being requested - */ - std::string& GetURI() - { - return document; - } - - /** Get IP address of requester. - * The requesting system's ip address will be returned. - * @return The IP address as a string - */ - std::string& GetIP() - { - return ipaddr; - } -}; - -/** You must return a HTTPDocument to the httpd module by using the Request class. - * When you initialize this class you may initialize it with all components required to - * form a valid HTTP response, including document data, headers, and a response code. - */ -class HTTPDocumentResponse : public Request -{ - public: - std::stringstream* document; - int responsecode; - HTTPHeaders headers; - HTTPRequest& src; - - /** Initialize a HTTPRequest ready for sending to m_httpd.so. - * @param opaque The socket pointer you obtained from the HTTPRequest at an earlier time - * @param doc A stringstream containing the document body - * @param response A valid HTTP/1.0 or HTTP/1.1 response code. The response text will be determined for you - * based upon the response code. - * @param extra Any extra headers to include with the defaults, seperated by carriage return and linefeed. - */ - HTTPDocumentResponse(Module* me, HTTPRequest& req, std::stringstream* doc, int response) - : Request(me, req.source, "HTTP-DOC"), document(doc), responsecode(response), src(req) - { - } -}; - -#endif - diff --git a/src/modules/m_abbreviation.cpp b/src/modules/m_abbreviation.cpp index 1e8f71176..d2fa09c4e 100644 --- a/src/modules/m_abbreviation.cpp +++ b/src/modules/m_abbreviation.cpp @@ -19,49 +19,37 @@ #include "inspircd.h" -/* $ModDesc: Provides the ability to abbreviate commands a-la BBC BASIC keywords. */ - class ModuleAbbreviation : public Module { public: - void init() - { - ServerInstance->Modules->Attach(I_OnPreCommand, this); - } - void Prioritize() { ServerInstance->Modules->SetPriority(this, I_OnPreCommand, PRIORITY_FIRST); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the ability to abbreviate commands a-la BBC BASIC keywords.",VF_VENDOR); } - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { /* Command is already validated, has a length of 0, or last character is not a . */ if (validated || command.empty() || *command.rbegin() != '.') return MOD_RES_PASSTHRU; - /* Whack the . off the end */ - command.erase(command.end() - 1); - /* Look for any command that starts with the same characters, if it does, replace the command string with it */ - size_t clen = command.length(); + size_t clen = command.length() - 1; std::string foundcommand, matchlist; bool foundmatch = false; - for (Commandtable::iterator n = ServerInstance->Parser->cmdlist.begin(); n != ServerInstance->Parser->cmdlist.end(); ++n) + const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands(); + for (CommandParser::CommandMap::const_iterator n = commands.begin(); n != commands.end(); ++n) { - if (n->first.length() < clen) - continue; - - if (command == n->first.substr(0, clen)) + if (!command.compare(0, clen, n->first, 0, clen)) { if (matchlist.length() > 450) { - user->WriteNumeric(420, "%s :Ambiguous abbreviation and too many possible matches.", user->nick.c_str()); + user->WriteNumeric(420, ":Ambiguous abbreviation and too many possible matches."); return MOD_RES_DENY; } @@ -79,16 +67,11 @@ class ModuleAbbreviation : public Module /* Ambiguous command, list the matches */ if (!matchlist.empty()) { - user->WriteNumeric(420, "%s :Ambiguous abbreviation, possible matches: %s%s", user->nick.c_str(), foundcommand.c_str(), matchlist.c_str()); + user->WriteNumeric(420, ":Ambiguous abbreviation, possible matches: %s%s", foundcommand.c_str(), matchlist.c_str()); return MOD_RES_DENY; } - if (foundcommand.empty()) - { - /* No match, we have to put the . back again so that the invalid command numeric looks correct. */ - command += '.'; - } - else + if (!foundcommand.empty()) { command = foundcommand; } diff --git a/src/modules/m_alias.cpp b/src/modules/m_alias.cpp index 32fc80b64..6bd59a780 100644 --- a/src/modules/m_alias.cpp +++ b/src/modules/m_alias.cpp @@ -22,15 +22,13 @@ #include "inspircd.h" -/* $ModDesc: Provides aliases of commands. */ - /** An alias definition */ class Alias { public: /** The text of the alias command */ - irc::string AliasedCommand; + std::string AliasedCommand; /** Text to replace with */ std::string ReplaceFormat; @@ -59,20 +57,22 @@ class Alias class ModuleAlias : public Module { - private: - char fprefix; /* We cant use a map, there may be multiple aliases with the same name. * We can, however, use a fancy invention: the multimap. Maps a key to one or more values. * -- w00t - */ - std::multimap<irc::string, Alias> Aliases; + */ + typedef insp::flat_multimap<std::string, Alias, irc::insensitive_swo> AliasMap; + + AliasMap Aliases; /* whether or not +B users are allowed to use fantasy commands */ bool AllowBots; + UserModeReference botmode; - virtual void ReadAliases() + public: + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* fantasy = ServerInstance->Config->ConfValue("fantasy"); AllowBots = fantasy->getBool("allowbots", false); @@ -85,8 +85,8 @@ class ModuleAlias : public Module { ConfigTag* tag = i->second; Alias a; - std::string aliastext = tag->getString("text"); - a.AliasedCommand = aliastext.c_str(); + a.AliasedCommand = tag->getString("text"); + std::transform(a.AliasedCommand.begin(), a.AliasedCommand.end(), a.AliasedCommand.begin(), ::toupper); tag->readString("replace", a.ReplaceFormat, true); a.RequiredNick = tag->getString("requires"); a.ULineOnly = tag->getBool("uline"); @@ -99,20 +99,12 @@ class ModuleAlias : public Module } } - public: - - void init() + ModuleAlias() + : botmode(this, "bot") { - ReadAliases(); - Implementation eventlist[] = { I_OnPreCommand, I_OnRehash, I_OnUserMessage }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual ~ModuleAlias() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides aliases of commands.", VF_VENDOR); } @@ -142,10 +134,8 @@ class ModuleAlias : public Module return word; } - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { - std::multimap<irc::string, Alias>::iterator i, upperbound; - /* If theyre not registered yet, we dont want * to know. */ @@ -153,19 +143,16 @@ class ModuleAlias : public Module return MOD_RES_PASSTHRU; /* We dont have any commands looking like this? Stop processing. */ - i = Aliases.find(command.c_str()); - if (i == Aliases.end()) + std::pair<AliasMap::iterator, AliasMap::iterator> iters = Aliases.equal_range(command); + if (iters.first == iters.second) return MOD_RES_PASSTHRU; - /* Avoid iterating on to different aliases if no patterns match. */ - upperbound = Aliases.upper_bound(command.c_str()); - irc::string c = command.c_str(); /* The parameters for the command in their original form, with the command stripped off */ - std::string compare = original_line.substr(command.length()); + std::string compare(original_line, command.length()); while (*(compare.c_str()) == ' ') compare.erase(compare.begin()); - while (i != upperbound) + for (AliasMap::iterator i = iters.first; i != iters.second; ++i) { if (i->second.UserCommand) { @@ -174,29 +161,27 @@ class ModuleAlias : public Module return MOD_RES_DENY; } } - - i++; } // If we made it here, no aliases actually matched. return MOD_RES_PASSTHRU; } - virtual void OnUserMessage(User *user, void *dest, int target_type, const std::string &text, char status, const CUList &exempt_list) + void OnUserMessage(User *user, void *dest, int target_type, const std::string &text, char status, const CUList &exempt_list, MessageType msgtype) CXX11_OVERRIDE { - if (target_type != TYPE_CHANNEL) + if ((target_type != TYPE_CHANNEL) || (msgtype != MSG_PRIVMSG)) { return; } // fcommands are only for local users. Spanningtree will send them back out as their original cmd. - if (!user || !IS_LOCAL(user)) + if (!IS_LOCAL(user)) { return; } /* Stop here if the user is +B and allowbot is set to no. */ - if (!AllowBots && user->IsModeSet('B')) + if (!AllowBots && user->IsModeSet(botmode)) { return; } @@ -207,37 +192,31 @@ class ModuleAlias : public Module // text is like "!moo cows bite me", we want "!moo" first irc::spacesepstream ss(text); ss.GetToken(scommand); - irc::string fcommand = scommand.c_str(); - if (fcommand.empty()) + if (scommand.empty()) { return; // wtfbbq } // we don't want to touch non-fantasy stuff - if (*fcommand.c_str() != fprefix) + if (*scommand.c_str() != fprefix) { return; } // nor do we give a shit about the prefix - fcommand.erase(fcommand.begin()); + scommand.erase(scommand.begin()); - std::multimap<irc::string, Alias>::iterator i = Aliases.find(fcommand); - - if (i == Aliases.end()) + std::pair<AliasMap::iterator, AliasMap::iterator> iters = Aliases.equal_range(scommand); + if (iters.first == iters.second) return; - /* Avoid iterating on to other aliases if no patterns match */ - std::multimap<irc::string, Alias>::iterator upperbound = Aliases.upper_bound(fcommand); - - /* The parameters for the command in their original form, with the command stripped off */ - std::string compare = text.substr(fcommand.length() + 1); + std::string compare(text, scommand.length() + 1); while (*(compare.c_str()) == ' ') compare.erase(compare.begin()); - while (i != upperbound) + for (AliasMap::iterator i = iters.first; i != iters.second; ++i) { if (i->second.ChannelCommand) { @@ -245,16 +224,12 @@ class ModuleAlias : public Module if (DoAlias(user, c, &(i->second), compare, text.substr(1))) return; } - - i++; } } int DoAlias(User *user, Channel *c, Alias *a, const std::string& compare, const std::string& safe) { - User *u = NULL; - /* Does it match the pattern? */ if (!a->format.empty()) { @@ -270,24 +245,22 @@ class ModuleAlias : public Module } } - if ((a->OperOnly) && (!IS_OPER(user))) + if ((a->OperOnly) && (!user->IsOper())) return 0; if (!a->RequiredNick.empty()) { - u = ServerInstance->FindNick(a->RequiredNick); + User* u = ServerInstance->FindNick(a->RequiredNick); if (!u) { - user->WriteNumeric(401, ""+user->nick+" "+a->RequiredNick+" :is currently unavailable. Please try again later."); + user->WriteNumeric(ERR_NOSUCHNICK, a->RequiredNick + " :is currently unavailable. Please try again later."); return 1; } - } - if ((u != NULL) && (!a->RequiredNick.empty()) && (a->ULineOnly)) - { - if (!ServerInstance->ULine(u->server)) + + if ((a->ULineOnly) && (!u->server->IsULine())) { - ServerInstance->SNO->WriteToSnoMask('a', "NOTICE -- Service "+a->RequiredNick+" required by alias "+std::string(a->AliasedCommand.c_str())+" is not on a u-lined server, possibly underhanded antics detected!"); - user->WriteNumeric(401, ""+user->nick+" "+a->RequiredNick+" :is an imposter! Please inform an IRC operator as soon as possible."); + ServerInstance->SNO->WriteToSnoMask('a', "NOTICE -- Service "+a->RequiredNick+" required by alias "+a->AliasedCommand+" is not on a u-lined server, possibly underhanded antics detected!"); + user->WriteNumeric(ERR_NOSUCHNICK, a->RequiredNick + " :is an imposter! Please inform an IRC operator as soon as possible."); return 1; } } @@ -316,7 +289,7 @@ class ModuleAlias : public Module void DoCommand(const std::string& newline, User* user, Channel *chan, const std::string &original_line) { std::string result; - result.reserve(MAXBUF); + result.reserve(newline.length()); for (unsigned int i = 0; i < newline.length(); i++) { char c = newline[i]; @@ -329,28 +302,28 @@ class ModuleAlias : public Module result.append(GetVar(var, original_line)); i += len - 1; } - else if (newline.substr(i, 5) == "$nick") + else if (!newline.compare(i, 5, "$nick", 5)) { result.append(user->nick); i += 4; } - else if (newline.substr(i, 5) == "$host") + else if (!newline.compare(i, 5, "$host", 5)) { result.append(user->host); i += 4; } - else if (newline.substr(i, 5) == "$chan") + else if (!newline.compare(i, 5, "$chan", 5)) { if (chan) result.append(chan->name); i += 4; } - else if (newline.substr(i, 6) == "$ident") + else if (!newline.compare(i, 6, "$ident", 6)) { result.append(user->ident); i += 5; } - else if (newline.substr(i, 6) == "$vhost") + else if (!newline.compare(i, 6, "$vhost", 6)) { result.append(user->dhost); i += 5; @@ -367,23 +340,18 @@ class ModuleAlias : public Module std::string command, token; ss.GetToken(command); - while (ss.GetToken(token) && (pars.size() <= MAXPARAMETERS)) + while (ss.GetToken(token)) { pars.push_back(token); } - ServerInstance->Parser->CallHandler(command, pars, user); + ServerInstance->Parser.CallHandler(command, pars, user); } - virtual void OnRehash(User* user) - { - ReadAliases(); - } - - virtual void Prioritize() + void Prioritize() { // Prioritise after spanningtree so that channel aliases show the alias before the effects. Module* linkmod = ServerInstance->Modules->Find("m_spanningtree.so"); - ServerInstance->Modules->SetPriority(this, I_OnUserMessage, PRIORITY_AFTER, &linkmod); + ServerInstance->Modules->SetPriority(this, I_OnUserMessage, PRIORITY_AFTER, linkmod); } }; diff --git a/src/modules/m_allowinvite.cpp b/src/modules/m_allowinvite.cpp index 08a5f542a..05e76113a 100644 --- a/src/modules/m_allowinvite.cpp +++ b/src/modules/m_allowinvite.cpp @@ -19,8 +19,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for channel mode +A, allowing /invite freely on a channel and extban A to deny specific users it */ - class AllowInvite : public SimpleChannelModeHandler { public: @@ -36,19 +34,12 @@ class ModuleAllowInvite : public Module { } - void init() - { - ServerInstance->Modules->AddService(ni); - Implementation eventlist[] = { I_OnUserPreInvite, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('A'); + tokens["EXTBAN"].push_back('A'); } - virtual ModResult OnUserPreInvite(User* user,User* dest,Channel* channel, time_t timeout) + ModResult OnUserPreInvite(User* user,User* dest,Channel* channel, time_t timeout) CXX11_OVERRIDE { if (IS_LOCAL(user)) { @@ -56,10 +47,10 @@ class ModuleAllowInvite : public Module if (res == MOD_RES_DENY) { // Matching extban, explicitly deny /invite - user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You are banned from using INVITE", user->nick.c_str(), channel->name.c_str()); + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You are banned from using INVITE", channel->name.c_str()); return res; } - if (channel->IsModeSet('A') || res == MOD_RES_ALLOW) + if (channel->IsModeSet(ni) || res == MOD_RES_ALLOW) { // Explicitly allow /invite return MOD_RES_ALLOW; @@ -69,11 +60,7 @@ class ModuleAllowInvite : public Module return MOD_RES_PASSTHRU; } - virtual ~ModuleAllowInvite() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for channel mode +A, allowing /invite freely on a channel and extban A to deny specific users it",VF_VENDOR); } diff --git a/src/modules/m_alltime.cpp b/src/modules/m_alltime.cpp index 38ae4b254..075064c62 100644 --- a/src/modules/m_alltime.cpp +++ b/src/modules/m_alltime.cpp @@ -21,22 +21,17 @@ #include "inspircd.h" -/* $ModDesc: Display timestamps from all servers connected to the network */ - class CommandAlltime : public Command { public: CommandAlltime(Module* Creator) : Command(Creator, "ALLTIME", 0) { flags_needed = 'o'; - translation.push_back(TR_END); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) { - char fmtdate[64]; - time_t now = ServerInstance->Time(); - strftime(fmtdate, sizeof(fmtdate), "%Y-%m-%d %H:%M:%S", gmtime(&now)); + const std::string fmtdate = InspIRCd::TimeString(ServerInstance->Time(), "%Y-%m-%d %H:%M:%S", true); std::string msg = ":" + ServerInstance->Config->ServerName + " NOTICE " + user->nick + " :System time is " + fmtdate + " (" + ConvToStr(ServerInstance->Time()) + ") on " + ServerInstance->Config->ServerName; @@ -52,7 +47,6 @@ class CommandAlltime : public Command } }; - class Modulealltime : public Module { CommandAlltime mycommand; @@ -62,16 +56,7 @@ class Modulealltime : public Module { } - void init() - { - ServerInstance->Modules->AddService(mycommand); - } - - virtual ~Modulealltime() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Display timestamps from all servers connected to the network", VF_OPTCOMMON | VF_VENDOR); } diff --git a/src/modules/m_auditorium.cpp b/src/modules/m_auditorium.cpp index 2a8edb9d4..7ad7ba1a3 100644 --- a/src/modules/m_auditorium.cpp +++ b/src/modules/m_auditorium.cpp @@ -22,55 +22,28 @@ #include "inspircd.h" -/* $ModDesc: Allows for auditorium channels (+u) where nobody can see others joining and parting or the nick list */ - -class AuditoriumMode : public ModeHandler +class AuditoriumMode : public SimpleChannelModeHandler { public: - AuditoriumMode(Module* Creator) : ModeHandler(Creator, "auditorium", 'u', PARAM_NONE, MODETYPE_CHANNEL) + AuditoriumMode(Module* Creator) : SimpleChannelModeHandler(Creator, "auditorium", 'u') { levelrequired = OP_VALUE; } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - if (channel->IsModeSet(this) == adding) - return MODEACTION_DENY; - channel->SetMode(this, adding); - return MODEACTION_ALLOW; - } }; class ModuleAuditorium : public Module { - private: AuditoriumMode aum; bool OpsVisible; bool OpsCanSee; bool OperCanSee; + public: ModuleAuditorium() : aum(this) { } - void init() - { - ServerInstance->Modules->AddService(aum); - - OnRehash(NULL); - - Implementation eventlist[] = { - I_OnUserJoin, I_OnUserPart, I_OnUserKick, - I_OnBuildNeighborList, I_OnNamesListItem, I_OnSendWhoLine, - I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ~ModuleAuditorium() - { - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("auditorium"); OpsVisible = tag->getBool("opvisible"); @@ -78,7 +51,7 @@ class ModuleAuditorium : public Module OperCanSee = tag->getBool("opercansee", true); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows for auditorium channels (+u) where nobody can see others joining and parting or the nick list", VF_VENDOR); } @@ -112,19 +85,16 @@ class ModuleAuditorium : public Module return false; } - void OnNamesListItem(User* issuer, Membership* memb, std::string &prefixes, std::string &nick) + ModResult OnNamesListItem(User* issuer, Membership* memb, std::string& prefixes, std::string& nick) CXX11_OVERRIDE { - // Some module already hid this from being displayed, don't bother - if (nick.empty()) - return; - if (IsVisible(memb)) - return; + return MOD_RES_PASSTHRU; if (CanSee(issuer, memb)) - return; + return MOD_RES_PASSTHRU; - nick.clear(); + // Don't display this user in the NAMES list + return MOD_RES_DENY; } /** Build CUList for showing this join/part/kick */ @@ -133,43 +103,45 @@ class ModuleAuditorium : public Module if (IsVisible(memb)) return; - const UserMembList* users = memb->chan->GetUsers(); - for(UserMembCIter i = users->begin(); i != users->end(); i++) + const Channel::MemberMap& users = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) { if (IS_LOCAL(i->first) && !CanSee(i->first, memb)) excepts.insert(i->first); } } - void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) + void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) CXX11_OVERRIDE { BuildExcept(memb, excepts); } - void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) + void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) CXX11_OVERRIDE { BuildExcept(memb, excepts); } - void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) + void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) CXX11_OVERRIDE { BuildExcept(memb, excepts); } - void OnBuildNeighborList(User* source, UserChanList &include, std::map<User*,bool> &exception) + void OnBuildNeighborList(User* source, IncludeChanList& include, std::map<User*, bool>& exception) CXX11_OVERRIDE { - UCListIter i = include.begin(); - while (i != include.end()) + for (IncludeChanList::iterator i = include.begin(); i != include.end(); ) { - Channel* c = *i++; - Membership* memb = c->GetUser(source); - if (!memb || IsVisible(memb)) + Membership* memb = *i; + if (IsVisible(memb)) + { + ++i; continue; + } + // this channel should not be considered when listing my neighbors - include.erase(c); + i = include.erase(i); // however, that might hide me from ops that can see me... - const UserMembList* users = c->GetUsers(); - for(UserMembCIter j = users->begin(); j != users->end(); j++) + const Channel::MemberMap& users = memb->chan->GetUsers(); + for(Channel::MemberMap::const_iterator j = users.begin(); j != users.end(); ++j) { if (IS_LOCAL(j->first) && CanSee(j->first, memb)) exception[j->first] = true; @@ -177,13 +149,11 @@ class ModuleAuditorium : public Module } } - void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, std::string& line) + void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, Membership* memb, std::string& line) CXX11_OVERRIDE { - Channel* channel = ServerInstance->FindChan(params[0]); - if (!channel) + if (!memb) return; - Membership* memb = channel->GetUser(user); - if ((!memb) || (IsVisible(memb))) + if (IsVisible(memb)) return; if (CanSee(source, memb)) return; diff --git a/src/modules/m_autoop.cpp b/src/modules/m_autoop.cpp index 0c0e8f579..2b9c2e1c2 100644 --- a/src/modules/m_autoop.cpp +++ b/src/modules/m_autoop.cpp @@ -19,9 +19,7 @@ #include "inspircd.h" -#include "u_listmode.h" - -/* $ModDesc: Provides support for the +w channel mode, autoop list */ +#include "listmode.h" /** Handles +w channel mode */ @@ -34,17 +32,13 @@ class AutoOpList : public ListModeBase tidy = false; } - ModeHandler* FindMode(const std::string& mid) + PrefixMode* FindMode(const std::string& mid) { if (mid.length() == 1) - return ServerInstance->Modes->FindMode(mid[0], MODETYPE_CHANNEL); - for(char c='A'; c <= 'z'; c++) - { - ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL); - if (mh && mh->name == mid) - return mh; - } - return NULL; + return ServerInstance->Modes->FindPrefixMode(mid[0]); + + ModeHandler* mh = ServerInstance->Modes->FindMode(mid, MODETYPE_CHANNEL); + return mh ? mh->IsPrefixMode() : NULL; } ModResult AccessCheck(User* source, Channel* channel, std::string ¶meter, bool adding) @@ -53,13 +47,13 @@ class AutoOpList : public ListModeBase if (pos == 0 || pos == std::string::npos) return adding ? MOD_RES_DENY : MOD_RES_PASSTHRU; unsigned int mylevel = channel->GetPrefixValue(source); - std::string mid = parameter.substr(0, pos); - ModeHandler* mh = FindMode(mid); + std::string mid(parameter, 0, pos); + PrefixMode* mh = FindMode(mid); - if (adding && (!mh || !mh->GetPrefixRank())) + if (adding && !mh) { - source->WriteNumeric(415, "%s %s :Cannot find prefix mode '%s' for autoop", - source->nick.c_str(), mid.c_str(), mid.c_str()); + source->WriteNumeric(415, "%s :Cannot find prefix mode '%s' for autoop", + mid.c_str(), mid.c_str()); return MOD_RES_DENY; } else if (!mh) @@ -70,8 +64,8 @@ class AutoOpList : public ListModeBase return MOD_RES_DENY; if (mh->GetLevelRequired() > mylevel) { - source->WriteNumeric(482, "%s %s :You must be able to set mode '%s' to include it in an autoop", - source->nick.c_str(), channel->name.c_str(), mid.c_str()); + source->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You must be able to set mode '%s' to include it in an autoop", + channel->name.c_str(), mid.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; @@ -82,62 +76,42 @@ class ModuleAutoOp : public Module { AutoOpList mh; -public: + public: ModuleAutoOp() : mh(this) { } - void init() - { - ServerInstance->Modules->AddService(mh); - mh.DoImplements(this); - - Implementation list[] = { I_OnPostJoin, }; - ServerInstance->Modules->Attach(list, this, sizeof(list)/sizeof(Implementation)); - } - - void OnPostJoin(Membership *memb) + void OnPostJoin(Membership *memb) CXX11_OVERRIDE { if (!IS_LOCAL(memb->user)) return; - modelist* list = mh.extItem.get(memb->chan); + ListModeBase::ModeList* list = mh.GetList(memb->chan); if (list) { - std::string modeline("+"); - std::vector<std::string> modechange; - modechange.push_back(memb->chan->name); - for (modelist::iterator it = list->begin(); it != list->end(); it++) + Modes::ChangeList changelist; + for (ListModeBase::ModeList::iterator it = list->begin(); it != list->end(); it++) { std::string::size_type colon = it->mask.find(':'); if (colon == std::string::npos) continue; if (memb->chan->CheckBan(memb->user, it->mask.substr(colon+1))) { - ModeHandler* given = mh.FindMode(it->mask.substr(0, colon)); - if (given && given->GetPrefixRank()) - modeline.push_back(given->GetModeChar()); + PrefixMode* given = mh.FindMode(it->mask.substr(0, colon)); + if (given) + changelist.push_add(given, memb->user->nick); } } - modechange.push_back(modeline); - for(std::string::size_type i = modeline.length(); i > 1; --i) // we use "i > 1" instead of "i" so we skip the + - modechange.push_back(memb->user->nick); - if(modechange.size() >= 3) - ServerInstance->SendGlobalMode(modechange, ServerInstance->FakeClient); + ServerInstance->Modes->Process(ServerInstance->FakeClient, memb->chan, NULL, changelist); } } - void OnSyncChannel(Channel* chan, Module* proto, void* opaque) - { - mh.DoSyncChannel(chan, proto, opaque); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { mh.DoRehash(); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the +w channel mode", VF_VENDOR); } diff --git a/src/modules/m_banexception.cpp b/src/modules/m_banexception.cpp index 1811f743d..b29b39747 100644 --- a/src/modules/m_banexception.cpp +++ b/src/modules/m_banexception.cpp @@ -22,10 +22,7 @@ #include "inspircd.h" -#include "u_listmode.h" - -/* $ModDesc: Provides support for the +e channel mode */ -/* $ModDep: ../../include/u_listmode.h */ +#include "listmode.h" /* Written by Om<om@inspircd.org>, April 2005. */ /* Rewritten to use the listmode utility by Om, December 2005 */ @@ -49,85 +46,63 @@ class ModuleBanException : public Module { BanException be; -public: + public: ModuleBanException() : be(this) { } - void init() + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(be); - - be.DoImplements(this); - Implementation list[] = { I_OnRehash, I_On005Numeric, I_OnExtBanCheck, I_OnCheckChannelBan }; - ServerInstance->Modules->Attach(list, this, sizeof(list)/sizeof(Implementation)); + tokens["EXCEPTS"] = "e"; } - void On005Numeric(std::string &output) + ModResult OnExtBanCheck(User *user, Channel *chan, char type) CXX11_OVERRIDE { - output.append(" EXCEPTS=e"); - } + ListModeBase::ModeList* list = be.GetList(chan); + if (!list) + return MOD_RES_PASSTHRU; - ModResult OnExtBanCheck(User *user, Channel *chan, char type) - { - if (chan != NULL) + for (ListModeBase::ModeList::iterator it = list->begin(); it != list->end(); it++) { - modelist *list = be.extItem.get(chan); - - if (!list) - return MOD_RES_PASSTHRU; + if (it->mask[0] != type || it->mask[1] != ':') + continue; - for (modelist::iterator it = list->begin(); it != list->end(); it++) + if (chan->CheckBan(user, it->mask.substr(2))) { - if (it->mask[0] != type || it->mask[1] != ':') - continue; - - if (chan->CheckBan(user, it->mask.substr(2))) - { - // They match an entry on the list, so let them pass this. - return MOD_RES_ALLOW; - } + // They match an entry on the list, so let them pass this. + return MOD_RES_ALLOW; } } return MOD_RES_PASSTHRU; } - ModResult OnCheckChannelBan(User* user, Channel* chan) + ModResult OnCheckChannelBan(User* user, Channel* chan) CXX11_OVERRIDE { - if (chan) + ListModeBase::ModeList* list = be.GetList(chan); + if (!list) { - modelist *list = be.extItem.get(chan); - - if (!list) - { - // No list, proceed normally - return MOD_RES_PASSTHRU; - } + // No list, proceed normally + return MOD_RES_PASSTHRU; + } - for (modelist::iterator it = list->begin(); it != list->end(); it++) + for (ListModeBase::ModeList::iterator it = list->begin(); it != list->end(); it++) + { + if (chan->CheckBan(user, it->mask)) { - if (chan->CheckBan(user, it->mask)) - { - // They match an entry on the list, so let them in. - return MOD_RES_ALLOW; - } + // They match an entry on the list, so let them in. + return MOD_RES_ALLOW; } } return MOD_RES_PASSTHRU; } - void OnSyncChannel(Channel* chan, Module* proto, void* opaque) - { - be.DoSyncChannel(chan, proto, opaque); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { be.DoRehash(); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the +e channel mode", VF_VENDOR); } diff --git a/src/modules/m_banredirect.cpp b/src/modules/m_banredirect.cpp index 1b9e361bf..d3490acc0 100644 --- a/src/modules/m_banredirect.cpp +++ b/src/modules/m_banredirect.cpp @@ -23,9 +23,7 @@ #include "inspircd.h" -#include "u_listmode.h" - -/* $ModDesc: Allows an extended ban (+b) syntax redirecting banned users to another channel */ +#include "listmode.h" /* Originally written by Om, January 2009 */ @@ -43,18 +41,20 @@ class BanRedirectEntry }; typedef std::vector<BanRedirectEntry> BanRedirectList; -typedef std::deque<std::string> StringDeque; class BanRedirect : public ModeWatcher { + ChanModeReference ban; public: SimpleExtItem<BanRedirectList> extItem; - BanRedirect(Module* parent) : ModeWatcher(parent, 'b', MODETYPE_CHANNEL), - extItem("banredirect", parent) + BanRedirect(Module* parent) + : ModeWatcher(parent, "ban", MODETYPE_CHANNEL) + , ban(parent, "ban") + , extItem("banredirect", ExtensionItem::EXT_CHANNEL, parent) { } - bool BeforeMode(User* source, User* dest, Channel* channel, std::string ¶m, bool adding, ModeType type) + bool BeforeMode(User* source, User* dest, Channel* channel, std::string ¶m, bool adding) { /* nick!ident@host -> nick!ident@host * nick!ident@host#chan -> nick!ident@host#chan @@ -63,14 +63,13 @@ class BanRedirect : public ModeWatcher * nick#chan -> nick!*@*#chan */ - if(channel && (type == MODETYPE_CHANNEL) && param.length()) + if ((channel) && !param.empty()) { BanRedirectList* redirects; std::string mask[4]; enum { NICK, IDENT, HOST, CHAN } current = NICK; std::string::iterator start_pos = param.begin(); - long maxbans = channel->GetMaxBans(); if (param.length() >= 2 && param[1] == ':') return true; @@ -78,9 +77,12 @@ class BanRedirect : public ModeWatcher if (param.find('#') == std::string::npos) return true; - if(adding && (channel->bans.size() > static_cast<unsigned>(maxbans))) + ListModeBase* banlm = static_cast<ListModeBase*>(*ban); + unsigned int maxbans = banlm->GetLimit(channel); + ListModeBase::ModeList* list = banlm->GetList(channel); + if ((list) && (adding) && (maxbans <= list->size())) { - source->WriteNumeric(478, "%s %s :Channel ban list for %s is full (maximum entries for this channel is %ld)", source->nick.c_str(), channel->name.c_str(), channel->name.c_str(), maxbans); + source->WriteNumeric(ERR_BANLISTFULL, "%s :Channel ban list for %s is full (maximum entries for this channel is %u)", channel->name.c_str(), channel->name.c_str(), maxbans); return false; } @@ -89,23 +91,25 @@ class BanRedirect : public ModeWatcher switch(*curr) { case '!': + if (current != NICK) + break; mask[current].assign(start_pos, curr); current = IDENT; start_pos = curr+1; break; case '@': + if (current != IDENT) + break; mask[current].assign(start_pos, curr); current = HOST; start_pos = curr+1; break; case '#': - /* bug #921: don't barf when redirecting to ## channels */ - if (current != CHAN) - { - mask[current].assign(start_pos, curr); - current = CHAN; - start_pos = curr; - } + if (current == CHAN) + break; + mask[current].assign(start_pos, curr); + current = CHAN; + start_pos = curr; break; } } @@ -144,27 +148,27 @@ class BanRedirect : public ModeWatcher { if (adding && IS_LOCAL(source)) { - if (!ServerInstance->IsChannel(mask[CHAN].c_str(), ServerInstance->Config->Limits.ChanMax)) + if (!ServerInstance->IsChannel(mask[CHAN])) { - source->WriteNumeric(403, "%s %s :Invalid channel name in redirection (%s)", source->nick.c_str(), channel->name.c_str(), mask[CHAN].c_str()); + source->WriteNumeric(ERR_NOSUCHCHANNEL, "%s :Invalid channel name in redirection (%s)", channel->name.c_str(), mask[CHAN].c_str()); return false; } Channel *c = ServerInstance->FindChan(mask[CHAN]); if (!c) { - source->WriteNumeric(690, "%s :Target channel %s must exist to be set as a redirect.",source->nick.c_str(),mask[CHAN].c_str()); + source->WriteNumeric(690, ":Target channel %s must exist to be set as a redirect.", mask[CHAN].c_str()); return false; } else if (adding && c->GetPrefixValue(source) < OP_VALUE) { - source->WriteNumeric(690, "%s :You must be opped on %s to set it as a redirect.",source->nick.c_str(), mask[CHAN].c_str()); + source->WriteNumeric(690, ":You must be opped on %s to set it as a redirect.", mask[CHAN].c_str()); return false; } if (assign(channel->name) == mask[CHAN]) { - source->WriteNumeric(690, "%s %s :You cannot set a ban redirection to the channel the ban is on", source->nick.c_str(), channel->name.c_str()); + source->WriteNumeric(690, "%s :You cannot set a ban redirection to the channel the ban is on", channel->name.c_str()); return false; } } @@ -224,26 +228,19 @@ class ModuleBanRedirect : public Module { BanRedirect re; bool nofollow; + ChanModeReference limitmode; + ChanModeReference redirectmode; public: ModuleBanRedirect() - : re(this) + : re(this) + , nofollow(false) + , limitmode(this, "limit") + , redirectmode(this, "redirect") { - nofollow = false; - } - - - void init() - { - if(!ServerInstance->Modes->AddModeWatcher(&re)) - throw ModuleException("Could not add mode watcher"); - - ServerInstance->Modules->AddService(re.extItem); - Implementation list[] = { I_OnUserPreJoin }; - ServerInstance->Modules->Attach(list, this, sizeof(list)/sizeof(Implementation)); } - virtual void OnCleanup(int target_type, void* item) + void OnCleanup(int target_type, void* item) CXX11_OVERRIDE { if(target_type == TYPE_CHANNEL) { @@ -252,33 +249,21 @@ class ModuleBanRedirect : public Module if(redirects) { - irc::modestacker modestack(false); - StringDeque stackresult; - std::vector<std::string> mode_junk; - mode_junk.push_back(chan->name); + ModeHandler* ban = ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL); + Modes::ChangeList changelist; for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) - { - modestack.Push('b', i->targetchan.insert(0, i->banmask)); - } + changelist.push_remove(ban, i->targetchan.insert(0, i->banmask)); for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) - { - modestack.PushPlus(); - modestack.Push('b', i->banmask); - } + changelist.push_add(ban, i->banmask); - while(modestack.GetStackedLine(stackresult)) - { - mode_junk.insert(mode_junk.end(), stackresult.begin(), stackresult.end()); - ServerInstance->SendMode(mode_junk, ServerInstance->FakeClient); - mode_junk.erase(mode_junk.begin() + 1, mode_junk.end()); - } + ServerInstance->Modes->Process(ServerInstance->FakeClient, chan, NULL, changelist, ModeParser::MODE_LOCALONLY); } } } - virtual ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (chan) { @@ -322,19 +307,19 @@ class ModuleBanRedirect : public Module std::string destlimit; if (destchan) - destlimit = destchan->GetModeParameter('l'); + destlimit = destchan->GetModeParameter(limitmode); - if(destchan && ServerInstance->Modules->Find("m_redirect.so") && destchan->IsModeSet('L') && !destlimit.empty() && (destchan->GetUserCounter() >= atoi(destlimit.c_str()))) + if(destchan && destchan->IsModeSet(redirectmode) && !destlimit.empty() && (destchan->GetUserCounter() >= atoi(destlimit.c_str()))) { - user->WriteNumeric(474, "%s %s :Cannot join channel (You are banned)", user->nick.c_str(), chan->name.c_str()); + user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You are banned)", chan->name.c_str()); return MOD_RES_DENY; } else { - user->WriteNumeric(474, "%s %s :Cannot join channel (You are banned)", user->nick.c_str(), chan->name.c_str()); - user->WriteNumeric(470, "%s %s %s :You are banned from this channel, so you are automatically transferred to the redirected channel.", user->nick.c_str(), chan->name.c_str(), redir->targetchan.c_str()); + user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You are banned)", chan->name.c_str()); + user->WriteNumeric(470, "%s %s :You are banned from this channel, so you are automatically transferred to the redirected channel.", chan->name.c_str(), redir->targetchan.c_str()); nofollow = true; - Channel::JoinUser(user, redir->targetchan.c_str(), false, "", false, ServerInstance->Time()); + Channel::JoinUser(user, redir->targetchan); nofollow = false; return MOD_RES_DENY; } @@ -345,14 +330,7 @@ class ModuleBanRedirect : public Module return MOD_RES_PASSTHRU; } - virtual ~ModuleBanRedirect() - { - /* XXX is this the best place to do this? */ - if (!ServerInstance->Modes->DelModeWatcher(&re)) - ServerInstance->Logs->Log("m_banredirect.so", DEBUG, "Failed to delete modewatcher!"); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows an extended ban (+b) syntax redirecting banned users to another channel", VF_COMMON|VF_VENDOR); } diff --git a/src/modules/m_bcrypt.cpp b/src/modules/m_bcrypt.cpp new file mode 100644 index 000000000..8a025a0d6 --- /dev/null +++ b/src/modules/m_bcrypt.cpp @@ -0,0 +1,987 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * Most of the code in this file is taken from + * http://openwall.com/crypt/crypt_blowfish-1.3.tar.gz + */ + +/* + * The crypt_blowfish homepage is: + * + * http://www.openwall.com/crypt/ + * + * This code comes from John the Ripper password cracker, with reentrant + * and crypt(3) interfaces added, but optimizations specific to password + * cracking removed. + * + * Written by Solar Designer <solar at openwall.com> in 1998-2014. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 1998-2014 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * It is my intent that you should be able to use this on your system, + * as part of a software package, or anywhere else to improve security, + * ensure compatibility, or for any other purpose. I would appreciate + * it if you give credit where it is due and keep your modifications in + * the public domain as well, but I don't require that in order to let + * you place this code and any modifications you make under a license + * of your choice. + * + * This implementation is fully compatible with OpenBSD's bcrypt.c for prefix + * "$2b$", originally by Niels Provos <provos at citi.umich.edu>, and it uses + * some of his ideas. The password hashing algorithm was designed by David + * Mazieres <dm at lcs.mit.edu>. For information on the level of + * compatibility for bcrypt hash prefixes other than "$2b$", please refer to + * the comments in BF_set_key() below and to the included crypt(3) man page. + * + * There's a paper on the algorithm that explains its design decisions: + * + * http://www.usenix.org/events/usenix99/provos.html + * + * Some of the tricks in BF_ROUND might be inspired by Eric Young's + * Blowfish library (I can't be sure if I would think of something if I + * hadn't seen his code). + */ + +#include <string.h> + +#ifdef __i386__ +#define BF_SCALE 1 +#elif defined(__x86_64__) || defined(__alpha__) || defined(__hppa__) +#define BF_SCALE 1 +#else +#define BF_SCALE 0 +#endif + +typedef unsigned int BF_word; +typedef signed int BF_word_signed; + +/* Number of Blowfish rounds, this is also hardcoded into a few places */ +#define BF_N 16 + +typedef BF_word BF_key[BF_N + 2]; + +typedef struct { + BF_word S[4][0x100]; + BF_key P; +} BF_ctx; + +/* + * Magic IV for 64 Blowfish encryptions that we do at the end. + * The string is "OrpheanBeholderScryDoubt" on big-endian. + */ +static BF_word BF_magic_w[6] = { + 0x4F727068, 0x65616E42, 0x65686F6C, + 0x64657253, 0x63727944, 0x6F756274 +}; + +/* + * P-box and S-box tables initialized with digits of Pi. + */ +static BF_ctx BF_init_state = { + { + { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + }, { + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + }, { + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + }, { + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + } + }, { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b + } +}; + +static unsigned char BF_itoa64[64 + 1] = + "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +static unsigned char BF_atoi64[0x60] = { + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 1, + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 64, 64, 64, 64, + 64, 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, 64, 64, 64, 64, 64, + 64, 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, 64, 64, 64, 64, 64 +}; + +#define BF_safe_atoi64(dst, src) \ +{ \ + tmp = (unsigned char)(src); \ + if ((unsigned int)(tmp -= 0x20) >= 0x60) return -1; \ + tmp = BF_atoi64[tmp]; \ + if (tmp > 63) return -1; \ + (dst) = tmp; \ +} + +static int BF_decode(BF_word *dst, const char *src, int size) +{ + unsigned char *dptr = (unsigned char *)dst; + unsigned char *end = dptr + size; + const unsigned char *sptr = (const unsigned char *)src; + unsigned int tmp, c1, c2, c3, c4; + + do { + BF_safe_atoi64(c1, *sptr++); + BF_safe_atoi64(c2, *sptr++); + *dptr++ = (c1 << 2) | ((c2 & 0x30) >> 4); + if (dptr >= end) break; + + BF_safe_atoi64(c3, *sptr++); + *dptr++ = ((c2 & 0x0F) << 4) | ((c3 & 0x3C) >> 2); + if (dptr >= end) break; + + BF_safe_atoi64(c4, *sptr++); + *dptr++ = ((c3 & 0x03) << 6) | c4; + } while (dptr < end); + + return 0; +} + +static void BF_encode(char *dst, const BF_word *src, int size) +{ + const unsigned char *sptr = (const unsigned char *)src; + const unsigned char *end = sptr + size; + unsigned char *dptr = (unsigned char *)dst; + unsigned int c1, c2; + + do { + c1 = *sptr++; + *dptr++ = BF_itoa64[c1 >> 2]; + c1 = (c1 & 0x03) << 4; + if (sptr >= end) { + *dptr++ = BF_itoa64[c1]; + break; + } + + c2 = *sptr++; + c1 |= c2 >> 4; + *dptr++ = BF_itoa64[c1]; + c1 = (c2 & 0x0f) << 2; + if (sptr >= end) { + *dptr++ = BF_itoa64[c1]; + break; + } + + c2 = *sptr++; + c1 |= c2 >> 6; + *dptr++ = BF_itoa64[c1]; + *dptr++ = BF_itoa64[c2 & 0x3f]; + } while (sptr < end); +} + +static void BF_swap(BF_word *x, int count) +{ + static int endianness_check = 1; + char *is_little_endian = (char *)&endianness_check; + BF_word tmp; + + if (*is_little_endian) + do { + tmp = *x; + tmp = (tmp << 16) | (tmp >> 16); + *x++ = ((tmp & 0x00FF00FF) << 8) | ((tmp >> 8) & 0x00FF00FF); + } while (--count); +} + +#if BF_SCALE +/* Architectures which can shift addresses left by 2 bits with no extra cost */ +#define BF_ROUND(L, R, N) \ + tmp1 = L & 0xFF; \ + tmp2 = L >> 8; \ + tmp2 &= 0xFF; \ + tmp3 = L >> 16; \ + tmp3 &= 0xFF; \ + tmp4 = L >> 24; \ + tmp1 = data.ctx.S[3][tmp1]; \ + tmp2 = data.ctx.S[2][tmp2]; \ + tmp3 = data.ctx.S[1][tmp3]; \ + tmp3 += data.ctx.S[0][tmp4]; \ + tmp3 ^= tmp2; \ + R ^= data.ctx.P[N + 1]; \ + tmp3 += tmp1; \ + R ^= tmp3; +#else +/* Architectures with no complicated addressing modes supported */ +#define BF_INDEX(S, i) \ + (*((BF_word *)(((unsigned char *)S) + (i)))) +#define BF_ROUND(L, R, N) \ + tmp1 = L & 0xFF; \ + tmp1 <<= 2; \ + tmp2 = L >> 6; \ + tmp2 &= 0x3FC; \ + tmp3 = L >> 14; \ + tmp3 &= 0x3FC; \ + tmp4 = L >> 22; \ + tmp4 &= 0x3FC; \ + tmp1 = BF_INDEX(data.ctx.S[3], tmp1); \ + tmp2 = BF_INDEX(data.ctx.S[2], tmp2); \ + tmp3 = BF_INDEX(data.ctx.S[1], tmp3); \ + tmp3 += BF_INDEX(data.ctx.S[0], tmp4); \ + tmp3 ^= tmp2; \ + R ^= data.ctx.P[N + 1]; \ + tmp3 += tmp1; \ + R ^= tmp3; +#endif + +/* + * Encrypt one block, BF_N is hardcoded here. + */ +#define BF_ENCRYPT \ + L ^= data.ctx.P[0]; \ + BF_ROUND(L, R, 0); \ + BF_ROUND(R, L, 1); \ + BF_ROUND(L, R, 2); \ + BF_ROUND(R, L, 3); \ + BF_ROUND(L, R, 4); \ + BF_ROUND(R, L, 5); \ + BF_ROUND(L, R, 6); \ + BF_ROUND(R, L, 7); \ + BF_ROUND(L, R, 8); \ + BF_ROUND(R, L, 9); \ + BF_ROUND(L, R, 10); \ + BF_ROUND(R, L, 11); \ + BF_ROUND(L, R, 12); \ + BF_ROUND(R, L, 13); \ + BF_ROUND(L, R, 14); \ + BF_ROUND(R, L, 15); \ + tmp4 = R; \ + R = L; \ + L = tmp4 ^ data.ctx.P[BF_N + 1]; + +#define BF_body() \ + L = R = 0; \ + ptr = data.ctx.P; \ + do { \ + ptr += 2; \ + BF_ENCRYPT; \ + *(ptr - 2) = L; \ + *(ptr - 1) = R; \ + } while (ptr < &data.ctx.P[BF_N + 2]); \ +\ + ptr = data.ctx.S[0]; \ + do { \ + ptr += 2; \ + BF_ENCRYPT; \ + *(ptr - 2) = L; \ + *(ptr - 1) = R; \ + } while (ptr < &data.ctx.S[3][0xFF]); + +static void BF_set_key(const char *key, BF_key expanded, BF_key initial, + unsigned char flags) +{ + const char *ptr = key; + unsigned int bug, i, j; + BF_word safety, sign, diff, tmp[2]; + +/* + * There was a sign extension bug in older revisions of this function. While + * we would have liked to simply fix the bug and move on, we have to provide + * a backwards compatibility feature (essentially the bug) for some systems and + * a safety measure for some others. The latter is needed because for certain + * multiple inputs to the buggy algorithm there exist easily found inputs to + * the correct algorithm that produce the same hash. Thus, we optionally + * deviate from the correct algorithm just enough to avoid such collisions. + * While the bug itself affected the majority of passwords containing + * characters with the 8th bit set (although only a percentage of those in a + * collision-producing way), the anti-collision safety measure affects + * only a subset of passwords containing the '\xff' character (not even all of + * those passwords, just some of them). This character is not found in valid + * UTF-8 sequences and is rarely used in popular 8-bit character encodings. + * Thus, the safety measure is unlikely to cause much annoyance, and is a + * reasonable tradeoff to use when authenticating against existing hashes that + * are not reliably known to have been computed with the correct algorithm. + * + * We use an approach that tries to minimize side-channel leaks of password + * information - that is, we mostly use fixed-cost bitwise operations instead + * of branches or table lookups. (One conditional branch based on password + * length remains. It is not part of the bug aftermath, though, and is + * difficult and possibly unreasonable to avoid given the use of C strings by + * the caller, which results in similar timing leaks anyway.) + * + * For actual implementation, we set an array index in the variable "bug" + * (0 means no bug, 1 means sign extension bug emulation) and a flag in the + * variable "safety" (bit 16 is set when the safety measure is requested). + * Valid combinations of settings are: + * + * Prefix "$2a$": bug = 0, safety = 0x10000 + * Prefix "$2b$": bug = 0, safety = 0 + * Prefix "$2x$": bug = 1, safety = 0 + * Prefix "$2y$": bug = 0, safety = 0 + */ + bug = (unsigned int)flags & 1; + safety = ((BF_word)flags & 2) << 15; + + sign = diff = 0; + + for (i = 0; i < BF_N + 2; i++) { + tmp[0] = tmp[1] = 0; + for (j = 0; j < 4; j++) { + tmp[0] <<= 8; + tmp[0] |= (unsigned char)*ptr; /* correct */ + tmp[1] <<= 8; + tmp[1] |= (BF_word_signed)(signed char)*ptr; /* bug */ +/* + * Sign extension in the first char has no effect - nothing to overwrite yet, + * and those extra 24 bits will be fully shifted out of the 32-bit word. For + * chars 2, 3, 4 in each four-char block, we set bit 7 of "sign" if sign + * extension in tmp[1] occurs. Once this flag is set, it remains set. + */ + if (j) + sign |= tmp[1] & 0x80; + if (!*ptr) + ptr = key; + else + ptr++; + } + diff |= tmp[0] ^ tmp[1]; /* Non-zero on any differences */ + + expanded[i] = tmp[bug]; + initial[i] = BF_init_state.P[i] ^ tmp[bug]; + } + +/* + * At this point, "diff" is zero iff the correct and buggy algorithms produced + * exactly the same result. If so and if "sign" is non-zero, which indicates + * that there was a non-benign sign extension, this means that we have a + * collision between the correctly computed hash for this password and a set of + * passwords that could be supplied to the buggy algorithm. Our safety measure + * is meant to protect from such many-buggy to one-correct collisions, by + * deviating from the correct algorithm in such cases. Let's check for this. + */ + diff |= diff >> 16; /* still zero iff exact match */ + diff &= 0xffff; /* ditto */ + diff += 0xffff; /* bit 16 set iff "diff" was non-zero (on non-match) */ + sign <<= 9; /* move the non-benign sign extension flag to bit 16 */ + sign &= ~diff & safety; /* action needed? */ + +/* + * If we have determined that we need to deviate from the correct algorithm, + * flip bit 16 in initial expanded key. (The choice of 16 is arbitrary, but + * let's stick to it now. It came out of the approach we used above, and it's + * not any worse than any other choice we could make.) + * + * It is crucial that we don't do the same to the expanded key used in the main + * Eksblowfish loop. By doing it to only one of these two, we deviate from a + * state that could be directly specified by a password to the buggy algorithm + * (and to the fully correct one as well, but that's a side-effect). + */ + initial[0] ^= sign; +} + +static const unsigned char flags_by_subtype[26] = + {2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 0}; + +static char *BF_crypt(const char *key, const char *setting, + char *output, int size, + BF_word min) +{ + struct { + BF_ctx ctx; + BF_key expanded_key; + union { + BF_word salt[4]; + BF_word output[6]; + } binary; + } data; + BF_word L, R; + BF_word tmp1, tmp2, tmp3, tmp4; + BF_word *ptr; + BF_word count; + int i; + + if (size < 7 + 22 + 31 + 1) { + return NULL; + } + + if (setting[0] != '$' || + setting[1] != '2' || + setting[2] < 'a' || setting[2] > 'z' || + !flags_by_subtype[(unsigned int)(unsigned char)setting[2] - 'a'] || + setting[3] != '$' || + setting[4] < '0' || setting[4] > '3' || + setting[5] < '0' || setting[5] > '9' || + (setting[4] == '3' && setting[5] > '1') || + setting[6] != '$') { + return NULL; + } + + count = (BF_word)1 << ((setting[4] - '0') * 10 + (setting[5] - '0')); + if (count < min || BF_decode(data.binary.salt, &setting[7], 16)) { + return NULL; + } + BF_swap(data.binary.salt, 4); + + BF_set_key(key, data.expanded_key, data.ctx.P, + flags_by_subtype[(unsigned int)(unsigned char)setting[2] - 'a']); + + memcpy(data.ctx.S, BF_init_state.S, sizeof(data.ctx.S)); + + L = R = 0; + for (i = 0; i < BF_N + 2; i += 2) { + L ^= data.binary.salt[i & 2]; + R ^= data.binary.salt[(i & 2) + 1]; + BF_ENCRYPT; + data.ctx.P[i] = L; + data.ctx.P[i + 1] = R; + } + + ptr = data.ctx.S[0]; + do { + ptr += 4; + L ^= data.binary.salt[(BF_N + 2) & 3]; + R ^= data.binary.salt[(BF_N + 3) & 3]; + BF_ENCRYPT; + *(ptr - 4) = L; + *(ptr - 3) = R; + + L ^= data.binary.salt[(BF_N + 4) & 3]; + R ^= data.binary.salt[(BF_N + 5) & 3]; + BF_ENCRYPT; + *(ptr - 2) = L; + *(ptr - 1) = R; + } while (ptr < &data.ctx.S[3][0xFF]); + + do { + int done; + + for (i = 0; i < BF_N + 2; i += 2) { + data.ctx.P[i] ^= data.expanded_key[i]; + data.ctx.P[i + 1] ^= data.expanded_key[i + 1]; + } + + done = 0; + do { + BF_body(); + if (done) + break; + done = 1; + + tmp1 = data.binary.salt[0]; + tmp2 = data.binary.salt[1]; + tmp3 = data.binary.salt[2]; + tmp4 = data.binary.salt[3]; + for (i = 0; i < BF_N; i += 4) { + data.ctx.P[i] ^= tmp1; + data.ctx.P[i + 1] ^= tmp2; + data.ctx.P[i + 2] ^= tmp3; + data.ctx.P[i + 3] ^= tmp4; + } + data.ctx.P[16] ^= tmp1; + data.ctx.P[17] ^= tmp2; + } while (1); + } while (--count); + + for (i = 0; i < 6; i += 2) { + L = BF_magic_w[i]; + R = BF_magic_w[i + 1]; + + count = 64; + do { + BF_ENCRYPT; + } while (--count); + + data.binary.output[i] = L; + data.binary.output[i + 1] = R; + } + + memcpy(output, setting, 7 + 22 - 1); + output[7 + 22 - 1] = BF_itoa64[(int) + BF_atoi64[(int)setting[7 + 22 - 1] - 0x20] & 0x30]; + +/* This has to be bug-compatible with the original implementation, so + * only encode 23 of the 24 bytes. :-) */ + BF_swap(data.binary.output, 6); + BF_encode(&output[7 + 22], data.binary.output, 23); + output[7 + 22 + 31] = '\0'; + + return output; +} + +static int _crypt_output_magic(const char *setting, char *output, int size) +{ + if (size < 3) + return -1; + + output[0] = '*'; + output[1] = '0'; + output[2] = '\0'; + + if (setting[0] == '*' && setting[1] == '0') + output[1] = '1'; + + return 0; +} + +/* + * Please preserve the runtime self-test. It serves two purposes at once: + * + * 1. We really can't afford the risk of producing incompatible hashes e.g. + * when there's something like gcc bug 26587 again, whereas an application or + * library integrating this code might not also integrate our external tests or + * it might not run them after every build. Even if it does, the miscompile + * might only occur on the production build, but not on a testing build (such + * as because of different optimization settings). It is painful to recover + * from incorrectly-computed hashes - merely fixing whatever broke is not + * enough. Thus, a proactive measure like this self-test is needed. + * + * 2. We don't want to leave sensitive data from our actual password hash + * computation on the stack or in registers. Previous revisions of the code + * would do explicit cleanups, but simply running the self-test after hash + * computation is more reliable. + * + * The performance cost of this quick self-test is around 0.6% at the "$2a$08" + * setting. + */ +static char *_crypt_blowfish_rn(const char *key, const char *setting, + char *output, int size) +{ + const char *test_key = "8b \xd0\xc1\xd2\xcf\xcc\xd8"; + const char *test_setting = "$2a$00$abcdefghijklmnopqrstuu"; + static const char * const test_hashes[2] = + {"i1D709vfamulimlGcq0qq3UvuUasvEa\0\x55", /* 'a', 'b', 'y' */ + "VUrPmXD6q/nVSSp7pNDhCR9071IfIRe\0\x55"}; /* 'x' */ + const char *test_hash = test_hashes[0]; + char *retval; + const char *p; + int ok; + struct { + char s[7 + 22 + 1]; + char o[7 + 22 + 31 + 1 + 1 + 1]; + } buf; + +/* Hash the supplied password */ + _crypt_output_magic(setting, output, size); + retval = BF_crypt(key, setting, output, size, 16); + +/* + * Do a quick self-test. It is important that we make both calls to BF_crypt() + * from the same scope such that they likely use the same stack locations, + * which makes the second call overwrite the first call's sensitive data on the + * stack and makes it more likely that any alignment related issues would be + * detected by the self-test. + */ + memcpy(buf.s, test_setting, sizeof(buf.s)); + if (retval) { + unsigned int flags = flags_by_subtype[ + (unsigned int)(unsigned char)setting[2] - 'a']; + test_hash = test_hashes[flags & 1]; + buf.s[2] = setting[2]; + } + memset(buf.o, 0x55, sizeof(buf.o)); + buf.o[sizeof(buf.o) - 1] = 0; + p = BF_crypt(test_key, buf.s, buf.o, sizeof(buf.o) - (1 + 1), 1); + + ok = (p == buf.o && + !memcmp(p, buf.s, 7 + 22) && + !memcmp(p + (7 + 22), test_hash, 31 + 1 + 1 + 1)); + + { + const char *k = "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"; + BF_key ae, ai, ye, yi; + BF_set_key(k, ae, ai, 2); /* $2a$ */ + BF_set_key(k, ye, yi, 4); /* $2y$ */ + ai[0] ^= 0x10000; /* undo the safety (for comparison) */ + ok = ok && ai[0] == 0xdb9c59bc && ye[17] == 0x33343500 && + !memcmp(ae, ye, sizeof(ae)) && + !memcmp(ai, yi, sizeof(ai)); + } + + if (ok) + return retval; + +/* Should not happen */ + _crypt_output_magic(setting, output, size); + /* pretend we don't support this hash type */ + return NULL; +} + +static char *_crypt_gensalt_blowfish_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + if (size < 16 || output_size < 7 + 22 + 1 || + (count && (count < 4 || count > 31)) || + prefix[0] != '$' || prefix[1] != '2' || + (prefix[2] != 'a' && prefix[2] != 'b' && prefix[2] != 'y')) { + if (output_size > 0) output[0] = '\0'; + return NULL; + } + + if (!count) count = 5; + + output[0] = '$'; + output[1] = '2'; + output[2] = prefix[2]; + output[3] = '$'; + output[4] = '0' + count / 10; + output[5] = '0' + count % 10; + output[6] = '$'; + + BF_encode(&output[7], (const BF_word *)input, 16); + output[7 + 22] = '\0'; + + return output; +} + +// Start inspircd-specific code + +#include "inspircd.h" +#include "modules/hash.h" + +class BCryptProvider : public HashProvider +{ + private: + std::string Salt() + { + char entropy[16]; + for (unsigned int i = 0; i < sizeof(entropy); ++i) + entropy[i] = ServerInstance->GenRandomInt(0xFF); + + char salt[32]; + if (!_crypt_gensalt_blowfish_rn("$2a$", rounds, entropy, sizeof(entropy), salt, sizeof(salt))) + throw ModuleException("Could not generate salt - this should never happen"); + + return salt; + } + + public: + unsigned int rounds; + + std::string Generate(const std::string& data, const std::string& salt) + { + char hash[64]; + _crypt_blowfish_rn(data.c_str(), salt.c_str(), hash, sizeof(hash)); + return hash; + } + + std::string GenerateRaw(const std::string& data) CXX11_OVERRIDE + { + return Generate(data, Salt()); + } + + bool Compare(const std::string& input, const std::string& hash) CXX11_OVERRIDE + { + std::string ret = Generate(input, hash); + if (ret.empty()) + return false; + + if (ret == hash) + return true; + return false; + } + + std::string ToPrintable(const std::string& raw) CXX11_OVERRIDE + { + return raw; + } + + BCryptProvider(Module* parent) + : HashProvider(parent, "bcrypt", 60) + , rounds(10) + { + } +}; + +class ModuleBCrypt : public Module +{ + BCryptProvider bcrypt; + + public: + ModuleBCrypt() : bcrypt(this) + { + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* conf = ServerInstance->Config->ConfValue("bcrypt"); + bcrypt.rounds = conf->getInt("rounds", 10, 1); + } + + Version GetVersion() + { + return Version("Implements bcrypt hashing", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleBCrypt) diff --git a/src/modules/m_blockamsg.cpp b/src/modules/m_blockamsg.cpp index be861447f..9614203c3 100644 --- a/src/modules/m_blockamsg.cpp +++ b/src/modules/m_blockamsg.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" -/* $ModDesc: Attempt to block /amsg, at least some of the irritating mIRC scripts. */ - enum BlockAction { IBLOCK_KILL, IBLOCK_KILLOPERS, IBLOCK_NOTICE, IBLOCK_NOTICEOPERS, IBLOCK_SILENT }; /* IBLOCK_NOTICE - Send a notice to the user informing them of what happened. * IBLOCK_NOTICEOPERS - Send a notice to the user informing them and send an oper notice. @@ -37,13 +35,13 @@ enum BlockAction { IBLOCK_KILL, IBLOCK_KILLOPERS, IBLOCK_NOTICE, IBLOCK_NOTICEOP */ class BlockedMessage { -public: + public: std::string message; irc::string target; time_t sent; - BlockedMessage(const std::string &msg, const irc::string &tgt, time_t when) - : message(msg), target(tgt), sent(when) + BlockedMessage(const std::string& msg, const std::string& tgt, time_t when) + : message(msg), target(tgt.c_str()), sent(when) { } }; @@ -55,46 +53,35 @@ class ModuleBlockAmsg : public Module SimpleExtItem<BlockedMessage> blockamsg; public: - ModuleBlockAmsg() : blockamsg("blockamsg", this) - { - } - - void init() - { - this->OnRehash(NULL); - ServerInstance->Modules->AddService(blockamsg); - Implementation eventlist[] = { I_OnRehash, I_OnPreCommand }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleBlockAmsg() + ModuleBlockAmsg() + : blockamsg("blockamsg", ExtensionItem::EXT_USER, this) { } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Attempt to block /amsg, at least some of the irritating mIRC scripts.",VF_VENDOR); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("blockamsg"); ForgetDelay = tag->getInt("delay", -1); std::string act = tag->getString("action"); - if(act == "notice") + if (act == "notice") action = IBLOCK_NOTICE; - else if(act == "noticeopers") + else if (act == "noticeopers") action = IBLOCK_NOTICEOPERS; - else if(act == "silent") + else if (act == "silent") action = IBLOCK_SILENT; - else if(act == "kill") + else if (act == "kill") action = IBLOCK_KILL; else action = IBLOCK_KILLOPERS; } - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { // Don't do anything with unregistered users if (user->registered != REG_ALL) @@ -102,33 +89,24 @@ class ModuleBlockAmsg : public Module if ((validated) && (parameters.size() >= 2) && ((command == "PRIVMSG") || (command == "NOTICE"))) { - // parameters[0] should have the target(s) in it. - // I think it will be faster to first check if there are any commas, and if there are then try and parse it out. - // Most messages have a single target so... + // parameters[0] is the target list, count how many channels are there + unsigned int targets = 0; + // Is the first target a channel? + if (*parameters[0].c_str() == '#') + targets = 1; - int targets = 1; - int userchans = 0; - - if(*parameters[0].c_str() != '#') + for (const char* c = parameters[0].c_str(); *c; c++) { - // Decrement if the first target wasn't a channel. - targets--; - } - - for(const char* c = parameters[0].c_str(); *c; c++) - if((*c == ',') && *(c+1) && (*(c+1) == '#')) + if ((*c == ',') && (*(c+1) == '#')) targets++; + } /* targets should now contain the number of channel targets the msg/notice was pointed at. * If the msg/notice was a PM there should be no channel targets and 'targets' should = 0. * We don't want to block PMs so... */ - if(targets == 0) - { + if (targets == 0) return MOD_RES_PASSTHRU; - } - - userchans = user->chans.size(); // Check that this message wasn't already sent within a few seconds. BlockedMessage* m = blockamsg.get(user); @@ -138,21 +116,21 @@ class ModuleBlockAmsg : public Module // OR // The number of target channels is equal to the number of channels the sender is on..a little suspicious. // Check it's more than 1 too, or else users on one channel would have fun. - if((m && (m->message == parameters[1]) && (m->target != parameters[0]) && (ForgetDelay != -1) && (m->sent >= ServerInstance->Time()-ForgetDelay)) || ((targets > 1) && (targets == userchans))) + if ((m && (m->message == parameters[1]) && (m->target != parameters[0]) && (ForgetDelay != -1) && (m->sent >= ServerInstance->Time()-ForgetDelay)) || ((targets > 1) && (targets == user->chans.size()))) { // Block it... - if(action == IBLOCK_KILLOPERS || action == IBLOCK_NOTICEOPERS) + if (action == IBLOCK_KILLOPERS || action == IBLOCK_NOTICEOPERS) ServerInstance->SNO->WriteToSnoMask('a', "%s had an /amsg or /ame denied", user->nick.c_str()); - if(action == IBLOCK_KILL || action == IBLOCK_KILLOPERS) + if (action == IBLOCK_KILL || action == IBLOCK_KILLOPERS) ServerInstance->Users->QuitUser(user, "Attempted to global message (/amsg or /ame)"); - else if(action == IBLOCK_NOTICE || action == IBLOCK_NOTICEOPERS) - user->WriteServ( "NOTICE %s :Global message (/amsg or /ame) denied", user->nick.c_str()); + else if (action == IBLOCK_NOTICE || action == IBLOCK_NOTICEOPERS) + user->WriteNotice("Global message (/amsg or /ame) denied"); return MOD_RES_DENY; } - if(m) + if (m) { // If there's already a BlockedMessage allocated, use it. m->message = parameters[1]; @@ -161,7 +139,7 @@ class ModuleBlockAmsg : public Module } else { - m = new BlockedMessage(parameters[1], parameters[0].c_str(), ServerInstance->Time()); + m = new BlockedMessage(parameters[1], parameters[0], ServerInstance->Time()); blockamsg.set(user, m); } } @@ -169,5 +147,4 @@ class ModuleBlockAmsg : public Module } }; - MODULE_INIT(ModuleBlockAmsg) diff --git a/src/modules/m_blockcaps.cpp b/src/modules/m_blockcaps.cpp index 200693699..0a64a75b5 100644 --- a/src/modules/m_blockcaps.cpp +++ b/src/modules/m_blockcaps.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support to block all-CAPS channel messages and notices */ - /** Handles the +B channel mode */ @@ -36,34 +34,21 @@ class BlockCaps : public SimpleChannelModeHandler class ModuleBlockCAPS : public Module { BlockCaps bc; - int percent; + unsigned int percent; unsigned int minlen; char capsmap[256]; -public: +public: ModuleBlockCAPS() : bc(this) { } - void init() - { - OnRehash(NULL); - ServerInstance->Modules->AddService(bc); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('B'); + tokens["EXTBAN"].push_back('B'); } - virtual void OnRehash(User* user) - { - ReadConf(); - } - - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (target_type == TYPE_CHANNEL) { @@ -76,28 +61,20 @@ public: if (res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; - if (!c->GetExtBanStatus(user, 'B').check(!c->IsModeSet('B'))) + if (!c->GetExtBanStatus(user, 'B').check(!c->IsModeSet(bc))) { - int caps = 0; - const char* actstr = "\1ACTION "; - int act = 0; - - for (std::string::iterator i = text.begin(); i != text.end(); i++) - { - /* Smart fix for suggestion from Jobe, ignore CTCP ACTION (part of /ME) */ - if (*actstr && *i == *actstr++ && act != -1) - { - act++; - continue; - } - else - act = -1; + std::string::size_type caps = 0; + unsigned int offset = 0; + // Ignore the beginning of the text if it's a CTCP ACTION (/me) + if (!text.compare(0, 8, "\1ACTION ", 8)) + offset = 8; + for (std::string::const_iterator i = text.begin() + offset; i != text.end(); ++i) caps += capsmap[(unsigned char)*i]; - } - if ( ((caps*100)/(int)text.length()) >= percent ) + + if (((caps * 100) / text.length()) >= percent) { - user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s %s :Your message cannot contain more than %d%% capital letters if it's longer than %d characters", user->nick.c_str(), c->name.c_str(), percent, minlen); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Your message cannot contain more than %d%% capital letters if it's longer than %d characters", c->name.c_str(), percent, minlen); return MOD_RES_DENY; } } @@ -105,37 +82,18 @@ public: return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - void ReadConf() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("blockcaps"); - percent = tag->getInt("percent", 100); - minlen = tag->getInt("minlen", 1); + percent = tag->getInt("percent", 100, 1, 100); + minlen = tag->getInt("minlen", 1, 1, ServerInstance->Config->Limits.MaxLine); std::string hmap = tag->getString("capsmap", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); memset(capsmap, 0, sizeof(capsmap)); for (std::string::iterator n = hmap.begin(); n != hmap.end(); n++) capsmap[(unsigned char)*n] = 1; - if (percent < 1 || percent > 100) - { - ServerInstance->Logs->Log("CONFIG",DEFAULT, "<blockcaps:percent> out of range, setting to default of 100."); - percent = 100; - } - if (minlen < 1 || minlen > MAXBUF-1) - { - ServerInstance->Logs->Log("CONFIG",DEFAULT, "<blockcaps:minlen> out of range, setting to default of 1."); - minlen = 1; - } - } - - virtual ~ModuleBlockCAPS() - { } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support to block all-CAPS channel messages and notices", VF_VENDOR); } diff --git a/src/modules/m_blockcolor.cpp b/src/modules/m_blockcolor.cpp index 3cc01b4c0..a08ad7c6f 100644 --- a/src/modules/m_blockcolor.cpp +++ b/src/modules/m_blockcolor.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +c to block color */ - /** Handles the +c channel mode */ class BlockColor : public SimpleChannelModeHandler @@ -42,19 +40,12 @@ class ModuleBlockColor : public Module { } - void init() + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(bc); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + tokens["EXTBAN"].push_back('c'); } - virtual void On005Numeric(std::string &output) - { - ServerInstance->AddExtBanChar('c'); - } - - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if ((target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) { @@ -64,7 +55,7 @@ class ModuleBlockColor : public Module if (res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; - if (!c->GetExtBanStatus(user, 'c').check(!c->IsModeSet('c'))) + if (!c->GetExtBanStatus(user, 'c').check(!c->IsModeSet(bc))) { for (std::string::iterator i = text.begin(); i != text.end(); i++) { @@ -76,7 +67,7 @@ class ModuleBlockColor : public Module case 21: case 22: case 31: - user->WriteNumeric(404, "%s %s :Can't send colors to channel (+c set)",user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Can't send colors to channel (+c set)", c->name.c_str()); return MOD_RES_DENY; break; } @@ -86,16 +77,7 @@ class ModuleBlockColor : public Module return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - virtual ~ModuleBlockColor() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +c to block color",VF_VENDOR); } diff --git a/src/modules/m_botmode.cpp b/src/modules/m_botmode.cpp index b29c58240..419af0153 100644 --- a/src/modules/m_botmode.cpp +++ b/src/modules/m_botmode.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides user mode +B to mark the user as a bot */ - /** Handles user mode +B */ class BotMode : public SimpleUserModeHandler @@ -31,40 +29,28 @@ class BotMode : public SimpleUserModeHandler BotMode(Module* Creator) : SimpleUserModeHandler(Creator, "bot", 'B') { } }; -class ModuleBotMode : public Module +class ModuleBotMode : public Module, public Whois::EventListener { BotMode bm; public: ModuleBotMode() - : bm(this) + : Whois::EventListener(this) + , bm(this) { } - void init() - { - ServerInstance->Modules->AddService(bm); - Implementation eventlist[] = { I_OnWhois }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleBotMode() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides user mode +B to mark the user as a bot",VF_VENDOR); } - virtual void OnWhois(User* src, User* dst) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - if (dst->IsModeSet('B')) + if (whois.GetTarget()->IsModeSet(bm)) { - ServerInstance->SendWhoisLine(src, dst, 335, src->nick+" "+dst->nick+" :is a bot on "+ServerInstance->Config->Network); + whois.SendLine(335, ":is a bot on " + ServerInstance->Config->Network); } } - }; - MODULE_INIT(ModuleBotMode) diff --git a/src/modules/m_callerid.cpp b/src/modules/m_callerid.cpp index 4147f0b16..5c6d14a90 100644 --- a/src/modules/m_callerid.cpp +++ b/src/modules/m_callerid.cpp @@ -22,20 +22,33 @@ #include "inspircd.h" -/* $ModDesc: Implementation of callerid, usermode +g, /accept */ +enum +{ + RPL_ACCEPTLIST = 281, + RPL_ENDOFACCEPT = 282, + ERR_ACCEPTFULL = 456, + ERR_ACCEPTEXIST = 457, + ERR_ACCEPTNOT = 458, + ERR_TARGUMODEG = 716, + RPL_TARGNOTIFY = 717, + RPL_UMODEGMSG = 718 +}; class callerid_data { public: + typedef insp::flat_set<User*> UserSet; + typedef std::vector<callerid_data*> CallerIdDataSet; + time_t lastnotify; /** Users I accept messages from */ - std::set<User*> accepting; + UserSet accepting; /** Users who list me as accepted */ - std::list<callerid_data *> wholistsme; + CallerIdDataSet wholistsme; callerid_data() : lastnotify(0) { } @@ -43,7 +56,7 @@ class callerid_data { std::ostringstream oss; oss << lastnotify; - for (std::set<User*>::const_iterator i = accepting.begin(); i != accepting.end(); ++i) + for (UserSet::const_iterator i = accepting.begin(); i != accepting.end(); ++i) { User* u = *i; // Encode UIDs. @@ -56,18 +69,26 @@ class callerid_data struct CallerIDExtInfo : public ExtensionItem { CallerIDExtInfo(Module* parent) - : ExtensionItem("callerid_data", parent) + : ExtensionItem("callerid_data", ExtensionItem::EXT_USER, parent) { } std::string serialize(SerializeFormat format, const Extensible* container, void* item) const { - callerid_data* dat = static_cast<callerid_data*>(item); - return dat->ToString(format); + std::string ret; + if (format != FORMAT_NETWORK) + { + callerid_data* dat = static_cast<callerid_data*>(item); + ret = dat->ToString(format); + } + return ret; } void unserialize(SerializeFormat format, Extensible* container, const std::string& value) { + if (format == FORMAT_NETWORK) + return; + callerid_data* dat = new callerid_data; irc::commasepstream s(value); std::string tok; @@ -76,9 +97,6 @@ struct CallerIDExtInfo : public ExtensionItem while (s.GetToken(tok)) { - if (tok.empty()) - continue; - User *u = ServerInstance->FindNick(tok); if ((u) && (u->registered == REG_ALL) && (!u->quitting) && (!IS_SERVER(u))) { @@ -111,21 +129,18 @@ struct CallerIDExtInfo : public ExtensionItem callerid_data* dat = static_cast<callerid_data*>(item); // We need to walk the list of users on our accept list, and remove ourselves from their wholistsme. - for (std::set<User *>::iterator it = dat->accepting.begin(); it != dat->accepting.end(); it++) + for (callerid_data::UserSet::iterator it = dat->accepting.begin(); it != dat->accepting.end(); ++it) { callerid_data *targ = this->get(*it, false); if (!targ) { - ServerInstance->Logs->Log("m_callerid", DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (1)"); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (1)"); continue; // shouldn't happen, but oh well. } - std::list<callerid_data*>::iterator it2 = std::find(targ->wholistsme.begin(), targ->wholistsme.end(), dat); - if (it2 != targ->wholistsme.end()) - targ->wholistsme.erase(it2); - else - ServerInstance->Logs->Log("m_callerid", DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (2)"); + if (!stdalgo::vector::swaperase(targ->wholistsme, dat)) + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (2)"); } delete dat; } @@ -139,6 +154,28 @@ public: class CommandAccept : public Command { + /** Pair: first is the target, second is true to add, false to remove + */ + typedef std::pair<User*, bool> ACCEPTAction; + + static ACCEPTAction GetTargetAndAction(std::string& tok, User* cmdfrom = NULL) + { + bool remove = (tok[0] == '-'); + if ((remove) || (tok[0] == '+')) + tok.erase(tok.begin()); + + User* target; + if (!cmdfrom || !IS_LOCAL(cmdfrom)) + target = ServerInstance->FindNick(tok); + else + target = ServerInstance->FindNickOnly(tok); + + if ((!target) || (target->registered != REG_ALL) || (target->quitting) || (IS_SERVER(target))) + target = NULL; + + return std::make_pair(target, !remove); + } + public: CallerIDExtInfo extInfo; unsigned int maxaccepts; @@ -147,42 +184,21 @@ public: { allow_empty_last_param = false; syntax = "*|(+|-)<nick>[,(+|-)<nick> ...]"; - TRANSLATE2(TR_CUSTOM, TR_END); + TRANSLATE1(TR_CUSTOM); } - virtual void EncodeParameter(std::string& parameter, int index) + void EncodeParameter(std::string& parameter, int index) { - if (index != 0) + // Send lists as-is (part of 2.0 compat) + if (parameter.find(',') != std::string::npos) return; - std::string out; - irc::commasepstream nicks(parameter); - std::string tok; - while (nicks.GetToken(tok)) - { - if (tok == "*") - { - continue; // Drop list requests, since remote servers ignore them anyway. - } - if (!out.empty()) - out.append(","); - bool dash = false; - if (tok[0] == '-') - { - dash = true; - tok.erase(0, 1); // Remove the dash. - } - else if (tok[0] == '+') - tok.erase(0, 1); - User* u = ServerInstance->FindNick(tok); - if ((!u) || (u->registered != REG_ALL) || (u->quitting) || (IS_SERVER(u))) - continue; + // Convert a [+|-]<nick> into a [-]<uuid> + ACCEPTAction action = GetTargetAndAction(parameter); + if (!action.first) + return; - if (dash) - out.append("-"); - out.append(u->uuid); - } - parameter = out; + parameter = (action.second ? "" : "-") + action.first->uuid; } /** Will take any number of nicks (up to MaxTargets), which can be seperated by commas. @@ -192,54 +208,58 @@ public: */ CmdResult Handle(const std::vector<std::string> ¶meters, User* user) { - if (ServerInstance->Parser->LoopCall(user, this, parameters, 0)) + if (CommandParser::LoopCall(user, this, parameters, 0)) return CMD_SUCCESS; + /* Even if callerid mode is not set, we let them manage their ACCEPT list so that if they go +g they can * have a list already setup. */ - const std::string& tok = parameters[0]; - - if (tok == "*") + if (parameters[0] == "*") { - if (IS_LOCAL(user)) - ListAccept(user); + ListAccept(user); return CMD_SUCCESS; } - else if (tok[0] == '-') + + std::string tok = parameters[0]; + ACCEPTAction action = GetTargetAndAction(tok, user); + if (!action.first) { - User* whotoremove; - if (IS_LOCAL(user)) - whotoremove = ServerInstance->FindNickOnly(tok.substr(1)); - else - whotoremove = ServerInstance->FindNick(tok.substr(1)); - - if (whotoremove) - return (RemoveAccept(user, whotoremove) ? CMD_SUCCESS : CMD_FAILURE); - else - return CMD_FAILURE; + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", tok.c_str()); + return CMD_FAILURE; } + + if ((!IS_LOCAL(user)) && (!IS_LOCAL(action.first))) + // Neither source nor target is local, forward the command to the server of target + return CMD_SUCCESS; + + // The second item in the pair is true if the first char is a '+' (or nothing), false if it's a '-' + if (action.second) + return (AddAccept(user, action.first) ? CMD_SUCCESS : CMD_FAILURE); else - { - const std::string target = (tok[0] == '+' ? tok.substr(1) : tok); - User* whotoadd; - if (IS_LOCAL(user)) - whotoadd = ServerInstance->FindNickOnly(target); - else - whotoadd = ServerInstance->FindNick(target); - - if ((whotoadd) && (whotoadd->registered == REG_ALL) && (!whotoadd->quitting) && (!IS_SERVER(whotoadd))) - return (AddAccept(user, whotoadd) ? CMD_SUCCESS : CMD_FAILURE); - else - { - user->WriteNumeric(401, "%s %s :No such nick/channel", user->nick.c_str(), tok.c_str()); - return CMD_FAILURE; - } - } + return (RemoveAccept(user, action.first) ? CMD_SUCCESS : CMD_FAILURE); } RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { - return ROUTE_BROADCAST; + // There is a list in parameters[0] in two cases: + // Either when the source is remote, this happens because 2.0 servers send comma seperated uuid lists, + // we don't split those but broadcast them, as before. + // + // Or if the source is local then LoopCall() runs OnPostCommand() after each entry in the list, + // meaning the linking module has sent an ACCEPT already for each entry in the list to the + // appropiate server and the ACCEPT with the list of nicks (this) doesn't need to be sent anywhere. + if ((!IS_LOCAL(user)) && (parameters[0].find(',') != std::string::npos)) + return ROUTE_BROADCAST; + + // Find the target + std::string targetstring = parameters[0]; + ACCEPTAction action = GetTargetAndAction(targetstring, user); + if (!action.first) + // Target is a "*" or source is local and the target is a list of nicks + return ROUTE_LOCALONLY; + + // Route to the server of the target + return ROUTE_UNICAST(action.first->server); } void ListAccept(User* user) @@ -247,10 +267,10 @@ public: callerid_data* dat = extInfo.get(user, false); if (dat) { - for (std::set<User*>::iterator i = dat->accepting.begin(); i != dat->accepting.end(); ++i) - user->WriteNumeric(281, "%s %s", user->nick.c_str(), (*i)->nick.c_str()); + for (callerid_data::UserSet::iterator i = dat->accepting.begin(); i != dat->accepting.end(); ++i) + user->WriteNumeric(RPL_ACCEPTLIST, (*i)->nick); } - user->WriteNumeric(282, "%s :End of ACCEPT list", user->nick.c_str()); + user->WriteNumeric(RPL_ENDOFACCEPT, ":End of ACCEPT list"); } bool AddAccept(User* user, User* whotoadd) @@ -259,12 +279,12 @@ public: callerid_data* dat = extInfo.get(user, true); if (dat->accepting.size() >= maxaccepts) { - user->WriteNumeric(456, "%s :Accept list is full (limit is %d)", user->nick.c_str(), maxaccepts); + user->WriteNumeric(ERR_ACCEPTFULL, ":Accept list is full (limit is %d)", maxaccepts); return false; } if (!dat->accepting.insert(whotoadd).second) { - user->WriteNumeric(457, "%s %s :is already on your accept list", user->nick.c_str(), whotoadd->nick.c_str()); + user->WriteNumeric(ERR_ACCEPTEXIST, "%s :is already on your accept list", whotoadd->nick.c_str()); return false; } @@ -272,7 +292,7 @@ public: callerid_data *targ = extInfo.get(whotoadd, true); targ->wholistsme.push_back(dat); - user->WriteServ("NOTICE %s :%s is now on your accept list", user->nick.c_str(), whotoadd->nick.c_str()); + user->WriteNotice(whotoadd->nick + " is now on your accept list"); return true; } @@ -282,43 +302,35 @@ public: callerid_data* dat = extInfo.get(user, false); if (!dat) { - user->WriteNumeric(458, "%s %s :is not on your accept list", user->nick.c_str(), whotoremove->nick.c_str()); + user->WriteNumeric(ERR_ACCEPTNOT, "%s :is not on your accept list", whotoremove->nick.c_str()); return false; } - std::set<User*>::iterator i = dat->accepting.find(whotoremove); - if (i == dat->accepting.end()) + if (!dat->accepting.erase(whotoremove)) { - user->WriteNumeric(458, "%s %s :is not on your accept list", user->nick.c_str(), whotoremove->nick.c_str()); + user->WriteNumeric(ERR_ACCEPTNOT, "%s :is not on your accept list", whotoremove->nick.c_str()); return false; } - dat->accepting.erase(i); - // Look up their list to remove me. callerid_data *dat2 = extInfo.get(whotoremove, false); if (!dat2) { // How the fuck is this possible. - ServerInstance->Logs->Log("m_callerid", DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (3)"); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (3)"); return false; } - std::list<callerid_data*>::iterator it = std::find(dat2->wholistsme.begin(), dat2->wholistsme.end(), dat); - if (it != dat2->wholistsme.end()) - // Found me! - dat2->wholistsme.erase(it); - else - ServerInstance->Logs->Log("m_callerid", DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (4)"); + if (!stdalgo::vector::swaperase(dat2->wholistsme, dat)) + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (4)"); - user->WriteServ("NOTICE %s :%s is no longer on your accept list", user->nick.c_str(), whotoremove->nick.c_str()); + user->WriteNotice(whotoremove->nick + " is no longer on your accept list"); return true; } }; class ModuleCallerID : public Module { -private: CommandAccept cmd; User_g myumode; @@ -338,17 +350,13 @@ private: return; // Iterate over the list of people who accept me, and remove all entries - for (std::list<callerid_data *>::iterator it = userdata->wholistsme.begin(); it != userdata->wholistsme.end(); it++) + for (callerid_data::CallerIdDataSet::iterator it = userdata->wholistsme.begin(); it != userdata->wholistsme.end(); ++it) { callerid_data *dat = *(it); // Find me on their callerid list - std::set<User *>::iterator it2 = dat->accepting.find(who); - - if (it2 != dat->accepting.end()) - dat->accepting.erase(it2); - else - ServerInstance->Logs->Log("m_callerid", DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (5)"); + if (!dat->accepting.erase(who)) + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (5)"); } userdata->wholistsme.clear(); @@ -359,53 +367,39 @@ public: { } - void init() - { - OnRehash(NULL); - - ServerInstance->Modules->AddService(myumode); - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(cmd.extInfo); - - Implementation eventlist[] = { I_OnRehash, I_OnUserPostNick, I_OnUserQuit, I_On005Numeric, I_OnUserPreNotice, I_OnUserPreMessage }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleCallerID() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implementation of callerid, usermode +g, /accept", VF_COMMON | VF_VENDOR); } - virtual void On005Numeric(std::string& output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output += " CALLERID=g"; + tokens["CALLERID"] = "g"; } - ModResult PreText(User* user, User* dest, std::string& text) + ModResult OnUserPreMessage(User* user, void* voiddest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { - if (!dest->IsModeSet('g') || (user == dest)) + if (!IS_LOCAL(user) || target_type != TYPE_USER) return MOD_RES_PASSTHRU; - if (operoverride && IS_OPER(user)) + User* dest = static_cast<User*>(voiddest); + if (!dest->IsModeSet(myumode) || (user == dest)) return MOD_RES_PASSTHRU; - callerid_data* dat = cmd.extInfo.get(dest, true); - std::set<User*>::iterator i = dat->accepting.find(user); + if (operoverride && user->IsOper()) + return MOD_RES_PASSTHRU; - if (i == dat->accepting.end()) + callerid_data* dat = cmd.extInfo.get(dest, true); + if (!dat->accepting.count(user)) { time_t now = ServerInstance->Time(); /* +g and *not* accepted */ - user->WriteNumeric(716, "%s %s :is in +g mode (server-side ignore).", user->nick.c_str(), dest->nick.c_str()); + user->WriteNumeric(ERR_TARGUMODEG, "%s :is in +g mode (server-side ignore).", dest->nick.c_str()); if (now > (dat->lastnotify + (time_t)notify_cooldown)) { - user->WriteNumeric(717, "%s %s :has been informed that you messaged them.", user->nick.c_str(), dest->nick.c_str()); - dest->SendText(":%s 718 %s %s %s@%s :is messaging you, and you have umode +g. Use /ACCEPT +%s to allow.", - ServerInstance->Config->ServerName.c_str(), dest->nick.c_str(), user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), user->nick.c_str()); + user->WriteNumeric(RPL_TARGNOTIFY, "%s :has been informed that you messaged them.", dest->nick.c_str()); + dest->SendText(":%s %03d %s %s %s@%s :is messaging you, and you have umode +g. Use /ACCEPT +%s to allow.", + ServerInstance->Config->ServerName.c_str(), RPL_UMODEGMSG, dest->nick.c_str(), user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), user->nick.c_str()); dat->lastnotify = now; } return MOD_RES_DENY; @@ -413,34 +407,18 @@ public: return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList &exempt_list) - { - if (IS_LOCAL(user) && target_type == TYPE_USER) - return PreText(user, (User*)dest, text); - - return MOD_RES_PASSTHRU; - } - - virtual ModResult OnUserPreNotice(User* user, void* dest, int target_type, std::string& text, char status, CUList &exempt_list) - { - if (IS_LOCAL(user) && target_type == TYPE_USER) - return PreText(user, (User*)dest, text); - - return MOD_RES_PASSTHRU; - } - - void OnUserPostNick(User* user, const std::string& oldnick) + void OnUserPostNick(User* user, const std::string& oldnick) CXX11_OVERRIDE { if (!tracknick) RemoveFromAllAccepts(user); } - void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) + void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE { RemoveFromAllAccepts(user); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("callerid"); cmd.maxaccepts = tag->getInt("maxaccepts", 16); @@ -451,5 +429,3 @@ public: }; MODULE_INIT(ModuleCallerID) - - diff --git a/src/modules/m_cap.cpp b/src/modules/m_cap.cpp index e9f4dae90..2c2178a18 100644 --- a/src/modules/m_cap.cpp +++ b/src/modules/m_cap.cpp @@ -19,9 +19,7 @@ #include "inspircd.h" -#include "m_cap.h" - -/* $ModDesc: Provides the CAP negotiation mechanism seen in ratbox-derived ircds */ +#include "modules/cap.h" /* CAP LS @@ -41,17 +39,21 @@ CAP END */ class CommandCAP : public Command { + Events::ModuleEventProvider capevprov; + public: LocalIntExt reghold; CommandCAP (Module* mod) : Command(mod, "CAP", 1), - reghold("CAP_REGHOLD", mod) + capevprov(mod, "event/cap"), + reghold("CAP_REGHOLD", ExtensionItem::EXT_USER, mod) { works_before_reg = true; } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { - irc::string subcommand = parameters[0].c_str(); + std::string subcommand(parameters[0].length(), ' '); + std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper); if (subcommand == "REQ") { @@ -66,22 +68,23 @@ class CommandCAP : public Command while (cap_stream.GetToken(cap_)) { + std::transform(cap_.begin(), cap_.end(), cap_.begin(), ::tolower); Data.wanted.push_back(cap_); } reghold.set(user, 1); - Data.Send(); + FOREACH_MOD_CUSTOM(capevprov, GenericCap, OnCapEvent, (Data)); if (Data.ack.size() > 0) { - std::string AckResult = irc::stringjoiner(" ", Data.ack, 0, Data.ack.size() - 1).GetJoined(); - user->WriteServ("CAP %s ACK :%s", user->nick.c_str(), AckResult.c_str()); + std::string AckResult = irc::stringjoiner(Data.ack); + user->WriteCommand("CAP", "ACK :" + AckResult); } if (Data.wanted.size() > 0) { - std::string NakResult = irc::stringjoiner(" ", Data.wanted, 0, Data.wanted.size() - 1).GetJoined(); - user->WriteServ("CAP %s NAK :%s", user->nick.c_str(), NakResult.c_str()); + std::string NakResult = irc::stringjoiner(Data.wanted); + user->WriteCommand("CAP", "NAK :" + NakResult); } } else if (subcommand == "END") @@ -93,29 +96,24 @@ class CommandCAP : public Command CapEvent Data(creator, user, subcommand == "LS" ? CapEvent::CAPEVENT_LS : CapEvent::CAPEVENT_LIST); reghold.set(user, 1); - Data.Send(); - - std::string Result; - if (Data.wanted.size() > 0) - Result = irc::stringjoiner(" ", Data.wanted, 0, Data.wanted.size() - 1).GetJoined(); + FOREACH_MOD_CUSTOM(capevprov, GenericCap, OnCapEvent, (Data)); - user->WriteServ("CAP %s %s :%s", user->nick.c_str(), subcommand.c_str(), Result.c_str()); + std::string Result = irc::stringjoiner(Data.wanted); + user->WriteCommand("CAP", subcommand + " :" + Result); } else if (subcommand == "CLEAR") { CapEvent Data(creator, user, CapEvent::CAPEVENT_CLEAR); reghold.set(user, 1); - Data.Send(); + FOREACH_MOD_CUSTOM(capevprov, GenericCap, OnCapEvent, (Data)); - std::string Result; - if (!Data.ack.empty()) - Result = irc::stringjoiner(" ", Data.ack, 0, Data.ack.size() - 1).GetJoined(); - user->WriteServ("CAP %s ACK :%s", user->nick.c_str(), Result.c_str()); + std::string Result = irc::stringjoiner(Data.ack); + user->WriteCommand("CAP", "ACK :" + Result); } else { - user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, "%s %s :Invalid CAP subcommand", user->nick.c_str(), subcommand.c_str()); + user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, "%s :Invalid CAP subcommand", subcommand.c_str()); return CMD_FAILURE; } @@ -132,16 +130,7 @@ class ModuleCAP : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(cmd.reghold); - - Implementation eventlist[] = { I_OnCheckReady }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnCheckReady(LocalUser* user) + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE { /* Users in CAP state get held until CAP END */ if (cmd.reghold.get(user)) @@ -150,15 +139,10 @@ class ModuleCAP : public Module return MOD_RES_PASSTHRU; } - ~ModuleCAP() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Client CAP extension support", VF_VENDOR); } }; MODULE_INIT(ModuleCAP) - diff --git a/src/modules/m_cap.h b/src/modules/m_cap.h deleted file mode 100644 index 409671f48..000000000 --- a/src/modules/m_cap.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef M_CAP_H -#define M_CAP_H - -class CapEvent : public Event -{ - public: - enum CapEventType - { - CAPEVENT_REQ, - CAPEVENT_LS, - CAPEVENT_LIST, - CAPEVENT_CLEAR - }; - - CapEventType type; - std::vector<std::string> wanted; - std::vector<std::string> ack; - User* user; - CapEvent(Module* sender, User* u, CapEventType capevtype) : Event(sender, "cap_request"), type(capevtype), user(u) {} -}; - -class GenericCap -{ - public: - LocalIntExt ext; - const std::string cap; - GenericCap(Module* parent, const std::string &Cap) : ext("cap_" + Cap, parent), cap(Cap) - { - ServerInstance->Modules->AddService(ext); - } - - void HandleEvent(Event& ev) - { - if (ev.id != "cap_request") - return; - - CapEvent *data = static_cast<CapEvent*>(&ev); - if (data->type == CapEvent::CAPEVENT_REQ) - { - for (std::vector<std::string>::iterator it = data->wanted.begin(); it != data->wanted.end(); ++it) - { - if (it->empty()) - continue; - bool enablecap = ((*it)[0] != '-'); - if (((enablecap) && (*it == cap)) || (*it == "-" + cap)) - { - // we can handle this, so ACK it, and remove it from the wanted list - data->ack.push_back(*it); - data->wanted.erase(it); - ext.set(data->user, enablecap ? 1 : 0); - break; - } - } - } - else if (data->type == CapEvent::CAPEVENT_LS) - { - data->wanted.push_back(cap); - } - else if (data->type == CapEvent::CAPEVENT_LIST) - { - if (ext.get(data->user)) - data->wanted.push_back(cap); - } - else if (data->type == CapEvent::CAPEVENT_CLEAR) - { - data->ack.push_back("-" + cap); - ext.set(data->user, 0); - } - } -}; - -#endif diff --git a/src/modules/m_cban.cpp b/src/modules/m_cban.cpp index fb78e41b2..4fb0653a9 100644 --- a/src/modules/m_cban.cpp +++ b/src/modules/m_cban.cpp @@ -23,25 +23,22 @@ #include "inspircd.h" #include "xline.h" -/* $ModDesc: Gives /cban, aka C:lines. Think Q:lines, for channels. */ - /** Holds a CBAN item */ class CBan : public XLine { -public: +private: + std::string displaytext; irc::string matchtext; +public: CBan(time_t s_time, long d, const std::string& src, const std::string& re, const std::string& ch) : XLine(s_time, d, src, re, "CBAN") { + this->displaytext = ch; this->matchtext = ch.c_str(); } - ~CBan() - { - } - // XXX I shouldn't have to define this bool Matches(User *u) { @@ -55,15 +52,9 @@ public: return false; } - void DisplayExpiry() + const std::string& Displayable() { - ServerInstance->SNO->WriteToSnoMask('x',"Removing expired CBan %s (set by %s %ld seconds ago)", - this->matchtext.c_str(), this->source.c_str(), (long int)(ServerInstance->Time() - this->set_time)); - } - - const char* Displayable() - { - return matchtext.c_str(); + return displaytext; } }; @@ -95,7 +86,6 @@ class CommandCBan : public Command CommandCBan(Module* Creator) : Command(Creator, "CBAN", 1, 3) { flags_needed = 'o'; this->syntax = "<channel> [<duration> :<reason>]"; - TRANSLATE4(TR_TEXT,TR_TEXT,TR_TEXT,TR_END); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) @@ -111,14 +101,14 @@ class CommandCBan : public Command } else { - user->WriteServ("NOTICE %s :*** CBan %s not found in list, try /stats C.",user->nick.c_str(),parameters[0].c_str()); + user->WriteNotice("*** CBan " + parameters[0] + " not found in list, try /stats C."); return CMD_FAILURE; } } else { // Adding - XXX todo make this respect <insane> tag perhaps.. - long duration = ServerInstance->Duration(parameters[1]); + unsigned long duration = InspIRCd::Duration(parameters[1]); const char *reason = (parameters.size() > 2) ? parameters[2].c_str() : "No reason supplied"; CBan* r = new CBan(ServerInstance->Time(), duration, user->nick.c_str(), reason, parameters[0].c_str()); @@ -131,14 +121,14 @@ class CommandCBan : public Command else { time_t c_requires_crap = duration + ServerInstance->Time(); - std::string timestr = ServerInstance->TimeString(c_requires_crap); + std::string timestr = InspIRCd::TimeString(c_requires_crap); ServerInstance->SNO->WriteGlobalSno('x', "%s added timed CBan for %s, expires on %s: %s", user->nick.c_str(), parameters[0].c_str(), timestr.c_str(), reason); } } else { delete r; - user->WriteServ("NOTICE %s :*** CBan for %s already exists", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** CBan for " + parameters[0] + " already exists"); return CMD_FAILURE; } } @@ -164,22 +154,18 @@ class ModuleCBan : public Module { } - void init() + void init() CXX11_OVERRIDE { ServerInstance->XLines->RegisterFactory(&f); - - ServerInstance->Modules->AddService(mycommand); - Implementation eventlist[] = { I_OnUserPreJoin, I_OnStats }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual ~ModuleCBan() + ~ModuleCBan() { ServerInstance->XLines->DelAll("CBAN"); ServerInstance->XLines->UnregisterFactory(&f); } - virtual ModResult OnStats(char symbol, User* user, string_list &out) + ModResult OnStats(char symbol, User* user, string_list &out) CXX11_OVERRIDE { if (symbol != 'C') return MOD_RES_PASSTHRU; @@ -188,27 +174,26 @@ class ModuleCBan : public Module return MOD_RES_DENY; } - virtual ModResult OnUserPreJoin(User *user, Channel *chan, const char *cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { XLine *rl = ServerInstance->XLines->MatchesLine("CBAN", cname); if (rl) { // Channel is banned. - user->WriteServ( "384 %s %s :Cannot join channel, CBANed (%s)", user->nick.c_str(), cname, rl->reason.c_str()); + user->WriteNumeric(384, "%s :Cannot join channel, CBANed (%s)", cname.c_str(), rl->reason.c_str()); ServerInstance->SNO->WriteGlobalSno('a', "%s tried to join %s which is CBANed (%s)", - user->nick.c_str(), cname, rl->reason.c_str()); + user->nick.c_str(), cname.c_str(), rl->reason.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Gives /cban, aka C:lines. Think Q:lines, for channels.", VF_COMMON | VF_VENDOR); } }; MODULE_INIT(ModuleCBan) - diff --git a/src/modules/m_censor.cpp b/src/modules/m_censor.cpp index 50c8e22a7..da22b5153 100644 --- a/src/modules/m_censor.cpp +++ b/src/modules/m_censor.cpp @@ -20,15 +20,9 @@ */ -/* $ModDesc: Provides user and channel +G mode */ - -#define _CRT_SECURE_NO_DEPRECATE -#define _SCL_SECURE_NO_DEPRECATE - #include "inspircd.h" -#include <iostream> -typedef std::map<irc::string,irc::string> censor_t; +typedef insp::flat_map<irc::string, irc::string> censor_t; /** Handles usermode +G */ @@ -55,24 +49,8 @@ class ModuleCensor : public Module public: ModuleCensor() : cu(this), cc(this) { } - void init() - { - /* Read the configuration file on startup. - */ - OnRehash(NULL); - ServerInstance->Modules->AddService(cu); - ServerInstance->Modules->AddService(cc); - Implementation eventlist[] = { I_OnRehash, I_OnUserPreMessage, I_OnUserPreNotice }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - - virtual ~ModuleCensor() - { - } - // format of a config entry is <badword text="shit" replace="poo"> - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; @@ -80,11 +58,11 @@ class ModuleCensor : public Module bool active = false; if (target_type == TYPE_USER) - active = ((User*)dest)->IsModeSet('G'); + active = ((User*)dest)->IsModeSet(cu); else if (target_type == TYPE_CHANNEL) { - active = ((Channel*)dest)->IsModeSet('G'); Channel* c = (Channel*)dest; + active = c->IsModeSet(cc); ModResult res = ServerInstance->OnCheckExemption(user,c,"censor"); if (res == MOD_RES_ALLOW) @@ -101,7 +79,7 @@ class ModuleCensor : public Module { if (index->second.empty()) { - user->WriteNumeric(ERR_WORDFILTERED, "%s %s %s :Your message contained a censored word, and was blocked", user->nick.c_str(), ((Channel*)dest)->name.c_str(), index->first.c_str()); + user->WriteNumeric(ERR_WORDFILTERED, "%s %s :Your message contained a censored word, and was blocked", ((Channel*)dest)->name.c_str(), index->first.c_str()); return MOD_RES_DENY; } @@ -112,12 +90,7 @@ class ModuleCensor : public Module return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { /* * reload our config file on rehash - we must destroy and re-allocate the classes @@ -136,7 +109,7 @@ class ModuleCensor : public Module } } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides user and channel +G mode",VF_VENDOR); } diff --git a/src/modules/m_cgiirc.cpp b/src/modules/m_cgiirc.cpp index cce2e7855..721d6ba08 100644 --- a/src/modules/m_cgiirc.cpp +++ b/src/modules/m_cgiirc.cpp @@ -25,11 +25,17 @@ #include "inspircd.h" #include "xline.h" - -/* $ModDesc: Change user's hosts connecting from known CGI:IRC hosts */ +#include "modules/dns.h" enum CGItype { PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC }; +// We need this method up here so that it can be accessed from anywhere +static void ChangeIP(User* user, const std::string& newip) +{ + ServerInstance->Users->RemoveCloneCounts(user); + user->SetClientIP(newip.c_str()); + ServerInstance->Users->AddClone(user); +} /** Holds a CGI site's details */ @@ -64,14 +70,12 @@ class CommandWebirc : public Command bool notify; StringExtItem realhost; StringExtItem realip; - LocalStringExt webirc_hostname; - LocalStringExt webirc_ip; CGIHostlist Hosts; CommandWebirc(Module* Creator) : Command(Creator, "WEBIRC", 4), - realhost("cgiirc_realhost", Creator), realip("cgiirc_realip", Creator), - webirc_hostname("cgiirc_webirc_hostname", Creator), webirc_ip("cgiirc_webirc_ip", Creator) + realhost("cgiirc_realhost", ExtensionItem::EXT_USER, Creator) + , realip("cgiirc_realip", ExtensionItem::EXT_USER, Creator) { works_before_reg = true; this->syntax = "password client hostname ip"; @@ -90,25 +94,25 @@ class CommandWebirc : public Command realhost.set(user, user->host); realip.set(user, user->GetIPString()); - bool host_ok = (parameters[2].length() < 64); + // Check if we're happy with the provided hostname. If it's problematic then make sure we won't set a host later, just the IP + bool host_ok = (parameters[2].length() <= ServerInstance->Config->Limits.MaxHost); const std::string& newhost = (host_ok ? parameters[2] : parameters[3]); if (notify) - ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick.c_str(), user->host.c_str(), newhost.c_str(), user->host.c_str()); + ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick.c_str(), user->host.c_str(), newhost.c_str(), user->host.c_str()); - // Check if we're happy with the provided hostname. If it's problematic then make sure we won't set a host later, just the IP - if (host_ok) - webirc_hostname.set(user, parameters[2]); - else - webirc_hostname.unset(user); + // Where the magic happens - change their IP + ChangeIP(user, parameters[3]); + // And follow this up by changing their host + user->host = user->dhost = newhost; + user->InvalidateCache(); - webirc_ip.set(user, parameters[3]); return CMD_SUCCESS; } } } - ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str()); + ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s tried to use WEBIRC, but didn't match any configured webirc blocks.", user->GetFullRealHost().c_str()); return CMD_FAILURE; } }; @@ -116,39 +120,44 @@ class CommandWebirc : public Command /** Resolver for CGI:IRC hostnames encoded in ident/GECOS */ -class CGIResolver : public Resolver +class CGIResolver : public DNS::Request { std::string typ; std::string theiruid; LocalIntExt& waiting; bool notify; public: - CGIResolver(Module* me, bool NotifyOpers, const std::string &source, LocalUser* u, - const std::string &type, bool &cached, LocalIntExt& ext) - : Resolver(source, DNS_QUERY_PTR4, cached, me), typ(type), theiruid(u->uuid), + CGIResolver(DNS::Manager *mgr, Module* me, bool NotifyOpers, const std::string &source, LocalUser* u, + const std::string &ttype, LocalIntExt& ext) + : DNS::Request(mgr, me, source, DNS::QUERY_PTR), typ(ttype), theiruid(u->uuid), waiting(ext), notify(NotifyOpers) { } - virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) + void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE { /* Check the user still exists */ User* them = ServerInstance->FindUUID(theiruid); if ((them) && (!them->quitting)) { - if (notify) - ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick.c_str(), them->host.c_str(), result.c_str(), typ.c_str()); + LocalUser* lu = IS_LOCAL(them); + if (!lu) + return; - if (result.length() > 64) + const DNS::ResourceRecord &ans_record = r->answers[0]; + if (ans_record.rdata.empty() || ans_record.rdata.length() > ServerInstance->Config->Limits.MaxHost) return; - them->host = result; - them->dhost = result; + + if (notify) + ServerInstance->SNO->WriteGlobalSno('w', "Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick.c_str(), them->host.c_str(), ans_record.rdata.c_str(), typ.c_str()); + + them->host = them->dhost = ans_record.rdata; them->InvalidateCache(); - them->CheckLines(true); + lu->CheckLines(true); } } - virtual void OnError(ResolverError e, const std::string &errormessage) + void OnError(const DNS::Query *r) CXX11_OVERRIDE { if (!notify) return; @@ -156,11 +165,11 @@ class CGIResolver : public Resolver User* them = ServerInstance->FindUUID(theiruid); if ((them) && (!them->quitting)) { - ServerInstance->SNO->WriteToSnoMask('a', "Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick.c_str(), them->host.c_str(), typ.c_str()); + ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick.c_str(), them->host.c_str(), typ.c_str()); } } - virtual ~CGIResolver() + ~CGIResolver() { User* them = ServerInstance->FindUUID(theiruid); if (!them) @@ -175,6 +184,7 @@ class ModuleCgiIRC : public Module { CommandWebirc cmd; LocalIntExt waiting; + dynamic_reference<DNS::Manager> DNS; static void RecheckClass(LocalUser* user) { @@ -183,14 +193,6 @@ class ModuleCgiIRC : public Module user->CheckClass(); } - static void ChangeIP(LocalUser* user, const std::string& newip) - { - ServerInstance->Users->RemoveCloneCounts(user); - user->SetClientIP(newip.c_str()); - ServerInstance->Users->AddLocalClone(user); - ServerInstance->Users->AddGlobalClone(user); - } - void HandleIdentOrPass(LocalUser* user, const std::string& newip, bool was_pass) { cmd.realhost.set(user, user->host); @@ -199,40 +201,42 @@ class ModuleCgiIRC : public Module user->host = user->dhost = user->GetIPString(); user->InvalidateCache(); RecheckClass(user); + // Don't create the resolver if the core couldn't put the user in a connect class or when dns is disabled - if (user->quitting || ServerInstance->Config->NoUserDns) + if (user->quitting || !DNS || !user->MyClass->resolvehostnames) return; + CGIResolver* r = new CGIResolver(*this->DNS, this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), waiting); try { - bool cached; - CGIResolver* r = new CGIResolver(this, cmd.notify, newip, user, (was_pass ? "PASS" : "IDENT"), cached, waiting); waiting.set(user, waiting.get(user) + 1); - ServerInstance->AddResolver(r, cached); + this->DNS->Process(r); } - catch (...) + catch (DNS::Exception &ex) { + int count = waiting.get(user); + if (count) + waiting.set(user, count - 1); + delete r; if (cmd.notify) - ServerInstance->SNO->WriteToSnoMask('a', "Connecting user %s detected as using CGI:IRC (%s), but I could not resolve their hostname!", user->nick.c_str(), user->host.c_str()); + ServerInstance->SNO->WriteToSnoMask('w', "Connecting user %s detected as using CGI:IRC (%s), but I could not resolve their hostname; %s", user->nick.c_str(), user->host.c_str(), ex.GetReason().c_str()); } } public: - ModuleCgiIRC() : cmd(this), waiting("cgiirc-delay", this) + ModuleCgiIRC() + : cmd(this) + , waiting("cgiirc-delay", ExtensionItem::EXT_USER, this) + , DNS(this, "DNS") { } - void init() + void init() CXX11_OVERRIDE { - OnRehash(NULL); - ServiceProvider* providerlist[] = { &cmd, &cmd.realhost, &cmd.realip, &cmd.webirc_hostname, &cmd.webirc_ip, &waiting }; - ServerInstance->Modules->AddServices(providerlist, sizeof(providerlist)/sizeof(ServiceProvider*)); - - Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + ServerInstance->SNO->EnableSnomask('w', "CGIIRC"); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { cmd.Hosts.clear(); @@ -251,7 +255,7 @@ public: { if (type == "webirc" && password.empty()) { - ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str()); + ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str()); } else { @@ -267,7 +271,7 @@ public: else { cgitype = PASS; - ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:type> value in config: %s, setting it to \"pass\"", type.c_str()); + ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Invalid <cgihost:type> value in config: %s, setting it to \"pass\"", type.c_str()); } cmd.Hosts.push_back(CGIhost(hostmask, cgitype, password)); @@ -275,27 +279,20 @@ public: } else { - ServerInstance->Logs->Log("CONFIG",DEFAULT, "m_cgiirc.so: Invalid <cgihost:mask> value in config: %s", hostmask.c_str()); + ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Invalid <cgihost:mask> value in config: %s", hostmask.c_str()); continue; } } } - ModResult OnCheckReady(LocalUser *user) + ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE { if (waiting.get(user)) return MOD_RES_DENY; - std::string *webirc_ip = cmd.webirc_ip.get(user); - if (!webirc_ip) + if (!cmd.realip.get(user)) return MOD_RES_PASSTHRU; - ChangeIP(user, *webirc_ip); - - std::string* webirc_hostname = cmd.webirc_hostname.get(user); - user->host = user->dhost = (webirc_hostname ? *webirc_hostname : user->GetIPString()); - user->InvalidateCache(); - RecheckClass(user); if (user->quitting) return MOD_RES_DENY; @@ -304,13 +301,10 @@ public: if (user->quitting) return MOD_RES_DENY; - cmd.webirc_hostname.unset(user); - cmd.webirc_ip.unset(user); - return MOD_RES_PASSTHRU; } - ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { for(CGIHostlist::iterator iter = cmd.Hosts.begin(); iter != cmd.Hosts.end(); iter++) { @@ -388,7 +382,7 @@ public: bool IsValidHost(const std::string &host) { - if(!host.size() || host.size() > 64) + if(!host.size() || host.size() > ServerInstance->Config->Limits.MaxHost) return false; for(unsigned int i = 0; i < host.size(); i++) @@ -407,11 +401,10 @@ public: return true; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Change user's hosts connecting from known CGI:IRC hosts",VF_VENDOR); } - }; MODULE_INIT(ModuleCgiIRC) diff --git a/src/modules/m_chancreate.cpp b/src/modules/m_chancreate.cpp index 997a92648..6cf4af235 100644 --- a/src/modules/m_chancreate.cpp +++ b/src/modules/m_chancreate.cpp @@ -21,26 +21,20 @@ #include "inspircd.h" -/* $ModDesc: Provides snomasks 'j' and 'J', to which notices about newly created channels are sent */ - class ModuleChanCreate : public Module { - private: public: - void init() + void init() CXX11_OVERRIDE { ServerInstance->SNO->EnableSnomask('j', "CHANCREATE"); - Implementation eventlist[] = { I_OnUserJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides snomasks 'j' and 'J', to which notices about newly created channels are sent",VF_VENDOR); } - - void OnUserJoin(Membership* memb, bool sync, bool created, CUList& except) + void OnUserJoin(Membership* memb, bool sync, bool created, CUList& except) CXX11_OVERRIDE { if ((created) && (IS_LOCAL(memb->user))) { diff --git a/src/modules/m_chanfilter.cpp b/src/modules/m_chanfilter.cpp index 651e659b5..53428a5a8 100644 --- a/src/modules/m_chanfilter.cpp +++ b/src/modules/m_chanfilter.cpp @@ -23,13 +23,8 @@ */ -/* $ModDesc: Provides channel-specific censor lists (like mode +G but varies from channel to channel) */ - -#define _CRT_SECURE_NO_DEPRECATE -#define _SCL_SECURE_NO_DEPRECATE - #include "inspircd.h" -#include "u_listmode.h" +#include "listmode.h" /** Handles channel mode +g */ @@ -38,31 +33,30 @@ class ChanFilter : public ListModeBase public: ChanFilter(Module* Creator) : ListModeBase(Creator, "filter", 'g', "End of channel spamfilter list", 941, 940, false, "chanfilter") { } - virtual bool ValidateParam(User* user, Channel* chan, std::string &word) + bool ValidateParam(User* user, Channel* chan, std::string &word) { - if ((word.length() > 35) || (word.empty())) + if (word.length() > 35) { - user->WriteNumeric(935, "%s %s %s :word is too %s for censor list",user->nick.c_str(), chan->name.c_str(), word.c_str(), (word.empty() ? "short" : "long")); + user->WriteNumeric(935, "%s %s :word is too long for censor list", chan->name.c_str(), word.c_str()); return false; } return true; } - virtual bool TellListTooLong(User* user, Channel* chan, std::string &word) + void TellListTooLong(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(939, "%s %s %s :Channel spamfilter list is full", user->nick.c_str(), chan->name.c_str(), word.c_str()); - return true; + user->WriteNumeric(939, "%s %s :Channel spamfilter list is full", chan->name.c_str(), word.c_str()); } - virtual void TellAlreadyOnList(User* user, Channel* chan, std::string &word) + void TellAlreadyOnList(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(937, "%s %s :The word %s is already on the spamfilter list",user->nick.c_str(), chan->name.c_str(), word.c_str()); + user->WriteNumeric(937, "%s :The word %s is already on the spamfilter list", chan->name.c_str(), word.c_str()); } - virtual void TellNotSet(User* user, Channel* chan, std::string &word) + void TellNotSet(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(938, "%s %s :No such spamfilter word is set",user->nick.c_str(), chan->name.c_str()); + user->WriteNumeric(938, "%s :No such spamfilter word is set", chan->name.c_str()); } }; @@ -78,42 +72,35 @@ class ModuleChanFilter : public Module { } - void init() - { - ServerInstance->Modules->AddService(cf); - - cf.DoImplements(this); - Implementation eventlist[] = { I_OnRehash, I_OnUserPreMessage, I_OnUserPreNotice, I_OnSyncChannel }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - OnRehash(NULL); - } - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { hidemask = ServerInstance->Config->ConfValue("chanfilter")->getBool("hidemask"); cf.DoRehash(); } - virtual ModResult ProcessMessages(User* user,Channel* chan,std::string &text) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { + if (target_type != TYPE_CHANNEL) + return MOD_RES_PASSTHRU; + + Channel* chan = static_cast<Channel*>(dest); ModResult res = ServerInstance->OnCheckExemption(user,chan,"filter"); if (!IS_LOCAL(user) || res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; - modelist* list = cf.extItem.get(chan); + ListModeBase::ModeList* list = cf.GetList(chan); if (list) { - for (modelist::iterator i = list->begin(); i != list->end(); i++) + for (ListModeBase::ModeList::iterator i = list->begin(); i != list->end(); i++) { if (InspIRCd::Match(text, i->mask)) { if (hidemask) - user->WriteNumeric(404, "%s %s :Cannot send to channel (your message contained a censored word)",user->nick.c_str(), chan->name.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Cannot send to channel (your message contained a censored word)", chan->name.c_str()); else - user->WriteNumeric(404, "%s %s %s :Cannot send to channel (your message contained a censored word)",user->nick.c_str(), chan->name.c_str(), i->mask.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s %s :Cannot send to channel (your message contained a censored word)", chan->name.c_str(), i->mask.c_str()); return MOD_RES_DENY; } } @@ -122,33 +109,10 @@ class ModuleChanFilter : public Module return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - if (target_type == TYPE_CHANNEL) - { - return ProcessMessages(user,(Channel*)dest,text); - } - return MOD_RES_PASSTHRU; - } - - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - virtual void OnSyncChannel(Channel* chan, Module* proto, void* opaque) - { - cf.DoSyncChannel(chan, proto, opaque); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel-specific censor lists (like mode +G but varies from channel to channel)", VF_VENDOR); } - - virtual ~ModuleChanFilter() - { - } }; MODULE_INIT(ModuleChanFilter) diff --git a/src/modules/m_chanhistory.cpp b/src/modules/m_chanhistory.cpp index e48e67fe5..a0929a0d0 100644 --- a/src/modules/m_chanhistory.cpp +++ b/src/modules/m_chanhistory.cpp @@ -19,8 +19,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel history for a given number of lines */ - struct HistoryItem { time_t ts; @@ -32,10 +30,13 @@ struct HistoryList { std::deque<HistoryItem> lines; unsigned int maxlen, maxtime; - HistoryList(unsigned int len, unsigned int time) : maxlen(len), maxtime(time) {} + std::string param; + + HistoryList(unsigned int len, unsigned int time, const std::string& oparam) + : maxlen(len), maxtime(time), param(oparam) { } }; -class HistoryMode : public ModeHandler +class HistoryMode : public ParamMode<HistoryMode, SimpleExtItem<HistoryList> > { bool IsValidDuration(const std::string& duration) { @@ -52,110 +53,98 @@ class HistoryMode : public ModeHandler } public: - SimpleExtItem<HistoryList> ext; unsigned int maxlines; - HistoryMode(Module* Creator) : ModeHandler(Creator, "history", 'H', PARAM_SETONLY, MODETYPE_CHANNEL), - ext("history", Creator) { } + HistoryMode(Module* Creator) + : ParamMode<HistoryMode, SimpleExtItem<HistoryList> >(Creator, "history", 'H') + { + } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) + std::string::size_type colon = parameter.find(':'); + if (colon == std::string::npos) + return MODEACTION_DENY; + + std::string duration(parameter, colon+1); + if ((IS_LOCAL(source)) && ((duration.length() > 10) || (!IsValidDuration(duration)))) + return MODEACTION_DENY; + + unsigned int len = ConvToInt(parameter.substr(0, colon)); + int time = InspIRCd::Duration(duration); + if (len == 0 || time < 0) + return MODEACTION_DENY; + if (len > maxlines && IS_LOCAL(source)) + return MODEACTION_DENY; + if (len > maxlines) + len = maxlines; + + HistoryList* history = ext.get(channel); + if (history) { - std::string::size_type colon = parameter.find(':'); - if (colon == std::string::npos) - return MODEACTION_DENY; - - std::string duration = parameter.substr(colon+1); - if ((IS_LOCAL(source)) && ((duration.length() > 10) || (!IsValidDuration(duration)))) - return MODEACTION_DENY; - - unsigned int len = ConvToInt(parameter.substr(0, colon)); - int time = ServerInstance->Duration(duration); - if (len == 0 || time < 0) - return MODEACTION_DENY; - if (len > maxlines && IS_LOCAL(source)) - return MODEACTION_DENY; - if (len > maxlines) - len = maxlines; - if (parameter == channel->GetModeParameter(this)) - return MODEACTION_DENY; - - HistoryList* history = ext.get(channel); - if (history) - { - // Shrink the list if the new line number limit is lower than the old one - if (len < history->lines.size()) - history->lines.erase(history->lines.begin(), history->lines.begin() + (history->lines.size() - len)); + // Shrink the list if the new line number limit is lower than the old one + if (len < history->lines.size()) + history->lines.erase(history->lines.begin(), history->lines.begin() + (history->lines.size() - len)); - history->maxlen = len; - history->maxtime = time; - } - else - { - ext.set(channel, new HistoryList(len, time)); - } - channel->SetModeParam('H', parameter); + history->maxlen = len; + history->maxtime = time; + history->param = parameter; } else { - if (!channel->IsModeSet('H')) - return MODEACTION_DENY; - ext.unset(channel); - channel->SetModeParam('H', ""); + ext.set(channel, new HistoryList(len, time, parameter)); } return MODEACTION_ALLOW; } + + void SerializeParam(Channel* chan, const HistoryList* history, std::string& out) + { + out.append(history->param); + } }; class ModuleChanHistory : public Module { HistoryMode m; bool sendnotice; + UserModeReference botmode; + bool dobots; public: - ModuleChanHistory() : m(this) - { - } - - void init() + ModuleChanHistory() : m(this), botmode(this, "bot") { - ServerInstance->Modules->AddService(m); - ServerInstance->Modules->AddService(m.ext); - - Implementation eventlist[] = { I_OnPostJoin, I_OnUserMessage, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); } - void OnRehash(User*) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("chanhistory"); m.maxlines = tag->getInt("maxlines", 50); sendnotice = tag->getBool("notice", true); + dobots = tag->getBool("bots", true); } - void OnUserMessage(User* user,void* dest,int target_type, const std::string &text, char status, const CUList&) + void OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList&, MessageType msgtype) CXX11_OVERRIDE { - if (target_type == TYPE_CHANNEL && status == 0) + if ((target_type == TYPE_CHANNEL) && (status == 0) && (msgtype == MSG_PRIVMSG)) { Channel* c = (Channel*)dest; HistoryList* list = m.ext.get(c); if (list) { - char buf[MAXBUF]; - snprintf(buf, MAXBUF, ":%s PRIVMSG %s :%s", - user->GetFullHost().c_str(), c->name.c_str(), text.c_str()); - list->lines.push_back(HistoryItem(buf)); + const std::string line = ":" + user->GetFullHost() + " PRIVMSG " + c->name + " :" + text; + list->lines.push_back(HistoryItem(line)); if (list->lines.size() > list->maxlen) list->lines.pop_front(); } } } - void OnPostJoin(Membership* memb) + void OnPostJoin(Membership* memb) CXX11_OVERRIDE { if (IS_REMOTE(memb->user)) return; + if (memb->user->IsModeSet(botmode) && !dobots) + return; + HistoryList* list = m.ext.get(memb->chan); if (!list) return; @@ -165,8 +154,7 @@ class ModuleChanHistory : public Module if (sendnotice) { - memb->user->WriteServ("NOTICE %s :Replaying up to %d lines of pre-join history spanning up to %d seconds", - memb->chan->name.c_str(), list->maxlen, list->maxtime); + memb->user->WriteNotice("Replaying up to " + ConvToStr(list->maxlen) + " lines of pre-join history spanning up to " + ConvToStr(list->maxtime) + " seconds"); } for(std::deque<HistoryItem>::iterator i = list->lines.begin(); i != list->lines.end(); ++i) @@ -176,7 +164,7 @@ class ModuleChanHistory : public Module } } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel history replayed on join", VF_VENDOR); } diff --git a/src/modules/m_chanlog.cpp b/src/modules/m_chanlog.cpp index 6dbc0e7a8..0624b4a86 100644 --- a/src/modules/m_chanlog.cpp +++ b/src/modules/m_chanlog.cpp @@ -20,31 +20,16 @@ #include "inspircd.h" -/* $ModDesc: Logs snomask output to channel(s). */ - class ModuleChanLog : public Module { - private: /* * Multimap so people can redirect a snomask to multiple channels. */ - typedef std::multimap<char, std::string> ChanLogTargets; + typedef insp::flat_multimap<char, std::string> ChanLogTargets; ChanLogTargets logstreams; public: - void init() - { - Implementation eventlist[] = { I_OnRehash, I_OnSendSnotice }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - OnRehash(NULL); - } - - virtual ~ModuleChanLog() - { - } - - virtual void OnRehash(User *user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { std::string snomasks; std::string channel; @@ -59,100 +44,44 @@ class ModuleChanLog : public Module if (channel.empty() || snomasks.empty()) { - ServerInstance->Logs->Log("m_chanlog", DEFAULT, "Malformed chanlog tag, ignoring"); + ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Malformed chanlog tag, ignoring"); continue; } for (std::string::const_iterator it = snomasks.begin(); it != snomasks.end(); it++) { logstreams.insert(std::make_pair(*it, channel)); - ServerInstance->Logs->Log("m_chanlog", DEFAULT, "Logging %c to %s", *it, channel.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Logging %c to %s", *it, channel.c_str()); } } } - virtual ModResult OnSendSnotice(char &sno, std::string &desc, const std::string &msg) + ModResult OnSendSnotice(char &sno, std::string &desc, const std::string &msg) CXX11_OVERRIDE { std::pair<ChanLogTargets::const_iterator, ChanLogTargets::const_iterator> itpair = logstreams.equal_range(sno); if (itpair.first == itpair.second) return MOD_RES_PASSTHRU; - char buf[MAXBUF]; - snprintf(buf, MAXBUF, "\2%s\2: %s", desc.c_str(), msg.c_str()); + const std::string snotice = "\2" + desc + "\2: " + msg; for (ChanLogTargets::const_iterator it = itpair.first; it != itpair.second; ++it) { Channel *c = ServerInstance->FindChan(it->second); if (c) { - c->WriteChannelWithServ(ServerInstance->Config->ServerName, "PRIVMSG %s :%s", c->name.c_str(), buf); - ServerInstance->PI->SendChannelPrivmsg(c, 0, buf); + c->WriteChannelWithServ(ServerInstance->Config->ServerName, "PRIVMSG %s :%s", c->name.c_str(), snotice.c_str()); + ServerInstance->PI->SendMessage(c, 0, snotice); } } return MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Logs snomask output to channel(s).", VF_VENDOR); } }; - MODULE_INIT(ModuleChanLog) - - - - - - - - - -/* - * This is for the "old" chanlog module which intercepted messages going to the logfile.. - * I don't consider it all that useful, and it's quite dangerous if setup incorrectly, so - * this is defined out but left intact in case someone wants to develop it further someday. - * - * -- w00t (aug 23rd, 2008) - */ -#define OLD_CHANLOG 0 - -#if OLD_CHANLOG -class ChannelLogStream : public LogStream -{ - private: - std::string channel; - - public: - ChannelLogStream(int loglevel, const std::string &chan) : LogStream(loglevel), channel(chan) - { - } - - virtual void OnLog(int loglevel, const std::string &type, const std::string &msg) - { - Channel *c = ServerInstance->FindChan(channel); - static bool Logging = false; - - if (loglevel < this->loglvl) - return; - - if (Logging) - return; - - if (c) - { - Logging = true; // this avoids (rare chance) loops with logging server IO on networks - char buf[MAXBUF]; - snprintf(buf, MAXBUF, "\2%s\2: %s", type.c_str(), msg.c_str()); - - c->WriteChannelWithServ(ServerInstance->Config->ServerName, "PRIVMSG %s :%s", c->name.c_str(), buf); - ServerInstance->PI->SendChannelPrivmsg(c, 0, buf); - Logging = false; - } - } -}; -#endif - diff --git a/src/modules/m_channames.cpp b/src/modules/m_channames.cpp index 325e8fee1..7513cb33a 100644 --- a/src/modules/m_channames.cpp +++ b/src/modules/m_channames.cpp @@ -19,83 +19,78 @@ #include "inspircd.h" -/* $ModDesc: Implements config tags which allow changing characters allowed in channel names */ - static std::bitset<256> allowedmap; -class NewIsChannelHandler : public HandlerBase2<bool, const char*, size_t> +class NewIsChannelHandler : public HandlerBase1<bool, const std::string&> { public: - NewIsChannelHandler() { } - virtual ~NewIsChannelHandler() { } - virtual bool Call(const char*, size_t); + bool Call(const std::string&); }; -bool NewIsChannelHandler::Call(const char* c, size_t max) +bool NewIsChannelHandler::Call(const std::string& channame) { - /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */ - if (!c || *c++ != '#') + if (channame.empty() || channame.length() > ServerInstance->Config->Limits.ChanMax || channame[0] != '#') + return false; + + for (std::string::const_iterator c = channame.begin(); c != channame.end(); ++c) + { + unsigned int i = *c & 0xFF; + if (!allowedmap[i]) return false; + } - while (*c && --max) - { - unsigned int i = *c++ & 0xFF; - if (!allowedmap[i]) - return false; - } - // a name of exactly max length will have max = 1 here; the null does not trigger --max - return max; + return true; } class ModuleChannelNames : public Module { - private: NewIsChannelHandler myhandler; - caller2<bool, const char*, size_t> rememberer; + caller1<bool, const std::string&> rememberer; bool badchan; + ChanModeReference permchannelmode; public: - ModuleChannelNames() : rememberer(ServerInstance->IsChannel), badchan(false) + ModuleChannelNames() + : rememberer(ServerInstance->IsChannel) + , badchan(false) + , permchannelmode(this, "permanent") { } - void init() + void init() CXX11_OVERRIDE { ServerInstance->IsChannel = &myhandler; - Implementation eventlist[] = { I_OnRehash, I_OnUserKick }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); } void ValidateChans() { + Modes::ChangeList removepermchan; + badchan = true; - std::vector<Channel*> chanvec; - for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); ++i) - { - if (!ServerInstance->IsChannel(i->second->name.c_str(), MAXBUF)) - chanvec.push_back(i->second); - } - std::vector<Channel*>::reverse_iterator c2 = chanvec.rbegin(); - while (c2 != chanvec.rend()) + const chan_hash& chans = ServerInstance->GetChans(); + for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ) { - Channel* c = *c2++; - if (c->IsModeSet('P') && c->GetUserCounter()) - { - std::vector<std::string> modes; - modes.push_back(c->name); - modes.push_back("-P"); + Channel* c = i->second; + // Move iterator before we begin kicking + ++i; + if (ServerInstance->IsChannel(c->name)) + continue; // The name of this channel is still valid - ServerInstance->SendGlobalMode(modes, ServerInstance->FakeClient); + if (c->IsModeSet(permchannelmode) && c->GetUserCounter()) + { + removepermchan.clear(); + removepermchan.push_remove(*permchannelmode); + ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, removepermchan); } - const UserMembList* users = c->GetUsers(); - for(UserMembCIter j = users->begin(); j != users->end(); ) + + Channel::MemberMap& users = c->userlist; + for (Channel::MemberMap::iterator j = users.begin(); j != users.end(); ) { if (IS_LOCAL(j->first)) { // KickUser invalidates the iterator - UserMembCIter it = j++; - c->KickUser(ServerInstance->FakeClient, it->first, "Channel name no longer valid"); + Channel::MemberMap::iterator it = j++; + c->KickUser(ServerInstance->FakeClient, it, "Channel name no longer valid"); } else ++j; @@ -104,7 +99,7 @@ class ModuleChannelNames : public Module badchan = false; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("channames"); std::string denyToken = tag->getString("denyrange"); @@ -134,24 +129,25 @@ class ModuleChannelNames : public Module ValidateChans(); } - virtual void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& except_list) + void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& except_list) CXX11_OVERRIDE { if (badchan) { - const UserMembList* users = memb->chan->GetUsers(); - for(UserMembCIter i = users->begin(); i != users->end(); i++) + const Channel::MemberMap& users = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) if (i->first != memb->user) except_list.insert(i->first); } } - virtual ~ModuleChannelNames() + CullResult cull() CXX11_OVERRIDE { ServerInstance->IsChannel = rememberer; ValidateChans(); + return Module::cull(); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements config tags which allow changing characters allowed in channel names", VF_VENDOR); } diff --git a/src/modules/m_channelban.cpp b/src/modules/m_channelban.cpp index 6eec486ea..189c0d0bc 100644 --- a/src/modules/m_channelban.cpp +++ b/src/modules/m_channelban.cpp @@ -20,50 +20,31 @@ #include "inspircd.h" -/* $ModDesc: Implements extban +b j: - matching channel bans */ - class ModuleBadChannelExtban : public Module { - private: public: - void init() - { - Implementation eventlist[] = { I_OnCheckBan, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ~ModuleBadChannelExtban() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Extban 'j' - channel status/join ban", VF_OPTCOMMON|VF_VENDOR); } - ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) + ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) CXX11_OVERRIDE { if ((mask.length() > 2) && (mask[0] == 'j') && (mask[1] == ':')) { - std::string rm = mask.substr(2); + std::string rm(mask, 2); char status = 0; ModeHandler* mh = ServerInstance->Modes->FindPrefix(rm[0]); if (mh) { - rm = mask.substr(3); + rm.assign(mask, 3, std::string::npos); status = mh->GetModeChar(); } - for (UCListIter i = user->chans.begin(); i != user->chans.end(); i++) + for (User::ChanList::iterator i = user->chans.begin(); i != user->chans.end(); i++) { - if (InspIRCd::Match((**i).name, rm)) + if (InspIRCd::Match((*i)->chan->name, rm)) { - if (status) - { - Membership* memb = (**i).GetUser(user); - if (memb && memb->hasMode(status)) - return MOD_RES_DENY; - } - else + if (!status || (*i)->hasMode(status)) return MOD_RES_DENY; } } @@ -71,12 +52,10 @@ class ModuleBadChannelExtban : public Module return MOD_RES_PASSTHRU; } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('j'); + tokens["EXTBAN"].push_back('j'); } }; - MODULE_INIT(ModuleBadChannelExtban) - diff --git a/src/modules/m_chanprotect.cpp b/src/modules/m_chanprotect.cpp deleted file mode 100644 index affd0c8d6..000000000 --- a/src/modules/m_chanprotect.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net> - * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org> - * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> - * Copyright (C) 2004-2008 Craig Edwards <craigedwards@brainbox.cc> - * Copyright (C) 2007 John Brooks <john.brooks@dereferenced.net> - * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "inspircd.h" - -/* $ModDesc: Provides channel modes +a and +q */ - -#define PROTECT_VALUE 40000 -#define FOUNDER_VALUE 50000 - -struct ChanProtectSettings -{ - bool DeprivSelf; - bool DeprivOthers; - bool FirstInGetsFounder; - bool booting; - ChanProtectSettings() : booting(true) {} -}; - -static ChanProtectSettings settings; - -/** Handles basic operation of +qa channel modes - */ -class FounderProtectBase -{ - private: - const std::string type; - const char mode; - const int list; - const int end; - public: - FounderProtectBase(char Mode, const std::string &mtype, int l, int e) : - type(mtype), mode(Mode), list(l), end(e) - { - } - - void RemoveMode(Channel* channel, irc::modestacker* stack) - { - const UserMembList* cl = channel->GetUsers(); - std::vector<std::string> mode_junk; - mode_junk.push_back(channel->name); - irc::modestacker modestack(false); - std::deque<std::string> stackresult; - - for (UserMembCIter i = cl->begin(); i != cl->end(); i++) - { - if (i->second->hasMode(mode)) - { - if (stack) - stack->Push(mode, i->first->nick); - else - modestack.Push(mode, i->first->nick); - } - } - - if (stack) - return; - - while (modestack.GetStackedLine(stackresult)) - { - mode_junk.insert(mode_junk.end(), stackresult.begin(), stackresult.end()); - ServerInstance->SendMode(mode_junk, ServerInstance->FakeClient); - mode_junk.erase(mode_junk.begin() + 1, mode_junk.end()); - } - } - - void DisplayList(User* user, Channel* channel) - { - const UserMembList* cl = channel->GetUsers(); - for (UserMembCIter i = cl->begin(); i != cl->end(); ++i) - { - if (i->second->hasMode(mode)) - { - user->WriteServ("%d %s %s %s", list, user->nick.c_str(), channel->name.c_str(), i->first->nick.c_str()); - } - } - user->WriteServ("%d %s %s :End of channel %s list", end, user->nick.c_str(), channel->name.c_str(), type.c_str()); - } - - bool CanRemoveOthers(User* u1, Channel* c) - { - Membership* m1 = c->GetUser(u1); - return (settings.DeprivOthers && m1 && m1->hasMode(mode)); - } -}; - -/** Abstraction of FounderProtectBase for channel mode +q - */ -class ChanFounder : public ModeHandler, public FounderProtectBase -{ - public: - ChanFounder(Module* Creator) - : ModeHandler(Creator, "founder", 'q', PARAM_ALWAYS, MODETYPE_CHANNEL), - FounderProtectBase('q', "founder", 386, 387) - { - ModeHandler::list = true; - levelrequired = FOUNDER_VALUE; - m_paramtype = TR_NICK; - } - - void setPrefix(int pfx) - { - prefix = pfx; - } - - unsigned int GetPrefixRank() - { - return FOUNDER_VALUE; - } - - void RemoveMode(Channel* channel, irc::modestacker* stack) - { - FounderProtectBase::RemoveMode(channel, stack); - } - - void RemoveMode(User* user, irc::modestacker* stack) - { - } - - ModResult AccessCheck(User* source, Channel* channel, std::string ¶meter, bool adding) - { - User* theuser = ServerInstance->FindNick(parameter); - // remove own privs? - if (source == theuser && !adding && settings.DeprivSelf) - return MOD_RES_ALLOW; - - if (!adding && FounderProtectBase::CanRemoveOthers(source, channel)) - { - return MOD_RES_PASSTHRU; - } - else - { - source->WriteNumeric(468, "%s %s :Only servers may set channel mode +q", source->nick.c_str(), channel->name.c_str()); - return MOD_RES_DENY; - } - } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - return MODEACTION_ALLOW; - } - - void DisplayList(User* user, Channel* channel) - { - FounderProtectBase::DisplayList(user,channel); - } -}; - -/** Abstraction of FounderProtectBase for channel mode +a - */ -class ChanProtect : public ModeHandler, public FounderProtectBase -{ - public: - ChanProtect(Module* Creator) - : ModeHandler(Creator, "admin", 'a', PARAM_ALWAYS, MODETYPE_CHANNEL), - FounderProtectBase('a',"protected user", 388, 389) - { - ModeHandler::list = true; - levelrequired = PROTECT_VALUE; - m_paramtype = TR_NICK; - } - - void setPrefix(int pfx) - { - prefix = pfx; - } - - - unsigned int GetPrefixRank() - { - return PROTECT_VALUE; - } - - void RemoveMode(Channel* channel, irc::modestacker* stack) - { - FounderProtectBase::RemoveMode(channel, stack); - } - - void RemoveMode(User* user, irc::modestacker* stack) - { - } - - ModResult AccessCheck(User* source, Channel* channel, std::string ¶meter, bool adding) - { - User* theuser = ServerInstance->FindNick(parameter); - // source has +q - if (channel->GetPrefixValue(source) > PROTECT_VALUE) - return MOD_RES_ALLOW; - - // removing own privs? - if (source == theuser && !adding && settings.DeprivSelf) - return MOD_RES_ALLOW; - - if (!adding && FounderProtectBase::CanRemoveOthers(source, channel)) - { - return MOD_RES_PASSTHRU; - } - else - { - source->WriteNumeric(482, "%s %s :You are not a channel founder", source->nick.c_str(), channel->name.c_str()); - return MOD_RES_DENY; - } - } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - return MODEACTION_ALLOW; - } - - void DisplayList(User* user, Channel* channel) - { - FounderProtectBase::DisplayList(user, channel); - } - -}; - -class ModuleChanProtect : public Module -{ - ChanProtect cp; - ChanFounder cf; - public: - ModuleChanProtect() : cp(this), cf(this) - { - } - - void init() - { - /* Load config stuff */ - LoadSettings(); - settings.booting = false; - - ServerInstance->Modules->AddService(cf); - ServerInstance->Modules->AddService(cp); - - Implementation eventlist[] = { I_OnUserPreJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void LoadSettings() - { - ConfigTag* tag = ServerInstance->Config->ConfValue("chanprotect"); - - settings.FirstInGetsFounder = tag->getBool("noservices"); - - std::string qpre = tag->getString("qprefix"); - char QPrefix = qpre.empty() ? 0 : qpre[0]; - - std::string apre = tag->getString("aprefix"); - char APrefix = apre.empty() ? 0 : apre[0]; - - if ((APrefix && QPrefix) && APrefix == QPrefix) - throw ModuleException("What the smeg, why are both your +q and +a prefixes the same character?"); - - if (settings.booting) - { - if (APrefix && ServerInstance->Modes->FindPrefix(APrefix) && ServerInstance->Modes->FindPrefix(APrefix) != &cp) - throw ModuleException("Looks like the +a prefix you picked for m_chanprotect is already in use. Pick another."); - - if (QPrefix && ServerInstance->Modes->FindPrefix(QPrefix) && ServerInstance->Modes->FindPrefix(QPrefix) != &cf) - throw ModuleException("Looks like the +q prefix you picked for m_chanprotect is already in use. Pick another."); - - cp.setPrefix(APrefix); - cf.setPrefix(QPrefix); - } - settings.DeprivSelf = tag->getBool("deprotectself", true); - settings.DeprivOthers = tag->getBool("deprotectothers", true); - } - - ModResult OnUserPreJoin(User *user, Channel *chan, const char *cname, std::string &privs, const std::string &keygiven) - { - // if the user is the first user into the channel, mark them as the founder, but only if - // the config option for it is set - - if (settings.FirstInGetsFounder && !chan) - privs += 'q'; - - return MOD_RES_PASSTHRU; - } - - Version GetVersion() - { - return Version("Founder and Protect modes (+qa)", VF_VENDOR); - } -}; - -MODULE_INIT(ModuleChanProtect) diff --git a/src/modules/m_check.cpp b/src/modules/m_check.cpp index 9c5c414f1..6f9c32fb1 100644 --- a/src/modules/m_check.cpp +++ b/src/modules/m_check.cpp @@ -20,16 +20,51 @@ */ -/* $ModDesc: Provides the /CHECK command to retrieve information on a user, channel, hostname or IP address */ - #include "inspircd.h" +#include "listmode.h" /** Handle /CHECK */ class CommandCheck : public Command { + UserModeReference snomaskmode; + + std::string GetSnomasks(User* user) + { + std::string ret; + if (snomaskmode) + ret = snomaskmode->GetUserParameter(user); + + if (ret.empty()) + ret = "+"; + return ret; + } + + static void dumpListMode(User* user, const std::string& checkstr, const ListModeBase::ModeList* list) + { + if (!list) + return; + + std::string buf = checkstr + " modelist"; + const std::string::size_type headlen = buf.length(); + const size_t maxline = ServerInstance->Config->Limits.MaxLine; + for (ListModeBase::ModeList::const_iterator i = list->begin(); i != list->end(); ++i) + { + if (buf.size() + i->mask.size() + 1 > maxline) + { + user->SendText(buf); + buf.erase(headlen); + } + buf.append(" ").append(i->mask); + } + if (buf.length() > headlen) + user->SendText(buf); + } + public: - CommandCheck(Module* parent) : Command(parent,"CHECK", 1) + CommandCheck(Module* parent) + : Command(parent,"CHECK", 1) + , snomaskmode(parent, "snomask") { flags_needed = 'o'; syntax = "<nickname>|<ip>|<hostmask>|<channel> <server>"; } @@ -92,26 +127,26 @@ class CommandCheck : public Command user->SendText(checkstr + " realnuh " + targuser->GetFullRealHost()); user->SendText(checkstr + " realname " + targuser->fullname); user->SendText(checkstr + " modes +" + targuser->FormatModes()); - user->SendText(checkstr + " snomasks +" + targuser->FormatNoticeMasks()); - user->SendText(checkstr + " server " + targuser->server); + user->SendText(checkstr + " snomasks " + GetSnomasks(targuser)); + user->SendText(checkstr + " server " + targuser->server->GetName()); user->SendText(checkstr + " uid " + targuser->uuid); user->SendText(checkstr + " signon " + timestring(targuser->signon)); user->SendText(checkstr + " nickts " + timestring(targuser->age)); if (loctarg) - user->SendText(checkstr + " lastmsg " + timestring(targuser->idle_lastmsg)); + user->SendText(checkstr + " lastmsg " + timestring(loctarg->idle_lastmsg)); - if (IS_AWAY(targuser)) + if (targuser->IsAway()) { /* user is away */ user->SendText(checkstr + " awaytime " + timestring(targuser->awaytime)); user->SendText(checkstr + " awaymsg " + targuser->awaymsg); } - if (IS_OPER(targuser)) + if (targuser->IsOper()) { OperInfo* oper = targuser->oper; /* user is an oper of type ____ */ - user->SendText(checkstr + " opertype " + oper->NameStr()); + user->SendText(checkstr + " opertype " + oper->name); if (loctarg) { std::string umodes; @@ -127,7 +162,7 @@ class CommandCheck : public Command } user->SendText(checkstr + " modeperms user=" + umodes + " channel=" + cmodes); std::string opcmds; - for(std::set<std::string>::iterator i = oper->AllowedOperCommands.begin(); i != oper->AllowedOperCommands.end(); i++) + for (OperInfo::PrivSet::const_iterator i = oper->AllowedOperCommands.begin(); i != oper->AllowedOperCommands.end(); ++i) { opcmds.push_back(' '); opcmds.append(*i); @@ -135,7 +170,7 @@ class CommandCheck : public Command std::stringstream opcmddump(opcmds); user->SendText(checkstr + " commandperms", opcmddump); std::string privs; - for(std::set<std::string>::iterator i = oper->AllowedPrivs.begin(); i != oper->AllowedPrivs.end(); i++) + for (OperInfo::PrivSet::const_iterator i = oper->AllowedPrivs.begin(); i != oper->AllowedPrivs.end(); ++i) { privs.push_back(' '); privs.append(*i); @@ -147,8 +182,8 @@ class CommandCheck : public Command if (loctarg) { - user->SendText(checkstr + " clientaddr " + irc::sockets::satouser(loctarg->client_sa)); - user->SendText(checkstr + " serveraddr " + irc::sockets::satouser(loctarg->server_sa)); + user->SendText(checkstr + " clientaddr " + loctarg->client_sa.str()); + user->SendText(checkstr + " serveraddr " + loctarg->server_sa.str()); std::string classname = loctarg->GetClass()->name; if (!classname.empty()) @@ -157,10 +192,14 @@ class CommandCheck : public Command else user->SendText(checkstr + " onip " + targuser->GetIPString()); - for (UCListIter i = targuser->chans.begin(); i != targuser->chans.end(); i++) + for (User::ChanList::iterator i = targuser->chans.begin(); i != targuser->chans.end(); i++) { - Channel* c = *i; - chliststr.append(c->GetPrefixChar(targuser)).append(c->name).append(" "); + Membership* memb = *i; + Channel* c = memb->chan; + char prefix = memb->GetPrefixChar(); + if (prefix) + chliststr.push_back(prefix); + chliststr.append(c->name).push_back(' '); } std::stringstream dump(chliststr); @@ -187,32 +226,25 @@ class CommandCheck : public Command /* now the ugly bit, spool current members of a channel. :| */ - const UserMembList *ulist= targchan->GetUsers(); + const Channel::MemberMap& ulist = targchan->GetUsers(); /* note that unlike /names, we do NOT check +i vs in the channel */ - for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++) + for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i) { - char tmpbuf[MAXBUF]; /* - * Unlike Asuka, I define a clone as coming from the same host. --w00t - */ - snprintf(tmpbuf, MAXBUF, "%-3lu %s%s (%s@%s) %s ", ServerInstance->Users->GlobalCloneCount(i->first), targchan->GetAllPrefixChars(i->first), i->first->nick.c_str(), i->first->ident.c_str(), i->first->dhost.c_str(), i->first->fullname.c_str()); - user->SendText(checkstr + " member " + tmpbuf); + * Unlike Asuka, I define a clone as coming from the same host. --w00t + */ + const UserManager::CloneCounts& clonecount = ServerInstance->Users->GetCloneCounts(i->first); + user->SendText("%s member %-3u %s%s (%s@%s) %s ", + checkstr.c_str(), clonecount.global, + i->second->GetAllPrefixChars(), i->first->nick.c_str(), + i->first->ident.c_str(), i->first->dhost.c_str(), i->first->fullname.c_str()); } - irc::modestacker modestack(true); - for(BanList::iterator b = targchan->bans.begin(); b != targchan->bans.end(); ++b) - { - modestack.Push('b', b->data); - } - std::vector<std::string> stackresult; - std::vector<TranslateType> dummy; - while (modestack.GetStackedLine(stackresult)) - { - creator->ProtoSendMode(user, TYPE_CHANNEL, targchan, stackresult, dummy); - stackresult.clear(); - } - FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(targchan,creator,user)); + const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes(); + for (ModeParser::ListModeList::const_iterator i = listmodes.begin(); i != listmodes.end(); ++i) + dumpListMode(user, checkstr, (*i)->GetList(targchan)); + dumpExt(user, checkstr, targchan); } else @@ -221,7 +253,8 @@ class CommandCheck : public Command long x = 0; /* hostname or other */ - for (user_hash::const_iterator a = ServerInstance->Users->clientlist->begin(); a != ServerInstance->Users->clientlist->end(); a++) + const user_hash& users = ServerInstance->Users->GetUsers(); + for (user_hash::const_iterator a = users.begin(); a != users.end(); ++a) { if (InspIRCd::Match(a->second->host, parameters[0], ascii_case_insensitive_map) || InspIRCd::Match(a->second->dhost, parameters[0], ascii_case_insensitive_map)) { @@ -252,42 +285,15 @@ class CommandCheck : public Command } }; - class ModuleCheck : public Module { - private: CommandCheck mycommand; public: ModuleCheck() : mycommand(this) { } - void init() - { - ServerInstance->Modules->AddService(mycommand); - } - - ~ModuleCheck() - { - } - - void ProtoSendMode(void* uv, TargetTypeFlags, void*, const std::vector<std::string>& result, const std::vector<TranslateType>&) - { - User* user = (User*)uv; - std::string checkstr(":"); - checkstr.append(ServerInstance->Config->ServerName); - checkstr.append(" 304 "); - checkstr.append(user->nick); - checkstr.append(" :CHECK modelist"); - for(unsigned int i=0; i < result.size(); i++) - { - checkstr.append(" "); - checkstr.append(result[i]); - } - user->SendText(checkstr); - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("CHECK command, view user, channel, IP address or hostname information", VF_VENDOR|VF_OPTCOMMON); } diff --git a/src/modules/m_chghost.cpp b/src/modules/m_chghost.cpp index 6aaed7831..43b2a323b 100644 --- a/src/modules/m_chghost.cpp +++ b/src/modules/m_chghost.cpp @@ -21,13 +21,10 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the CHGHOST command */ - /** Handle /CHGHOST */ class CommandChghost : public Command { - private: char* hostmap; public: CommandChghost(Module* Creator, char* hmap) : Command(Creator,"CHGHOST", 2), hostmap(hmap) @@ -35,16 +32,16 @@ class CommandChghost : public Command allow_empty_last_param = false; flags_needed = 'o'; syntax = "<nick> <newhost>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) { const char* x = parameters[1].c_str(); - if (parameters[1].length() > 63) + if (parameters[1].length() > ServerInstance->Config->Limits.MaxHost) { - user->WriteServ("NOTICE %s :*** CHGHOST: Host too long", user->nick.c_str()); + user->WriteNotice("*** CHGHOST: Host too long"); return CMD_FAILURE; } @@ -52,7 +49,7 @@ class CommandChghost : public Command { if (!hostmap[(unsigned char)*x]) { - user->WriteServ("NOTICE "+user->nick+" :*** CHGHOST: Invalid characters in hostname"); + user->WriteNotice("*** CHGHOST: Invalid characters in hostname"); return CMD_FAILURE; } } @@ -60,15 +57,15 @@ class CommandChghost : public Command User* dest = ServerInstance->FindNick(parameters[0]); // Allow services to change the host of unregistered users - if ((!dest) || ((dest->registered != REG_ALL) && (!ServerInstance->ULine(user->server)))) + if ((!dest) || ((dest->registered != REG_ALL) && (!user->server->IsULine()))) { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); return CMD_FAILURE; } if (IS_LOCAL(dest)) { - if ((dest->ChangeDisplayedHost(parameters[1].c_str())) && (!ServerInstance->ULine(user->server))) + if ((dest->ChangeDisplayedHost(parameters[1])) && (!user->server->IsULine())) { // fix by brain - ulines set hosts silently ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used CHGHOST to make the displayed host of "+dest->nick+" become "+dest->dhost); @@ -92,20 +89,13 @@ class ModuleChgHost : public Module { CommandChghost cmd; char hostmap[256]; + public: ModuleChgHost() : cmd(this, hostmap) { } - void init() - { - OnRehash(NULL); - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { std::string hmap = ServerInstance->Config->ConfValue("hostname")->getString("charmap", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_/0123456789"); @@ -114,15 +104,10 @@ class ModuleChgHost : public Module hostmap[(unsigned char)*n] = 1; } - ~ModuleChgHost() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the CHGHOST command", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleChgHost) diff --git a/src/modules/m_chgident.cpp b/src/modules/m_chgident.cpp index 2112e45a3..c855216bf 100644 --- a/src/modules/m_chgident.cpp +++ b/src/modules/m_chgident.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the CHGIDENT command */ - /** Handle /CHGIDENT */ class CommandChgident : public Command @@ -34,7 +32,7 @@ class CommandChgident : public Command allow_empty_last_param = false; flags_needed = 'o'; syntax = "<nick> <newident>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) @@ -43,27 +41,27 @@ class CommandChgident : public Command if ((!dest) || (dest->registered != REG_ALL)) { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); return CMD_FAILURE; } if (parameters[1].length() > ServerInstance->Config->Limits.IdentMax) { - user->WriteServ("NOTICE %s :*** CHGIDENT: Ident is too long", user->nick.c_str()); + user->WriteNotice("*** CHGIDENT: Ident is too long"); return CMD_FAILURE; } - if (!ServerInstance->IsIdent(parameters[1].c_str())) + if (!ServerInstance->IsIdent(parameters[1])) { - user->WriteServ("NOTICE %s :*** CHGIDENT: Invalid characters in ident", user->nick.c_str()); + user->WriteNotice("*** CHGIDENT: Invalid characters in ident"); return CMD_FAILURE; } if (IS_LOCAL(dest)) { - dest->ChangeIdent(parameters[1].c_str()); + dest->ChangeIdent(parameters[1]); - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) ServerInstance->SNO->WriteGlobalSno('a', "%s used CHGIDENT to change %s's ident to '%s'", user->nick.c_str(), dest->nick.c_str(), dest->ident.c_str()); } @@ -79,7 +77,6 @@ class CommandChgident : public Command } }; - class ModuleChgIdent : public Module { CommandChgident cmd; @@ -89,21 +86,10 @@ public: { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleChgIdent() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the CHGIDENT command", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleChgIdent) - diff --git a/src/modules/m_chgname.cpp b/src/modules/m_chgname.cpp index 73ae3d487..830d5070b 100644 --- a/src/modules/m_chgname.cpp +++ b/src/modules/m_chgname.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the CHGNAME command */ - /** Handle /CHGNAME */ class CommandChgname : public Command @@ -32,7 +30,7 @@ class CommandChgname : public Command allow_empty_last_param = false; flags_needed = 'o'; syntax = "<nick> <newname>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) @@ -41,25 +39,25 @@ class CommandChgname : public Command if ((!dest) || (dest->registered != REG_ALL)) { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); return CMD_FAILURE; } if (parameters[1].empty()) { - user->WriteServ("NOTICE %s :*** CHGNAME: GECOS must be specified", user->nick.c_str()); + user->WriteNotice("*** CHGNAME: GECOS must be specified"); return CMD_FAILURE; } if (parameters[1].length() > ServerInstance->Config->Limits.MaxGecos) { - user->WriteServ("NOTICE %s :*** CHGNAME: GECOS too long", user->nick.c_str()); + user->WriteNotice("*** CHGNAME: GECOS too long"); return CMD_FAILURE; } if (IS_LOCAL(dest)) { - dest->ChangeName(parameters[1].c_str()); + dest->ChangeName(parameters[1]); ServerInstance->SNO->WriteGlobalSno('a', "%s used CHGNAME to change %s's GECOS to '%s'", user->nick.c_str(), dest->nick.c_str(), dest->fullname.c_str()); } @@ -75,7 +73,6 @@ class CommandChgname : public Command } }; - class ModuleChgName : public Module { CommandChgname cmd; @@ -85,20 +82,10 @@ public: { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleChgName() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the CHGNAME command", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleChgName) diff --git a/src/modules/m_clearchan.cpp b/src/modules/m_clearchan.cpp new file mode 100644 index 000000000..5fcec36f1 --- /dev/null +++ b/src/modules/m_clearchan.cpp @@ -0,0 +1,218 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2014 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "xline.h" + +class CommandClearChan : public Command +{ + public: + Channel* activechan; + + CommandClearChan(Module* Creator) + : Command(Creator, "CLEARCHAN", 1, 3) + { + syntax = "<channel> [<KILL|KICK|G|Z>] [<reason>]"; + flags_needed = 'o'; + + // Stop the linking mod from forwarding ENCAP'd CLEARCHAN commands, see below why + force_manual_route = true; + } + + CmdResult Handle(const std::vector<std::string>& parameters, User* user) + { + Channel* chan = activechan = ServerInstance->FindChan(parameters[0]); + if (!chan) + { + user->WriteNotice("The channel " + parameters[0] + " does not exist."); + return CMD_FAILURE; + } + + // See what method the oper wants to use, default to KILL + std::string method("KILL"); + if (parameters.size() > 1) + { + method = parameters[1]; + std::transform(method.begin(), method.end(), method.begin(), ::toupper); + } + + XLineFactory* xlf = NULL; + bool kick = (method == "KICK"); + if ((!kick) && (method != "KILL")) + { + if ((method != "Z") && (method != "G")) + { + user->WriteNotice("Invalid method for clearing " + chan->name); + return CMD_FAILURE; + } + + xlf = ServerInstance->XLines->GetFactory(method); + if (!xlf) + return CMD_FAILURE; + } + + const std::string reason = parameters.size() > 2 ? parameters.back() : "Clearing " + chan->name; + + if (!user->server->IsSilentULine()) + ServerInstance->SNO->WriteToSnoMask((IS_LOCAL(user) ? 'a' : 'A'), user->nick + " has cleared \002" + chan->name + "\002 (" + method + "): " + reason); + + user->WriteNotice("Clearing \002" + chan->name + "\002 (" + method + "): " + reason); + + { + // Route this command manually so it is sent before the QUITs we are about to generate. + // The idea is that by the time our QUITs reach the next hop, it has already removed all their + // clients from the channel, meaning victims on other servers won't see the victims on this + // server quitting. + std::vector<std::string> eparams; + eparams.push_back(chan->name); + eparams.push_back(method); + eparams.push_back(":"); + eparams.back().append(reason); + ServerInstance->PI->BroadcastEncap(this->name, eparams, user, user); + } + + // Attach to the appropriate hook so we're able to hide the QUIT/KICK messages + Implementation hook = (kick ? I_OnUserKick : I_OnBuildNeighborList); + ServerInstance->Modules->Attach(hook, creator); + + std::string mask; + // Now remove all local non-opers from the channel + Channel::MemberMap& users = chan->userlist; + for (Channel::MemberMap::iterator i = users.begin(); i != users.end(); ) + { + User* curr = i->first; + const Channel::MemberMap::iterator currit = i; + ++i; + + if (!IS_LOCAL(curr) || curr->IsOper()) + continue; + + // If kicking users, remove them and skip the QuitUser() + if (kick) + { + chan->KickUser(ServerInstance->FakeClient, currit, reason); + continue; + } + + // If we are banning users then create the XLine and add it + if (xlf) + { + XLine* xline; + try + { + mask = ((method[0] == 'Z') ? curr->GetIPString() : "*@" + curr->host); + xline = xlf->Generate(ServerInstance->Time(), 60*60, user->nick, reason, mask); + } + catch (ModuleException& ex) + { + // Nothing, move on to the next user + continue; + } + + if (!ServerInstance->XLines->AddLine(xline, user)) + delete xline; + } + + ServerInstance->Users->QuitUser(curr, reason); + } + + ServerInstance->Modules->Detach(hook, creator); + if (xlf) + ServerInstance->XLines->ApplyLines(); + + return CMD_SUCCESS; + } +}; + +class ModuleClearChan : public Module +{ + CommandClearChan cmd; + + public: + ModuleClearChan() + : cmd(this) + { + } + + void init() + { + // Only attached while we are working; don't react to events otherwise + ServerInstance->Modules->DetachAll(this); + } + + void OnBuildNeighborList(User* source, IncludeChanList& include, std::map<User*, bool>& exception) CXX11_OVERRIDE + { + bool found = false; + for (IncludeChanList::iterator i = include.begin(); i != include.end(); ++i) + { + if ((*i)->chan == cmd.activechan) + { + // Don't show the QUIT to anyone in the channel by default + include.erase(i); + found = true; + break; + } + } + + const Channel::MemberMap& users = cmd.activechan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) + { + LocalUser* curr = IS_LOCAL(i->first); + if (!curr) + continue; + + if (curr->IsOper()) + { + // If another module has removed the channel we're working on from the list of channels + // to consider for sending the QUIT to then don't add exceptions for opers, because the + // module before us doesn't want them to see it or added the exceptions already. + // If there is a value for this oper in excepts already, this won't overwrite it. + if (found) + exception.insert(std::make_pair(curr, true)); + continue; + } + else if (!include.empty() && curr->chans.size() > 1) + { + // This is a victim and potentially has another common channel with the user quitting, + // add a negative exception overwriting the previous value, if any. + exception[curr] = false; + } + } + } + + void OnUserKick(User* source, Membership* memb, const std::string& reason, CUList& excepts) CXX11_OVERRIDE + { + // Hide the KICK from all non-opers + User* leaving = memb->user; + const Channel::MemberMap& users = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) + { + User* curr = i->first; + if ((IS_LOCAL(curr)) && (!curr->IsOper()) && (curr != leaving)) + excepts.insert(curr); + } + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Adds /CLEARCHAN that allows opers to masskick, masskill or mass-G/ZLine users on a channel", VF_VENDOR|VF_OPTCOMMON); + } +}; + +MODULE_INIT(ModuleClearChan) diff --git a/src/modules/m_cloaking.cpp b/src/modules/m_cloaking.cpp index 105d68833..1534043ce 100644 --- a/src/modules/m_cloaking.cpp +++ b/src/modules/m_cloaking.cpp @@ -24,16 +24,10 @@ #include "inspircd.h" -#include "hash.h" - -/* $ModDesc: Provides masking of user hostnames */ +#include "modules/hash.h" enum CloakMode { - /** 1.2-compatible host-based cloak */ - MODE_COMPAT_HOST, - /** 1.2-compatible IP-only cloak */ - MODE_COMPAT_IPONLY, /** 2.0 cloak of "half" of the hostname plus the full IP hash */ MODE_HALF_CLOAK, /** 2.0 cloak of IP hash, split at 2 common CIDR range points */ @@ -49,14 +43,13 @@ class CloakUser : public ModeHandler { public: LocalStringExt ext; - std::string debounce_uid; time_t debounce_ts; int debounce_count; CloakUser(Module* source) : ModeHandler(source, "cloak", 'x', PARAM_NONE, MODETYPE_USER), - ext("cloaked_host", source), debounce_ts(0), debounce_count(0) + ext("cloaked_host", ExtensionItem::EXT_USER, source), debounce_ts(0), debounce_count(0) { } @@ -70,7 +63,7 @@ class CloakUser : public ModeHandler */ if (!user) { - dest->SetMode('x',adding); + dest->SetMode(this, adding); return MODEACTION_ALLOW; } @@ -87,7 +80,7 @@ class CloakUser : public ModeHandler debounce_ts = ServerInstance->Time(); } - if (adding == user->IsModeSet('x')) + if (adding == user->IsModeSet(this)) return MODEACTION_DENY; /* don't allow this user to spam modechanges */ @@ -106,8 +99,8 @@ class CloakUser : public ModeHandler } if (cloak) { - user->ChangeDisplayedHost(cloak->c_str()); - user->SetMode('x',true); + user->ChangeDisplayedHost(*cloak); + user->SetMode(this, true); return MODEACTION_ALLOW; } else @@ -118,12 +111,11 @@ class CloakUser : public ModeHandler /* User is removing the mode, so restore their real host * and make it match the displayed one. */ - user->SetMode('x',false); + user->SetMode(this, false); user->ChangeDisplayedHost(user->host.c_str()); return MODEACTION_ALLOW; } } - }; class CommandCloak : public Command @@ -147,7 +139,6 @@ class ModuleCloaking : public Module std::string prefix; std::string suffix; std::string key; - unsigned int compatkey[4]; const char* xtab[4]; dynamic_reference<HashProvider> Hash; @@ -155,18 +146,6 @@ class ModuleCloaking : public Module { } - void init() - { - OnRehash(NULL); - - ServerInstance->Modules->AddService(cu); - ServerInstance->Modules->AddService(ck); - ServerInstance->Modules->AddService(cu.ext); - - Implementation eventlist[] = { I_OnRehash, I_OnCheckBan, I_OnUserConnect, I_OnChangeHost }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - /** This function takes a domain name string and returns just the last two domain parts, * or the last domain part if only two are available. Failing that it just returns what it was given. * @@ -213,7 +192,7 @@ class ModuleCloaking : public Module input.append(1, '\0'); // null does not terminate a C++ string input.append(item); - std::string rv = Hash->sum(input).substr(0,len); + std::string rv = Hash->GenerateRaw(input).substr(0,len); for(int i=0; i < len; i++) { // this discards 3 bits per byte. We have an @@ -224,63 +203,6 @@ class ModuleCloaking : public Module return rv; } - std::string CompatCloak4(const char* ip) - { - irc::sepstream seps(ip, '.'); - std::string octet[4]; - int i[4]; - - for (int j = 0; j < 4; j++) - { - seps.GetToken(octet[j]); - i[j] = atoi(octet[j].c_str()); - } - - octet[3] = octet[0] + "." + octet[1] + "." + octet[2] + "." + octet[3]; - octet[2] = octet[0] + "." + octet[1] + "." + octet[2]; - octet[1] = octet[0] + "." + octet[1]; - - /* Reset the Hash module and send it our IV */ - - std::string rv; - - /* Send the Hash module a different hex table for each octet group's Hash sum */ - for (int k = 0; k < 4; k++) - { - rv.append(Hash->sumIV(compatkey, xtab[(compatkey[k]+i[k]) % 4], octet[k]).substr(0,6)); - if (k < 3) - rv.append("."); - } - /* Stick them all together */ - return rv; - } - - std::string CompatCloak6(const char* ip) - { - std::vector<std::string> hashies; - std::string item; - int rounds = 0; - - /* Reset the Hash module and send it our IV */ - - for (const char* input = ip; *input; input++) - { - item += *input; - if (item.length() > 7) - { - hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8)); - item.clear(); - } - rounds++; - } - if (!item.empty()) - { - hashies.push_back(Hash->sumIV(compatkey, xtab[(compatkey[0]+rounds) % 4], item).substr(0,8)); - } - /* Stick them all together */ - return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined(); - } - std::string SegmentIP(const irc::sockets::sockaddrs& ip, bool full) { std::string bindata; @@ -348,7 +270,7 @@ class ModuleCloaking : public Module return rv; } - ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) + ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE { LocalUser* lu = IS_LOCAL(user); if (!lu) @@ -359,9 +281,8 @@ class ModuleCloaking : public Module /* Check if they have a cloaked host, but are not using it */ if (cloak && *cloak != user->dhost) { - char cmask[MAXBUF]; - snprintf(cmask, MAXBUF, "%s!%s@%s", user->nick.c_str(), user->ident.c_str(), cloak->c_str()); - if (InspIRCd::Match(cmask,mask)) + const std::string cloakMask = user->nick + "!" + user->ident + "@" + *cloak; + if (InspIRCd::Match(cloakMask, mask)) return MOD_RES_DENY; } return MOD_RES_PASSTHRU; @@ -375,32 +296,22 @@ class ModuleCloaking : public Module // this unsets umode +x on every host change. If we are actually doing a +x // mode change, we will call SetMode back to true AFTER the host change is done. - void OnChangeHost(User* u, const std::string& host) + void OnChangeHost(User* u, const std::string& host) CXX11_OVERRIDE { - if(u->IsModeSet('x')) + if (u->IsModeSet(cu)) { - u->SetMode('x', false); - u->WriteServ("MODE %s -x", u->nick.c_str()); + u->SetMode(cu, false); + u->WriteCommand("MODE", "-" + ConvToStr(cu.GetModeChar())); } } - ~ModuleCloaking() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { std::string testcloak = "broken"; if (Hash) { switch (mode) { - case MODE_COMPAT_HOST: - testcloak = prefix + "-" + Hash->sumIV(compatkey, xtab[0], "*").substr(0,10); - break; - case MODE_COMPAT_IPONLY: - testcloak = Hash->sumIV(compatkey, xtab[0], "*").substr(0,10); - break; case MODE_HALF_CLOAK: testcloak = prefix + SegmentCloak("*", 3, 8) + suffix; break; @@ -411,82 +322,23 @@ class ModuleCloaking : public Module return Version("Provides masking of user hostnames", VF_COMMON|VF_VENDOR, testcloak); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("cloak"); prefix = tag->getString("prefix"); suffix = tag->getString("suffix", ".IP"); std::string modestr = tag->getString("mode"); - if (modestr == "compat-host") - mode = MODE_COMPAT_HOST; - else if (modestr == "compat-ip") - mode = MODE_COMPAT_IPONLY; - else if (modestr == "half") + if (modestr == "half") mode = MODE_HALF_CLOAK; else if (modestr == "full") mode = MODE_OPAQUE; else - throw ModuleException("Bad value for <cloak:mode>; must be one of compat-host, compat-ip, half, full"); - - if (mode == MODE_COMPAT_HOST || mode == MODE_COMPAT_IPONLY) - { - bool lowercase = tag->getBool("lowercase"); - - /* These are *not* using the need_positive parameter of ReadInteger - - * that will limit the valid values to only the positive values in a - * signed int. Instead, accept any value that fits into an int and - * cast it to an unsigned int. That will, a bit oddly, give us the full - * spectrum of an unsigned integer. - Special - * - * We must limit the keys or else we get different results on - * amd64/x86 boxes. - psychon */ - const unsigned int limit = 0x80000000; - compatkey[0] = (unsigned int) tag->getInt("key1"); - compatkey[1] = (unsigned int) tag->getInt("key2"); - compatkey[2] = (unsigned int) tag->getInt("key3"); - compatkey[3] = (unsigned int) tag->getInt("key4"); - - if (!lowercase) - { - xtab[0] = "F92E45D871BCA630"; - xtab[1] = "A1B9D80C72E653F4"; - xtab[2] = "1ABC078934DEF562"; - xtab[3] = "ABCDEF5678901234"; - } - else - { - xtab[0] = "f92e45d871bca630"; - xtab[1] = "a1b9d80c72e653f4"; - xtab[2] = "1abc078934def562"; - xtab[3] = "abcdef5678901234"; - } - - if (prefix.empty()) - prefix = ServerInstance->Config->Network; + throw ModuleException("Bad value for <cloak:mode>; must be half or full"); - if (!compatkey[0] || !compatkey[1] || !compatkey[2] || !compatkey[3] || - compatkey[0] >= limit || compatkey[1] >= limit || compatkey[2] >= limit || compatkey[3] >= limit) - { - std::string detail; - if (!compatkey[0] || compatkey[0] >= limit) - detail = "<cloak:key1> is not valid, it may be set to a too high/low value, or it may not exist."; - else if (!compatkey[1] || compatkey[1] >= limit) - detail = "<cloak:key2> is not valid, it may be set to a too high/low value, or it may not exist."; - else if (!compatkey[2] || compatkey[2] >= limit) - detail = "<cloak:key3> is not valid, it may be set to a too high/low value, or it may not exist."; - else if (!compatkey[3] || compatkey[3] >= limit) - detail = "<cloak:key4> is not valid, it may be set to a too high/low value, or it may not exist."; - - throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED! - " + detail); - } - } - else - { - key = tag->getString("key"); - if (key.empty() || key == "secret") - throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret."); - } + key = tag->getString("key"); + if (key.empty() || key == "secret") + throw ModuleException("You have not defined cloak keys for m_cloaking. Define <cloak:key> as a network-wide secret."); } std::string GenCloak(const irc::sockets::sockaddrs& ip, const std::string& ipstr, const std::string& host) @@ -495,29 +347,6 @@ class ModuleCloaking : public Module switch (mode) { - case MODE_COMPAT_HOST: - { - if (ipstr != host) - { - std::string tail = LastTwoDomainParts(host); - - // xtab is not used here due to a bug in 1.2 cloaking - chost = prefix + "-" + Hash->sumIV(compatkey, "0123456789abcdef", host).substr(0,8) + tail; - - /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes - * according to the DNS RFC) then they get cloaked as an IP. - */ - if (chost.length() <= 64) - break; - } - // fall through to IP cloak - } - case MODE_COMPAT_IPONLY: - if (ip.sa.sa_family == AF_INET6) - chost = CompatCloak6(ipstr.c_str()); - else - chost = CompatCloak4(ipstr.c_str()); - break; case MODE_HALF_CLOAK: { if (ipstr != host) @@ -533,7 +362,7 @@ class ModuleCloaking : public Module return chost; } - void OnUserConnect(LocalUser* dest) + void OnUserConnect(LocalUser* dest) CXX11_OVERRIDE { std::string* cloak = cu.ext.get(dest); if (cloak) @@ -554,7 +383,7 @@ CmdResult CommandCloak::Handle(const std::vector<std::string> ¶meters, User else cloak = mod->GenCloak(sa, "", parameters[0]); - user->WriteServ("NOTICE %s :*** Cloak for %s is %s", user->nick.c_str(), parameters[0].c_str(), cloak.c_str()); + user->WriteNotice("*** Cloak for " + parameters[0] + " is " + cloak); return CMD_SUCCESS; } diff --git a/src/modules/m_clones.cpp b/src/modules/m_clones.cpp index 92b1bda78..c51c8d3b4 100644 --- a/src/modules/m_clones.cpp +++ b/src/modules/m_clones.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides the /CLONES command to retrieve information on clones. */ - /** Handle /CLONES */ class CommandClones : public Command @@ -50,11 +48,12 @@ class CommandClones : public Command user->WriteServ(clonesstr + " START"); /* hostname or other */ - // XXX I really don't like marking global_clones public for this. at all. -- w00t - for (clonemap::iterator x = ServerInstance->Users->global_clones.begin(); x != ServerInstance->Users->global_clones.end(); x++) + const UserManager::CloneMap& clonemap = ServerInstance->Users->GetCloneMap(); + for (UserManager::CloneMap::const_iterator i = clonemap.begin(); i != clonemap.end(); ++i) { - if (x->second >= limit) - user->WriteServ(clonesstr + " "+ ConvToStr(x->second) + " " + x->first.str()); + const UserManager::CloneCounts& counts = i->second; + if (counts.global >= limit) + user->WriteServ(clonesstr + " " + ConvToStr(counts.global) + " " + i->first.str()); } user->WriteServ(clonesstr + " END"); @@ -63,31 +62,18 @@ class CommandClones : public Command } }; - class ModuleClones : public Module { - private: CommandClones cmd; public: ModuleClones() : cmd(this) { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleClones() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the /CLONES command to retrieve information on clones.", VF_VENDOR); } - - }; MODULE_INIT(ModuleClones) diff --git a/src/modules/m_close.cpp b/src/modules/m_close.cpp index 8b0ea3417..f3c751f17 100644 --- a/src/modules/m_close.cpp +++ b/src/modules/m_close.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides /CLOSE functionality */ - /** Handle /CLOSE */ class CommandClose : public Command @@ -30,13 +28,15 @@ class CommandClose : public Command /* Command 'close', needs operator */ CommandClose(Module* Creator) : Command(Creator,"CLOSE", 0) { - flags_needed = 'o'; } + flags_needed = 'o'; + } CmdResult Handle (const std::vector<std::string> ¶meters, User *src) { std::map<std::string,int> closed; - for (LocalUserList::const_iterator u = ServerInstance->Users->local_users.begin(); u != ServerInstance->Users->local_users.end(); ++u) + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator u = list.begin(); u != list.end(); ++u) { LocalUser* user = *u; if (user->registered != REG_ALL) @@ -50,13 +50,14 @@ class CommandClose : public Command int total = 0; for (std::map<std::string,int>::iterator ci = closed.begin(); ci != closed.end(); ci++) { - src->WriteServ("NOTICE %s :*** Closed %d unknown connection%s from [%s]",src->nick.c_str(),(*ci).second,((*ci).second>1)?"s":"",(*ci).first.c_str()); - total += (*ci).second; + src->WriteNotice("*** Closed " + ConvToStr(ci->second) + " unknown " + (ci->second == 1 ? "connection" : "connections") + + " from [" + ci->first + "]"); + total += ci->second; } if (total) - src->WriteServ("NOTICE %s :*** %i unknown connection%s closed",src->nick.c_str(),total,(total>1)?"s":""); + src->WriteNotice("*** " + ConvToStr(total) + " unknown " + (total == 1 ? "connection" : "connections") + " closed"); else - src->WriteServ("NOTICE %s :*** No unknown connections found",src->nick.c_str()); + src->WriteNotice("*** No unknown connections found"); return CMD_SUCCESS; } @@ -71,16 +72,7 @@ class ModuleClose : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleClose() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides /CLOSE functionality", VF_VENDOR); } diff --git a/src/modules/m_commonchans.cpp b/src/modules/m_commonchans.cpp index afa17add4..eab53b9bc 100644 --- a/src/modules/m_commonchans.cpp +++ b/src/modules/m_commonchans.cpp @@ -19,8 +19,6 @@ #include "inspircd.h" -/* $ModDesc: Adds user mode +c, which if set, users must be on a common channel with you to private message you */ - /** Handles user mode +c */ class PrivacyMode : public SimpleUserModeHandler @@ -37,41 +35,24 @@ class ModulePrivacyMode : public Module { } - void init() - { - ServerInstance->Modules->AddService(pm); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModulePrivacyMode() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Adds user mode +c, which if set, users must be on a common channel with you to private message you", VF_VENDOR); } - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (target_type == TYPE_USER) { User* t = (User*)dest; - if (!IS_OPER(user) && (t->IsModeSet('c')) && (!ServerInstance->ULine(user->server)) && !user->SharesChannelWith(t)) + if (!user->IsOper() && (t->IsModeSet(pm)) && (!user->server->IsULine()) && !user->SharesChannelWith(t)) { - user->WriteNumeric(ERR_CANTSENDTOUSER, "%s %s :You are not permitted to send private messages to this user (+c set)", user->nick.c_str(), t->nick.c_str()); + user->WriteNumeric(ERR_CANTSENDTOUSER, "%s :You are not permitted to send private messages to this user (+c set)", t->nick.c_str()); return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user, dest, target_type, text, status, exempt_list); - } }; - MODULE_INIT(ModulePrivacyMode) diff --git a/src/modules/m_conn_join.cpp b/src/modules/m_conn_join.cpp index 6b13ab1aa..b22dbdf4d 100644 --- a/src/modules/m_conn_join.cpp +++ b/src/modules/m_conn_join.cpp @@ -22,45 +22,94 @@ #include "inspircd.h" -/* $ModDesc: Forces users to join the specified channel(s) on connect */ +static void JoinChannels(LocalUser* u, const std::string& chanlist) +{ + irc::commasepstream chans(chanlist); + std::string chan; + + while (chans.GetToken(chan)) + { + if (ServerInstance->IsChannel(chan)) + Channel::JoinUser(u, chan); + } +} + +class JoinTimer : public Timer +{ + private: + LocalUser* const user; + const std::string channels; + SimpleExtItem<JoinTimer>& ext; + + public: + JoinTimer(LocalUser* u, SimpleExtItem<JoinTimer>& ex, const std::string& chans, unsigned int delay) + : Timer(delay, false) + , user(u), channels(chans), ext(ex) + { + ServerInstance->Timers.AddTimer(this); + } + + bool Tick(time_t time) CXX11_OVERRIDE + { + if (user->chans.empty()) + JoinChannels(user, channels); + + ext.unset(user); + return false; + } +}; class ModuleConnJoin : public Module { - public: - void init() - { - Implementation eventlist[] = { I_OnPostConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } + SimpleExtItem<JoinTimer> ext; + std::string defchans; + unsigned int defdelay; - void Prioritize() - { - ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_LAST); - } + public: + ModuleConnJoin() + : ext("join_timer", ExtensionItem::EXT_USER, this) + { + } - Version GetVersion() - { - return Version("Forces users to join the specified channel(s) on connect", VF_VENDOR); - } + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* tag = ServerInstance->Config->ConfValue("autojoin"); + defchans = tag->getString("channel"); + defdelay = tag->getInt("delay", 0, 0, 60); + } - void OnPostConnect(User* user) - { - if (!IS_LOCAL(user)) - return; + void Prioritize() + { + ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_LAST); + } - std::string chanlist = ServerInstance->Config->ConfValue("autojoin")->getString("channel"); - chanlist = user->GetClass()->config->getString("autojoin", chanlist); + Version GetVersion() CXX11_OVERRIDE + { + return Version("Forces users to join the specified channel(s) on connect", VF_VENDOR); + } - irc::commasepstream chans(chanlist); - std::string chan; + void OnPostConnect(User* user) CXX11_OVERRIDE + { + LocalUser* localuser = IS_LOCAL(user); + if (!localuser) + return; - while (chans.GetToken(chan)) - { - if (ServerInstance->IsChannel(chan.c_str(), ServerInstance->Config->Limits.ChanMax)) - Channel::JoinUser(user, chan.c_str(), false, "", false, ServerInstance->Time()); - } + std::string chanlist = localuser->GetClass()->config->getString("autojoin"); + unsigned int chandelay = localuser->GetClass()->config->getInt("autojoindelay", 0, 0, 60); + + if (chanlist.empty()) + { + if (defchans.empty()) + return; + chanlist = defchans; + chandelay = defdelay; } -}; + if (!chandelay) + JoinChannels(localuser, chanlist); + else + ext.set(localuser, new JoinTimer(localuser, ext, chanlist, chandelay)); + } +}; MODULE_INIT(ModuleConnJoin) diff --git a/src/modules/m_conn_umodes.cpp b/src/modules/m_conn_umodes.cpp index a21462ddf..7a8d66ae7 100644 --- a/src/modules/m_conn_umodes.cpp +++ b/src/modules/m_conn_umodes.cpp @@ -22,32 +22,21 @@ #include "inspircd.h" -/* $ModDesc: Sets (and unsets) modes on users when they connect */ - class ModuleModesOnConnect : public Module { public: - void init() - { - ServerInstance->Modules->Attach(I_OnUserConnect, this); - } - void Prioritize() { // for things like +x on connect, important, otherwise we have to resort to config order (bleh) -- w00t ServerInstance->Modules->SetPriority(this, I_OnUserConnect, PRIORITY_FIRST); } - virtual ~ModuleModesOnConnect() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Sets (and unsets) modes on users when they connect", VF_VENDOR); } - virtual void OnUserConnect(LocalUser* user) + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE { // Backup and zero out the disabled usermodes, so that we can override them here. char save[64]; @@ -62,26 +51,14 @@ class ModuleModesOnConnect : public Module std::string buf; std::stringstream ss(ThisModes); - std::vector<std::string> tokens; - - // split ThisUserModes into modes and mode params - while (ss >> buf) - tokens.push_back(buf); - std::vector<std::string> modes; modes.push_back(user->nick); - modes.push_back(tokens[0]); - if (tokens.size() > 1) - { - // process mode params - for (unsigned int k = 1; k < tokens.size(); k++) - { - modes.push_back(tokens[k]); - } - } + // split ThisUserModes into modes and mode params + while (ss >> buf) + modes.push_back(buf); - ServerInstance->Parser->CallHandler("MODE", modes, user); + ServerInstance->Parser.CallHandler("MODE", modes, user); } memcpy(ServerInstance->Config->DisabledUModes, save, 64); diff --git a/src/modules/m_conn_waitpong.cpp b/src/modules/m_conn_waitpong.cpp index 1d48220a6..87b6b51f2 100644 --- a/src/modules/m_conn_waitpong.cpp +++ b/src/modules/m_conn_waitpong.cpp @@ -24,8 +24,6 @@ #include "inspircd.h" -/* $ModDesc: Forces connecting clients to send a PONG message back to the server before they can complete their connection */ - class ModuleWaitPong : public Module { bool sendsnotice; @@ -34,39 +32,31 @@ class ModuleWaitPong : public Module public: ModuleWaitPong() - : ext("waitpong_pingstr", this) - { - } - - void init() + : ext("waitpong_pingstr", ExtensionItem::EXT_USER, this) { - ServerInstance->Modules->AddService(ext); - OnRehash(NULL); - Implementation eventlist[] = { I_OnUserRegister, I_OnCheckReady, I_OnPreCommand, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("waitpong"); sendsnotice = tag->getBool("sendsnotice", true); killonbadreply = tag->getBool("killonbadreply", true); } - ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { std::string pingrpl = ServerInstance->GenRandomStr(10); user->Write("PING :%s", pingrpl.c_str()); if(sendsnotice) - user->WriteServ("NOTICE %s :*** If you are having problems connecting due to ping timeouts, please type /quote PONG %s or /raw PONG %s now.", user->nick.c_str(), pingrpl.c_str(), pingrpl.c_str()); + user->WriteNotice("*** If you are having problems connecting due to ping timeouts, please type /quote PONG " + pingrpl + " or /raw PONG " + pingrpl + " now."); ext.set(user, pingrpl); return MOD_RES_PASSTHRU; } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser* user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser* user, bool validated, const std::string &original_line) CXX11_OVERRIDE { if (command == "PONG") { @@ -90,20 +80,15 @@ class ModuleWaitPong : public Module return MOD_RES_PASSTHRU; } - ModResult OnCheckReady(LocalUser* user) + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE { return ext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU; } - ~ModuleWaitPong() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Require pong prior to registration", VF_VENDOR); } - }; MODULE_INIT(ModuleWaitPong) diff --git a/src/modules/m_connectban.cpp b/src/modules/m_connectban.cpp index 26120add9..fcb4b09ed 100644 --- a/src/modules/m_connectban.cpp +++ b/src/modules/m_connectban.cpp @@ -20,61 +20,39 @@ #include "inspircd.h" #include "xline.h" -/* $ModDesc: Throttles the connections of IP ranges who try to connect flood. */ - class ModuleConnectBan : public Module { - private: - clonemap connects; + typedef std::map<irc::sockets::cidr_mask, unsigned int> ConnectMap; + ConnectMap connects; unsigned int threshold; unsigned int banduration; unsigned int ipv4_cidr; unsigned int ipv6_cidr; - public: - void init() - { - Implementation eventlist[] = { I_OnSetUserIP, I_OnGarbageCollect, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } + std::string banmessage; - virtual ~ModuleConnectBan() - { - } - - virtual Version GetVersion() + public: + Version GetVersion() CXX11_OVERRIDE { return Version("Throttles the connections of IP ranges who try to connect flood.", VF_VENDOR); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("connectban"); - ipv4_cidr = tag->getInt("ipv4cidr", 32); - if (ipv4_cidr == 0) - ipv4_cidr = 32; - - ipv6_cidr = tag->getInt("ipv6cidr", 128); - if (ipv6_cidr == 0) - ipv6_cidr = 128; - - threshold = tag->getInt("threshold", 10); - if (threshold == 0) - threshold = 10; - - banduration = ServerInstance->Duration(tag->getString("duration", "10m")); - if (banduration == 0) - banduration = 10*60; + ipv4_cidr = tag->getInt("ipv4cidr", 32, 1, 32); + ipv6_cidr = tag->getInt("ipv6cidr", 128, 1, 128); + threshold = tag->getInt("threshold", 10, 1); + banduration = tag->getDuration("duration", 10*60, 1); + banmessage = tag->getString("banmessage", "Your IP range has been attempting to connect too many times in too short a duration. Wait a while, and you will be able to connect."); } - virtual void OnSetUserIP(LocalUser* u) + void OnSetUserIP(LocalUser* u) CXX11_OVERRIDE { if (u->exempt) return; int range = 32; - clonemap::iterator i; switch (u->client_sa.sa.sa_family) { @@ -87,7 +65,7 @@ class ModuleConnectBan : public Module } irc::sockets::cidr_mask mask(u->client_sa, range); - i = connects.find(mask); + ConnectMap::iterator i = connects.find(mask); if (i != connects.end()) { @@ -96,7 +74,7 @@ class ModuleConnectBan : public Module if (i->second >= threshold) { // Create zline for set duration. - ZLine* zl = new ZLine(ServerInstance->Time(), banduration, ServerInstance->Config->ServerName, "Your IP range has been attempting to connect too many times in too short a duration. Wait a while, and you will be able to connect.", mask.str()); + ZLine* zl = new ZLine(ServerInstance->Time(), banduration, ServerInstance->Config->ServerName, banmessage, mask.str()); if (!ServerInstance->XLines->AddLine(zl, NULL)) { delete zl; @@ -104,7 +82,7 @@ class ModuleConnectBan : public Module } ServerInstance->XLines->ApplyLines(); std::string maskstr = mask.str(); - std::string timestr = ServerInstance->TimeString(zl->expiry); + std::string timestr = InspIRCd::TimeString(zl->expiry); ServerInstance->SNO->WriteGlobalSno('x',"Module m_connectban added Z:line on *@%s to expire on %s: Connect flooding", maskstr.c_str(), timestr.c_str()); ServerInstance->SNO->WriteGlobalSno('a', "Connect flooding from IP range %s (%d)", maskstr.c_str(), threshold); @@ -117,9 +95,9 @@ class ModuleConnectBan : public Module } } - virtual void OnGarbageCollect() + void OnGarbageCollect() { - ServerInstance->Logs->Log("m_connectban",DEBUG, "Clearing map."); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Clearing map."); connects.clear(); } }; diff --git a/src/modules/m_connflood.cpp b/src/modules/m_connflood.cpp index f77691e32..2ab906e27 100644 --- a/src/modules/m_connflood.cpp +++ b/src/modules/m_connflood.cpp @@ -21,11 +21,8 @@ #include "inspircd.h" -/* $ModDesc: Connection throttle */ - class ModuleConnFlood : public Module { -private: int seconds, timeout, boot_wait; unsigned int conns; unsigned int maxconns; @@ -39,19 +36,12 @@ public: { } - void init() - { - InitConf(); - Implementation eventlist[] = { I_OnRehash, I_OnUserRegister }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Connection throttle", VF_VENDOR); } - void InitConf() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { /* read configuration variables */ ConfigTag* tag = ServerInstance->Config->ConfValue("connflood"); @@ -67,7 +57,7 @@ public: first = ServerInstance->Time(); } - virtual ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { if (user->exempt) return MOD_RES_PASSTHRU; @@ -114,12 +104,6 @@ public: } return MOD_RES_PASSTHRU; } - - virtual void OnRehash(User* user) - { - InitConf(); - } - }; MODULE_INIT(ModuleConnFlood) diff --git a/src/modules/m_customprefix.cpp b/src/modules/m_customprefix.cpp index dfc60e082..f6f9a84f6 100644 --- a/src/modules/m_customprefix.cpp +++ b/src/modules/m_customprefix.cpp @@ -19,89 +19,37 @@ #include "inspircd.h" -/* $ModDesc: Allows custom prefix modes to be created. */ - -class CustomPrefixMode : public ModeHandler +class CustomPrefixMode : public PrefixMode { public: reference<ConfigTag> tag; - int rank; bool depriv; + CustomPrefixMode(Module* parent, ConfigTag* Tag) - : ModeHandler(parent, Tag->getString("name"), 0, PARAM_ALWAYS, MODETYPE_CHANNEL), tag(Tag) + : PrefixMode(parent, Tag->getString("name"), 0, Tag->getInt("rank")) + , tag(Tag) { - list = true; - m_paramtype = TR_NICK; std::string v = tag->getString("prefix"); prefix = v.c_str()[0]; v = tag->getString("letter"); mode = v.c_str()[0]; - rank = tag->getInt("rank"); - levelrequired = tag->getInt("ranktoset", rank); + levelrequired = tag->getInt("ranktoset", prefixrank); depriv = tag->getBool("depriv", true); } - unsigned int GetPrefixRank() - { - return rank; - } - ModResult AccessCheck(User* src, Channel*, std::string& value, bool adding) { if (!adding && src->nick == value && depriv) return MOD_RES_ALLOW; return MOD_RES_PASSTHRU; } - - void RemoveMode(Channel* channel, irc::modestacker* stack) - { - const UserMembList* cl = channel->GetUsers(); - std::vector<std::string> mode_junk; - mode_junk.push_back(channel->name); - irc::modestacker modestack(false); - std::deque<std::string> stackresult; - - for (UserMembCIter i = cl->begin(); i != cl->end(); i++) - { - if (i->second->hasMode(mode)) - { - if (stack) - stack->Push(this->GetModeChar(), i->first->nick); - else - modestack.Push(this->GetModeChar(), i->first->nick); - } - } - - if (stack) - return; - - while (modestack.GetStackedLine(stackresult)) - { - mode_junk.insert(mode_junk.end(), stackresult.begin(), stackresult.end()); - ServerInstance->SendMode(mode_junk, ServerInstance->FakeClient); - mode_junk.erase(mode_junk.begin() + 1, mode_junk.end()); - } - } - - void RemoveMode(User* user, irc::modestacker* stack) - { - } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - return MODEACTION_ALLOW; - } }; class ModuleCustomPrefix : public Module { std::vector<CustomPrefixMode*> modes; public: - ModuleCustomPrefix() - { - } - - void init() + void init() CXX11_OVERRIDE { ConfigTagList tags = ServerInstance->Config->ConfTags("customprefix"); while (tags.first != tags.second) @@ -110,7 +58,7 @@ class ModuleCustomPrefix : public Module tags.first++; CustomPrefixMode* mh = new CustomPrefixMode(this, tag); modes.push_back(mh); - if (mh->rank <= 0) + if (mh->GetPrefixRank() == 0) throw ModuleException("Rank must be specified for prefix at " + tag->getTagLocation()); if (!isalpha(mh->GetModeChar())) throw ModuleException("Mode must be a letter for prefix at " + tag->getTagLocation()); @@ -120,18 +68,17 @@ class ModuleCustomPrefix : public Module } catch (ModuleException& e) { - throw ModuleException(e.err + " (while creating mode from " + tag->getTagLocation() + ")"); + throw ModuleException(e.GetReason() + " (while creating mode from " + tag->getTagLocation() + ")"); } } } ~ModuleCustomPrefix() { - for (std::vector<CustomPrefixMode*>::iterator i = modes.begin(); i != modes.end(); i++) - delete *i; + stdalgo::delete_all(modes); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides custom prefix channel modes", VF_VENDOR); } diff --git a/src/modules/m_customtitle.cpp b/src/modules/m_customtitle.cpp index c65645bc9..b86bf1809 100644 --- a/src/modules/m_customtitle.cpp +++ b/src/modules/m_customtitle.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides the TITLE command which allows setting of CUSTOM WHOIS TITLE line */ - /** Handle /TITLE */ class CommandTitle : public Command @@ -30,32 +28,15 @@ class CommandTitle : public Command public: StringExtItem ctitle; CommandTitle(Module* Creator) : Command(Creator,"TITLE", 2), - ctitle("ctitle", Creator) + ctitle("ctitle", ExtensionItem::EXT_USER, Creator) { syntax = "<user> <password>"; } - bool OneOfMatches(const char* host, const char* ip, const char* hostlist) - { - std::stringstream hl(hostlist); - std::string xhost; - while (hl >> xhost) - { - if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map)) - { - return true; - } - } - return false; - } - CmdResult Handle(const std::vector<std::string> ¶meters, User* user) { - char TheHost[MAXBUF]; - char TheIP[MAXBUF]; - - snprintf(TheHost,MAXBUF,"%s@%s",user->ident.c_str(), user->host.c_str()); - snprintf(TheIP, MAXBUF,"%s@%s",user->ident.c_str(), user->GetIPString()); + const std::string userHost = user->ident + "@" + user->host; + const std::string userIP = user->ident + "@" + user->GetIPString(); ConfigTagList tags = ServerInstance->Config->ConfTags("title"); for (ConfigIter i = tags.first; i != tags.second; ++i) @@ -67,65 +48,57 @@ class CommandTitle : public Command std::string title = i->second->getString("title"); std::string vhost = i->second->getString("vhost"); - if (Name == parameters[0] && !ServerInstance->PassCompare(user, pass, parameters[1], hash) && OneOfMatches(TheHost,TheIP,host.c_str()) && !title.empty()) + if (Name == parameters[0] && ServerInstance->PassCompare(user, pass, parameters[1], hash) && + InspIRCd::MatchMask(host, userHost, userIP) && !title.empty()) { ctitle.set(user, title); ServerInstance->PI->SendMetaData(user, "ctitle", title); if (!vhost.empty()) - user->ChangeDisplayedHost(vhost.c_str()); + user->ChangeDisplayedHost(vhost); - user->WriteServ("NOTICE %s :Custom title set to '%s'",user->nick.c_str(), title.c_str()); + user->WriteNotice("Custom title set to '" + title + "'"); return CMD_SUCCESS; } } - user->WriteServ("NOTICE %s :Invalid title credentials",user->nick.c_str()); + user->WriteNotice("Invalid title credentials"); return CMD_SUCCESS; } }; -class ModuleCustomTitle : public Module +class ModuleCustomTitle : public Module, public Whois::LineEventListener { CommandTitle cmd; public: - ModuleCustomTitle() : cmd(this) - { - } - - void init() + ModuleCustomTitle() + : Whois::LineEventListener(this) + , cmd(this) { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(cmd.ctitle); - ServerInstance->Modules->Attach(I_OnWhoisLine, this); } // :kenny.chatspike.net 320 Brain Azhrarn :is getting paid to play games. - ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) + ModResult OnWhoisLine(Whois::Context& whois, unsigned int& numeric, std::string& text) CXX11_OVERRIDE { /* We use this and not OnWhois because this triggers for remote, too */ if (numeric == 312) { /* Insert our numeric before 312 */ - const std::string* ctitle = cmd.ctitle.get(dest); + const std::string* ctitle = cmd.ctitle.get(whois.GetTarget()); if (ctitle) { - ServerInstance->SendWhoisLine(user, dest, 320, "%s %s :%s",user->nick.c_str(), dest->nick.c_str(), ctitle->c_str()); + whois.SendLine(320, ":%s", ctitle->c_str()); } } /* Don't block anything */ return MOD_RES_PASSTHRU; } - ~ModuleCustomTitle() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Custom Title for users", VF_OPTCOMMON | VF_VENDOR); } diff --git a/src/modules/m_cycle.cpp b/src/modules/m_cycle.cpp index 383e7b5a2..c8b6bd8b4 100644 --- a/src/modules/m_cycle.cpp +++ b/src/modules/m_cycle.cpp @@ -20,23 +20,21 @@ #include "inspircd.h" -/* $ModDesc: Provides command CYCLE, acts as a server-side HOP command to part and rejoin a channel. */ - /** Handle /CYCLE */ -class CommandCycle : public Command +class CommandCycle : public SplitCommand { public: - CommandCycle(Module* Creator) : Command(Creator,"CYCLE", 1) + CommandCycle(Module* Creator) + : SplitCommand(Creator, "CYCLE", 1) { Penalty = 3; syntax = "<channel> :[reason]"; - TRANSLATE3(TR_TEXT, TR_TEXT, TR_END); } - CmdResult Handle (const std::vector<std::string> ¶meters, User *user) + CmdResult HandleLocal(const std::vector<std::string> ¶meters, LocalUser* user) { Channel* channel = ServerInstance->FindChan(parameters[0]); - std::string reason = ConvToStr("Cycling"); + std::string reason = "Cycling"; if (parameters.size() > 1) { @@ -46,34 +44,27 @@ class CommandCycle : public Command if (!channel) { - user->WriteNumeric(403, "%s %s :No such channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHCHANNEL, "%s :No such channel", parameters[0].c_str()); return CMD_FAILURE; } if (channel->HasUser(user)) { - /* - * technically, this is only ever sent locally, but pays to be safe ;p - */ - if (IS_LOCAL(user)) + if (channel->GetPrefixValue(user) < VOICE_VALUE && channel->IsBanned(user)) { - if (channel->GetPrefixValue(user) < VOICE_VALUE && channel->IsBanned(user)) - { - /* banned, boned. drop the message. */ - user->WriteServ("NOTICE "+user->nick+" :*** You may not cycle, as you are banned on channel " + channel->name); - return CMD_FAILURE; - } - - channel->PartUser(user, reason); - - Channel::JoinUser(user, parameters[0].c_str(), true, "", false, ServerInstance->Time()); + // User is banned, send an error and don't cycle them + user->WriteNotice("*** You may not cycle, as you are banned on channel " + channel->name); + return CMD_FAILURE; } + channel->PartUser(user, reason); + Channel::JoinUser(user, parameters[0], true); + return CMD_SUCCESS; } else { - user->WriteNumeric(442, "%s %s :You're not on that channel", user->nick.c_str(), channel->name.c_str()); + user->WriteNumeric(ERR_NOTONCHANNEL, "%s :You're not on that channel", channel->name.c_str()); } return CMD_FAILURE; @@ -84,26 +75,17 @@ class CommandCycle : public Command class ModuleCycle : public Module { CommandCycle cmd; + public: ModuleCycle() : cmd(this) { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleCycle() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides command CYCLE, acts as a server-side HOP command to part and rejoin a channel.", VF_VENDOR); } - }; MODULE_INIT(ModuleCycle) diff --git a/src/modules/m_dccallow.cpp b/src/modules/m_dccallow.cpp index 829c1d337..f011fa449 100644 --- a/src/modules/m_dccallow.cpp +++ b/src/modules/m_dccallow.cpp @@ -25,8 +25,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the /DCCALLOW command */ - class BannedFileList { public: @@ -53,12 +51,16 @@ typedef std::vector<DCCAllow> dccallowlist; dccallowlist* dl; typedef std::vector<BannedFileList> bannedfilelist; bannedfilelist bfl; -SimpleExtItem<dccallowlist>* ext; +typedef SimpleExtItem<dccallowlist> DCCAllowExt; class CommandDccallow : public Command { + DCCAllowExt& ext; + public: - CommandDccallow(Module* parent) : Command(parent, "DCCALLOW", 0) + CommandDccallow(Module* parent, DCCAllowExt& Ext) + : Command(parent, "DCCALLOW", 0) + , ext(Ext) { syntax = "[(+|-)<nick> [<time>]]|[LIST|HELP]"; /* XXX we need to fix this so it can work with translation stuff (i.e. move +- into a seperate param */ @@ -94,12 +96,12 @@ class CommandDccallow : public Command } else { - user->WriteNumeric(998, "%s :DCCALLOW command not understood. For help on DCCALLOW, type /DCCALLOW HELP", user->nick.c_str()); + user->WriteNumeric(998, ":DCCALLOW command not understood. For help on DCCALLOW, type /DCCALLOW HELP"); return CMD_FAILURE; } } - std::string nick = parameters[0].substr(1); + std::string nick(parameters[0], 1); User *target = ServerInstance->FindNickOnly(nick); if ((target) && (!IS_SERVER(target)) && (!target->quitting) && (target->registered == REG_ALL)) @@ -108,7 +110,7 @@ class CommandDccallow : public Command if (action == '-') { // check if it contains any entries - dl = ext->get(user); + dl = ext.get(user); if (dl) { for (dccallowlist::iterator i = dl->begin(); i != dl->end(); ++i) @@ -117,7 +119,7 @@ class CommandDccallow : public Command if (i->nickname == target->nick) { dl->erase(i); - user->WriteNumeric(995, "%s %s :Removed %s from your DCCALLOW list", user->nick.c_str(), user->nick.c_str(), target->nick.c_str()); + user->WriteNumeric(995, "%s :Removed %s from your DCCALLOW list", user->nick.c_str(), target->nick.c_str()); break; } } @@ -127,15 +129,15 @@ class CommandDccallow : public Command { if (target == user) { - user->WriteNumeric(996, "%s %s :You cannot add yourself to your own DCCALLOW list!", user->nick.c_str(), user->nick.c_str()); + user->WriteNumeric(996, "%s :You cannot add yourself to your own DCCALLOW list!", user->nick.c_str()); return CMD_FAILURE; } - dl = ext->get(user); + dl = ext.get(user); if (!dl) { dl = new dccallowlist; - ext->set(user, dl); + ext.set(user, dl); // add this user to the userlist ul.push_back(user); } @@ -144,7 +146,7 @@ class CommandDccallow : public Command { if (k->nickname == target->nick) { - user->WriteNumeric(996, "%s %s :%s is already on your DCCALLOW list", user->nick.c_str(), user->nick.c_str(), target->nick.c_str()); + user->WriteNumeric(996, "%s :%s is already on your DCCALLOW list", user->nick.c_str(), target->nick.c_str()); return CMD_FAILURE; } } @@ -152,10 +154,10 @@ class CommandDccallow : public Command std::string mask = target->nick+"!"+target->ident+"@"+target->dhost; std::string default_length = ServerInstance->Config->ConfValue("dccallow")->getString("length"); - long length; + unsigned long length; if (parameters.size() < 2) { - length = ServerInstance->Duration(default_length); + length = InspIRCd::Duration(default_length); } else if (!atoi(parameters[1].c_str())) { @@ -163,10 +165,10 @@ class CommandDccallow : public Command } else { - length = ServerInstance->Duration(parameters[1]); + length = InspIRCd::Duration(parameters[1]); } - if (!ServerInstance->IsValidMask(mask)) + if (!InspIRCd::IsValidMask(mask)) { return CMD_FAILURE; } @@ -175,11 +177,11 @@ class CommandDccallow : public Command if (length > 0) { - user->WriteNumeric(993, "%s %s :Added %s to DCCALLOW list for %ld seconds", user->nick.c_str(), user->nick.c_str(), target->nick.c_str(), length); + user->WriteNumeric(993, "%s :Added %s to DCCALLOW list for %ld seconds", user->nick.c_str(), target->nick.c_str(), length); } else { - user->WriteNumeric(994, "%s %s :Added %s to DCCALLOW list for this session", user->nick.c_str(), user->nick.c_str(), target->nick.c_str()); + user->WriteNumeric(994, "%s :Added %s to DCCALLOW list for this session", user->nick.c_str(), target->nick.c_str()); } /* route it. */ @@ -189,7 +191,7 @@ class CommandDccallow : public Command else { // nick doesn't exist - user->WriteNumeric(401, "%s %s :No such nick/channel", user->nick.c_str(), nick.c_str()); + user->WriteNumeric(401, "%s :No such nick/channel", nick.c_str()); return CMD_FAILURE; } } @@ -203,26 +205,26 @@ class CommandDccallow : public Command void DisplayHelp(User* user) { - user->WriteNumeric(998, "%s :DCCALLOW [(+|-)<nick> [<time>]]|[LIST|HELP]", user->nick.c_str()); - user->WriteNumeric(998, "%s :You may allow DCCs from specific users by specifying a", user->nick.c_str()); - user->WriteNumeric(998, "%s :DCC allow for the user you want to receive DCCs from.", user->nick.c_str()); - user->WriteNumeric(998, "%s :For example, to allow the user Brain to send you inspircd.exe", user->nick.c_str()); - user->WriteNumeric(998, "%s :you would type:", user->nick.c_str()); - user->WriteNumeric(998, "%s :/DCCALLOW +Brain", user->nick.c_str()); - user->WriteNumeric(998, "%s :Brain would then be able to send you files. They would have to", user->nick.c_str()); - user->WriteNumeric(998, "%s :resend the file again if the server gave them an error message", user->nick.c_str()); - user->WriteNumeric(998, "%s :before you added them to your DCCALLOW list.", user->nick.c_str()); - user->WriteNumeric(998, "%s :DCCALLOW entries will be temporary by default, if you want to add", user->nick.c_str()); - user->WriteNumeric(998, "%s :them to your DCCALLOW list until you leave IRC, type:", user->nick.c_str()); - user->WriteNumeric(998, "%s :/DCCALLOW +Brain 0", user->nick.c_str()); - user->WriteNumeric(998, "%s :To remove the user from your DCCALLOW list, type:", user->nick.c_str()); - user->WriteNumeric(998, "%s :/DCCALLOW -Brain", user->nick.c_str()); - user->WriteNumeric(998, "%s :To see the users in your DCCALLOW list, type:", user->nick.c_str()); - user->WriteNumeric(998, "%s :/DCCALLOW LIST", user->nick.c_str()); - user->WriteNumeric(998, "%s :NOTE: If the user leaves IRC or changes their nickname", user->nick.c_str()); - user->WriteNumeric(998, "%s : they will be removed from your DCCALLOW list.", user->nick.c_str()); - user->WriteNumeric(998, "%s : your DCCALLOW list will be deleted when you leave IRC.", user->nick.c_str()); - user->WriteNumeric(999, "%s :End of DCCALLOW HELP", user->nick.c_str()); + user->WriteNumeric(998, ":DCCALLOW [(+|-)<nick> [<time>]]|[LIST|HELP]"); + user->WriteNumeric(998, ":You may allow DCCs from specific users by specifying a"); + user->WriteNumeric(998, ":DCC allow for the user you want to receive DCCs from."); + user->WriteNumeric(998, ":For example, to allow the user Brain to send you inspircd.exe"); + user->WriteNumeric(998, ":you would type:"); + user->WriteNumeric(998, ":/DCCALLOW +Brain"); + user->WriteNumeric(998, ":Brain would then be able to send you files. They would have to"); + user->WriteNumeric(998, ":resend the file again if the server gave them an error message"); + user->WriteNumeric(998, ":before you added them to your DCCALLOW list."); + user->WriteNumeric(998, ":DCCALLOW entries will be temporary by default, if you want to add"); + user->WriteNumeric(998, ":them to your DCCALLOW list until you leave IRC, type:"); + user->WriteNumeric(998, ":/DCCALLOW +Brain 0"); + user->WriteNumeric(998, ":To remove the user from your DCCALLOW list, type:"); + user->WriteNumeric(998, ":/DCCALLOW -Brain"); + user->WriteNumeric(998, ":To see the users in your DCCALLOW list, type:"); + user->WriteNumeric(998, ":/DCCALLOW LIST"); + user->WriteNumeric(998, ":NOTE: If the user leaves IRC or changes their nickname"); + user->WriteNumeric(998, ": they will be removed from your DCCALLOW list."); + user->WriteNumeric(998, ": your DCCALLOW list will be deleted when you leave IRC."); + user->WriteNumeric(999, ":End of DCCALLOW HELP"); LocalUser* localuser = IS_LOCAL(user); if (localuser) @@ -232,76 +234,53 @@ class CommandDccallow : public Command void DisplayDCCAllowList(User* user) { // display current DCCALLOW list - user->WriteNumeric(990, "%s :Users on your DCCALLOW list:", user->nick.c_str()); + user->WriteNumeric(990, ":Users on your DCCALLOW list:"); - dl = ext->get(user); + dl = ext.get(user); if (dl) { for (dccallowlist::const_iterator c = dl->begin(); c != dl->end(); ++c) { - user->WriteNumeric(991, "%s %s :%s (%s)", user->nick.c_str(), user->nick.c_str(), c->nickname.c_str(), c->hostmask.c_str()); + user->WriteNumeric(991, "%s :%s (%s)", user->nick.c_str(), c->nickname.c_str(), c->hostmask.c_str()); } } - user->WriteNumeric(992, "%s :End of DCCALLOW list", user->nick.c_str()); + user->WriteNumeric(992, ":End of DCCALLOW list"); } }; class ModuleDCCAllow : public Module { + DCCAllowExt ext; CommandDccallow cmd; - public: + public: ModuleDCCAllow() - : cmd(this) - { - ext = NULL; - } - - void init() - { - ext = new SimpleExtItem<dccallowlist>("dccallow", this); - ServerInstance->Modules->AddService(*ext); - ServerInstance->Modules->AddService(cmd); - ReadFileConf(); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_OnUserQuit, I_OnUserPostNick, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void OnRehash(User* user) + : ext("dccallow", ExtensionItem::EXT_USER, this) + , cmd(this, ext) { - ReadFileConf(); } - virtual void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) + void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) CXX11_OVERRIDE { - dccallowlist* udl = ext->get(user); + dccallowlist* udl = ext.get(user); // remove their DCCALLOW list if they have one if (udl) - { - userlist::iterator it = std::find(ul.begin(), ul.end(), user); - if (it != ul.end()) - ul.erase(it); - } + stdalgo::erase(ul, user); // remove them from any DCCALLOW lists // they are currently on RemoveNick(user); } - virtual void OnUserPostNick(User* user, const std::string &oldnick) + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE { RemoveNick(user); } - virtual ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreNotice(user, dest, target_type, text, status, exempt_list); - } - - virtual ModResult OnUserPreNotice(User* user, void* dest, int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; @@ -323,7 +302,7 @@ class ModuleDCCAllow : public Module if (strncmp(text.c_str(), "\1DCC ", 5) == 0) { - dl = ext->get(u); + dl = ext.get(u); if (dl && dl->size()) { for (dccallowlist::const_iterator iter = dl->begin(); iter != dl->end(); ++iter) @@ -375,16 +354,16 @@ class ModuleDCCAllow : public Module if ((!found) && (defaultaction == "allow")) return MOD_RES_PASSTHRU; - user->WriteServ("NOTICE %s :The user %s is not accepting DCC SENDs from you. Your file %s was not sent.", user->nick.c_str(), u->nick.c_str(), filename.c_str()); - u->WriteServ("NOTICE %s :%s (%s@%s) attempted to send you a file named %s, which was blocked.", u->nick.c_str(), user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), filename.c_str()); - u->WriteServ("NOTICE %s :If you trust %s and were expecting this, you can type /DCCALLOW HELP for information on the DCCALLOW system.", u->nick.c_str(), user->nick.c_str()); + user->WriteNotice("The user " + u->nick + " is not accepting DCC SENDs from you. Your file " + filename + " was not sent."); + u->WriteNotice(user->nick + " (" + user->ident + "@" + user->dhost + ") attempted to send you a file named " + filename + ", which was blocked."); + u->WriteNotice("If you trust " + user->nick + " and were expecting this, you can type /DCCALLOW HELP for information on the DCCALLOW system."); return MOD_RES_DENY; } else if ((type == "CHAT") && (blockchat)) { - user->WriteServ("NOTICE %s :The user %s is not accepting DCC CHAT requests from you.", user->nick.c_str(), u->nick.c_str()); - u->WriteServ("NOTICE %s :%s (%s@%s) attempted to initiate a DCC CHAT session, which was blocked.", u->nick.c_str(), user->nick.c_str(), user->ident.c_str(), user->dhost.c_str()); - u->WriteServ("NOTICE %s :If you trust %s and were expecting this, you can type /DCCALLOW HELP for information on the DCCALLOW system.", u->nick.c_str(), user->nick.c_str()); + user->WriteNotice("The user " + u->nick + " is not accepting DCC CHAT requests from you."); + u->WriteNotice(user->nick + " (" + user->ident + "@" + user->dhost + ") attempted to initiate a DCC CHAT session, which was blocked."); + u->WriteNotice("If you trust " + user->nick + " and were expecting this, you can type /DCCALLOW HELP for information on the DCCALLOW system."); return MOD_RES_DENY; } } @@ -398,7 +377,7 @@ class ModuleDCCAllow : public Module for (userlist::iterator iter = ul.begin(); iter != ul.end();) { User* u = (User*)(*iter); - dl = ext->get(u); + dl = ext.get(u); if (dl) { if (dl->size()) @@ -408,7 +387,7 @@ class ModuleDCCAllow : public Module { if (iter2->length != 0 && (iter2->set_on + iter2->length) <= ServerInstance->Time()) { - u->WriteNumeric(997, "%s %s :DCCALLOW entry for %s has expired", u->nick.c_str(), u->nick.c_str(), iter2->nickname.c_str()); + u->WriteNumeric(997, "%s :DCCALLOW entry for %s has expired", u->nick.c_str(), iter2->nickname.c_str()); iter2 = dl->erase(iter2); } else @@ -432,7 +411,7 @@ class ModuleDCCAllow : public Module for (userlist::iterator iter = ul.begin(); iter != ul.end();) { User *u = (User*)(*iter); - dl = ext->get(u); + dl = ext.get(u); if (dl) { if (dl->size()) @@ -442,8 +421,8 @@ class ModuleDCCAllow : public Module if (i->nickname == user->nick) { - u->WriteServ("NOTICE %s :%s left the network or changed their nickname and has been removed from your DCCALLOW list", u->nick.c_str(), i->nickname.c_str()); - u->WriteNumeric(995, "%s %s :Removed %s from your DCCALLOW list", u->nick.c_str(), u->nick.c_str(), i->nickname.c_str()); + u->WriteNotice(i->nickname + " left the network or changed their nickname and has been removed from your DCCALLOW list"); + u->WriteNumeric(995, "%s :Removed %s from your DCCALLOW list", u->nick.c_str(), i->nickname.c_str()); dl->erase(i); break; } @@ -472,7 +451,7 @@ class ModuleDCCAllow : public Module } } - void ReadFileConf() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { bfl.clear(); ConfigTagList tags = ServerInstance->Config->ConfTags("banfile"); @@ -485,12 +464,7 @@ class ModuleDCCAllow : public Module } } - virtual ~ModuleDCCAllow() - { - delete ext; - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the /DCCALLOW command", VF_COMMON | VF_VENDOR); } diff --git a/src/modules/m_deaf.cpp b/src/modules/m_deaf.cpp index 43b24cfae..fd9b322c0 100644 --- a/src/modules/m_deaf.cpp +++ b/src/modules/m_deaf.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides usermode +d to block channel messages and channel notices */ - /** User mode +d - filter out channel messages and channel notices */ class User_d : public ModeHandler @@ -32,31 +30,20 @@ class User_d : public ModeHandler ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) { + if (adding == dest->IsModeSet(this)) + return MODEACTION_DENY; + if (adding) - { - if (!dest->IsModeSet('d')) - { - dest->WriteServ("NOTICE %s :*** You have enabled usermode +d, deaf mode. This mode means you WILL NOT receive any messages from any channels you are in. If you did NOT mean to do this, use /mode %s -d.", dest->nick.c_str(), dest->nick.c_str()); - dest->SetMode('d',true); - return MODEACTION_ALLOW; - } - } - else - { - if (dest->IsModeSet('d')) - { - dest->SetMode('d',false); - return MODEACTION_ALLOW; - } - } - return MODEACTION_DENY; + dest->WriteNotice("*** You have enabled usermode +d, deaf mode. This mode means you WILL NOT receive any messages from any channels you are in. If you did NOT mean to do this, use /mode " + dest->nick + " -d."); + + dest->SetMode(this, adding); + return MODEACTION_ALLOW; } }; class ModuleDeaf : public Module { User_d m1; - std::string deaf_bypasschars; std::string deaf_bypasschars_uline; @@ -66,84 +53,40 @@ class ModuleDeaf : public Module { } - void init() - { - ServerInstance->Modules->AddService(m1); - - OnRehash(NULL); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("deaf"); deaf_bypasschars = tag->getString("bypasschars"); deaf_bypasschars_uline = tag->getString("bypasscharsuline"); } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - if (target_type == TYPE_CHANNEL) - { - Channel* chan = (Channel*)dest; - if (chan) - this->BuildDeafList(MSG_NOTICE, chan, user, status, text, exempt_list); - } - - return MOD_RES_PASSTHRU; - } - - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { - if (target_type == TYPE_CHANNEL) - { - Channel* chan = (Channel*)dest; - if (chan) - this->BuildDeafList(MSG_PRIVMSG, chan, user, status, text, exempt_list); - } + if (target_type != TYPE_CHANNEL) + return MOD_RES_PASSTHRU; - return MOD_RES_PASSTHRU; - } - - virtual void BuildDeafList(MessageType message_type, Channel* chan, User* sender, char status, const std::string &text, CUList &exempt_list) - { - const UserMembList *ulist = chan->GetUsers(); - bool is_a_uline; - bool is_bypasschar, is_bypasschar_avail; - bool is_bypasschar_uline, is_bypasschar_uline_avail; - - is_bypasschar = is_bypasschar_avail = is_bypasschar_uline = is_bypasschar_uline_avail = 0; - if (!deaf_bypasschars.empty()) - { - is_bypasschar_avail = 1; - if (deaf_bypasschars.find(text[0], 0) != std::string::npos) - is_bypasschar = 1; - } - if (!deaf_bypasschars_uline.empty()) - { - is_bypasschar_uline_avail = 1; - if (deaf_bypasschars_uline.find(text[0], 0) != std::string::npos) - is_bypasschar_uline = 1; - } + Channel* chan = static_cast<Channel*>(dest); + bool is_bypasschar = (deaf_bypasschars.find(text[0]) != std::string::npos); + bool is_bypasschar_uline = (deaf_bypasschars_uline.find(text[0]) != std::string::npos); /* * If we have no bypasschars_uline in config, and this is a bypasschar (regular) * Than it is obviously going to get through +d, no build required */ - if (!is_bypasschar_uline_avail && is_bypasschar) - return; + if (!deaf_bypasschars_uline.empty() && is_bypasschar) + return MOD_RES_PASSTHRU; - for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++) + const Channel::MemberMap& ulist = chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i) { /* not +d ? */ - if (!i->first->IsModeSet('d')) + if (!i->first->IsModeSet(m1)) continue; /* deliver message */ /* matched both U-line only and regular bypasses */ if (is_bypasschar && is_bypasschar_uline) continue; /* deliver message */ - is_a_uline = ServerInstance->ULine(i->first->server); + bool is_a_uline = i->first->server->IsULine(); /* matched a U-line only bypass */ if (is_bypasschar_uline && is_a_uline) continue; /* deliver message */ @@ -151,23 +94,20 @@ class ModuleDeaf : public Module if (is_bypasschar && !is_a_uline) continue; /* deliver message */ - if (status && !strchr(chan->GetAllPrefixChars(i->first), status)) + if (status && !strchr(i->second->GetAllPrefixChars(), status)) continue; /* don't deliver message! */ exempt_list.insert(i->first); } - } - virtual ~ModuleDeaf() - { + return MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides usermode +d to block channel messages and channel notices", VF_VENDOR); } - }; MODULE_INIT(ModuleDeaf) diff --git a/src/modules/m_delayjoin.cpp b/src/modules/m_delayjoin.cpp index 20d4c8e8f..e864a8289 100644 --- a/src/modules/m_delayjoin.cpp +++ b/src/modules/m_delayjoin.cpp @@ -20,14 +20,10 @@ */ -/* $ModDesc: Allows for delay-join channels (+D) where users don't appear to join until they speak */ - #include "inspircd.h" -#include <stdarg.h> class DelayJoinMode : public ModeHandler { - private: CUList empty; public: DelayJoinMode(Module* Parent) : ModeHandler(Parent, "delayjoin", 'D', PARAM_NONE, MODETYPE_CHANNEL) @@ -43,33 +39,27 @@ class ModuleDelayJoin : public Module DelayJoinMode djm; public: LocalIntExt unjoined; - ModuleDelayJoin() : djm(this), unjoined("delayjoin", this) + ModuleDelayJoin() + : djm(this) + , unjoined("delayjoin", ExtensionItem::EXT_MEMBERSHIP, this) { } - void init() - { - ServerInstance->Modules->AddService(djm); - ServerInstance->Modules->AddService(unjoined); - Implementation eventlist[] = { I_OnUserJoin, I_OnUserPart, I_OnUserKick, I_OnBuildNeighborList, I_OnNamesListItem, I_OnText, I_OnRawMode }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - ~ModuleDelayJoin(); - Version GetVersion(); - void OnNamesListItem(User* issuer, Membership*, std::string &prefixes, std::string &nick); - void OnUserJoin(Membership*, bool, bool, CUList&); + Version GetVersion() CXX11_OVERRIDE; + ModResult OnNamesListItem(User* issuer, Membership*, std::string& prefixes, std::string& nick) CXX11_OVERRIDE; + void OnUserJoin(Membership*, bool, bool, CUList&) CXX11_OVERRIDE; void CleanUser(User* user); - void OnUserPart(Membership*, std::string &partmessage, CUList&); - void OnUserKick(User* source, Membership*, const std::string &reason, CUList&); - void OnBuildNeighborList(User* source, UserChanList &include, std::map<User*,bool> &exception); - void OnText(User* user, void* dest, int target_type, const std::string &text, char status, CUList &exempt_list); - ModResult OnRawMode(User* user, Channel* channel, const char mode, const std::string ¶m, bool adding, int pcnt); + void OnUserPart(Membership*, std::string &partmessage, CUList&) CXX11_OVERRIDE; + void OnUserKick(User* source, Membership*, const std::string &reason, CUList&) CXX11_OVERRIDE; + void OnBuildNeighborList(User* source, IncludeChanList& include, std::map<User*, bool>& exception) CXX11_OVERRIDE; + void OnText(User* user, void* dest, int target_type, const std::string &text, char status, CUList &exempt_list) CXX11_OVERRIDE; + ModResult OnRawMode(User* user, Channel* channel, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE; }; ModeAction DelayJoinMode::OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) { /* no change */ - if (channel->IsModeSet('D') == adding) + if (channel->IsModeSet(this) == adding) return MODEACTION_DENY; if (!adding) @@ -78,38 +68,36 @@ ModeAction DelayJoinMode::OnModeChange(User* source, User* dest, Channel* channe * Make all users visible, as +D is being removed. If we don't do this, * they remain permanently invisible on this channel! */ - const UserMembList* names = channel->GetUsers(); - for (UserMembCIter n = names->begin(); n != names->end(); ++n) + const Channel::MemberMap& users = channel->GetUsers(); + for (Channel::MemberMap::const_iterator n = users.begin(); n != users.end(); ++n) creator->OnText(n->first, channel, TYPE_CHANNEL, "", 0, empty); } - channel->SetMode('D', adding); + channel->SetMode(this, adding); return MODEACTION_ALLOW; } -ModuleDelayJoin::~ModuleDelayJoin() -{ -} - Version ModuleDelayJoin::GetVersion() { return Version("Allows for delay-join channels (+D) where users don't appear to join until they speak", VF_VENDOR); } -void ModuleDelayJoin::OnNamesListItem(User* issuer, Membership* memb, std::string &prefixes, std::string &nick) +ModResult ModuleDelayJoin::OnNamesListItem(User* issuer, Membership* memb, std::string& prefixes, std::string& nick) { /* don't prevent the user from seeing themself */ if (issuer == memb->user) - return; + return MOD_RES_PASSTHRU; /* If the user is hidden by delayed join, hide them from the NAMES list */ if (unjoined.get(memb)) - nick.clear(); + return MOD_RES_DENY; + + return MOD_RES_PASSTHRU; } static void populate(CUList& except, Membership* memb) { - const UserMembList* users = memb->chan->GetUsers(); - for(UserMembCIter i = users->begin(); i != users->end(); i++) + const Channel::MemberMap& users = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) { if (i->first == memb->user || !IS_LOCAL(i->first)) continue; @@ -119,7 +107,7 @@ static void populate(CUList& except, Membership* memb) void ModuleDelayJoin::OnUserJoin(Membership* memb, bool sync, bool created, CUList& except) { - if (memb->chan->IsModeSet('D')) + if (memb->chan->IsModeSet(djm)) { unjoined.set(memb, 1); populate(except, memb); @@ -138,24 +126,20 @@ void ModuleDelayJoin::OnUserKick(User* source, Membership* memb, const std::stri populate(except, memb); } -void ModuleDelayJoin::OnBuildNeighborList(User* source, UserChanList &include, std::map<User*,bool> &exception) +void ModuleDelayJoin::OnBuildNeighborList(User* source, IncludeChanList& include, std::map<User*, bool>& exception) { - UCListIter i = include.begin(); - while (i != include.end()) + for (IncludeChanList::iterator i = include.begin(); i != include.end(); ) { - Channel* c = *i++; - Membership* memb = c->GetUser(source); - if (memb && unjoined.get(memb)) - include.erase(c); + Membership* memb = *i; + if (unjoined.get(memb)) + i = include.erase(i); + else + ++i; } } void ModuleDelayJoin::OnText(User* user, void* dest, int target_type, const std::string &text, char status, CUList &exempt_list) { - /* Server origin */ - if (!user) - return; - if (target_type != TYPE_CHANNEL) return; @@ -177,14 +161,13 @@ void ModuleDelayJoin::OnText(User* user, void* dest, int target_type, const std: } /* make the user visible if he receives any mode change */ -ModResult ModuleDelayJoin::OnRawMode(User* user, Channel* channel, const char mode, const std::string ¶m, bool adding, int pcnt) +ModResult ModuleDelayJoin::OnRawMode(User* user, Channel* channel, ModeHandler* mh, const std::string& param, bool adding) { - if (!user || !channel || param.empty()) + if (!channel || param.empty()) return MOD_RES_PASSTHRU; - ModeHandler* mh = ServerInstance->Modes->FindMode(mode, MODETYPE_CHANNEL); // If not a prefix mode then we got nothing to do here - if (!mh || !mh->GetPrefixRank()) + if (!mh->IsPrefixMode()) return MOD_RES_PASSTHRU; User* dest; diff --git a/src/modules/m_delaymsg.cpp b/src/modules/m_delaymsg.cpp index 978ab55d2..f64297e15 100644 --- a/src/modules/m_delaymsg.cpp +++ b/src/modules/m_delaymsg.cpp @@ -19,14 +19,13 @@ #include "inspircd.h" -/* $ModDesc: Provides channelmode +d <int>, to deny messages to a channel until <int> seconds. */ - -class DelayMsgMode : public ModeHandler +class DelayMsgMode : public ParamMode<DelayMsgMode, LocalIntExt> { public: LocalIntExt jointime; - DelayMsgMode(Module* Parent) : ModeHandler(Parent, "delaymsg", 'd', PARAM_SETONLY, MODETYPE_CHANNEL) - , jointime("delaymsg", Parent) + DelayMsgMode(Module* Parent) + : ParamMode<DelayMsgMode, LocalIntExt>(Parent, "delaymsg", 'd') + , jointime("delaymsg", ExtensionItem::EXT_MEMBERSHIP, Parent) { levelrequired = OP_VALUE; } @@ -36,65 +35,51 @@ class DelayMsgMode : public ModeHandler return (atoi(their_param.c_str()) < atoi(our_param.c_str())); } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding); + ModeAction OnSet(User* source, Channel* chan, std::string& parameter); + void OnUnset(User* source, Channel* chan); + + void SerializeParam(Channel* chan, int n, std::string& out) + { + out += ConvToStr(n); + } }; class ModuleDelayMsg : public Module { - private: DelayMsgMode djm; + bool allownotice; public: ModuleDelayMsg() : djm(this) { } - void init() - { - ServerInstance->Modules->AddService(djm); - ServerInstance->Modules->AddService(djm.jointime); - Implementation eventlist[] = { I_OnUserJoin, I_OnUserPreMessage, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - Version GetVersion(); - void OnUserJoin(Membership* memb, bool sync, bool created, CUList&); - ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string &text, char status, CUList &exempt_list); - ModResult OnUserPreNotice(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list); - void OnRehash(User* user); + Version GetVersion() CXX11_OVERRIDE; + void OnUserJoin(Membership* memb, bool sync, bool created, CUList&) CXX11_OVERRIDE; + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE; + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE; }; -ModeAction DelayMsgMode::OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) +ModeAction DelayMsgMode::OnSet(User* source, Channel* chan, std::string& parameter) { - if (adding) - { - if ((channel->IsModeSet('d')) && (channel->GetModeParameter('d') == parameter)) - return MODEACTION_DENY; - - /* Setting a new limit, sanity check */ - long limit = atoi(parameter.c_str()); - - /* Wrap low values at 32768 */ - if (limit < 0) - limit = 0x7FFF; + // Setting a new limit, sanity check + unsigned int limit = ConvToInt(parameter); + if (limit == 0) + limit = 1; - parameter = ConvToStr(limit); - } - else - { - if (!channel->IsModeSet('d')) - return MODEACTION_DENY; - - /* - * Clean up metadata - */ - const UserMembList* names = channel->GetUsers(); - for (UserMembCIter n = names->begin(); n != names->end(); ++n) - jointime.set(n->second, 0); - } - channel->SetModeParam('d', adding ? parameter : ""); + ext.set(chan, limit); return MODEACTION_ALLOW; } +void DelayMsgMode::OnUnset(User* source, Channel* chan) +{ + /* + * Clean up metadata + */ + const Channel::MemberMap& users = chan->GetUsers(); + for (Channel::MemberMap::const_iterator n = users.begin(); n != users.end(); ++n) + jointime.set(n->second, 0); +} + Version ModuleDelayMsg::GetVersion() { return Version("Provides channelmode +d <int>, to deny messages to a channel until <int> seconds.", VF_VENDOR); @@ -102,19 +87,18 @@ Version ModuleDelayMsg::GetVersion() void ModuleDelayMsg::OnUserJoin(Membership* memb, bool sync, bool created, CUList&) { - if ((IS_LOCAL(memb->user)) && (memb->chan->IsModeSet('d'))) + if ((IS_LOCAL(memb->user)) && (memb->chan->IsModeSet(djm))) { djm.jointime.set(memb, ServerInstance->Time()); } } -ModResult ModuleDelayMsg::OnUserPreMessage(User* user, void* dest, int target_type, std::string &text, char status, CUList &exempt_list) +ModResult ModuleDelayMsg::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) { - /* Server origin */ - if ((!user) || (!IS_LOCAL(user))) + if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; - if (target_type != TYPE_CHANNEL) + if ((target_type != TYPE_CHANNEL) || ((!allownotice) && (msgtype == MSG_NOTICE))) return MOD_RES_PASSTHRU; Channel* channel = (Channel*) dest; @@ -128,14 +112,14 @@ ModResult ModuleDelayMsg::OnUserPreMessage(User* user, void* dest, int target_ty if (ts == 0) return MOD_RES_PASSTHRU; - std::string len = channel->GetModeParameter('d'); + int len = djm.ext.get(channel); - if (ts + atoi(len.c_str()) > ServerInstance->Time()) + if ((ts + len) > ServerInstance->Time()) { if (channel->GetPrefixValue(user) < VOICE_VALUE) { - user->WriteNumeric(404, "%s %s :You must wait %s seconds after joining to send to channel (+d)", - user->nick.c_str(), channel->name.c_str(), len.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :You must wait %d seconds after joining to send to channel (+d)", + channel->name.c_str(), len); return MOD_RES_DENY; } } @@ -147,19 +131,10 @@ ModResult ModuleDelayMsg::OnUserPreMessage(User* user, void* dest, int target_ty return MOD_RES_PASSTHRU; } -ModResult ModuleDelayMsg::OnUserPreNotice(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list) -{ - return OnUserPreMessage(user, dest, target_type, text, status, exempt_list); -} - -void ModuleDelayMsg::OnRehash(User* user) +void ModuleDelayMsg::ReadConfig(ConfigStatus& status) { ConfigTag* tag = ServerInstance->Config->ConfValue("delaymsg"); - if (tag->getBool("allownotice", true)) - ServerInstance->Modules->Detach(I_OnUserPreNotice, this); - else - ServerInstance->Modules->Attach(I_OnUserPreNotice, this); + allownotice = tag->getBool("allownotice", true); } MODULE_INIT(ModuleDelayMsg) - diff --git a/src/modules/m_denychans.cpp b/src/modules/m_denychans.cpp index 39d9e0d34..6378ba273 100644 --- a/src/modules/m_denychans.cpp +++ b/src/modules/m_denychans.cpp @@ -22,18 +22,17 @@ #include "inspircd.h" -/* $ModDesc: Implements config tags which allow blocking of joins to channels */ - class ModuleDenyChannels : public Module { + ChanModeReference redirectmode; + public: - void init() + ModuleDenyChannels() + : redirectmode(this, "redirect") { - Implementation eventlist[] = { I_OnUserPreJoin, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { /* check for redirect validity and loops/chains */ ConfigTagList tags = ServerInstance->Config->ConfTags("badchan"); @@ -45,10 +44,10 @@ class ModuleDenyChannels : public Module if (!redirect.empty()) { - if (!ServerInstance->IsChannel(redirect.c_str(), ServerInstance->Config->Limits.ChanMax)) + if (!ServerInstance->IsChannel(redirect)) { - if (user) - user->WriteServ("NOTICE %s :Invalid badchan redirect '%s'", user->nick.c_str(), redirect.c_str()); + if (status.srcuser) + status.srcuser->WriteNotice("Invalid badchan redirect '" + redirect + "'"); throw ModuleException("Invalid badchan redirect, not a channel"); } @@ -67,8 +66,8 @@ class ModuleDenyChannels : public Module if (!goodchan) { /* <badchan:redirect> is a badchan */ - if (user) - user->WriteServ("NOTICE %s :Badchan %s redirects to badchan %s", user->nick.c_str(), name.c_str(), redirect.c_str()); + if (status.srcuser) + status.srcuser->WriteNotice("Badchan " + name + " redirects to badchan " + redirect); throw ModuleException("Badchan redirect loop"); } } @@ -77,24 +76,20 @@ class ModuleDenyChannels : public Module } } - virtual ~ModuleDenyChannels() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements config tags which allow blocking of joins to channels", VF_VENDOR); } - virtual ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { ConfigTagList tags = ServerInstance->Config->ConfTags("badchan"); for (ConfigIter j = tags.first; j != tags.second; ++j) { if (InspIRCd::Match(cname, j->second->getString("name"))) { - if (IS_OPER(user) && j->second->getBool("allowopers")) + if (user->IsOper() && j->second->getBool("allowopers")) { return MOD_RES_PASSTHRU; } @@ -112,19 +107,19 @@ class ModuleDenyChannels : public Module } } - if (ServerInstance->IsChannel(redirect.c_str(), ServerInstance->Config->Limits.ChanMax)) + if (ServerInstance->IsChannel(redirect)) { /* simple way to avoid potential loops: don't redirect to +L channels */ Channel *newchan = ServerInstance->FindChan(redirect); - if ((!newchan) || (!(newchan->IsModeSet('L')))) + if ((!newchan) || (!newchan->IsModeSet(redirectmode))) { - user->WriteNumeric(926, "%s %s :Channel %s is forbidden, redirecting to %s: %s",user->nick.c_str(),cname,cname,redirect.c_str(), reason.c_str()); - Channel::JoinUser(user,redirect.c_str(),false,"",false,ServerInstance->Time()); + user->WriteNumeric(926, "%s :Channel %s is forbidden, redirecting to %s: %s", cname.c_str(),cname.c_str(),redirect.c_str(), reason.c_str()); + Channel::JoinUser(user, redirect); return MOD_RES_DENY; } } - user->WriteNumeric(926, "%s %s :Channel %s is forbidden: %s",user->nick.c_str(),cname,cname,reason.c_str()); + user->WriteNumeric(926, "%s :Channel %s is forbidden: %s", cname.c_str(),cname.c_str(),reason.c_str()); return MOD_RES_DENY; } } diff --git a/src/modules/m_devoice.cpp b/src/modules/m_devoice.cpp index 2b5de2bd6..4e4b3a354 100644 --- a/src/modules/m_devoice.cpp +++ b/src/modules/m_devoice.cpp @@ -24,8 +24,6 @@ * Syntax: /DEVOICE <#chan> */ -/* $ModDesc: Provides voiced users with the ability to devoice themselves. */ - #include "inspircd.h" /** Handle /DEVOICE @@ -36,24 +34,17 @@ class CommandDevoice : public Command CommandDevoice(Module* Creator) : Command(Creator,"DEVOICE", 1) { syntax = "<channel>"; - TRANSLATE2(TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { - Channel* c = ServerInstance->FindChan(parameters[0]); - if (c && c->HasUser(user)) - { - std::vector<std::string> modes; - modes.push_back(parameters[0]); - modes.push_back("-v"); - modes.push_back(user->nick); - - ServerInstance->SendGlobalMode(modes, ServerInstance->FakeClient); - return CMD_SUCCESS; - } + std::vector<std::string> modes; + modes.push_back(parameters[0]); + modes.push_back("-v"); + modes.push_back(user->nick); - return CMD_FAILURE; + ServerInstance->Parser.CallHandler("MODE", modes, ServerInstance->FakeClient); + return CMD_SUCCESS; } }; @@ -65,16 +56,7 @@ class ModuleDeVoice : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleDeVoice() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides voiced users with the ability to devoice themselves.", VF_VENDOR); } diff --git a/src/modules/m_dnsbl.cpp b/src/modules/m_dnsbl.cpp index d4101686a..5eaa8c279 100644 --- a/src/modules/m_dnsbl.cpp +++ b/src/modules/m_dnsbl.cpp @@ -23,8 +23,7 @@ #include "inspircd.h" #include "xline.h" - -/* $ModDesc: Provides handling of DNS blacklists */ +#include "modules/dns.h" /* Class holding data for a single entry */ class DNSBLConfEntry : public refcountbase @@ -40,13 +39,12 @@ class DNSBLConfEntry : public refcountbase unsigned char records[256]; unsigned long stats_hits, stats_misses; DNSBLConfEntry(): type(A_BITMASK),duration(86400),bitmask(0),stats_hits(0), stats_misses(0) {} - ~DNSBLConfEntry() { } }; /** Resolver for CGI:IRC hostnames encoded in ident/GECOS */ -class DNSBLResolver : public Resolver +class DNSBLResolver : public DNS::Request { std::string theiruid; LocalStringExt& nameExt; @@ -55,170 +53,167 @@ class DNSBLResolver : public Resolver public: - DNSBLResolver(Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf, bool &cached) - : Resolver(hostname, DNS_QUERY_A, cached, me), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf) + DNSBLResolver(DNS::Manager *mgr, Module *me, LocalStringExt& match, LocalIntExt& ctr, const std::string &hostname, LocalUser* u, reference<DNSBLConfEntry> conf) + : DNS::Request(mgr, me, hostname, DNS::QUERY_A, true), theiruid(u->uuid), nameExt(match), countExt(ctr), ConfEntry(conf) { } /* Note: This may be called multiple times for multiple A record results */ - virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) + void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE { /* Check the user still exists */ LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid); - if (them) + if (!them) + return; + + const DNS::ResourceRecord &ans_record = r->answers[0]; + + int i = countExt.get(them); + if (i) + countExt.set(them, i - 1); + + // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d + + unsigned int bitmask = 0, record = 0; + bool match = false; + in_addr resultip; + + inet_aton(ans_record.rdata.c_str(), &resultip); + + switch (ConfEntry->type) + { + case DNSBLConfEntry::A_BITMASK: + bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */ + bitmask &= ConfEntry->bitmask; + match = (bitmask != 0); + break; + case DNSBLConfEntry::A_RECORD: + record = resultip.s_addr >> 24; /* Last octet */ + match = (ConfEntry->records[record] == 1); + break; + } + + if (match) { - int i = countExt.get(them); - if (i) - countExt.set(them, i - 1); - // Now we calculate the bitmask: 256*(256*(256*a+b)+c)+d - if(result.length()) + std::string reason = ConfEntry->reason; + std::string::size_type x = reason.find("%ip%"); + while (x != std::string::npos) { - unsigned int bitmask = 0, record = 0; - bool match = false; - in_addr resultip; + reason.erase(x, 4); + reason.insert(x, them->GetIPString()); + x = reason.find("%ip%"); + } - inet_aton(result.c_str(), &resultip); + ConfEntry->stats_hits++; - switch (ConfEntry->type) + switch (ConfEntry->banaction) + { + case DNSBLConfEntry::I_KILL: { - case DNSBLConfEntry::A_BITMASK: - bitmask = resultip.s_addr >> 24; /* Last octet (network byte order) */ - bitmask &= ConfEntry->bitmask; - match = (bitmask != 0); - break; - case DNSBLConfEntry::A_RECORD: - record = resultip.s_addr >> 24; /* Last octet */ - match = (ConfEntry->records[record] == 1); + ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")"); break; } - - if (match) + case DNSBLConfEntry::I_MARK: { - std::string reason = ConfEntry->reason; - std::string::size_type x = reason.find("%ip%"); - while (x != std::string::npos) + if (!ConfEntry->ident.empty()) { - reason.erase(x, 4); - reason.insert(x, them->GetIPString()); - x = reason.find("%ip%"); + them->WriteNumeric(304, ":Your ident has been set to " + ConfEntry->ident + " because you matched " + reason); + them->ChangeIdent(ConfEntry->ident); } - ConfEntry->stats_hits++; - - switch (ConfEntry->banaction) + if (!ConfEntry->host.empty()) { - case DNSBLConfEntry::I_KILL: - { - ServerInstance->Users->QuitUser(them, "Killed (" + reason + ")"); - break; - } - case DNSBLConfEntry::I_MARK: - { - if (!ConfEntry->ident.empty()) - { - them->WriteServ("304 " + them->nick + " :Your ident has been set to " + ConfEntry->ident + " because you matched " + reason); - them->ChangeIdent(ConfEntry->ident.c_str()); - } - - if (!ConfEntry->host.empty()) - { - them->WriteServ("304 " + them->nick + " :Your host has been set to " + ConfEntry->host + " because you matched " + reason); - them->ChangeDisplayedHost(ConfEntry->host.c_str()); - } - - nameExt.set(them, ConfEntry->name); - break; - } - case DNSBLConfEntry::I_KLINE: - { - KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), - "*", them->GetIPString()); - if (ServerInstance->XLines->AddLine(kl,NULL)) - { - std::string timestr = ServerInstance->TimeString(kl->expiry); - ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s", - them->GetIPString(), timestr.c_str(), reason.c_str()); - ServerInstance->XLines->ApplyLines(); - } - else - { - delete kl; - return; - } - break; - } - case DNSBLConfEntry::I_GLINE: - { - GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), - "*", them->GetIPString()); - if (ServerInstance->XLines->AddLine(gl,NULL)) - { - std::string timestr = ServerInstance->TimeString(gl->expiry); - ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s", - them->GetIPString(), timestr.c_str(), reason.c_str()); - ServerInstance->XLines->ApplyLines(); - } - else - { - delete gl; - return; - } - break; - } - case DNSBLConfEntry::I_ZLINE: - { - ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), - them->GetIPString()); - if (ServerInstance->XLines->AddLine(zl,NULL)) - { - std::string timestr = ServerInstance->TimeString(zl->expiry); - ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s", - them->GetIPString(), timestr.c_str(), reason.c_str()); - ServerInstance->XLines->ApplyLines(); - } - else - { - delete zl; - return; - } - break; - } - case DNSBLConfEntry::I_UNKNOWN: - { - break; - } - break; + them->WriteNumeric(304, ":Your host has been set to " + ConfEntry->host + " because you matched " + reason); + them->ChangeDisplayedHost(ConfEntry->host); } - ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s%s detected as being on a DNS blacklist (%s) with result %d", them->nick.empty() ? "<unknown>" : "", them->GetFullRealHost().c_str(), ConfEntry->domain.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record); + nameExt.set(them, ConfEntry->name); + break; + } + case DNSBLConfEntry::I_KLINE: + { + KLine* kl = new KLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), + "*", them->GetIPString()); + if (ServerInstance->XLines->AddLine(kl,NULL)) + { + std::string timestr = InspIRCd::TimeString(kl->expiry); + ServerInstance->SNO->WriteGlobalSno('x',"K:line added due to DNSBL match on *@%s to expire on %s: %s", + them->GetIPString().c_str(), timestr.c_str(), reason.c_str()); + ServerInstance->XLines->ApplyLines(); + } + else + { + delete kl; + return; + } + break; + } + case DNSBLConfEntry::I_GLINE: + { + GLine* gl = new GLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), + "*", them->GetIPString()); + if (ServerInstance->XLines->AddLine(gl,NULL)) + { + std::string timestr = InspIRCd::TimeString(gl->expiry); + ServerInstance->SNO->WriteGlobalSno('x',"G:line added due to DNSBL match on *@%s to expire on %s: %s", + them->GetIPString().c_str(), timestr.c_str(), reason.c_str()); + ServerInstance->XLines->ApplyLines(); + } + else + { + delete gl; + return; + } + break; + } + case DNSBLConfEntry::I_ZLINE: + { + ZLine* zl = new ZLine(ServerInstance->Time(), ConfEntry->duration, ServerInstance->Config->ServerName.c_str(), reason.c_str(), + them->GetIPString()); + if (ServerInstance->XLines->AddLine(zl,NULL)) + { + std::string timestr = InspIRCd::TimeString(zl->expiry); + ServerInstance->SNO->WriteGlobalSno('x',"Z:line added due to DNSBL match on *@%s to expire on %s: %s", + them->GetIPString().c_str(), timestr.c_str(), reason.c_str()); + ServerInstance->XLines->ApplyLines(); + } + else + { + delete zl; + return; + } + break; } - else - ConfEntry->stats_misses++; + case DNSBLConfEntry::I_UNKNOWN: + default: + break; } - else - ConfEntry->stats_misses++; + + ServerInstance->SNO->WriteGlobalSno('a', "Connecting user %s%s detected as being on a DNS blacklist (%s) with result %d", them->nick.empty() ? "<unknown>" : "", them->GetFullRealHost().c_str(), ConfEntry->domain.c_str(), (ConfEntry->type==DNSBLConfEntry::A_BITMASK) ? bitmask : record); } + else + ConfEntry->stats_misses++; } - virtual void OnError(ResolverError e, const std::string &errormessage) + void OnError(const DNS::Query *q) CXX11_OVERRIDE { LocalUser* them = (LocalUser*)ServerInstance->FindUUID(theiruid); - if (them) - { - int i = countExt.get(them); - if (i) - countExt.set(them, i - 1); - } - } + if (!them) + return; - virtual ~DNSBLResolver() - { + int i = countExt.get(them); + if (i) + countExt.set(them, i - 1); + + if (q->error == DNS::ERROR_NO_RECORDS || q->error == DNS::ERROR_DOMAIN_NOT_FOUND) + ConfEntry->stats_misses++; } }; class ModuleDNSBL : public Module { std::vector<reference<DNSBLConfEntry> > DNSBLConfEntries; + dynamic_reference<DNS::Manager> DNS; LocalStringExt nameExt; LocalIntExt countExt; @@ -241,25 +236,21 @@ class ModuleDNSBL : public Module return DNSBLConfEntry::I_UNKNOWN; } public: - ModuleDNSBL() : nameExt("dnsbl_match", this), countExt("dnsbl_pending", this) { } - - void init() + ModuleDNSBL() + : DNS(this, "DNS") + , nameExt("dnsbl_match", ExtensionItem::EXT_USER, this) + , countExt("dnsbl_pending", ExtensionItem::EXT_USER, this) { - ReadConf(); - ServerInstance->Modules->AddService(nameExt); - ServerInstance->Modules->AddService(countExt); - Implementation eventlist[] = { I_OnRehash, I_OnSetUserIP, I_OnStats, I_OnSetConnectClass, I_OnCheckReady }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides handling of DNS blacklists", VF_VENDOR); } /** Fill our conf vector with data */ - void ReadConf() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { DNSBLConfEntries.clear(); @@ -291,7 +282,7 @@ class ModuleDNSBL : public Module } e->banaction = str2banaction(tag->getString("action")); - e->duration = ServerInstance->Duration(tag->getString("duration", "60")); + e->duration = tag->getDuration("duration", 60, 1); /* Use portparser for record replies */ @@ -316,11 +307,6 @@ class ModuleDNSBL : public Module std::string location = tag->getTagLocation(); ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid banaction", location.c_str()); } - else if (e->duration <= 0) - { - std::string location = tag->getTagLocation(); - ServerInstance->SNO->WriteGlobalSno('a', "DNSBL(%s): Invalid duration", location.c_str()); - } else { if (e->reason.empty()) @@ -336,14 +322,9 @@ class ModuleDNSBL : public Module } } - void OnRehash(User* user) + void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE { - ReadConf(); - } - - void OnSetUserIP(LocalUser* user) - { - if ((user->exempt) || (user->client_sa.sa.sa_family != AF_INET)) + if ((user->exempt) || !DNS) return; if (user->MyClass) @@ -352,40 +333,61 @@ class ModuleDNSBL : public Module return; } else - ServerInstance->Logs->Log("m_dnsbl", DEBUG, "User has no connect class in OnSetUserIP"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User has no connect class in OnSetUserIP"); - unsigned char a, b, c, d; - char reversedipbuf[128]; std::string reversedip; + if (user->client_sa.sa.sa_family == AF_INET) + { + unsigned int a, b, c, d; + d = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF; + c = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF; + b = (unsigned int) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF; + a = (unsigned int) user->client_sa.in4.sin_addr.s_addr & 0xFF; - d = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 24) & 0xFF; - c = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 16) & 0xFF; - b = (unsigned char) (user->client_sa.in4.sin_addr.s_addr >> 8) & 0xFF; - a = (unsigned char) user->client_sa.in4.sin_addr.s_addr & 0xFF; + reversedip = ConvToStr(d) + "." + ConvToStr(c) + "." + ConvToStr(b) + "." + ConvToStr(a); + } + else if (user->client_sa.sa.sa_family == AF_INET6) + { + const unsigned char* ip = user->client_sa.in6.sin6_addr.s6_addr; - snprintf(reversedipbuf, 128, "%d.%d.%d.%d", d, c, b, a); - reversedip = std::string(reversedipbuf); + std::string buf = BinToHex(ip, 16); + for (std::string::const_reverse_iterator it = buf.rbegin(); it != buf.rend(); ++it) + { + reversedip.push_back(*it); + reversedip.push_back('.'); + } + } + else + return; + + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Reversed IP %s -> %s", user->GetIPString().c_str(), reversedip.c_str()); countExt.set(user, DNSBLConfEntries.size()); // For each DNSBL, we will run through this lookup - unsigned int i = 0; - while (i < DNSBLConfEntries.size()) + for (unsigned i = 0; i < DNSBLConfEntries.size(); ++i) { // Fill hostname with a dnsbl style host (d.c.b.a.domain.tld) std::string hostname = reversedip + "." + DNSBLConfEntries[i]->domain; /* now we'd need to fire off lookups for `hostname'. */ - bool cached; - DNSBLResolver *r = new DNSBLResolver(this, nameExt, countExt, hostname, user, DNSBLConfEntries[i], cached); - ServerInstance->AddResolver(r, cached); + DNSBLResolver *r = new DNSBLResolver(*this->DNS, this, nameExt, countExt, hostname, user, DNSBLConfEntries[i]); + try + { + this->DNS->Process(r); + } + catch (DNS::Exception &ex) + { + delete r; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason()); + } + if (user->quitting) break; - i++; } } - ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) + ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE { std::string dnsbl; if (!myclass->config->readString("dnsbl", dnsbl)) @@ -396,15 +398,15 @@ class ModuleDNSBL : public Module return MOD_RES_PASSTHRU; return MOD_RES_DENY; } - - ModResult OnCheckReady(LocalUser *user) + + ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE { if (countExt.get(user)) return MOD_RES_DENY; return MOD_RES_PASSTHRU; } - ModResult OnStats(char symbol, User* user, string_list &results) + ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE { if (symbol != 'd') return MOD_RES_PASSTHRU; @@ -416,12 +418,12 @@ class ModuleDNSBL : public Module total_hits += (*i)->stats_hits; total_misses += (*i)->stats_misses; - results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " + + results.push_back("304 " + user->nick + " :DNSBLSTATS DNSbl \"" + (*i)->name + "\" had " + ConvToStr((*i)->stats_hits) + " hits and " + ConvToStr((*i)->stats_misses) + " misses"); } - results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits)); - results.push_back(ServerInstance->Config->ServerName + " 304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses)); + results.push_back("304 " + user->nick + " :DNSBLSTATS Total hits: " + ConvToStr(total_hits)); + results.push_back("304 " + user->nick + " :DNSBLSTATS Total misses: " + ConvToStr(total_misses)); return MOD_RES_PASSTHRU; } diff --git a/src/modules/m_exemptchanops.cpp b/src/modules/m_exemptchanops.cpp index 8d6d65af2..076445644 100644 --- a/src/modules/m_exemptchanops.cpp +++ b/src/modules/m_exemptchanops.cpp @@ -18,9 +18,7 @@ #include "inspircd.h" -#include "u_listmode.h" - -/* $ModDesc: Provides the ability to allow channel operators to be exempt from certain modes. */ +#include "listmode.h" /** Handles channel mode +X */ @@ -31,30 +29,42 @@ class ExemptChanOps : public ListModeBase bool ValidateParam(User* user, Channel* chan, std::string &word) { - // TODO actually make sure there's a prop for this - if ((word.length() > 35) || (word.empty())) + std::string::size_type p = word.find(':'); + if (p == std::string::npos) + { + user->WriteNumeric(955, "%s %s :Invalid exemptchanops entry, format is <restriction>:<prefix>", chan->name.c_str(), word.c_str()); + return false; + } + + std::string restriction(word, 0, p); + // If there is a '-' in the restriction string ignore it and everything after it + // to support "auditorium-vis" and "auditorium-see" in m_auditorium + p = restriction.find('-'); + if (p != std::string::npos) + restriction.erase(p); + + if (!ServerInstance->Modes->FindMode(restriction, MODETYPE_CHANNEL)) { - user->WriteNumeric(955, "%s %s %s :word is too %s for exemptchanops list",user->nick.c_str(), chan->name.c_str(), word.c_str(), (word.empty() ? "short" : "long")); + user->WriteNumeric(955, "%s %s :Unknown restriction", chan->name.c_str(), restriction.c_str()); return false; } return true; } - bool TellListTooLong(User* user, Channel* chan, std::string &word) + void TellListTooLong(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(959, "%s %s %s :Channel exemptchanops list is full", user->nick.c_str(), chan->name.c_str(), word.c_str()); - return true; + user->WriteNumeric(959, "%s %s :Channel exemptchanops list is full", chan->name.c_str(), word.c_str()); } void TellAlreadyOnList(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(957, "%s %s :The word %s is already on the exemptchanops list",user->nick.c_str(), chan->name.c_str(), word.c_str()); + user->WriteNumeric(957, "%s :The word %s is already on the exemptchanops list", chan->name.c_str(), word.c_str()); } void TellNotSet(User* user, Channel* chan, std::string &word) { - user->WriteNumeric(958, "%s %s :No such exemptchanops word is set",user->nick.c_str(), chan->name.c_str()); + user->WriteNumeric(958, "%s :No such exemptchanops word is set", chan->name.c_str()); } }; @@ -63,18 +73,14 @@ class ExemptHandler : public HandlerBase3<ModResult, User*, Channel*, const std: public: ExemptChanOps ec; ExemptHandler(Module* me) : ec(me) {} - - ModeHandler* FindMode(const std::string& mid) + + PrefixMode* FindMode(const std::string& mid) { if (mid.length() == 1) - return ServerInstance->Modes->FindMode(mid[0], MODETYPE_CHANNEL); - for(char c='A'; c <= 'z'; c++) - { - ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL); - if (mh && mh->name == mid) - return mh; - } - return NULL; + return ServerInstance->Modes->FindPrefixMode(mid[0]); + + ModeHandler* mh = ServerInstance->Modes->FindMode(mid, MODETYPE_CHANNEL); + return mh ? mh->IsPrefixMode() : NULL; } ModResult Call(User* user, Channel* chan, const std::string& restriction) @@ -82,21 +88,21 @@ class ExemptHandler : public HandlerBase3<ModResult, User*, Channel*, const std: unsigned int mypfx = chan->GetPrefixValue(user); std::string minmode; - modelist* list = ec.extItem.get(chan); + ListModeBase::ModeList* list = ec.GetList(chan); if (list) { - for (modelist::iterator i = list->begin(); i != list->end(); ++i) + for (ListModeBase::ModeList::iterator i = list->begin(); i != list->end(); ++i) { std::string::size_type pos = (*i).mask.find(':'); if (pos == std::string::npos) continue; - if ((*i).mask.substr(0,pos) == restriction) - minmode = (*i).mask.substr(pos + 1); + if (!i->mask.compare(0, pos, restriction)) + minmode.assign(i->mask, pos + 1, std::string::npos); } } - ModeHandler* mh = FindMode(minmode); + PrefixMode* mh = FindMode(minmode); if (mh && mypfx >= mh->GetPrefixRank()) return MOD_RES_ALLOW; if (mh || minmode == "*") @@ -108,23 +114,16 @@ class ExemptHandler : public HandlerBase3<ModResult, User*, Channel*, const std: class ModuleExemptChanOps : public Module { - std::string defaults; ExemptHandler eh; public: - ModuleExemptChanOps() : eh(this) { } - void init() + void init() CXX11_OVERRIDE { - ServerInstance->Modules->AddService(eh.ec); - Implementation eventlist[] = { I_OnRehash, I_OnSyncChannel }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); ServerInstance->OnCheckExemption = &eh; - - OnRehash(NULL); } ~ModuleExemptChanOps() @@ -132,20 +131,15 @@ class ModuleExemptChanOps : public Module ServerInstance->OnCheckExemption = &ServerInstance->HandleOnCheckExemption; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the ability to allow channel operators to be exempt from certain modes.",VF_VENDOR); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { eh.ec.DoRehash(); } - - void OnSyncChannel(Channel* chan, Module* proto, void* opaque) - { - eh.ec.DoSyncChannel(chan, proto, opaque); - } }; MODULE_INIT(ModuleExemptChanOps) diff --git a/src/modules/m_filter.cpp b/src/modules/m_filter.cpp index 4090f5600..34d0bebb3 100644 --- a/src/modules/m_filter.cpp +++ b/src/modules/m_filter.cpp @@ -22,11 +22,7 @@ #include "inspircd.h" #include "xline.h" -#include "m_regex.h" - -/* $ModDesc: Text (spam) filtering */ - -class ModuleFilter; +#include "modules/regex.h" enum FilterFlags { @@ -48,6 +44,7 @@ enum FilterAction class FilterResult { public: + Regex* regex; std::string freeform; std::string reason; FilterAction action; @@ -60,9 +57,12 @@ class FilterResult bool flag_notice; bool flag_strip_color; - FilterResult(const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla) : - freeform(free), reason(rea), action(act), gline_time(gt) + FilterResult(dynamic_reference<RegexFactory>& RegexEngine, const std::string& free, const std::string& rea, FilterAction act, long gt, const std::string& fla) + : freeform(free), reason(rea), action(act), gline_time(gt) { + if (!RegexEngine) + throw ModuleException("Regex module implementing '"+RegexEngine.GetProvider()+"' is not loaded!"); + regex = RegexEngine->Create(free); this->FillFlags(fla); } @@ -154,17 +154,10 @@ class CommandFilter : public Command } }; -class ImplFilter : public FilterResult -{ - public: - Regex* regex; - - ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs); -}; - - class ModuleFilter : public Module { + typedef insp::flat_set<std::string, irc::insensitive_swo> ExemptTargetSet; + bool initing; RegexFactory* factory; void FreeFilters(); @@ -173,28 +166,30 @@ class ModuleFilter : public Module CommandFilter filtcommand; dynamic_reference<RegexFactory> RegexEngine; - std::vector<ImplFilter> filters; + std::vector<FilterResult> filters; int flags; - std::set<std::string> exemptfromfilter; // List of channel names excluded from filtering. + // List of channel names excluded from filtering. + ExemptTargetSet exemptedchans; + + // List of target nicknames excluded from filtering. + ExemptTargetSet exemptednicks; ModuleFilter(); - void init(); CullResult cull(); - ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list); + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE; FilterResult* FilterMatch(User* user, const std::string &text, int flags); bool DeleteFilter(const std::string &freeform); std::pair<bool, std::string> AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flags); - ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list); - void OnRehash(User* user); - Version GetVersion(); + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE; + Version GetVersion() CXX11_OVERRIDE; std::string EncodeFilter(FilterResult* filter); FilterResult DecodeFilter(const std::string &data); - void OnSyncNetwork(Module* proto, void* opaque); - void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata); - ModResult OnStats(char symbol, User* user, string_list &results); - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line); - void OnUnloadModule(Module* mod); + void OnSyncNetwork(ProtocolInterface::Server& server) CXX11_OVERRIDE; + void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) CXX11_OVERRIDE; + ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE; + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE; + void OnUnloadModule(Module* mod) CXX11_OVERRIDE; bool AppliesToMe(User* user, FilterResult* filter, int flags); void ReadFilters(); static bool StringToFilterAction(const std::string& str, FilterAction& fa); @@ -209,13 +204,13 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User Module *me = creator; if (static_cast<ModuleFilter *>(me)->DeleteFilter(parameters[0])) { - user->WriteServ("NOTICE %s :*** Removed filter '%s'", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** Removed filter '" + parameters[0] + "'"); ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" removed filter '"+parameters[0]+"'"); return CMD_SUCCESS; } else { - user->WriteServ("NOTICE %s :*** Filter '%s' not found in list, try /stats s.", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** Filter '" + parameters[0] + "' not found in list, try /stats s."); return CMD_FAILURE; } } @@ -232,7 +227,7 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User if (!ModuleFilter::StringToFilterAction(parameters[1], type)) { - user->WriteServ("NOTICE %s :*** Invalid filter type '%s'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'.", user->nick.c_str(), parameters[1].c_str()); + user->WriteNotice("*** Invalid filter type '" + parameters[1] + "'. Supported types are 'gline', 'none', 'block', 'silent' and 'kill'."); return CMD_FAILURE; } @@ -240,12 +235,12 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User { if (parameters.size() >= 5) { - duration = ServerInstance->Duration(parameters[3]); + duration = InspIRCd::Duration(parameters[3]); reasonindex = 4; } else { - user->WriteServ("NOTICE %s :*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter.", user->nick.c_str()); + user->WriteNotice("*** Not enough parameters: When setting a gline type filter, a gline duration must be specified as the third parameter."); return CMD_FAILURE; } } @@ -258,9 +253,9 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User std::pair<bool, std::string> result = static_cast<ModuleFilter *>(me)->AddFilter(freeform, type, parameters[reasonindex], duration, flags); if (result.first) { - user->WriteServ("NOTICE %s :*** Added filter '%s', type '%s'%s%s, flags '%s', reason: '%s'", user->nick.c_str(), freeform.c_str(), - parameters[1].c_str(), (duration ? ", duration " : ""), (duration ? parameters[3].c_str() : ""), - flags.c_str(), parameters[reasonindex].c_str()); + user->WriteNotice("*** Added filter '" + freeform + "', type '" + parameters[1] + "'" + + (duration ? ", duration " + parameters[3] : "") + ", flags '" + flags + "', reason: '" + + parameters[reasonindex] + "'"); ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'a' : 'A', "FILTER: "+user->nick+" added filter '"+freeform+"', type '"+parameters[1]+"', "+(duration ? "duration "+parameters[3]+", " : "")+"flags '"+flags+"', reason: "+parameters[reasonindex]); @@ -268,13 +263,13 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User } else { - user->WriteServ("NOTICE %s :*** Filter '%s' could not be added: %s", user->nick.c_str(), freeform.c_str(), result.second.c_str()); + user->WriteNotice("*** Filter '" + freeform + "' could not be added: " + result.second); return CMD_FAILURE; } } else { - user->WriteServ("NOTICE %s :*** Not enough parameters.", user->nick.c_str()); + user->WriteNotice("*** Not enough parameters."); return CMD_FAILURE; } @@ -283,7 +278,7 @@ CmdResult CommandFilter::Handle(const std::vector<std::string> ¶meters, User bool ModuleFilter::AppliesToMe(User* user, FilterResult* filter, int iflags) { - if ((filter->flag_no_opers) && IS_OPER(user)) + if ((filter->flag_no_opers) && user->IsOper()) return false; if ((iflags & FLAG_PRIVMSG) && (!filter->flag_privmsg)) return false; @@ -301,14 +296,6 @@ ModuleFilter::ModuleFilter() { } -void ModuleFilter::init() -{ - ServerInstance->Modules->AddService(filtcommand); - Implementation eventlist[] = { I_OnPreCommand, I_OnStats, I_OnSyncNetwork, I_OnDecodeMetaData, I_OnUserPreMessage, I_OnUserPreNotice, I_OnRehash, I_OnUnloadModule }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); -} - CullResult ModuleFilter::cull() { FreeFilters(); @@ -317,29 +304,19 @@ CullResult ModuleFilter::cull() void ModuleFilter::FreeFilters() { - for (std::vector<ImplFilter>::const_iterator i = filters.begin(); i != filters.end(); ++i) + for (std::vector<FilterResult>::const_iterator i = filters.begin(); i != filters.end(); ++i) delete i->regex; filters.clear(); } -ModResult ModuleFilter::OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) +ModResult ModuleFilter::OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) { + // Leave remote users and servers alone if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; - flags = FLAG_PRIVMSG; - return OnUserPreNotice(user,dest,target_type,text,status,exempt_list); -} - -ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) -{ - /* Leave ulines alone */ - if ((ServerInstance->ULine(user->server)) || (!IS_LOCAL(user))) - return MOD_RES_PASSTHRU; - - if (!flags) - flags = FLAG_NOTICE; + flags = (msgtype == MSG_PRIVMSG) ? FLAG_PRIVMSG : FLAG_NOTICE; FilterResult* f = this->FilterMatch(user, text, flags); if (f) @@ -348,12 +325,16 @@ ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, s if (target_type == TYPE_USER) { User* t = (User*)dest; + // Check if the target nick is exempted, if yes, ignore this message + if (exemptednicks.count(t->nick)) + return MOD_RES_PASSTHRU; + target = t->nick; } else if (target_type == TYPE_CHANNEL) { Channel* t = (Channel*)dest; - if (exemptfromfilter.find(t->name) != exemptfromfilter.end()) + if (exemptedchans.count(t->name)) return MOD_RES_PASSTHRU; target = t->name; @@ -362,16 +343,16 @@ ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, s { ServerInstance->SNO->WriteGlobalSno('a', "FILTER: "+user->nick+" had their message filtered, target was "+target+": "+f->reason); if (target_type == TYPE_CHANNEL) - user->WriteNumeric(404, "%s %s :Message to channel blocked and opers notified (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Message to channel blocked and opers notified (%s)", target.c_str(), f->reason.c_str()); else - user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked and opers notified: "+f->reason); + user->WriteNotice("Your message to "+target+" was blocked and opers notified: "+f->reason); } else if (f->action == FA_SILENT) { if (target_type == TYPE_CHANNEL) - user->WriteNumeric(404, "%s %s :Message to channel blocked (%s)",user->nick.c_str(), target.c_str(), f->reason.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Message to channel blocked (%s)", target.c_str(), f->reason.c_str()); else - user->WriteServ("NOTICE "+user->nick+" :Your message to "+target+" was blocked: "+f->reason); + user->WriteNotice("Your message to "+target+" was blocked: "+f->reason); } else if (f->action == FA_KILL) { @@ -388,7 +369,7 @@ ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, s delete gl; } - ServerInstance->Logs->Log("FILTER",DEFAULT,"FILTER: "+ user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action)); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, user->nick + " had their message filtered, target was " + target + ": " + f->reason + " Action: " + ModuleFilter::FilterActionToString(f->action)); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; @@ -396,7 +377,7 @@ ModResult ModuleFilter::OnUserPreNotice(User* user,void* dest,int target_type, s ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) { - if (validated && IS_LOCAL(user)) + if (validated) { flags = 0; bool parting; @@ -416,7 +397,7 @@ ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::stri if (parameters.size() < 2) return MOD_RES_PASSTHRU; - if (exemptfromfilter.find(parameters[0]) != exemptfromfilter.end()) + if (exemptedchans.count(parameters[0])) return MOD_RES_PASSTHRU; parting = true; @@ -446,7 +427,7 @@ ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::stri /* Are they parting, if so, kill is applicable */ if ((parting) && (f->action == FA_KILL)) { - user->WriteServ("NOTICE %s :*** Your PART message was filtered: %s", user->nick.c_str(), f->reason.c_str()); + user->WriteNotice("*** Your PART message was filtered: " + f->reason); ServerInstance->Users->QuitUser(user, "Filtered: " + f->reason); } if (f->action == FA_GLINE) @@ -466,15 +447,25 @@ ModResult ModuleFilter::OnPreCommand(std::string &command, std::vector<std::stri return MOD_RES_PASSTHRU; } -void ModuleFilter::OnRehash(User* user) +void ModuleFilter::ReadConfig(ConfigStatus& status) { ConfigTagList tags = ServerInstance->Config->ConfTags("exemptfromfilter"); - exemptfromfilter.clear(); + exemptedchans.clear(); + exemptednicks.clear(); + for (ConfigIter i = tags.first; i != tags.second; ++i) { - std::string chan = i->second->getString("channel"); - if (!chan.empty()) - exemptfromfilter.insert(chan); + ConfigTag* tag = i->second; + + // If "target" is not found, try the old "channel" key to keep compatibility with 2.0 configs + const std::string target = tag->getString("target", tag->getString("channel")); + if (!target.empty()) + { + if (target[0] == '#') + exemptedchans.insert(target); + else + exemptednicks.insert(target); + } } std::string newrxengine = ServerInstance->Config->ConfValue("filteropts")->getString("engine"); @@ -554,11 +545,11 @@ FilterResult ModuleFilter::DecodeFilter(const std::string &data) return res; } -void ModuleFilter::OnSyncNetwork(Module* proto, void* opaque) +void ModuleFilter::OnSyncNetwork(ProtocolInterface::Server& server) { - for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); ++i) + for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i) { - proto->ProtoSendMetaData(opaque, NULL, "filter", EncodeFilter(&(*i))); + server.SendMetaData("filter", EncodeFilter(&(*i))); } } @@ -573,27 +564,19 @@ void ModuleFilter::OnDecodeMetaData(Extensible* target, const std::string &extna } catch (ModuleException& e) { - ServerInstance->Logs->Log("m_filter", DEBUG, "Error when unserializing filter: " + std::string(e.GetReason())); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Error when unserializing filter: " + e.GetReason()); } } } -ImplFilter::ImplFilter(ModuleFilter* mymodule, const std::string &rea, FilterAction act, long glinetime, const std::string &pat, const std::string &flgs) - : FilterResult(pat, rea, act, glinetime, flgs) -{ - if (!mymodule->RegexEngine) - throw ModuleException("Regex module implementing '"+mymodule->RegexEngine.GetProvider()+"' is not loaded!"); - regex = mymodule->RegexEngine->Create(pat); -} - FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int flgs) { static std::string stripped_text; stripped_text.clear(); - for (std::vector<ImplFilter>::iterator index = filters.begin(); index != filters.end(); index++) + for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); ++i) { - FilterResult* filter = dynamic_cast<FilterResult*>(&(*index)); + FilterResult* filter = &*i; /* Skip ones that dont apply to us */ if (!AppliesToMe(user, filter, flgs)) @@ -605,20 +588,15 @@ FilterResult* ModuleFilter::FilterMatch(User* user, const std::string &text, int InspIRCd::StripColor(stripped_text); } - //ServerInstance->Logs->Log("m_filter", DEBUG, "Match '%s' against '%s'", text.c_str(), index->freeform.c_str()); - if (index->regex->Matches(filter->flag_strip_color ? stripped_text : text)) - { - //ServerInstance->Logs->Log("m_filter", DEBUG, "MATCH"); - return &*index; - } - //ServerInstance->Logs->Log("m_filter", DEBUG, "NO MATCH"); + if (filter->regex->Matches(filter->flag_strip_color ? stripped_text : text)) + return filter; } return NULL; } bool ModuleFilter::DeleteFilter(const std::string &freeform) { - for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++) + for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++) { if (i->freeform == freeform) { @@ -632,7 +610,7 @@ bool ModuleFilter::DeleteFilter(const std::string &freeform) std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform, FilterAction type, const std::string &reason, long duration, const std::string &flgs) { - for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++) + for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++) { if (i->freeform == freeform) { @@ -642,11 +620,11 @@ std::pair<bool, std::string> ModuleFilter::AddFilter(const std::string &freeform try { - filters.push_back(ImplFilter(this, reason, type, duration, freeform, flgs)); + filters.push_back(FilterResult(RegexEngine, freeform, reason, type, duration, flgs)); } catch (ModuleException &e) { - ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", freeform.c_str(), e.GetReason().c_str()); return std::make_pair(false, e.GetReason()); } return std::make_pair(true, ""); @@ -695,7 +673,7 @@ void ModuleFilter::ReadFilters() std::string reason = i->second->getString("reason"); std::string action = i->second->getString("action"); std::string flgs = i->second->getString("flags"); - long gline_time = ServerInstance->Duration(i->second->getString("duration")); + unsigned long gline_time = i->second->getDuration("duration", 10*60, 1); if (flgs.empty()) flgs = "*"; @@ -705,12 +683,12 @@ void ModuleFilter::ReadFilters() try { - filters.push_back(ImplFilter(this, reason, fa, gline_time, pattern, flgs)); - ServerInstance->Logs->Log("m_filter", DEFAULT, "Regular expression %s loaded.", pattern.c_str()); + filters.push_back(FilterResult(RegexEngine, pattern, reason, fa, gline_time, flgs)); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Regular expression %s loaded.", pattern.c_str()); } catch (ModuleException &e) { - ServerInstance->Logs->Log("m_filter", DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error in regular expression '%s': %s", pattern.c_str(), e.GetReason().c_str()); } } } @@ -719,13 +697,17 @@ ModResult ModuleFilter::OnStats(char symbol, User* user, string_list &results) { if (symbol == 's') { - for (std::vector<ImplFilter>::iterator i = filters.begin(); i != filters.end(); i++) + for (std::vector<FilterResult>::iterator i = filters.begin(); i != filters.end(); i++) + { + results.push_back("223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason); + } + for (ExemptTargetSet::const_iterator i = exemptedchans.begin(); i != exemptedchans.end(); ++i) { - results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :"+RegexEngine.GetProvider()+":"+i->freeform+" "+i->GetFlags()+" "+FilterActionToString(i->action)+" "+ConvToStr(i->gline_time)+" :"+i->reason); + results.push_back("223 "+user->nick+" :EXEMPT "+(*i)); } - for (std::set<std::string>::iterator i = exemptfromfilter.begin(); i != exemptfromfilter.end(); ++i) + for (ExemptTargetSet::const_iterator i = exemptednicks.begin(); i != exemptednicks.end(); ++i) { - results.push_back(ServerInstance->Config->ServerName+" 223 "+user->nick+" :EXEMPT "+(*i)); + results.push_back("223 "+user->nick+" :EXEMPT "+(*i)); } } return MOD_RES_PASSTHRU; diff --git a/src/modules/m_flashpolicyd.cpp b/src/modules/m_flashpolicyd.cpp new file mode 100644 index 000000000..8f847e111 --- /dev/null +++ b/src/modules/m_flashpolicyd.cpp @@ -0,0 +1,165 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class FlashPDSocket; + +namespace +{ + insp::intrusive_list<FlashPDSocket> sockets; + std::string policy_reply; + const std::string expected_request("<policy-file-request/>\0", 23); +} + +class FlashPDSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<FlashPDSocket> +{ + /** True if this object is in the cull list + */ + bool waitingcull; + + bool Tick(time_t currtime) CXX11_OVERRIDE + { + AddToCull(); + return false; + } + + public: + FlashPDSocket(int newfd, unsigned int timeoutsec) + : BufferedSocket(newfd) + , Timer(timeoutsec) + , waitingcull(false) + { + ServerInstance->Timers.AddTimer(this); + } + + ~FlashPDSocket() + { + sockets.erase(this); + } + + void OnError(BufferedSocketError) CXX11_OVERRIDE + { + AddToCull(); + } + + void OnDataReady() CXX11_OVERRIDE + { + if (recvq == expected_request) + WriteData(policy_reply); + AddToCull(); + } + + void AddToCull() + { + if (waitingcull) + return; + + waitingcull = true; + Close(); + ServerInstance->GlobalCulls.AddItem(this); + } +}; + +class ModuleFlashPD : public Module +{ + unsigned int timeout; + + public: + ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE + { + if (from->bind_tag->getString("type") != "flashpolicyd") + return MOD_RES_PASSTHRU; + + if (policy_reply.empty()) + return MOD_RES_DENY; + + sockets.push_front(new FlashPDSocket(nfd, timeout)); + return MOD_RES_ALLOW; + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* tag = ServerInstance->Config->ConfValue("flashpolicyd"); + timeout = tag->getInt("timeout", 5, 1); + std::string file = tag->getString("file"); + + if (!file.empty()) + { + try + { + FileReader reader(file); + policy_reply = reader.GetString(); + } + catch (CoreException&) + { + const std::string error_message = "A file was specified for FlashPD, but it could not be loaded."; + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, error_message); + ServerInstance->SNO->WriteGlobalSno('a', error_message); + policy_reply.clear(); + } + return; + } + + // A file was not specified. Set the default setting. + // We allow access to all client ports by default + std::string to_ports; + for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i) + { + ListenSocket* ls = *i; + if (ls->bind_tag->getString("type", "clients") != "clients" || ls->bind_tag->getString("ssl", "plaintext") != "plaintext") + continue; + + to_ports.append(ConvToStr(ls->bind_port)).push_back(','); + } + + if (to_ports.empty()) + { + policy_reply.clear(); + return; + } + + to_ports.erase(to_ports.size() - 1); + + policy_reply = +"<?xml version=\"1.0\"?>\ +<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\ +<cross-domain-policy>\ +<site-control permitted-cross-domain-policies=\"master-only\"/>\ +<allow-access-from domain=\"*\" to-ports=\"" + to_ports + "\" />\ +</cross-domain-policy>"; + } + + CullResult cull() + { + for (insp::intrusive_list<FlashPDSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i) + { + FlashPDSocket* sock = *i; + sock->AddToCull(); + } + return Module::cull(); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Flash Policy Daemon. Allows Flash IRC clients to connect", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleFlashPD) diff --git a/src/modules/m_gecosban.cpp b/src/modules/m_gecosban.cpp index 1497c1b87..a15f19418 100644 --- a/src/modules/m_gecosban.cpp +++ b/src/modules/m_gecosban.cpp @@ -19,27 +19,15 @@ #include "inspircd.h" -/* $ModDesc: Implements extban +b r: - realname (gecos) bans */ - class ModuleGecosBan : public Module { public: - void init() - { - Implementation eventlist[] = { I_OnCheckBan, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ~ModuleGecosBan() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Extban 'r' - realname (gecos) ban", VF_OPTCOMMON|VF_VENDOR); } - ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) + ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) CXX11_OVERRIDE { if ((mask.length() > 2) && (mask[0] == 'r') && (mask[1] == ':')) { @@ -49,9 +37,9 @@ class ModuleGecosBan : public Module return MOD_RES_PASSTHRU; } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('r'); + tokens["EXTBAN"].push_back('r'); } }; diff --git a/src/modules/m_globalload.cpp b/src/modules/m_globalload.cpp index aed65045f..a3f3242f0 100644 --- a/src/modules/m_globalload.cpp +++ b/src/modules/m_globalload.cpp @@ -22,8 +22,6 @@ */ -/* $ModDesc: Allows global loading of a module. */ - #include "inspircd.h" /** Handle /GLOADMODULE @@ -35,7 +33,6 @@ class CommandGloadmodule : public Command { flags_needed = 'o'; syntax = "<modulename> [servermask]"; - TRANSLATE3(TR_TEXT, TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -47,11 +44,11 @@ class CommandGloadmodule : public Command if (ServerInstance->Modules->Load(parameters[0].c_str())) { ServerInstance->SNO->WriteToSnoMask('a', "NEW MODULE '%s' GLOBALLY LOADED BY '%s'",parameters[0].c_str(), user->nick.c_str()); - user->WriteNumeric(975, "%s %s :Module successfully loaded.",user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(RPL_LOADEDMODULE, "%s :Module successfully loaded.", parameters[0].c_str()); } else { - user->WriteNumeric(974, "%s %s :%s",user->nick.c_str(), parameters[0].c_str(), ServerInstance->Modules->LastError().c_str()); + user->WriteNumeric(ERR_CANTLOADMODULE, "%s :%s", parameters[0].c_str(), ServerInstance->Modules->LastError().c_str()); } } else @@ -79,6 +76,13 @@ class CommandGunloadmodule : public Command CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { + if (!ServerInstance->Config->ConfValue("security")->getBool("allowcoreunload") && + InspIRCd::Match(parameters[0], "core_*.so", ascii_case_insensitive_map)) + { + user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s :You cannot unload core commands!", parameters[0].c_str()); + return CMD_FAILURE; + } + std::string servername = parameters.size() > 1 ? parameters[1] : "*"; if (InspIRCd::Match(ServerInstance->Config->ServerName.c_str(), servername)) @@ -94,11 +98,11 @@ class CommandGunloadmodule : public Command } else { - user->WriteNumeric(972, "%s %s :%s",user->nick.c_str(), parameters[0].c_str(), ServerInstance->Modules->LastError().c_str()); + user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s :%s", parameters[0].c_str(), ServerInstance->Modules->LastError().c_str()); } } else - user->SendText(":%s 972 %s %s :No such module", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), parameters[0].c_str()); + user->SendText(":%s %03d %s %s :No such module", ServerInstance->Config->ServerName.c_str(), ERR_CANTUNLOADMODULE, user->nick.c_str(), parameters[0].c_str()); } else ServerInstance->SNO->WriteToSnoMask('a', "MODULE '%s' GLOBAL UNLOAD BY '%s' (not unloaded here)",parameters[0].c_str(), user->nick.c_str()); @@ -125,8 +129,8 @@ class GReloadModuleWorker : public HandlerBase1<void, bool> ServerInstance->SNO->WriteToSnoMask('a', "MODULE '%s' GLOBALLY RELOADED BY '%s'%s", name.c_str(), nick.c_str(), result ? "" : " (failed here)"); User* user = ServerInstance->FindNick(uid); if (user) - user->WriteNumeric(975, "%s %s :Module %ssuccessfully reloaded.", - user->nick.c_str(), name.c_str(), result ? "" : "un"); + user->WriteNumeric(RPL_LOADEDMODULE, "%s :Module %ssuccessfully reloaded.", + name.c_str(), result ? "" : "un"); ServerInstance->GlobalCulls.AddItem(this); } }; @@ -157,7 +161,7 @@ class CommandGreloadmodule : public Command } else { - user->WriteNumeric(975, "%s %s :Could not find module by that name", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(RPL_LOADEDMODULE, "%s :Could not find module by that name", parameters[0].c_str()); return CMD_FAILURE; } } @@ -185,22 +189,10 @@ class ModuleGlobalLoad : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd1); - ServerInstance->Modules->AddService(cmd2); - ServerInstance->Modules->AddService(cmd3); - } - - ~ModuleGlobalLoad() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows global loading of a module.", VF_COMMON | VF_VENDOR); } }; MODULE_INIT(ModuleGlobalLoad) - diff --git a/src/modules/m_globops.cpp b/src/modules/m_globops.cpp index 85d84252b..1cb87324b 100644 --- a/src/modules/m_globops.cpp +++ b/src/modules/m_globops.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for GLOBOPS and snomask +g */ - /** Handle /GLOBOPS */ class CommandGlobops : public Command @@ -33,7 +31,6 @@ class CommandGlobops : public Command CommandGlobops(Module* Creator) : Command(Creator,"GLOBOPS", 1,1) { flags_needed = 'o'; syntax = "<any-text>"; - TRANSLATE2(TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -49,17 +46,15 @@ class ModuleGlobops : public Module public: ModuleGlobops() : cmd(this) {} - void init() + void init() CXX11_OVERRIDE { - ServerInstance->Modules->AddService(cmd); ServerInstance->SNO->EnableSnomask('g',"GLOBOPS"); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for GLOBOPS and snomask +g", VF_VENDOR); } - }; MODULE_INIT(ModuleGlobops) diff --git a/src/modules/m_halfop.cpp b/src/modules/m_halfop.cpp deleted file mode 100644 index 3194fcde8..000000000 --- a/src/modules/m_halfop.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -/* $ModDesc: Channel half-operator mode provider */ - -#include "inspircd.h" - -class ModeChannelHalfOp : public ModeHandler -{ - public: - ModeChannelHalfOp(Module* parent); - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding); - unsigned int GetPrefixRank(); - void RemoveMode(Channel* channel, irc::modestacker* stack = NULL); - void RemoveMode(User* user, irc::modestacker* stack = NULL); - - ModResult AccessCheck(User* src, Channel*, std::string& value, bool adding) - { - if (!adding && src->nick == value) - return MOD_RES_ALLOW; - return MOD_RES_PASSTHRU; - } -}; - -ModeChannelHalfOp::ModeChannelHalfOp(Module* parent) : ModeHandler(parent, "halfop", 'h', PARAM_ALWAYS, MODETYPE_CHANNEL) -{ - list = true; - prefix = '%'; - levelrequired = OP_VALUE; - m_paramtype = TR_NICK; -} - -unsigned int ModeChannelHalfOp::GetPrefixRank() -{ - return HALFOP_VALUE; -} - -void ModeChannelHalfOp::RemoveMode(Channel* channel, irc::modestacker* stack) -{ - const UserMembList* clist = channel->GetUsers(); - - for (UserMembCIter i = clist->begin(); i != clist->end(); i++) - { - if (stack) - { - stack->Push(this->GetModeChar(), i->first->nick); - } - else - { - std::vector<std::string> parameters; - parameters.push_back(channel->name); - parameters.push_back("-h"); - parameters.push_back(i->first->nick); - ServerInstance->SendMode(parameters, ServerInstance->FakeClient); - } - } - -} - -void ModeChannelHalfOp::RemoveMode(User*, irc::modestacker* stack) -{ -} - -ModeAction ModeChannelHalfOp::OnModeChange(User* source, User*, Channel* channel, std::string ¶meter, bool adding) -{ - return MODEACTION_ALLOW; -} - -class ModuleHalfop : public Module -{ - ModeChannelHalfOp mh; - public: - ModuleHalfop() : mh(this) - { - } - - void init() - { - ServerInstance->Modules->AddService(mh); - } - - Version GetVersion() - { - return Version("Channel half-operator mode provider", VF_VENDOR); - } -}; - -MODULE_INIT(ModuleHalfop) diff --git a/src/modules/m_helpop.cpp b/src/modules/m_helpop.cpp index 4bbe8785e..ef9ae5e22 100644 --- a/src/modules/m_helpop.cpp +++ b/src/modules/m_helpop.cpp @@ -21,11 +21,10 @@ */ -/* $ModDesc: Provides the /HELPOP command for useful information */ - #include "inspircd.h" -static std::map<irc::string, std::string> helpop_map; +typedef std::map<std::string, std::string, irc::insensitive_swo> HelpopMap; +static HelpopMap helpop_map; /** Handles user mode +h */ @@ -42,41 +41,40 @@ class Helpop : public SimpleUserModeHandler */ class CommandHelpop : public Command { + const std::string startkey; public: - CommandHelpop(Module* Creator) : Command(Creator, "HELPOP", 0) + CommandHelpop(Module* Creator) + : Command(Creator, "HELPOP", 0) + , startkey("start") { syntax = "<any-text>"; } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { - irc::string parameter("start"); - if (parameters.size() > 0) - parameter = parameters[0].c_str(); + const std::string& parameter = (!parameters.empty() ? parameters[0] : startkey); if (parameter == "index") { /* iterate over all helpop items */ - user->WriteServ("290 %s :HELPOP topic index", user->nick.c_str()); - for (std::map<irc::string, std::string>::iterator iter = helpop_map.begin(); iter != helpop_map.end(); iter++) - { - user->WriteServ("292 %s : %s", user->nick.c_str(), iter->first.c_str()); - } - user->WriteServ("292 %s :*** End of HELPOP topic index", user->nick.c_str()); + user->WriteNumeric(290, ":HELPOP topic index"); + for (HelpopMap::const_iterator iter = helpop_map.begin(); iter != helpop_map.end(); iter++) + user->WriteNumeric(292, ": %s", iter->first.c_str()); + user->WriteNumeric(292, ":*** End of HELPOP topic index"); } else { - user->WriteServ("290 %s :*** HELPOP for %s", user->nick.c_str(), parameter.c_str()); - user->WriteServ("292 %s : -", user->nick.c_str()); + user->WriteNumeric(290, ":*** HELPOP for %s", parameter.c_str()); + user->WriteNumeric(292, ": -"); - std::map<irc::string, std::string>::iterator iter = helpop_map.find(parameter); + HelpopMap::const_iterator iter = helpop_map.find(parameter); if (iter == helpop_map.end()) { iter = helpop_map.find("nohelp"); } - std::string value = iter->second; + const std::string& value = iter->second; irc::sepstream stream(value, '\n'); std::string token = "*"; @@ -84,48 +82,40 @@ class CommandHelpop : public Command { // Writing a blank line will not work with some clients if (token.empty()) - user->WriteServ("292 %s : ", user->nick.c_str()); + user->WriteNumeric(292, ": "); else - user->WriteServ("292 %s :%s", user->nick.c_str(), token.c_str()); + user->WriteNumeric(292, ":%s", token.c_str()); } - user->WriteServ("292 %s : -", user->nick.c_str()); - user->WriteServ("292 %s :*** End of HELPOP", user->nick.c_str()); + user->WriteNumeric(292, ": -"); + user->WriteNumeric(292, ":*** End of HELPOP"); } return CMD_SUCCESS; } }; -class ModuleHelpop : public Module +class ModuleHelpop : public Module, public Whois::EventListener { - private: CommandHelpop cmd; Helpop ho; public: ModuleHelpop() - : cmd(this), ho(this) + : Whois::EventListener(this) + , cmd(this) + , ho(this) { } - void init() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - ReadConfig(); - ServerInstance->Modules->AddService(ho); - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnRehash, I_OnWhois }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void ReadConfig() - { - std::map<irc::string, std::string> help; + HelpopMap help; ConfigTagList tags = ServerInstance->Config->ConfTags("helpop"); for(ConfigIter i = tags.first; i != tags.second; ++i) { ConfigTag* tag = i->second; - irc::string key = assign(tag->getString("key")); + std::string key = tag->getString("key"); std::string value; tag->readString("value", value, true); /* Linefeeds allowed */ @@ -151,20 +141,15 @@ class ModuleHelpop : public Module helpop_map.swap(help); } - void OnRehash(User* user) - { - ReadConfig(); - } - - void OnWhois(User* src, User* dst) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - if (dst->IsModeSet('h')) + if (whois.GetTarget()->IsModeSet(ho)) { - ServerInstance->SendWhoisLine(src, dst, 310, src->nick+" "+dst->nick+" :is available for help."); + whois.SendLine(310, ":is available for help."); } } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the /HELPOP command for useful information", VF_VENDOR); } diff --git a/src/modules/m_hidechans.cpp b/src/modules/m_hidechans.cpp index 008c62208..cd3ac2c26 100644 --- a/src/modules/m_hidechans.cpp +++ b/src/modules/m_hidechans.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for hiding channels with user mode +I */ - /** Handles user mode +I */ class HideChans : public SimpleUserModeHandler @@ -39,29 +37,17 @@ class ModuleHideChans : public Module { } - void init() - { - ServerInstance->Modules->AddService(hm); - Implementation eventlist[] = { I_OnWhoisLine, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - - virtual ~ModuleHideChans() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for hiding channels with user mode +I", VF_VENDOR); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { AffectsOpers = ServerInstance->Config->ConfValue("hidechans")->getBool("affectsopers"); } - ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) + ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) CXX11_OVERRIDE { /* always show to self */ if (user == dest) @@ -72,7 +58,7 @@ class ModuleHideChans : public Module return MOD_RES_PASSTHRU; /* don't touch if -I */ - if (!dest->IsModeSet('I')) + if (!dest->IsModeSet(hm)) return MOD_RES_PASSTHRU; /* if it affects opers, we don't care if they are opered */ @@ -88,5 +74,4 @@ class ModuleHideChans : public Module } }; - MODULE_INIT(ModuleHideChans) diff --git a/src/modules/m_hidelist.cpp b/src/modules/m_hidelist.cpp new file mode 100644 index 000000000..cde8371fc --- /dev/null +++ b/src/modules/m_hidelist.cpp @@ -0,0 +1,87 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2014 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class ListWatcher : public ModeWatcher +{ + // Minimum rank required to view the list + const unsigned int minrank; + + public: + ListWatcher(Module* mod, const std::string& modename, unsigned int rank) + : ModeWatcher(mod, modename, MODETYPE_CHANNEL) + , minrank(rank) + { + } + + bool BeforeMode(User* user, User* destuser, Channel* chan, std::string& param, bool adding) + { + // Only handle listmode list requests + if (!param.empty()) + return true; + + // If the user requesting the list is a member of the channel see if they have the + // rank required to view the list + Membership* memb = chan->GetUser(user); + if ((memb) && (memb->getRank() >= minrank)) + return true; + + if (user->HasPrivPermission("channels/auspex")) + return true; + + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You do not have access to view the %s list", chan->name.c_str(), GetModeName().c_str()); + return false; + } +}; + +class ModuleHideList : public Module +{ + std::vector<ListWatcher*> watchers; + + public: + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + stdalgo::delete_all(watchers); + watchers.clear(); + + ConfigTagList tags = ServerInstance->Config->ConfTags("hidelist"); + for (ConfigIter i = tags.first; i != tags.second; ++i) + { + ConfigTag* tag = i->second; + std::string modename = tag->getString("mode"); + // If rank is set to 0 everyone inside the channel can view the list, + // but non-members may not + unsigned int rank = tag->getInt("rank", HALFOP_VALUE, 0); + watchers.push_back(new ListWatcher(this, modename, rank)); + } + } + + ~ModuleHideList() + { + stdalgo::delete_all(watchers); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides support for hiding the list of listmodes", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleHideList) diff --git a/src/modules/m_hideoper.cpp b/src/modules/m_hideoper.cpp index 88b0c4cdf..81b9b888f 100644 --- a/src/modules/m_hideoper.cpp +++ b/src/modules/m_hideoper.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for hiding oper status with user mode +H */ - /** Handles user mode +H */ class HideOper : public SimpleUserModeHandler @@ -43,24 +41,12 @@ class ModuleHideOper : public Module { } - void init() - { - ServerInstance->Modules->AddService(hm); - Implementation eventlist[] = { I_OnWhoisLine, I_OnSendWhoLine, I_OnStats }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - - virtual ~ModuleHideOper() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for hiding oper status with user mode +H", VF_VENDOR); } - ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) + ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) CXX11_OVERRIDE { /* Dont display numeric 313 (RPL_WHOISOPER) if they have +H set and the * person doing the WHOIS is not an oper @@ -68,7 +54,7 @@ class ModuleHideOper : public Module if (numeric != 313) return MOD_RES_PASSTHRU; - if (!dest->IsModeSet('H')) + if (!dest->IsModeSet(hm)) return MOD_RES_PASSTHRU; if (!user->HasPrivPermission("users/auspex")) @@ -77,9 +63,9 @@ class ModuleHideOper : public Module return MOD_RES_PASSTHRU; } - void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, std::string& line) + void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, Membership* memb, std::string& line) CXX11_OVERRIDE { - if (user->IsModeSet('H') && !source->HasPrivPermission("users/auspex")) + if (user->IsModeSet(hm) && !source->HasPrivPermission("users/auspex")) { // hide the "*" that marks the user as an oper from the /WHO line std::string::size_type spcolon = line.find(" :"); @@ -95,27 +81,28 @@ class ModuleHideOper : public Module } } - ModResult OnStats(char symbol, User* user, string_list &results) + ModResult OnStats(char symbol, User* user, string_list& results) CXX11_OVERRIDE { if (symbol != 'P') return MOD_RES_PASSTHRU; unsigned int count = 0; - for (std::list<User*>::const_iterator i = ServerInstance->Users->all_opers.begin(); i != ServerInstance->Users->all_opers.end(); ++i) + const UserManager::OperList& opers = ServerInstance->Users->all_opers; + for (UserManager::OperList::const_iterator i = opers.begin(); i != opers.end(); ++i) { User* oper = *i; - if (!ServerInstance->ULine(oper->server) && (IS_OPER(user) || !oper->IsModeSet('H'))) + if (!oper->server->IsULine() && (user->IsOper() || !oper->IsModeSet(hm))) { - results.push_back(ServerInstance->Config->ServerName+" 249 " + user->nick + " :" + oper->nick + " (" + oper->ident + "@" + oper->dhost + ") Idle: " + - (IS_LOCAL(oper) ? ConvToStr(ServerInstance->Time() - oper->idle_lastmsg) + " secs" : "unavailable")); + LocalUser* lu = IS_LOCAL(oper); + results.push_back("249 " + user->nick + " :" + oper->nick + " (" + oper->ident + "@" + oper->dhost + ") Idle: " + + (lu ? ConvToStr(ServerInstance->Time() - lu->idle_lastmsg) + " secs" : "unavailable")); count++; } } - results.push_back(ServerInstance->Config->ServerName+" 249 "+user->nick+" :"+ConvToStr(count)+" OPER(s)"); + results.push_back("249 "+user->nick+" :"+ConvToStr(count)+" OPER(s)"); return MOD_RES_DENY; } }; - MODULE_INIT(ModuleHideOper) diff --git a/src/modules/m_hostchange.cpp b/src/modules/m_hostchange.cpp index 7433fccd3..6d5896ef5 100644 --- a/src/modules/m_hostchange.cpp +++ b/src/modules/m_hostchange.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides masking of user hostnames in a different way to m_cloaking */ - /** Holds information on a host set by m_hostchange */ class Host @@ -47,21 +45,13 @@ typedef std::vector<std::pair<std::string, Host> > hostchanges_t; class ModuleHostChange : public Module { - private: hostchanges_t hostchanges; std::string MySuffix; std::string MyPrefix; std::string MySeparator; public: - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnRehash, I_OnUserConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* host = ServerInstance->Config->ConfValue("host"); MySuffix = host->getString("suffix"); @@ -97,14 +87,14 @@ class ModuleHostChange : public Module } } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { // returns the version number of the module to be // listed in /MODULES return Version("Provides masking of user hostnames in a different way to m_cloaking", VF_VENDOR); } - virtual void OnUserConnect(LocalUser* user) + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE { for (hostchanges_t::iterator i = hostchanges.begin(); i != hostchanges.end(); i++) { @@ -160,9 +150,9 @@ class ModuleHostChange : public Module } if (!newhost.empty()) { - user->WriteServ("NOTICE "+user->nick+" :Setting your virtual host: " + newhost); - if (!user->ChangeDisplayedHost(newhost.c_str())) - user->WriteServ("NOTICE "+user->nick+" :Could not set your virtual host: " + newhost); + user->WriteNotice("Setting your virtual host: " + newhost); + if (!user->ChangeDisplayedHost(newhost)) + user->WriteNotice("Could not set your virtual host: " + newhost); return; } } diff --git a/src/modules/m_hostcycle.cpp b/src/modules/m_hostcycle.cpp new file mode 100644 index 000000000..e8a0abbf1 --- /dev/null +++ b/src/modules/m_hostcycle.cpp @@ -0,0 +1,114 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class ModuleHostCycle : public Module +{ + /** Send fake quit/join/mode messages for host or ident cycle. + */ + static void DoHostCycle(User* user, const std::string& newident, const std::string& newhost, const char* quitmsg) + { + // GetFullHost() returns the original data at the time this function is called + const std::string quitline = ":" + user->GetFullHost() + " QUIT :" + quitmsg; + + already_sent_t silent_id = ++LocalUser::already_sent_id; + already_sent_t seen_id = ++LocalUser::already_sent_id; + + IncludeChanList include_chans(user->chans.begin(), user->chans.end()); + std::map<User*,bool> exceptions; + + FOREACH_MOD(OnBuildNeighborList, (user, include_chans, exceptions)); + + for (std::map<User*,bool>::iterator i = exceptions.begin(); i != exceptions.end(); ++i) + { + LocalUser* u = IS_LOCAL(i->first); + if (u && !u->quitting) + { + if (i->second) + { + u->already_sent = seen_id; + u->Write(quitline); + } + else + { + u->already_sent = silent_id; + } + } + } + + std::string newfullhost = user->nick + "!" + newident + "@" + newhost; + + for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i) + { + Membership* memb = *i; + Channel* c = memb->chan; + const std::string joinline = ":" + newfullhost + " JOIN " + c->name; + std::string modeline; + + if (!memb->modes.empty()) + { + modeline = ":" + (ServerInstance->Config->CycleHostsFromUser ? newfullhost : ServerInstance->Config->ServerName) + + " MODE " + c->name + " +" + memb->modes; + + for (size_t j = 0; j < memb->modes.length(); j++) + modeline.append(" ").append(user->nick); + } + + const Channel::MemberMap& ulist = c->GetUsers(); + for (Channel::MemberMap::const_iterator j = ulist.begin(); j != ulist.end(); ++j) + { + LocalUser* u = IS_LOCAL(j->first); + if (u == NULL || u == user) + continue; + if (u->already_sent == silent_id) + continue; + + if (u->already_sent != seen_id) + { + u->Write(quitline); + u->already_sent = seen_id; + } + + u->Write(joinline); + if (!memb->modes.empty()) + u->Write(modeline); + } + } + } + + public: + void OnChangeIdent(User* user, const std::string& newident) CXX11_OVERRIDE + { + DoHostCycle(user, newident, user->dhost, "Changing ident"); + } + + void OnChangeHost(User* user, const std::string& newhost) CXX11_OVERRIDE + { + DoHostCycle(user, user->ident, newhost, "Changing host"); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Cycles users in all their channels when their host or ident changes", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleHostCycle) diff --git a/src/modules/m_httpd.cpp b/src/modules/m_httpd.cpp index 2b079c6ff..760647d47 100644 --- a/src/modules/m_httpd.cpp +++ b/src/modules/m_httpd.cpp @@ -23,16 +23,15 @@ #include "inspircd.h" -#include "httpd.h" - -/* $ModDesc: Provides HTTP serving facilities to modules */ -/* $ModDep: httpd.h */ +#include "iohook.h" +#include "modules/httpd.h" class ModuleHttpServer; static ModuleHttpServer* HttpModule; -static bool claimed; -static std::set<HttpServerSocket*> sockets; +static insp::intrusive_list<HttpServerSocket> sockets; +static Events::ModuleEventProvider* aclevprov; +static Events::ModuleEventProvider* reqevprov; /** HTTP socket states */ @@ -45,7 +44,7 @@ enum HttpState /** A socket used for HTTP transport */ -class HttpServerSocket : public BufferedSocket +class HttpServerSocket : public BufferedSocket, public Timer, public insp::intrusive_list_node<HttpServerSocket> { HttpState InternalState; std::string ip; @@ -58,18 +57,29 @@ class HttpServerSocket : public BufferedSocket std::string uri; std::string http_version; - public: - const time_t createtime; + /** True if this object is in the cull list + */ + bool waitingcull; + + bool Tick(time_t currtime) CXX11_OVERRIDE + { + AddToCull(); + return false; + } - HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) - : BufferedSocket(newfd), ip(IP), postsize(0) - , createtime(ServerInstance->Time()) + public: + HttpServerSocket(int newfd, const std::string& IP, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server, unsigned int timeoutsec) + : BufferedSocket(newfd) + , Timer(timeoutsec) + , InternalState(HTTP_SERVE_WAIT_REQUEST) + , ip(IP) + , postsize(0) + , waitingcull(false) { - InternalState = HTTP_SERVE_WAIT_REQUEST; + ServerInstance->Timers.AddTimer(this); - FOREACH_MOD(I_OnHookIO, OnHookIO(this, via)); - if (GetIOHook()) - GetIOHook()->OnStreamSocketAccept(this, client, server); + if (via->iohookprov) + via->iohookprov->OnAccept(this, client, server); } ~HttpServerSocket() @@ -77,9 +87,9 @@ class HttpServerSocket : public BufferedSocket sockets.erase(this); } - virtual void OnError(BufferedSocketError) + void OnError(BufferedSocketError) CXX11_OVERRIDE { - ServerInstance->GlobalCulls.AddItem(this); + AddToCull(); } std::string Response(int response) @@ -188,13 +198,8 @@ class HttpServerSocket : public BufferedSocket WriteData(http_version + " "+ConvToStr(response)+" "+Response(response)+"\r\n"); - time_t local = ServerInstance->Time(); - struct tm *timeinfo = gmtime(&local); - char *date = asctime(timeinfo); - date[strlen(date) - 1] = '\0'; - rheaders.CreateHeader("Date", date); - - rheaders.CreateHeader("Server", BRANCH); + rheaders.CreateHeader("Date", InspIRCd::TimeString(ServerInstance->Time(), "%a, %d %b %Y %H:%M:%S GMT", true)); + rheaders.CreateHeader("Server", INSPIRCD_BRANCH); rheaders.SetHeader("Content-Length", ConvToStr(size)); if (size) @@ -225,7 +230,7 @@ class HttpServerSocket : public BufferedSocket if (reqbuffer.length() >= 8192) { - ServerInstance->Logs->Log("m_httpd",DEBUG, "m_httpd dropped connection due to an oversized request buffer"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "m_httpd dropped connection due to an oversized request buffer"); reqbuffer.clear(); SetError("Buffer"); } @@ -265,7 +270,7 @@ class HttpServerSocket : public BufferedSocket continue; } - std::string cheader = reqbuffer.substr(hbegin, hend - hbegin); + std::string cheader(reqbuffer, hbegin, hend - hbegin); std::string::size_type fieldsep = cheader.find(':'); if ((fieldsep == std::string::npos) || (fieldsep == 0) || (fieldsep == cheader.length() - 1)) @@ -296,7 +301,7 @@ class HttpServerSocket : public BufferedSocket if (reqbuffer.length() >= postsize) { - postdata = reqbuffer.substr(0, postsize); + postdata.assign(reqbuffer, 0, postsize); reqbuffer.erase(0, postsize); } else if (!reqbuffer.empty()) @@ -318,14 +323,14 @@ class HttpServerSocket : public BufferedSocket { InternalState = HTTP_SERVE_SEND_DATA; - claimed = false; - HTTPRequest acl((Module*)HttpModule, "httpd_acl", request_type, uri, &headers, this, ip, postdata); - acl.Send(); - if (!claimed) + ModResult MOD_RESULT; + HTTPRequest acl(request_type, uri, &headers, this, ip, postdata); + FIRST_MOD_RESULT_CUSTOM(*aclevprov, HTTPACLEventListener, OnHTTPACLCheck, MOD_RESULT, (acl)); + if (MOD_RESULT != MOD_RES_DENY) { - HTTPRequest url((Module*)HttpModule, "httpd_url", request_type, uri, &headers, this, ip, postdata); - url.Send(); - if (!claimed) + HTTPRequest url(request_type, uri, &headers, this, ip, postdata); + FIRST_MOD_RESULT_CUSTOM(*reqevprov, HTTPRequestEventListener, OnHTTPRequest, MOD_RESULT, (url)); + if (MOD_RESULT == MOD_RES_PASSTHRU) { SendHTTPError(404); } @@ -337,73 +342,78 @@ class HttpServerSocket : public BufferedSocket SendHeaders(n->str().length(), response, *hheaders); WriteData(n->str()); } + + void AddToCull() + { + if (waitingcull) + return; + + waitingcull = true; + Close(); + ServerInstance->GlobalCulls.AddItem(this); + } +}; + +class HTTPdAPIImpl : public HTTPdAPIBase +{ + public: + HTTPdAPIImpl(Module* parent) + : HTTPdAPIBase(parent) + { + } + + void SendResponse(HTTPDocumentResponse& resp) CXX11_OVERRIDE + { + resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers); + } }; class ModuleHttpServer : public Module { + HTTPdAPIImpl APIImpl; unsigned int timeoutsec; + Events::ModuleEventProvider acleventprov; + Events::ModuleEventProvider reqeventprov; public: - - void init() + ModuleHttpServer() + : APIImpl(this) + , acleventprov(this, "event/http-acl") + , reqeventprov(this, "event/http-request") { - HttpModule = this; - Implementation eventlist[] = { I_OnAcceptConnection, I_OnBackgroundTimer, I_OnRehash, I_OnUnloadModule }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); + aclevprov = &acleventprov; + reqevprov = &reqeventprov; } - void OnRehash(User* user) + void init() CXX11_OVERRIDE { - ConfigTag* tag = ServerInstance->Config->ConfValue("httpd"); - timeoutsec = tag->getInt("timeout"); + HttpModule = this; } - void OnRequest(Request& request) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - if (strcmp(request.id, "HTTP-DOC") != 0) - return; - HTTPDocumentResponse& resp = static_cast<HTTPDocumentResponse&>(request); - claimed = true; - resp.src.sock->Page(resp.document, resp.responsecode, &resp.headers); + ConfigTag* tag = ServerInstance->Config->ConfValue("httpd"); + timeoutsec = tag->getInt("timeout", 10, 1); } - ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) + ModResult OnAcceptConnection(int nfd, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE { if (from->bind_tag->getString("type") != "httpd") return MOD_RES_PASSTHRU; int port; std::string incomingip; irc::sockets::satoap(*client, incomingip, port); - sockets.insert(new HttpServerSocket(nfd, incomingip, from, client, server)); + sockets.push_front(new HttpServerSocket(nfd, incomingip, from, client, server, timeoutsec)); return MOD_RES_ALLOW; } - void OnBackgroundTimer(time_t curtime) - { - if (!timeoutsec) - return; - - time_t oldest_allowed = curtime - timeoutsec; - for (std::set<HttpServerSocket*>::const_iterator i = sockets.begin(); i != sockets.end(); ) - { - HttpServerSocket* sock = *i; - ++i; - if (sock->createtime < oldest_allowed) - { - sock->cull(); - delete sock; - } - } - } - void OnUnloadModule(Module* mod) { - for (std::set<HttpServerSocket*>::const_iterator i = sockets.begin(); i != sockets.end(); ) + for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ) { HttpServerSocket* sock = *i; ++i; - if (sock->GetIOHook() == mod) + if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod) { sock->cull(); delete sock; @@ -411,20 +421,17 @@ class ModuleHttpServer : public Module } } - CullResult cull() + CullResult cull() CXX11_OVERRIDE { - std::set<HttpServerSocket*> local; - local.swap(sockets); - for (std::set<HttpServerSocket*>::const_iterator i = local.begin(); i != local.end(); ++i) + for (insp::intrusive_list<HttpServerSocket>::const_iterator i = sockets.begin(); i != sockets.end(); ++i) { HttpServerSocket* sock = *i; - sock->cull(); - delete sock; + sock->AddToCull(); } return Module::cull(); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides HTTP serving facilities to modules", VF_VENDOR); } diff --git a/src/modules/m_httpd_acl.cpp b/src/modules/m_httpd_acl.cpp index c25cabc0a..866fa0e86 100644 --- a/src/modules/m_httpd_acl.cpp +++ b/src/modules/m_httpd_acl.cpp @@ -19,10 +19,7 @@ #include "inspircd.h" -#include "httpd.h" -#include "protocol.h" - -/* $ModDesc: Provides access control lists (passwording of resources, ip restrictions etc) to m_httpd.so dependent modules */ +#include "modules/httpd.h" class HTTPACL { @@ -37,19 +34,22 @@ class HTTPACL const std::string &set_whitelist, const std::string &set_blacklist) : path(set_path), username(set_username), password(set_password), whitelist(set_whitelist), blacklist(set_blacklist) { } - - ~HTTPACL() { } }; -class ModuleHTTPAccessList : public Module +class ModuleHTTPAccessList : public Module, public HTTPACLEventListener { - std::string stylesheet; std::vector<HTTPACL> acl_list; + HTTPdAPI API; public: + ModuleHTTPAccessList() + : HTTPACLEventListener(this) + , API(this) + { + } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { acl_list.clear(); ConfigTagList acls = ServerInstance->Config->ConfTags("httpdacl"); @@ -86,38 +86,29 @@ class ModuleHTTPAccessList : public Module } } - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "Read ACL: path=%s pass=%s whitelist=%s blacklist=%s", path.c_str(), + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Read ACL: path=%s pass=%s whitelist=%s blacklist=%s", path.c_str(), password.c_str(), whitelist.c_str(), blacklist.c_str()); acl_list.push_back(HTTPACL(path, username, password, whitelist, blacklist)); } } - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnEvent, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - void BlockAccess(HTTPRequest* http, int returnval, const std::string &extraheaderkey = "", const std::string &extraheaderval="") { - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "BlockAccess (%d)", returnval); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BlockAccess (%d)", returnval); std::stringstream data("Access to this resource is denied by an access control list. Please contact your IRC administrator."); HTTPDocumentResponse response(this, *http, &data, returnval); - response.headers.SetHeader("X-Powered-By", "m_httpd_acl.so"); + response.headers.SetHeader("X-Powered-By", MODNAME); if (!extraheaderkey.empty()) response.headers.SetHeader(extraheaderkey, extraheaderval); - response.Send(); + API->SendResponse(response); } - void OnEvent(Event& event) + bool IsAccessAllowed(HTTPRequest* http) { - if (event.id == "httpd_acl") { - ServerInstance->Logs->Log("m_http_stats", DEBUG,"Handling httpd acl event"); - HTTPRequest* http = (HTTPRequest*)&event; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd acl event"); for (std::vector<HTTPACL>::const_iterator this_acl = acl_list.begin(); this_acl != acl_list.end(); ++this_acl) { @@ -133,10 +124,10 @@ class ModuleHTTPAccessList : public Module { if (InspIRCd::Match(http->GetIP(), entry, ascii_case_insensitive_map)) { - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "Denying access to blacklisted resource %s (matched by pattern %s) from ip %s (matched by entry %s)", + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Denying access to blacklisted resource %s (matched by pattern %s) from ip %s (matched by entry %s)", http->GetURI().c_str(), this_acl->path.c_str(), http->GetIP().c_str(), entry.c_str()); BlockAccess(http, 403); - return; + return false; } } } @@ -155,16 +146,16 @@ class ModuleHTTPAccessList : public Module if (!allow_access) { - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "Denying access to whitelisted resource %s (matched by pattern %s) from ip %s (Not in whitelist)", + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Denying access to whitelisted resource %s (matched by pattern %s) from ip %s (Not in whitelist)", http->GetURI().c_str(), this_acl->path.c_str(), http->GetIP().c_str()); BlockAccess(http, 403); - return; + return false; } } if (!this_acl->password.empty() && !this_acl->username.empty()) { /* Password auth, first look to see if we have a basic authentication header */ - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "Checking HTTP auth password for resource %s (matched by pattern %s) from ip %s, against username %s", + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Checking HTTP auth password for resource %s (matched by pattern %s) from ip %s, against username %s", http->GetURI().c_str(), this_acl->path.c_str(), http->GetIP().c_str(), this_acl->username.c_str()); if (http->headers->IsSet("Authorization")) @@ -183,7 +174,7 @@ class ModuleHTTPAccessList : public Module sep.GetToken(base64); std::string userpass = Base64ToBin(base64); - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "HTTP authorization: %s (%s)", userpass.c_str(), base64.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "HTTP authorization: %s (%s)", userpass.c_str(), base64.c_str()); irc::sepstream userpasspair(userpass, ':'); if (userpasspair.GetToken(user)) @@ -193,8 +184,8 @@ class ModuleHTTPAccessList : public Module /* Access granted if username and password are correct */ if (user == this_acl->username && pass == this_acl->password) { - ServerInstance->Logs->Log("m_httpd_acl", DEBUG, "HTTP authorization: password and username match"); - return; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "HTTP authorization: password and username match"); + return true; } else /* Invalid password */ @@ -213,20 +204,25 @@ class ModuleHTTPAccessList : public Module /* No password given at all, access denied */ BlockAccess(http, 401, "WWW-Authenticate", "Basic realm=\"Restricted Object\""); } + return false; } /* A path may only match one ACL (the first it finds in the config file) */ - return; + break; } } } + return true; } - virtual ~ModuleHTTPAccessList() + ModResult OnHTTPACLCheck(HTTPRequest& req) CXX11_OVERRIDE { + if (IsAccessAllowed(&req)) + return MOD_RES_PASSTHRU; + return MOD_RES_DENY; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides access control lists (passwording of resources, ip restrictions etc) to m_httpd.so dependent modules", VF_VENDOR); } diff --git a/src/modules/m_httpd_config.cpp b/src/modules/m_httpd_config.cpp index 62314cd7e..6fd7f4050 100644 --- a/src/modules/m_httpd_config.cpp +++ b/src/modules/m_httpd_config.cpp @@ -19,18 +19,17 @@ #include "inspircd.h" -#include "httpd.h" -#include "protocol.h" +#include "modules/httpd.h" -/* $ModDesc: Allows for the server configuration to be viewed over HTTP via m_httpd.so */ - -class ModuleHttpConfig : public Module +class ModuleHttpConfig : public Module, public HTTPRequestEventListener { + HTTPdAPI API; + public: - void init() + ModuleHttpConfig() + : HTTPRequestEventListener(this) + , API(this) { - Implementation eventlist[] = { I_OnEvent }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } std::string Sanitize(const std::string &str) @@ -67,14 +66,12 @@ class ModuleHttpConfig : public Module return ret; } - void OnEvent(Event& event) + ModResult HandleRequest(HTTPRequest* http) { std::stringstream data(""); - if (event.id == "httpd_url") { - ServerInstance->Logs->Log("m_http_stats", DEBUG,"Handling httpd event"); - HTTPRequest* http = (HTTPRequest*)&event; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd event"); if ((http->GetURI() == "/config") || (http->GetURI() == "/config/")) { @@ -95,18 +92,21 @@ class ModuleHttpConfig : public Module data << "</body></html>"; /* Send the document back to m_httpd */ HTTPDocumentResponse response(this, *http, &data, 200); - response.headers.SetHeader("X-Powered-By", "m_httpd_config.so"); + response.headers.SetHeader("X-Powered-By", MODNAME); response.headers.SetHeader("Content-Type", "text/html"); - response.Send(); + API->SendResponse(response); + return MOD_RES_DENY; // Handled } } + return MOD_RES_PASSTHRU; } - virtual ~ModuleHttpConfig() + ModResult OnHTTPRequest(HTTPRequest& req) CXX11_OVERRIDE { + return HandleRequest(&req); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows for the server configuration to be viewed over HTTP via m_httpd.so", VF_VENDOR); } diff --git a/src/modules/m_httpd_stats.cpp b/src/modules/m_httpd_stats.cpp index 2fc7ca7de..ad0b4bb72 100644 --- a/src/modules/m_httpd_stats.cpp +++ b/src/modules/m_httpd_stats.cpp @@ -22,22 +22,19 @@ #include "inspircd.h" -#include "httpd.h" +#include "modules/httpd.h" #include "xline.h" -#include "protocol.h" -/* $ModDesc: Provides statistics over HTTP via m_httpd.so */ - -class ModuleHttpStats : public Module +class ModuleHttpStats : public Module, public HTTPRequestEventListener { - static std::map<char, char const*> const &entities; + static const insp::flat_map<char, char const*>& entities; + HTTPdAPI API; public: - - void init() + ModuleHttpStats() + : HTTPRequestEventListener(this) + , API(this) { - Implementation eventlist[] = { I_OnEvent }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } std::string Sanitize(const std::string &str) @@ -47,7 +44,7 @@ class ModuleHttpStats : public Module for (std::string::const_iterator x = str.begin(); x != str.end(); ++x) { - std::map<char, char const*>::const_iterator it = entities.find(*x); + insp::flat_map<char, char const*>::const_iterator it = entities.find(*x); if (it != entities.end()) { @@ -91,14 +88,12 @@ class ModuleHttpStats : public Module data << "</metadata>"; } - void OnEvent(Event& event) + ModResult HandleRequest(HTTPRequest* http) { std::stringstream data(""); - if (event.id == "httpd_url") { - ServerInstance->Logs->Log("m_http_stats", DEBUG,"Handling httpd event"); - HTTPRequest* http = (HTTPRequest*)&event; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Handling httpd event"); if ((http->GetURI() == "/stats") || (http->GetURI() == "/stats/")) { @@ -107,19 +102,19 @@ class ModuleHttpStats : public Module << Sanitize(ServerInstance->GetVersionString()) << "</version></server>"; data << "<general>"; - data << "<usercount>" << ServerInstance->Users->clientlist->size() << "</usercount>"; - data << "<channelcount>" << ServerInstance->chanlist->size() << "</channelcount>"; + data << "<usercount>" << ServerInstance->Users->GetUsers().size() << "</usercount>"; + data << "<channelcount>" << ServerInstance->GetChans().size() << "</channelcount>"; data << "<opercount>" << ServerInstance->Users->all_opers.size() << "</opercount>"; - data << "<socketcount>" << (ServerInstance->SE->GetUsedFds()) << "</socketcount><socketmax>" << ServerInstance->SE->GetMaxFds() << "</socketmax><socketengine>" << ServerInstance->SE->GetName() << "</socketengine>"; - - time_t current_time = 0; - current_time = ServerInstance->Time(); - time_t server_uptime = current_time - ServerInstance->startup_time; - struct tm* stime; - stime = gmtime(&server_uptime); - data << "<uptime><days>" << stime->tm_yday << "</days><hours>" << stime->tm_hour << "</hours><mins>" << stime->tm_min << "</mins><secs>" << stime->tm_sec << "</secs><boot_time_t>" << ServerInstance->startup_time << "</boot_time_t></uptime>"; + data << "<socketcount>" << (SocketEngine::GetUsedFds()) << "</socketcount><socketmax>" << SocketEngine::GetMaxFds() << "</socketmax><socketengine>" INSPIRCD_SOCKETENGINE_NAME "</socketengine>"; + data << "<uptime><boot_time_t>" << ServerInstance->startup_time << "</boot_time_t></uptime>"; - data << "<isupport>" << Sanitize(ServerInstance->Config->data005) << "</isupport></general><xlines>"; + data << "<isupport>"; + const std::vector<std::string>& isupport = ServerInstance->ISupport.GetLines(); + for (std::vector<std::string>::const_iterator it = isupport.begin(); it != isupport.end(); it++) + { + data << Sanitize(*it) << std::endl; + } + data << "</isupport></general><xlines>"; std::vector<std::string> xltypes = ServerInstance->XLines->GetAllTypes(); for (std::vector<std::string>::iterator it = xltypes.begin(); it != xltypes.end(); ++it) { @@ -138,35 +133,35 @@ class ModuleHttpStats : public Module } data << "</xlines><modulelist>"; - std::vector<std::string> module_names = ServerInstance->Modules->GetAllModuleNames(0); + const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules(); - for (std::vector<std::string>::iterator i = module_names.begin(); i != module_names.end(); ++i) + for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i) { - Module* m = ServerInstance->Modules->Find(i->c_str()); - Version v = m->GetVersion(); - data << "<module><name>" << *i << "</name><description>" << Sanitize(v.description) << "</description></module>"; + Version v = i->second->GetVersion(); + data << "<module><name>" << i->first << "</name><description>" << Sanitize(v.description) << "</description></module>"; } data << "</modulelist><channellist>"; - for (chan_hash::const_iterator a = ServerInstance->chanlist->begin(); a != ServerInstance->chanlist->end(); ++a) + const chan_hash& chans = ServerInstance->GetChans(); + for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i) { - Channel* c = a->second; + Channel* c = i->second; data << "<channel>"; - data << "<usercount>" << c->GetUsers()->size() << "</usercount><channelname>" << Sanitize(c->name) << "</channelname>"; + data << "<usercount>" << c->GetUsers().size() << "</usercount><channelname>" << Sanitize(c->name) << "</channelname>"; data << "<channeltopic>"; data << "<topictext>" << Sanitize(c->topic) << "</topictext>"; data << "<setby>" << Sanitize(c->setby) << "</setby>"; data << "<settime>" << c->topicset << "</settime>"; data << "</channeltopic>"; data << "<channelmodes>" << Sanitize(c->ChanModes(true)) << "</channelmodes>"; - const UserMembList* ulist = c->GetUsers(); - for (UserMembCIter x = ulist->begin(); x != ulist->end(); ++x) + const Channel::MemberMap& ulist = c->GetUsers(); + for (Channel::MemberMap::const_iterator x = ulist.begin(); x != ulist.end(); ++x) { Membership* memb = x->second; data << "<channelmember><uid>" << memb->user->uuid << "</uid><privs>" - << Sanitize(c->GetAllPrefixChars(x->first)) << "</privs><modes>" + << Sanitize(memb->GetAllPrefixChars()) << "</privs><modes>" << memb->modes << "</modes>"; DumpMeta(data, memb); data << "</channelmember>"; @@ -179,23 +174,24 @@ class ModuleHttpStats : public Module data << "</channellist><userlist>"; - for (user_hash::const_iterator a = ServerInstance->Users->clientlist->begin(); a != ServerInstance->Users->clientlist->end(); ++a) + const user_hash& users = ServerInstance->Users->GetUsers(); + for (user_hash::const_iterator i = users.begin(); i != users.end(); ++i) { - User* u = a->second; + User* u = i->second; data << "<user>"; data << "<nickname>" << u->nick << "</nickname><uuid>" << u->uuid << "</uuid><realhost>" << u->host << "</realhost><displayhost>" << u->dhost << "</displayhost><gecos>" - << Sanitize(u->fullname) << "</gecos><server>" << u->server << "</server>"; - if (IS_AWAY(u)) + << Sanitize(u->fullname) << "</gecos><server>" << u->server->GetName() << "</server>"; + if (u->IsAway()) data << "<away>" << Sanitize(u->awaymsg) << "</away><awaytime>" << u->awaytime << "</awaytime>"; - if (IS_OPER(u)) - data << "<opertype>" << Sanitize(u->oper->NameStr()) << "</opertype>"; + if (u->IsOper()) + data << "<opertype>" << Sanitize(u->oper->name) << "</opertype>"; data << "<modes>" << u->FormatModes() << "</modes><ident>" << Sanitize(u->ident) << "</ident>"; LocalUser* lu = IS_LOCAL(u); if (lu) data << "<port>" << lu->GetServerPort() << "</port><servaddr>" - << irc::sockets::satouser(lu->server_sa) << "</servaddr>"; + << lu->server_sa.str() << "</servaddr>"; data << "<ipaddress>" << u->GetIPString() << "</ipaddress>"; DumpMeta(data, u); @@ -205,10 +201,10 @@ class ModuleHttpStats : public Module data << "</userlist><serverlist>"; - ProtoServerList sl; + ProtocolInterface::ServerList sl; ServerInstance->PI->GetServerList(sl); - for (ProtoServerList::iterator b = sl.begin(); b != sl.end(); ++b) + for (ProtocolInterface::ServerList::const_iterator b = sl.begin(); b != sl.end(); ++b) { data << "<server>"; data << "<servername>" << b->servername << "</servername>"; @@ -225,26 +221,29 @@ class ModuleHttpStats : public Module /* Send the document back to m_httpd */ HTTPDocumentResponse response(this, *http, &data, 200); - response.headers.SetHeader("X-Powered-By", "m_httpd_stats.so"); + response.headers.SetHeader("X-Powered-By", MODNAME); response.headers.SetHeader("Content-Type", "text/xml"); - response.Send(); + API->SendResponse(response); + return MOD_RES_DENY; // Handled } } + return MOD_RES_PASSTHRU; } - virtual ~ModuleHttpStats() + ModResult OnHTTPRequest(HTTPRequest& req) CXX11_OVERRIDE { + return HandleRequest(&req); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides statistics over HTTP via m_httpd.so", VF_VENDOR); } }; -static std::map<char, char const*> const &init_entities() +static const insp::flat_map<char, char const*>& init_entities() { - static std::map<char, char const*> entities; + static insp::flat_map<char, char const*> entities; entities['<'] = "lt"; entities['>'] = "gt"; entities['&'] = "amp"; @@ -252,6 +251,6 @@ static std::map<char, char const*> const &init_entities() return entities; } -std::map<char, char const*> const &ModuleHttpStats::entities = init_entities (); +const insp::flat_map<char, char const*>& ModuleHttpStats::entities = init_entities(); MODULE_INIT(ModuleHttpStats) diff --git a/src/modules/m_ident.cpp b/src/modules/m_ident.cpp index f0ced1db7..0e5aa43ae 100644 --- a/src/modules/m_ident.cpp +++ b/src/modules/m_ident.cpp @@ -24,8 +24,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for RFC1413 ident lookups */ - /* -------------------------------------------------------------- * Note that this is the third incarnation of m_ident. The first * two attempts were pretty crashy, mainly due to the fact we tried @@ -119,33 +117,32 @@ class IdentRequestSocket : public EventHandler } /* Attempt to bind (ident requests must come from the ip the query is referring to */ - if (ServerInstance->SE->Bind(GetFd(), bindaddr) < 0) + if (SocketEngine::Bind(GetFd(), bindaddr) < 0) { this->Close(); throw ModuleException("failed to bind()"); } - ServerInstance->SE->NonBlocking(GetFd()); + SocketEngine::NonBlocking(GetFd()); /* Attempt connection (nonblocking) */ - if (ServerInstance->SE->Connect(this, &connaddr.sa, connaddr.sa_size()) == -1 && errno != EINPROGRESS) + if (SocketEngine::Connect(this, &connaddr.sa, connaddr.sa_size()) == -1 && errno != EINPROGRESS) { this->Close(); throw ModuleException("connect() failed"); } /* Add fd to socket engine */ - if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE)) + if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE)) { this->Close(); throw ModuleException("out of fds"); } } - virtual void OnConnected() + void OnEventHandlerWrite() CXX11_OVERRIDE { - ServerInstance->Logs->Log("m_ident",DEBUG,"OnConnected()"); - ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); + SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE); char req[32]; @@ -161,34 +158,10 @@ class IdentRequestSocket : public EventHandler /* Send failed if we didnt write the whole ident request -- * might as well give up if this happens! */ - if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size) + if (SocketEngine::Send(this, req, req_size, 0) < req_size) done = true; } - virtual void HandleEvent(EventType et, int errornum = 0) - { - switch (et) - { - case EVENT_READ: - /* fd readable event, received ident response */ - ReadResponse(); - break; - case EVENT_WRITE: - /* fd writeable event, successfully connected! */ - OnConnected(); - break; - case EVENT_ERROR: - /* fd error event, ohshi- */ - ServerInstance->Logs->Log("m_ident",DEBUG,"EVENT_ERROR"); - /* We *must* Close() here immediately or we get a - * huge storm of EVENT_ERROR events! - */ - Close(); - done = true; - break; - } - } - void Close() { /* Remove ident socket from engine, and close it, but dont detatch it @@ -196,10 +169,8 @@ class IdentRequestSocket : public EventHandler */ if (GetFd() > -1) { - ServerInstance->Logs->Log("m_ident",DEBUG,"Close ident socket %d", GetFd()); - ServerInstance->SE->DelFd(this); - ServerInstance->SE->Close(GetFd()); - this->SetFd(-1); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Close ident socket %d", GetFd()); + SocketEngine::Close(this); } } @@ -208,13 +179,13 @@ class IdentRequestSocket : public EventHandler return done; } - void ReadResponse() + void OnEventHandlerRead() CXX11_OVERRIDE { /* We don't really need to buffer for incomplete replies here, since IDENT replies are * extremely short - there is *no* sane reason it'd be in more than one packet */ - char ibuf[MAXBUF]; - int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0); + char ibuf[256]; + int recvresult = SocketEngine::Recv(this, ibuf, sizeof(ibuf)-1, 0); /* Close (but don't delete from memory) our socket * and flag as done since the ident lookup has finished @@ -228,7 +199,7 @@ class IdentRequestSocket : public EventHandler if (recvresult < 3) return; - ServerInstance->Logs->Log("m_ident",DEBUG,"ReadResponse()"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "ReadResponse()"); /* Truncate at the first null character, but first make sure * there is at least one null char (at the end of the buffer). @@ -260,67 +231,66 @@ class IdentRequestSocket : public EventHandler * we're done. */ result += *i; - if (!ServerInstance->IsIdent(result.c_str())) + if (!ServerInstance->IsIdent(result)) { result.erase(result.end()-1); break; } } } -}; -class ModuleIdent : public Module -{ - int RequestTimeout; - SimpleExtItem<IdentRequestSocket> ext; - public: - ModuleIdent() : ext("ident_socket", this) + void OnEventHandlerError(int errornum) CXX11_OVERRIDE { + Close(); + done = true; } - void init() + CullResult cull() CXX11_OVERRIDE { - ServerInstance->Modules->AddService(ext); - OnRehash(NULL); - Implementation eventlist[] = { - I_OnRehash, I_OnUserInit, I_OnCheckReady, - I_OnUserDisconnect, I_OnSetConnectClass - }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + Close(); + return EventHandler::cull(); } +}; - ~ModuleIdent() +class ModuleIdent : public Module +{ + int RequestTimeout; + bool NoLookupPrefix; + SimpleExtItem<IdentRequestSocket, stdalgo::culldeleter> ext; + public: + ModuleIdent() + : ext("ident_socket", ExtensionItem::EXT_USER, this) { } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for RFC1413 ident lookups", VF_VENDOR); } - virtual void OnRehash(User *user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - RequestTimeout = ServerInstance->Config->ConfValue("ident")->getInt("timeout", 5); - if (!RequestTimeout) - RequestTimeout = 5; + ConfigTag* tag = ServerInstance->Config->ConfValue("ident"); + RequestTimeout = tag->getInt("timeout", 5, 1); + NoLookupPrefix = tag->getBool("nolookupprefix", false); } - void OnUserInit(LocalUser *user) + void OnUserInit(LocalUser *user) CXX11_OVERRIDE { ConfigTag* tag = user->MyClass->config; if (!tag->getBool("useident", true)) return; - user->WriteServ("NOTICE Auth :*** Looking up your ident..."); + user->WriteNotice("*** Looking up your ident..."); try { - IdentRequestSocket *isock = new IdentRequestSocket(IS_LOCAL(user)); + IdentRequestSocket *isock = new IdentRequestSocket(user); ext.set(user, isock); } catch (ModuleException &e) { - ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Ident exception: " + e.GetReason()); } } @@ -328,18 +298,17 @@ class ModuleIdent : public Module * creating a Timer object and especially better than creating a * Timer per ident lookup! */ - virtual ModResult OnCheckReady(LocalUser *user) + ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE { /* Does user have an ident socket attached at all? */ IdentRequestSocket *isock = ext.get(user); if (!isock) { - ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :("); + if ((NoLookupPrefix) && (user->ident[0] != '~')) + user->ident.insert(user->ident.begin(), 1, '~'); return MOD_RES_PASSTHRU; } - ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket"); - time_t compare = isock->age; compare += RequestTimeout; @@ -347,28 +316,24 @@ class ModuleIdent : public Module if (ServerInstance->Time() >= compare) { /* Ident timeout */ - user->WriteServ("NOTICE Auth :*** Ident request timed out."); - ServerInstance->Logs->Log("m_ident",DEBUG, "Timeout"); + user->WriteNotice("*** Ident request timed out."); } else if (!isock->HasResult()) { // time still good, no result yet... hold the registration - ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet"); return MOD_RES_DENY; } - ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!"); - /* wooo, got a result (it will be good, or bad) */ if (isock->result.empty()) { user->ident.insert(user->ident.begin(), 1, '~'); - user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident.c_str()); + user->WriteNotice("*** Could not find your ident, using " + user->ident + " instead."); } else { user->ident = isock->result; - user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", user->ident.c_str()); + user->WriteNotice("*** Found your ident, '" + user->ident + "'"); } user->InvalidateCache(); @@ -377,35 +342,12 @@ class ModuleIdent : public Module return MOD_RES_PASSTHRU; } - ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) + ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE { if (myclass->config->getBool("requireident") && user->ident[0] == '~') return MOD_RES_DENY; return MOD_RES_PASSTHRU; } - - virtual void OnCleanup(int target_type, void *item) - { - /* Module unloading, tidy up users */ - if (target_type == TYPE_USER) - { - LocalUser* user = IS_LOCAL((User*) item); - if (user) - OnUserDisconnect(user); - } - } - - virtual void OnUserDisconnect(LocalUser *user) - { - /* User disconnect (generic socket detatch event) */ - IdentRequestSocket *isock = ext.get(user); - if (isock) - { - isock->Close(); - ext.unset(user); - } - } }; MODULE_INIT(ModuleIdent) - diff --git a/src/modules/m_inviteexception.cpp b/src/modules/m_inviteexception.cpp index 747a3b30a..6229e1fa2 100644 --- a/src/modules/m_inviteexception.cpp +++ b/src/modules/m_inviteexception.cpp @@ -22,10 +22,7 @@ #include "inspircd.h" -#include "u_listmode.h" - -/* $ModDesc: Provides support for the +I channel mode */ -/* $ModDep: ../../include/u_listmode.h */ +#include "listmode.h" /* * Written by Om <om@inspircd.org>, April 2005. @@ -54,27 +51,17 @@ public: { } - void init() - { - ServerInstance->Modules->AddService(ie); - - OnRehash(NULL); - ie.DoImplements(this); - Implementation eventlist[] = { I_On005Numeric, I_OnCheckInvite, I_OnCheckKey, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" INVEX=I"); + tokens["INVEX"] = "I"; } - ModResult OnCheckInvite(User* user, Channel* chan) + ModResult OnCheckInvite(User* user, Channel* chan) CXX11_OVERRIDE { - modelist* list = ie.extItem.get(chan); + ListModeBase::ModeList* list = ie.GetList(chan); if (list) { - for (modelist::iterator it = list->begin(); it != list->end(); it++) + for (ListModeBase::ModeList::iterator it = list->begin(); it != list->end(); it++) { if (chan->CheckBan(user, it->mask)) { @@ -86,25 +73,20 @@ public: return MOD_RES_PASSTHRU; } - ModResult OnCheckKey(User* user, Channel* chan, const std::string& key) + ModResult OnCheckKey(User* user, Channel* chan, const std::string& key) CXX11_OVERRIDE { if (invite_bypass_key) return OnCheckInvite(user, chan); return MOD_RES_PASSTHRU; } - void OnSyncChannel(Channel* chan, Module* proto, void* opaque) - { - ie.DoSyncChannel(chan, proto, opaque); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { invite_bypass_key = ServerInstance->Config->ConfValue("inviteexception")->getBool("bypasskey", true); ie.DoRehash(); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the +I channel mode", VF_VENDOR); } diff --git a/src/modules/m_ircv3.cpp b/src/modules/m_ircv3.cpp index da42d823d..caee0d329 100644 --- a/src/modules/m_ircv3.cpp +++ b/src/modules/m_ircv3.cpp @@ -16,119 +16,76 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -/* $ModDesc: Provides support for extended-join, away-notify and account-notify CAP capabilities */ - #include "inspircd.h" -#include "account.h" -#include "m_cap.h" +#include "modules/account.h" +#include "modules/cap.h" -class ModuleIRCv3 : public Module +class WriteNeighboursWithExt : public User::ForEachNeighborHandler { - GenericCap cap_accountnotify; - GenericCap cap_awaynotify; - GenericCap cap_extendedjoin; - bool accountnotify; - bool awaynotify; - bool extendedjoin; + const LocalIntExt& ext; + const std::string& msg; - CUList last_excepts; - - void WriteNeighboursWithExt(User* user, const std::string& line, const LocalIntExt& ext) + void Execute(LocalUser* user) CXX11_OVERRIDE { - UserChanList chans(user->chans); + if (ext.get(user)) + user->Write(msg); + } - std::map<User*, bool> exceptions; - FOREACH_MOD(I_OnBuildNeighborList, OnBuildNeighborList(user, chans, exceptions)); + public: + WriteNeighboursWithExt(User* user, const std::string& message, const LocalIntExt& extension) + : ext(extension) + , msg(message) + { + user->ForEachNeighbor(*this, false); + } +}; - // Send it to all local users who were explicitly marked as neighbours by modules and have the required ext - for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i) - { - LocalUser* u = IS_LOCAL(i->first); - if ((u) && (i->second) && (ext.get(u))) - u->Write(line); - } +class ModuleIRCv3 : public Module, public AccountEventListener +{ + GenericCap cap_accountnotify; + GenericCap cap_awaynotify; + GenericCap cap_extendedjoin; - // Now consider sending it to all other users who has at least a common channel with the user - std::set<User*> already_sent; - for (UCListIter i = chans.begin(); i != chans.end(); ++i) - { - const UserMembList* userlist = (*i)->GetUsers(); - for (UserMembList::const_iterator m = userlist->begin(); m != userlist->end(); ++m) - { - /* - * Send the line if the channel member in question meets all of the following criteria: - * - local - * - not the user who is doing the action (i.e. whose channels we're iterating) - * - has the given extension - * - not on the except list built by modules - * - we haven't sent the line to the member yet - * - */ - LocalUser* member = IS_LOCAL(m->first); - if ((member) && (member != user) && (ext.get(member)) && (exceptions.find(member) == exceptions.end()) && (already_sent.insert(member).second)) - member->Write(line); - } - } - } + CUList last_excepts; public: - ModuleIRCv3() : cap_accountnotify(this, "account-notify"), + ModuleIRCv3() + : AccountEventListener(this) + , cap_accountnotify(this, "account-notify"), cap_awaynotify(this, "away-notify"), cap_extendedjoin(this, "extended-join") { } - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnUserJoin, I_OnPostJoin, I_OnSetAway, I_OnEvent, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* conf = ServerInstance->Config->ConfValue("ircv3"); - accountnotify = conf->getBool("accountnotify", conf->getBool("accoutnotify", true)); - awaynotify = conf->getBool("awaynotify", true); - extendedjoin = conf->getBool("extendedjoin", true); + cap_accountnotify.SetActive(conf->getBool("accountnotify", true)); + cap_awaynotify.SetActive(conf->getBool("awaynotify", true)); + cap_extendedjoin.SetActive(conf->getBool("extendedjoin", true)); } - void OnEvent(Event& ev) + void OnAccountChange(User* user, const std::string& newaccount) CXX11_OVERRIDE { - if (awaynotify) - cap_awaynotify.HandleEvent(ev); - if (extendedjoin) - cap_extendedjoin.HandleEvent(ev); - - if (accountnotify) - { - cap_accountnotify.HandleEvent(ev); - - if (ev.id == "account_login") - { - AccountEvent* ae = static_cast<AccountEvent*>(&ev); - - // :nick!user@host ACCOUNT account - // or - // :nick!user@host ACCOUNT * - std::string line = ":" + ae->user->GetFullHost() + " ACCOUNT "; - if (ae->account.empty()) - line += "*"; - else - line += std::string(ae->account); - - WriteNeighboursWithExt(ae->user, line, cap_accountnotify.ext); - } - } + // :nick!user@host ACCOUNT account + // or + // :nick!user@host ACCOUNT * + std::string line = ":" + user->GetFullHost() + " ACCOUNT "; + if (newaccount.empty()) + line += "*"; + else + line += newaccount; + + WriteNeighboursWithExt(user, line, cap_accountnotify.ext); } - void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) + void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) CXX11_OVERRIDE { // Remember who is not going to see the JOIN because of other modules - if ((awaynotify) && (IS_AWAY(memb->user))) + if ((cap_awaynotify.IsActive()) && (memb->user->IsAway())) last_excepts = excepts; - if (!extendedjoin) + if (!cap_extendedjoin.IsActive()) return; /* @@ -143,8 +100,8 @@ class ModuleIRCv3 : public Module std::string line; std::string mode; - const UserMembList* userlist = memb->chan->GetUsers(); - for (UserMembCIter it = userlist->begin(); it != userlist->end(); ++it) + const Channel::MemberMap& userlist = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator it = userlist.begin(); it != userlist.end(); ++it) { // Send the extended join line if the current member is local, has the extended-join cap and isn't excepted User* member = IS_LOCAL(it->first); @@ -195,9 +152,9 @@ class ModuleIRCv3 : public Module } } - ModResult OnSetAway(User* user, const std::string &awaymsg) + ModResult OnSetAway(User* user, const std::string &awaymsg) CXX11_OVERRIDE { - if (awaynotify) + if (cap_awaynotify.IsActive()) { // Going away: n!u@h AWAY :reason // Back from away: n!u@h AWAY @@ -210,15 +167,15 @@ class ModuleIRCv3 : public Module return MOD_RES_PASSTHRU; } - void OnPostJoin(Membership *memb) + void OnPostJoin(Membership *memb) CXX11_OVERRIDE { - if ((!awaynotify) || (!IS_AWAY(memb->user))) + if ((!cap_awaynotify.IsActive()) || (!memb->user->IsAway())) return; std::string line = ":" + memb->user->GetFullHost() + " AWAY :" + memb->user->awaymsg; - const UserMembList* userlist = memb->chan->GetUsers(); - for (UserMembCIter it = userlist->begin(); it != userlist->end(); ++it) + const Channel::MemberMap& userlist = memb->chan->GetUsers(); + for (Channel::MemberMap::const_iterator it = userlist.begin(); it != userlist.end(); ++it) { // Send the away notify line if the current member is local, has the away-notify cap and isn't excepted User* member = IS_LOCAL(it->first); @@ -236,7 +193,7 @@ class ModuleIRCv3 : public Module ServerInstance->Modules->SetPriority(this, I_OnUserJoin, PRIORITY_LAST); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for extended-join, away-notify and account-notify CAP capabilities", VF_VENDOR); } diff --git a/src/modules/m_joinflood.cpp b/src/modules/m_joinflood.cpp index 63bcc38a4..52802f168 100644 --- a/src/modules/m_joinflood.cpp +++ b/src/modules/m_joinflood.cpp @@ -23,35 +23,32 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +j (join flood protection) */ - /** Holds settings and state associated with channel mode +j */ class joinfloodsettings { public: - int secs; - int joins; + unsigned int secs; + unsigned int joins; time_t reset; time_t unlocktime; - int counter; - bool locked; + unsigned int counter; - joinfloodsettings(int b, int c) : secs(b), joins(c) + joinfloodsettings(unsigned int b, unsigned int c) + : secs(b), joins(c), unlocktime(0), counter(0) { reset = ServerInstance->Time() + secs; - counter = 0; - locked = false; - }; + } void addjoin() { - counter++; if (ServerInstance->Time() > reset) { - counter = 0; + counter = 1; reset = ServerInstance->Time() + secs; } + else + counter++; } bool shouldlock() @@ -66,155 +63,87 @@ class joinfloodsettings bool islocked() { - if (locked) - { - if (ServerInstance->Time() > unlocktime) - { - locked = false; - return false; - } - else - { - return true; - } - } - return false; + if (ServerInstance->Time() > unlocktime) + unlocktime = 0; + + return (unlocktime != 0); } void lock() { - locked = true; unlocktime = ServerInstance->Time() + 60; } + bool operator==(const joinfloodsettings& other) const + { + return ((this->secs == other.secs) && (this->joins == other.joins)); + } }; /** Handles channel mode +j */ -class JoinFlood : public ModeHandler +class JoinFlood : public ParamMode<JoinFlood, SimpleExtItem<joinfloodsettings> > { public: - SimpleExtItem<joinfloodsettings> ext; - JoinFlood(Module* Creator) : ModeHandler(Creator, "joinflood", 'j', PARAM_SETONLY, MODETYPE_CHANNEL), - ext("joinflood", Creator) { } + JoinFlood(Module* Creator) + : ParamMode<JoinFlood, SimpleExtItem<joinfloodsettings> >(Creator, "joinflood", 'j') + { + } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) + std::string::size_type colon = parameter.find(':'); + if ((colon == std::string::npos) || (parameter.find('-') != std::string::npos)) { - char ndata[MAXBUF]; - char* data = ndata; - strlcpy(ndata,parameter.c_str(),MAXBUF); - char* joins = data; - char* secs = NULL; - while (*data) - { - if (*data == ':') - { - *data = 0; - data++; - secs = data; - break; - } - else data++; - } - if (secs) - - { - /* Set up the flood parameters for this channel */ - int njoins = atoi(joins); - int nsecs = atoi(secs); - if ((njoins<1) || (nsecs<1)) - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - parameter.clear(); - return MODEACTION_DENY; - } - else - { - joinfloodsettings* f = ext.get(channel); - if (!f) - { - parameter = ConvToStr(njoins) + ":" +ConvToStr(nsecs); - f = new joinfloodsettings(nsecs, njoins); - ext.set(channel, f); - channel->SetModeParam('j', parameter); - return MODEACTION_ALLOW; - } - else - { - std::string cur_param = channel->GetModeParameter('j'); - parameter = ConvToStr(njoins) + ":" +ConvToStr(nsecs); - if (cur_param == parameter) - { - // mode params match - return MODEACTION_DENY; - } - else - { - // new mode param, replace old with new - f = new joinfloodsettings(nsecs, njoins); - ext.set(channel, f); - channel->SetModeParam('j', parameter); - return MODEACTION_ALLOW; - } - } - } - } - else - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - return MODEACTION_DENY; - } + source->WriteNumeric(608, "%s :Invalid flood parameter",channel->name.c_str()); + return MODEACTION_DENY; } - else + + /* Set up the flood parameters for this channel */ + unsigned int njoins = ConvToInt(parameter.substr(0, colon)); + unsigned int nsecs = ConvToInt(parameter.substr(colon+1)); + if ((njoins<1) || (nsecs<1)) { - if (channel->IsModeSet('j')) - { - ext.unset(channel); - channel->SetModeParam('j', ""); - return MODEACTION_ALLOW; - } + source->WriteNumeric(608, "%s :Invalid flood parameter",channel->name.c_str()); + return MODEACTION_DENY; } - return MODEACTION_DENY; + + ext.set(channel, new joinfloodsettings(nsecs, njoins)); + return MODEACTION_ALLOW; + } + + void SerializeParam(Channel* chan, const joinfloodsettings* jfs, std::string& out) + { + out.append(ConvToStr(jfs->joins)).push_back(':'); + out.append(ConvToStr(jfs->secs)); } }; class ModuleJoinFlood : public Module { - JoinFlood jf; public: - ModuleJoinFlood() : jf(this) { } - void init() - { - ServerInstance->Modules->AddService(jf); - ServerInstance->Modules->AddService(jf.ext); - Implementation eventlist[] = { I_OnUserPreJoin, I_OnUserJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (chan) { joinfloodsettings *f = jf.ext.get(chan); if (f && f->islocked()) { - user->WriteNumeric(609, "%s %s :This channel is temporarily unavailable (+j). Please try again later.",user->nick.c_str(),chan->name.c_str()); + user->WriteNumeric(609, "%s :This channel is temporarily unavailable (+j). Please try again later.",chan->name.c_str()); return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) + void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) CXX11_OVERRIDE { /* We arent interested in JOIN events caused by a network burst */ if (sync) @@ -235,11 +164,7 @@ class ModuleJoinFlood : public Module } } - ~ModuleJoinFlood() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +j (join flood protection)", VF_VENDOR); } diff --git a/src/modules/m_jumpserver.cpp b/src/modules/m_jumpserver.cpp index dce8f0bd5..599144448 100644 --- a/src/modules/m_jumpserver.cpp +++ b/src/modules/m_jumpserver.cpp @@ -20,8 +20,7 @@ #include "inspircd.h" - -/* $ModDesc: Provides support for the RPL_REDIR numeric and the /JUMPSERVER command. */ +#include "modules/ssl.h" /** Handle /JUMPSERVER */ @@ -32,11 +31,14 @@ class CommandJumpserver : public Command std::string redirect_to; std::string reason; int port; + int sslport; CommandJumpserver(Module* Creator) : Command(Creator, "JUMPSERVER", 0, 4) { - flags_needed = 'o'; syntax = "[<server> <port> <+/-an> <reason>]"; + flags_needed = 'o'; + syntax = "[<server> <port>[:<sslport>] <+/-an> <reason>]"; port = 0; + sslport = 0; redirect_new_users = false; } @@ -53,11 +55,12 @@ class CommandJumpserver : public Command if (!parameters.size()) { if (port) - user->WriteServ("NOTICE %s :*** Disabled jumpserver (previously set to '%s:%d')", user->nick.c_str(), redirect_to.c_str(), port); + user->WriteNotice("*** Disabled jumpserver (previously set to '" + redirect_to + ":" + ConvToStr(port) + "')"); else - user->WriteServ("NOTICE %s :*** Jumpserver was not enabled.", user->nick.c_str()); + user->WriteNotice("*** Jumpserver was not enabled."); port = 0; + sslport = 0; redirect_to.clear(); return CMD_SUCCESS; } @@ -84,27 +87,34 @@ class CommandJumpserver : public Command redirect_new_users = direction; break; default: - user->WriteServ("NOTICE %s :*** Invalid JUMPSERVER flag: %c", user->nick.c_str(), *n); + user->WriteNotice("*** Invalid JUMPSERVER flag: " + ConvToStr(*n)); return CMD_FAILURE; break; } } - if (!atoi(parameters[1].c_str())) + size_t delimpos = parameters[1].find(':'); + port = ConvToInt(parameters[1].substr(0, delimpos ? delimpos : std::string::npos)); + sslport = (delimpos == std::string::npos ? 0 : ConvToInt(parameters[1].substr(delimpos + 1))); + + if (parameters[1].find_first_not_of("0123456789:") != std::string::npos + || parameters[1].rfind(':') != delimpos + || port > 65535 || sslport > 65535) { - user->WriteServ("NOTICE %s :*** Invalid port number", user->nick.c_str()); + user->WriteNotice("*** Invalid port number"); return CMD_FAILURE; } if (redirect_all_immediately) { /* Redirect everyone but the oper sending the command */ - for (LocalUserList::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); ++i) + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i) { - User* t = *i; - if (!IS_OPER(t)) + LocalUser* t = *i; + if (!t->IsOper()) { - t->WriteNumeric(10, "%s %s %s :Please use this Server/Port instead", t->nick.c_str(), parameters[0].c_str(), parameters[1].c_str()); + t->WriteNumeric(RPL_REDIR, "%s %d :Please use this Server/Port instead", parameters[0].c_str(), GetPort(t)); ServerInstance->Users->QuitUser(t, reason); n_done++; } @@ -116,24 +126,24 @@ class CommandJumpserver : public Command } if (redirect_new_users) - { redirect_to = parameters[0]; - port = atoi(parameters[1].c_str()); - } - user->WriteServ("NOTICE %s :*** Set jumpserver to server '%s' port '%s', flags '+%s%s'%s%s%s: %s", user->nick.c_str(), parameters[0].c_str(), parameters[1].c_str(), - redirect_all_immediately ? "a" : "", - redirect_new_users ? "n" : "", - n_done ? " (" : "", - n_done ? n_done_s.c_str() : "", - n_done ? " user(s) redirected)" : "", - reason.c_str()); + user->WriteNotice("*** Set jumpserver to server '" + parameters[0] + "' port '" + (port ? ConvToStr(port) : "Auto") + ", SSL " + (sslport ? ConvToStr(sslport) : "Auto") + "', flags '+" + + (redirect_all_immediately ? "a" : "") + (redirect_new_users ? "n'" : "'") + + (n_done ? " (" + n_done_s + "user(s) redirected): " : ": ") + reason); } return CMD_SUCCESS; } -}; + int GetPort(LocalUser* user) + { + int p = (SSLClientCert::GetCertificate(&user->eh) ? sslport : port); + if (p == 0) + p = user->GetServerPort(); + return p; + } +}; class ModuleJumpServer : public Module { @@ -143,40 +153,30 @@ class ModuleJumpServer : public Module { } - void init() + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(js); - Implementation eventlist[] = { I_OnUserRegister, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleJumpServer() - { - } - - virtual ModResult OnUserRegister(LocalUser* user) - { - if (js.port && js.redirect_new_users) + if (js.redirect_new_users) { - user->WriteNumeric(10, "%s %s %d :Please use this Server/Port instead", - user->nick.c_str(), js.redirect_to.c_str(), js.port); + int port = js.GetPort(user); + user->WriteNumeric(RPL_REDIR, "%s %d :Please use this Server/Port instead", + js.redirect_to.c_str(), port); ServerInstance->Users->QuitUser(user, js.reason); return MOD_RES_PASSTHRU; } return MOD_RES_PASSTHRU; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { // Emergency way to unlock - if (!user) js.redirect_new_users = false; + if (!status.srcuser) + js.redirect_new_users = false; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the RPL_REDIR numeric and the /JUMPSERVER command.", VF_VENDOR); } - }; MODULE_INIT(ModuleJumpServer) diff --git a/src/modules/m_kicknorejoin.cpp b/src/modules/m_kicknorejoin.cpp index a914f3869..b8a776667 100644 --- a/src/modules/m_kicknorejoin.cpp +++ b/src/modules/m_kicknorejoin.cpp @@ -25,49 +25,94 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +J (delay rejoin after kick) */ +class KickRejoinData +{ + struct KickedUser + { + std::string uuid; + time_t expire; + + KickedUser(User* user, unsigned int Delay) + : uuid(user->uuid) + , expire(ServerInstance->Time() + Delay) + { + } + }; + + typedef std::vector<KickedUser> KickedList; + + mutable KickedList kicked; + + public: + const unsigned int delay; + + KickRejoinData(unsigned int Delay) : delay(Delay) { } + + bool canjoin(LocalUser* user) const + { + for (KickedList::iterator i = kicked.begin(); i != kicked.end(); ) + { + KickedUser& rec = *i; + if (rec.expire > ServerInstance->Time()) + { + if (rec.uuid == user->uuid) + return false; + ++i; + } + else + { + // Expired record, remove. + stdalgo::vector::swaperase(kicked, i); + if (kicked.empty()) + break; + } + } + return true; + } -typedef std::map<std::string, time_t> delaylist; + void add(User* user) + { + // One user can be in the list multiple times if the user gets kicked, force joins + // (skipping OnUserPreJoin) and gets kicked again, but that's okay because canjoin() + // works correctly in this case as well + kicked.push_back(KickedUser(user, delay)); + } +}; /** Handles channel mode +J */ -class KickRejoin : public ModeHandler +class KickRejoin : public ParamMode<KickRejoin, SimpleExtItem<KickRejoinData> > { + const unsigned int max; public: - unsigned int max; - SimpleExtItem<delaylist> ext; KickRejoin(Module* Creator) - : ModeHandler(Creator, "kicknorejoin", 'J', PARAM_SETONLY, MODETYPE_CHANNEL) - , ext("norejoinusers", Creator) + : ParamMode<KickRejoin, SimpleExtItem<KickRejoinData> >(Creator, "kicknorejoin", 'J') + , max(60) { } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) - { - int v = ConvToInt(parameter); - if (v <= 0) - return MODEACTION_DENY; - if (parameter == channel->GetModeParameter(this)) - return MODEACTION_DENY; + int v = ConvToInt(parameter); + if (v <= 0) + return MODEACTION_DENY; - if ((IS_LOCAL(source) && ((unsigned int)v > max))) - v = max; + if ((IS_LOCAL(source) && ((unsigned int)v > max))) + v = max; - parameter = ConvToStr(v); - channel->SetModeParam(this, parameter); - } - else - { - if (!channel->IsModeSet(this)) - return MODEACTION_DENY; - - ext.unset(channel); - channel->SetModeParam(this, ""); - } + ext.set(channel, new KickRejoinData(v)); return MODEACTION_ALLOW; } + + void SerializeParam(Channel* chan, const KickRejoinData* krd, std::string& out) + { + out.append(ConvToStr(krd->delay)); + } + + std::string GetModuleSettings() const + { + return ConvToStr(max); + } }; class ModuleKickNoRejoin : public Module @@ -75,85 +120,41 @@ class ModuleKickNoRejoin : public Module KickRejoin kr; public: - ModuleKickNoRejoin() : kr(this) { } - void init() - { - ServerInstance->Modules->AddService(kr); - ServerInstance->Modules->AddService(kr.ext); - Implementation eventlist[] = { I_OnUserPreJoin, I_OnUserKick, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - - void OnRehash(User* user) - { - kr.max = ServerInstance->Duration(ServerInstance->Config->ConfValue("kicknorejoin")->getString("maxtime")); - if (!kr.max) - kr.max = 30*60; - } - - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (chan) { - delaylist* dl = kr.ext.get(chan); - if (dl) + const KickRejoinData* data = kr.ext.get(chan); + if ((data) && (!data->canjoin(user))) { - for (delaylist::iterator iter = dl->begin(); iter != dl->end(); ) - { - if (iter->second > ServerInstance->Time()) - { - if (iter->first == user->uuid) - { - std::string modeparam = chan->GetModeParameter(&kr); - user->WriteNumeric(ERR_DELAYREJOIN, "%s %s :You must wait %s seconds after being kicked to rejoin (+J)", - user->nick.c_str(), chan->name.c_str(), modeparam.c_str()); - return MOD_RES_DENY; - } - ++iter; - } - else - { - // Expired record, remove. - dl->erase(iter++); - } - } - - if (dl->empty()) - kr.ext.unset(chan); + user->WriteNumeric(ERR_DELAYREJOIN, "%s :You must wait %u seconds after being kicked to rejoin (+J)", chan->name.c_str(), data->delay); + return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) + void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) CXX11_OVERRIDE { - if (memb->chan->IsModeSet(&kr) && (IS_LOCAL(memb->user)) && (source != memb->user)) + if ((!IS_LOCAL(memb->user)) || (source == memb->user)) + return; + + KickRejoinData* data = kr.ext.get(memb->chan); + if (data) { - delaylist* dl = kr.ext.get(memb->chan); - if (!dl) - { - dl = new delaylist; - kr.ext.set(memb->chan, dl); - } - (*dl)[memb->user->uuid] = ServerInstance->Time() + ConvToInt(memb->chan->GetModeParameter(&kr)); + data->add(memb->user); } } - ~ModuleKickNoRejoin() + Version GetVersion() CXX11_OVERRIDE { - } - - Version GetVersion() - { - return Version("Channel mode to delay rejoin after kick", VF_VENDOR); + return Version("Channel mode to delay rejoin after kick", VF_VENDOR | VF_COMMON, kr.GetModuleSettings()); } }; - MODULE_INIT(ModuleKickNoRejoin) diff --git a/src/modules/m_knock.cpp b/src/modules/m_knock.cpp index 8d2aa4543..26397bc9c 100644 --- a/src/modules/m_knock.cpp +++ b/src/modules/m_knock.cpp @@ -21,20 +21,23 @@ #include "inspircd.h" -/* $ModDesc: Provides support for /KNOCK and channel mode +K */ - /** Handles the /KNOCK command */ class CommandKnock : public Command { + SimpleChannelModeHandler& noknockmode; + ChanModeReference inviteonlymode; + public: bool sendnotice; bool sendnumeric; - CommandKnock(Module* Creator) : Command(Creator,"KNOCK", 2, 2) + CommandKnock(Module* Creator, SimpleChannelModeHandler& Noknockmode) + : Command(Creator,"KNOCK", 2, 2) + , noknockmode(Noknockmode) + , inviteonlymode(Creator, "inviteonly") { syntax = "<channel> <reason>"; Penalty = 5; - TRANSLATE3(TR_TEXT, TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -42,25 +45,25 @@ class CommandKnock : public Command Channel* c = ServerInstance->FindChan(parameters[0]); if (!c) { - user->WriteNumeric(401, "%s %s :No such channel",user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such channel", parameters[0].c_str()); return CMD_FAILURE; } if (c->HasUser(user)) { - user->WriteNumeric(480, "%s :Can't KNOCK on %s, you are already on that channel.", user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(ERR_KNOCKONCHAN, "%s :Can't KNOCK on %s, you are already on that channel.", c->name.c_str(), c->name.c_str()); return CMD_FAILURE; } - if (c->IsModeSet('K')) + if (c->IsModeSet(noknockmode)) { - user->WriteNumeric(480, "%s :Can't KNOCK on %s, +K is set.",user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(480, ":Can't KNOCK on %s, +K is set.", c->name.c_str()); return CMD_FAILURE; } - if (!c->IsModeSet('i')) + if (!c->IsModeSet(inviteonlymode)) { - user->WriteNumeric(480, "%s :Can't KNOCK on %s, channel is not invite only so knocking is pointless!",user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(ERR_CHANOPEN, "%s :Can't KNOCK on %s, channel is not invite only so knocking is pointless!", c->name.c_str(), c->name.c_str()); return CMD_FAILURE; } @@ -70,7 +73,7 @@ class CommandKnock : public Command if (sendnumeric) c->WriteChannelWithServ(ServerInstance->Config->ServerName, "710 %s %s %s :is KNOCKing: %s", c->name.c_str(), c->name.c_str(), user->GetFullHost().c_str(), parameters[1].c_str()); - user->WriteServ("NOTICE %s :KNOCKing on %s", user->nick.c_str(), c->name.c_str()); + user->WriteNotice("KNOCKing on " + c->name); return CMD_SUCCESS; } @@ -80,33 +83,19 @@ class CommandKnock : public Command } }; -/** Handles channel mode +K - */ -class Knock : public SimpleChannelModeHandler -{ - public: - Knock(Module* Creator) : SimpleChannelModeHandler(Creator, "noknock", 'K') { } -}; - class ModuleKnock : public Module { + SimpleChannelModeHandler kn; CommandKnock cmd; - Knock kn; - public: - ModuleKnock() : cmd(this), kn(this) - { - } - void init() + public: + ModuleKnock() + : kn(this, "noknock", 'K') + , cmd(this, kn) { - ServerInstance->Modules->AddService(kn); - ServerInstance->Modules->AddService(cmd); - - ServerInstance->Modules->Attach(I_OnRehash, this); - OnRehash(NULL); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { std::string knocknotify = ServerInstance->Config->ConfValue("knock")->getString("notify"); irc::string notify(knocknotify.c_str()); @@ -128,7 +117,7 @@ class ModuleKnock : public Module } } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for /KNOCK and channel mode +K", VF_OPTCOMMON | VF_VENDOR); } diff --git a/src/modules/m_ldapauth.cpp b/src/modules/m_ldapauth.cpp new file mode 100644 index 000000000..7da63284a --- /dev/null +++ b/src/modules/m_ldapauth.cpp @@ -0,0 +1,434 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Adam <Adam@anope.org> + * Copyright (C) 2011 Pierre Carrier <pierre@spotify.com> + * Copyright (C) 2009-2010 Robin Burchell <robin+git@viroteck.net> + * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> + * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> + * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> + * Copyright (C) 2008 Dennis Friis <peavey@inspircd.org> + * Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "modules/ldap.h" + +namespace +{ + Module* me; + std::string killreason; + LocalIntExt* authed; + bool verbose; + std::string vhost; + LocalStringExt* vhosts; + std::vector<std::pair<std::string, std::string> > requiredattributes; +} + +class BindInterface : public LDAPInterface +{ + const std::string provider; + const std::string uid; + std::string DN; + bool checkingAttributes; + bool passed; + int attrCount; + + static std::string SafeReplace(const std::string& text, std::map<std::string, std::string>& replacements) + { + std::string result; + result.reserve(text.length()); + + for (unsigned int i = 0; i < text.length(); ++i) + { + char c = text[i]; + if (c == '$') + { + // find the first nonalpha + i++; + unsigned int start = i; + + while (i < text.length() - 1 && isalpha(text[i + 1])) + ++i; + + std::string key(text, start, (i - start) + 1); + result.append(replacements[key]); + } + else + result.push_back(c); + } + + return result; + } + + static void SetVHost(User* user, const std::string& DN) + { + if (!vhost.empty()) + { + irc::commasepstream stream(DN); + + // mashed map of key:value parts of the DN + std::map<std::string, std::string> dnParts; + + std::string dnPart; + while (stream.GetToken(dnPart)) + { + std::string::size_type pos = dnPart.find('='); + if (pos == std::string::npos) // malformed + continue; + + std::string key(dnPart, 0, pos); + std::string value(dnPart, pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself + dnParts[key] = value; + } + + // change host according to config key + vhosts->set(user, SafeReplace(vhost, dnParts)); + } + } + + public: + BindInterface(Module* c, const std::string& p, const std::string& u, const std::string& dn) + : LDAPInterface(c) + , provider(p), uid(u), DN(dn), checkingAttributes(false), passed(false), attrCount(0) + { + } + + void OnResult(const LDAPResult& r) CXX11_OVERRIDE + { + User* user = ServerInstance->FindUUID(uid); + dynamic_reference<LDAPProvider> LDAP(me, provider); + + if (!user || !LDAP) + { + if (!checkingAttributes || !--attrCount) + delete this; + return; + } + + if (!checkingAttributes && requiredattributes.empty()) + { + // We're done, there are no attributes to check + SetVHost(user, DN); + authed->set(user, 1); + + delete this; + return; + } + + // Already checked attributes? + if (checkingAttributes) + { + if (!passed) + { + // Only one has to pass + passed = true; + + SetVHost(user, DN); + authed->set(user, 1); + } + + // Delete this if this is the last ref + if (!--attrCount) + delete this; + + return; + } + + // check required attributes + checkingAttributes = true; + + for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it) + { + // Note that only one of these has to match for it to be success + const std::string& attr = it->first; + const std::string& val = it->second; + + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str()); + try + { + LDAP->Compare(this, DN, attr, val); + ++attrCount; + } + catch (LDAPException &ex) + { + if (verbose) + ServerInstance->SNO->WriteToSnoMask('c', "Unable to compare attributes %s=%s: %s", attr.c_str(), val.c_str(), ex.GetReason().c_str()); + } + } + + // Nothing done + if (!attrCount) + { + if (verbose) + ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (unable to validate attributes)", user->GetFullRealHost().c_str()); + ServerInstance->Users->QuitUser(user, killreason); + delete this; + } + } + + void OnError(const LDAPResult& err) CXX11_OVERRIDE + { + if (checkingAttributes && --attrCount) + return; + + if (passed) + { + delete this; + return; + } + + User* user = ServerInstance->FindUUID(uid); + if (user) + { + if (verbose) + ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), err.getError().c_str()); + ServerInstance->Users->QuitUser(user, killreason); + } + + delete this; + } +}; + +class SearchInterface : public LDAPInterface +{ + const std::string provider; + const std::string uid; + + public: + SearchInterface(Module* c, const std::string& p, const std::string& u) + : LDAPInterface(c), provider(p), uid(u) + { + } + + void OnResult(const LDAPResult& r) CXX11_OVERRIDE + { + LocalUser* user = static_cast<LocalUser*>(ServerInstance->FindUUID(uid)); + dynamic_reference<LDAPProvider> LDAP(me, provider); + if (!LDAP || r.empty() || !user) + { + if (user) + ServerInstance->Users->QuitUser(user, killreason); + delete this; + return; + } + + try + { + const LDAPAttributes& a = r.get(0); + std::string bindDn = a.get("dn"); + if (bindDn.empty()) + { + ServerInstance->Users->QuitUser(user, killreason); + delete this; + return; + } + + LDAP->Bind(new BindInterface(this->creator, provider, uid, bindDn), bindDn, user->password); + } + catch (LDAPException& ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason()); + } + delete this; + } + + void OnError(const LDAPResult& err) CXX11_OVERRIDE + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: %s", err.getError().c_str()); + User* user = ServerInstance->FindUUID(uid); + if (user) + ServerInstance->Users->QuitUser(user, killreason); + delete this; + } +}; + +class AdminBindInterface : public LDAPInterface +{ + const std::string provider; + const std::string uuid; + const std::string base; + const std::string what; + + public: + AdminBindInterface(Module* c, const std::string& p, const std::string& u, const std::string& b, const std::string& w) + : LDAPInterface(c), provider(p), uuid(u), base(b), what(w) + { + } + + void OnResult(const LDAPResult& r) CXX11_OVERRIDE + { + dynamic_reference<LDAPProvider> LDAP(me, provider); + if (LDAP) + { + try + { + LDAP->Search(new SearchInterface(this->creator, provider, uuid), base, what); + } + catch (LDAPException& ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason()); + } + } + delete this; + } + + void OnError(const LDAPResult& err) CXX11_OVERRIDE + { + ServerInstance->SNO->WriteToSnoMask('a', "Error binding as manager to LDAP server: " + err.getError()); + delete this; + } +}; + +class ModuleLDAPAuth : public Module +{ + dynamic_reference<LDAPProvider> LDAP; + LocalIntExt ldapAuthed; + LocalStringExt ldapVhost; + std::string base; + std::string attribute; + std::vector<std::string> allowpatterns; + std::vector<std::string> whitelistedcidrs; + bool useusername; + +public: + ModuleLDAPAuth() + : LDAP(this, "LDAP") + , ldapAuthed("ldapauth", ExtensionItem::EXT_USER, this) + , ldapVhost("ldapauth_vhost", ExtensionItem::EXT_USER, this) + { + me = this; + authed = &ldapAuthed; + vhosts = &ldapVhost; + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth"); + whitelistedcidrs.clear(); + requiredattributes.clear(); + + base = tag->getString("baserdn"); + attribute = tag->getString("attribute"); + killreason = tag->getString("killreason"); + vhost = tag->getString("host"); + // Set to true if failed connects should be reported to operators + verbose = tag->getBool("verbose"); + useusername = tag->getBool("userfield"); + + LDAP.SetProvider("LDAP/" + tag->getString("dbid")); + + ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist"); + + for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i) + { + std::string cidr = i->second->getString("cidr"); + if (!cidr.empty()) { + whitelistedcidrs.push_back(cidr); + } + } + + ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire"); + + for (ConfigIter i = attributetags.first; i != attributetags.second; ++i) + { + const std::string attr = i->second->getString("attribute"); + const std::string val = i->second->getString("value"); + + if (!attr.empty() && !val.empty()) + requiredattributes.push_back(make_pair(attr, val)); + } + + std::string allowpattern = tag->getString("allowpattern"); + irc::spacesepstream ss(allowpattern); + for (std::string more; ss.GetToken(more); ) + { + allowpatterns.push_back(more); + } + } + + void OnUserConnect(LocalUser *user) CXX11_OVERRIDE + { + std::string* cc = ldapVhost.get(user); + if (cc) + { + user->ChangeDisplayedHost(*cc); + ldapVhost.unset(user); + } + } + + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE + { + for (std::vector<std::string>::const_iterator i = allowpatterns.begin(); i != allowpatterns.end(); ++i) + { + if (InspIRCd::Match(user->nick, *i)) + { + ldapAuthed.set(user,1); + return MOD_RES_PASSTHRU; + } + } + + for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++) + { + if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map)) + { + ldapAuthed.set(user,1); + return MOD_RES_PASSTHRU; + } + } + + if (user->password.empty()) + { + if (verbose) + ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str()); + ServerInstance->Users->QuitUser(user, killreason); + return MOD_RES_DENY; + } + + if (!LDAP) + { + if (verbose) + ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Unable to find LDAP provider)", user->GetFullRealHost().c_str()); + ServerInstance->Users->QuitUser(user, killreason); + return MOD_RES_DENY; + } + + try + { + std::string what = attribute + "=" + (useusername ? user->ident : user->nick); + LDAP->BindAsManager(new AdminBindInterface(this, LDAP.GetProvider(), user->uuid, base, what)); + } + catch (LDAPException &ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "LDAP exception: " + ex.GetReason()); + ServerInstance->Users->QuitUser(user, killreason); + } + + return MOD_RES_DENY; + } + + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE + { + return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY; + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleLDAPAuth) diff --git a/src/modules/m_ldapoper.cpp b/src/modules/m_ldapoper.cpp new file mode 100644 index 000000000..9deb9a203 --- /dev/null +++ b/src/modules/m_ldapoper.cpp @@ -0,0 +1,248 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Adam <Adam@anope.org> + * Copyright (C) 2009 Robin Burchell <robin+git@viroteck.net> + * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> + * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> + * Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "modules/ldap.h" + +namespace +{ + Module* me; +} + +class LDAPOperBase : public LDAPInterface +{ + protected: + const std::string uid; + const std::string opername; + const std::string password; + + void Fallback(User* user) + { + if (!user) + return; + + Command* oper_command = ServerInstance->Parser.GetHandler("OPER"); + if (!oper_command) + return; + + std::vector<std::string> params; + params.push_back(opername); + params.push_back(password); + oper_command->Handle(params, user); + } + + void Fallback() + { + User* user = ServerInstance->FindUUID(uid); + Fallback(user); + } + + public: + LDAPOperBase(Module* mod, const std::string& uuid, const std::string& oper, const std::string& pass) + : LDAPInterface(mod) + , uid(uuid), opername(oper), password(pass) + { + } + + void OnError(const LDAPResult& err) CXX11_OVERRIDE + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: %s", err.getError().c_str()); + Fallback(); + delete this; + } +}; + +class BindInterface : public LDAPOperBase +{ + public: + BindInterface(Module* mod, const std::string& uuid, const std::string& oper, const std::string& pass) + : LDAPOperBase(mod, uuid, oper, pass) + { + } + + void OnResult(const LDAPResult& r) CXX11_OVERRIDE + { + User* user = ServerInstance->FindUUID(uid); + ServerConfig::OperIndex::const_iterator iter = ServerInstance->Config->oper_blocks.find(opername); + + if (!user || iter == ServerInstance->Config->oper_blocks.end()) + { + Fallback(); + delete this; + return; + } + + OperInfo* ifo = iter->second; + user->Oper(ifo); + delete this; + } +}; + +class SearchInterface : public LDAPOperBase +{ + const std::string provider; + + bool HandleResult(const LDAPResult& result) + { + dynamic_reference<LDAPProvider> LDAP(me, provider); + if (!LDAP || result.empty()) + return false; + + try + { + const LDAPAttributes& attr = result.get(0); + std::string bindDn = attr.get("dn"); + if (bindDn.empty()) + return false; + + LDAP->Bind(new BindInterface(this->creator, uid, opername, password), bindDn, password); + } + catch (LDAPException& ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason()); + } + + return true; + } + + public: + SearchInterface(Module* mod, const std::string& prov, const std::string &uuid, const std::string& oper, const std::string& pass) + : LDAPOperBase(mod, uuid, oper, pass) + , provider(prov) + { + } + + void OnResult(const LDAPResult& result) CXX11_OVERRIDE + { + if (!HandleResult(result)) + Fallback(); + delete this; + } +}; + +class AdminBindInterface : public LDAPInterface +{ + const std::string provider; + const std::string user; + const std::string opername; + const std::string password; + const std::string base; + const std::string what; + + public: + AdminBindInterface(Module* c, const std::string& p, const std::string& u, const std::string& o, const std::string& pa, const std::string& b, const std::string& w) + : LDAPInterface(c), provider(p), user(u), opername(p), password(pa), base(b), what(w) + { + } + + void OnResult(const LDAPResult& r) CXX11_OVERRIDE + { + dynamic_reference<LDAPProvider> LDAP(me, provider); + if (LDAP) + { + try + { + LDAP->Search(new SearchInterface(this->creator, provider, user, opername, password), base, what); + } + catch (LDAPException& ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason()); + } + } + delete this; + } + + void OnError(const LDAPResult& err) CXX11_OVERRIDE + { + ServerInstance->SNO->WriteToSnoMask('a', "Error binding as manager to LDAP server: " + err.getError()); + delete this; + } +}; + +class ModuleLDAPAuth : public Module +{ + dynamic_reference<LDAPProvider> LDAP; + std::string base; + std::string attribute; + + public: + ModuleLDAPAuth() + : LDAP(this, "LDAP") + { + me = this; + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* tag = ServerInstance->Config->ConfValue("ldapoper"); + + LDAP.SetProvider("LDAP/" + tag->getString("dbid")); + base = tag->getString("baserdn"); + attribute = tag->getString("attribute"); + } + + ModResult OnPreCommand(std::string& command, std::vector<std::string>& parameters, LocalUser* user, bool validated, const std::string& original_line) CXX11_OVERRIDE + { + if (validated && command == "OPER" && parameters.size() >= 2) + { + const std::string& opername = parameters[0]; + const std::string& password = parameters[1]; + + ServerConfig::OperIndex::const_iterator it = ServerInstance->Config->oper_blocks.find(opername); + if (it == ServerInstance->Config->oper_blocks.end()) + return MOD_RES_PASSTHRU; + + ConfigTag* tag = it->second->oper_block; + if (!tag) + return MOD_RES_PASSTHRU; + + std::string acceptedhosts = tag->getString("host"); + std::string hostname = user->ident + "@" + user->host; + if (!InspIRCd::MatchMask(acceptedhosts, hostname, user->GetIPString())) + return MOD_RES_PASSTHRU; + + if (!LDAP) + return MOD_RES_PASSTHRU; + + try + { + std::string what = attribute + "=" + opername; + LDAP->BindAsManager(new AdminBindInterface(this, LDAP.GetProvider(), user->uuid, opername, password, base, what)); + return MOD_RES_DENY; + } + catch (LDAPException& ex) + { + ServerInstance->SNO->WriteToSnoMask('a', "LDAP exception: " + ex.GetReason()); + } + } + + return MOD_RES_PASSTHRU; + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Adds the ability to authenticate opers via LDAP", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleLDAPAuth) diff --git a/src/modules/m_lockserv.cpp b/src/modules/m_lockserv.cpp index 4983ae16a..65b9aa036 100644 --- a/src/modules/m_lockserv.cpp +++ b/src/modules/m_lockserv.cpp @@ -20,18 +20,16 @@ #include "inspircd.h" -/* $ModDesc: Allows locking of the server to stop all incoming connections till unlocked again */ - /** Adds numerics * 988 <nick> <servername> :Closed for new connections * 989 <nick> <servername> :Open for new connections -*/ - + */ class CommandLockserv : public Command { bool& locked; -public: + + public: CommandLockserv(Module* Creator, bool& lock) : Command(Creator, "LOCKSERV", 0), locked(lock) { flags_needed = 'o'; @@ -41,12 +39,12 @@ public: { if (locked) { - user->WriteServ("NOTICE %s :The server is already locked.", user->nick.c_str()); + user->WriteNotice("The server is already locked."); return CMD_FAILURE; } locked = true; - user->WriteNumeric(988, "%s %s :Closed for new connections", user->nick.c_str(), user->server.c_str()); + user->WriteNumeric(988, "%s :Closed for new connections", user->server->GetName().c_str()); ServerInstance->SNO->WriteGlobalSno('a', "Oper %s used LOCKSERV to temporarily disallow new connections", user->nick.c_str()); return CMD_SUCCESS; } @@ -54,10 +52,9 @@ public: class CommandUnlockserv : public Command { -private: bool& locked; -public: + public: CommandUnlockserv(Module* Creator, bool &lock) : Command(Creator, "UNLOCKSERV", 0), locked(lock) { flags_needed = 'o'; @@ -67,12 +64,12 @@ public: { if (!locked) { - user->WriteServ("NOTICE %s :The server isn't locked.", user->nick.c_str()); + user->WriteNotice("The server isn't locked."); return CMD_FAILURE; } locked = false; - user->WriteNumeric(989, "%s %s :Open for new connections", user->nick.c_str(), user->server.c_str()); + user->WriteNumeric(989, "%s :Open for new connections", user->server->GetName().c_str()); ServerInstance->SNO->WriteGlobalSno('a', "Oper %s used UNLOCKSERV to allow new connections", user->nick.c_str()); return CMD_SUCCESS; } @@ -80,37 +77,28 @@ public: class ModuleLockserv : public Module { -private: bool locked; CommandLockserv lockcommand; CommandUnlockserv unlockcommand; -public: + public: ModuleLockserv() : lockcommand(this, locked), unlockcommand(this, locked) { } - void init() + void init() CXX11_OVERRIDE { locked = false; - ServerInstance->Modules->AddService(lockcommand); - ServerInstance->Modules->AddService(unlockcommand); - Implementation eventlist[] = { I_OnUserRegister, I_OnRehash, I_OnCheckReady }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual ~ModuleLockserv() - { - } - - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { // Emergency way to unlock - if (!user) locked = false; + if (!status.srcuser) + locked = false; } - virtual ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { if (locked) { @@ -120,12 +108,12 @@ public: return MOD_RES_PASSTHRU; } - virtual ModResult OnCheckReady(LocalUser* user) + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE { return locked ? MOD_RES_DENY : MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows locking of the server to stop all incoming connections until unlocked again", VF_VENDOR); } diff --git a/src/modules/m_maphide.cpp b/src/modules/m_maphide.cpp index 546e342ae..41de2997d 100644 --- a/src/modules/m_maphide.cpp +++ b/src/modules/m_maphide.cpp @@ -19,44 +19,30 @@ #include "inspircd.h" -/* $ModDesc: Hide /MAP and /LINKS in the same form as ircu (mostly useless) */ - class ModuleMapHide : public Module { std::string url; public: - void init() - { - Implementation eventlist[] = { I_OnPreCommand, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { url = ServerInstance->Config->ConfValue("security")->getString("maphide"); } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { - if (validated && !IS_OPER(user) && !url.empty() && (command == "MAP" || command == "LINKS")) + if (validated && !user->IsOper() && !url.empty() && (command == "MAP" || command == "LINKS")) { - user->WriteServ("NOTICE %s :/%s has been disabled; visit %s", user->nick.c_str(), command.c_str(), url.c_str()); + user->WriteNotice("/" + command + " has been disabled; visit " + url); return MOD_RES_DENY; } else return MOD_RES_PASSTHRU; } - virtual ~ModuleMapHide() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Hide /MAP and /LINKS in the same form as ircu (mostly useless)", VF_VENDOR); } }; MODULE_INIT(ModuleMapHide) - diff --git a/src/modules/m_md5.cpp b/src/modules/m_md5.cpp index c902ee3cb..6cec05a18 100644 --- a/src/modules/m_md5.cpp +++ b/src/modules/m_md5.cpp @@ -21,13 +21,8 @@ */ -/* $ModDesc: Allows for MD5 encrypted oper passwords */ - #include "inspircd.h" -#ifdef HAS_STDINT -#include <stdint.h> -#endif -#include "hash.h" +#include "modules/hash.h" /* The four core functions - F1 is optimized somewhat */ #define F1(x, y, z) (z ^ (x & (y ^ z))) @@ -39,10 +34,6 @@ #define MD5STEP(f,w,x,y,z,in,s) \ (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x) -#ifndef HAS_STDINT -typedef unsigned int uint32_t; -#endif - typedef uint32_t word32; /* NOT unsigned long. We don't support 16 bit platforms, anyway. */ typedef unsigned char byte; @@ -253,36 +244,15 @@ class MD5Provider : public HashProvider MD5Final((unsigned char*)dest, &context); } - - void GenHash(const char* src, char* dest, const char* xtab, unsigned int* ikey, size_t srclen) - { - unsigned char bytes[16]; - - MyMD5((char*)bytes, (void*)src, srclen, ikey); - - for (int i = 0; i < 16; i++) - { - *dest++ = xtab[bytes[i] / 16]; - *dest++ = xtab[bytes[i] % 16]; - } - *dest++ = 0; - } public: - std::string sum(const std::string& data) + std::string GenerateRaw(const std::string& data) { char res[16]; MyMD5(res, (void*)data.data(), data.length(), NULL); return std::string(res, 16); } - std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata) - { - char res[33]; - GenHash(sdata.data(), res, HexMap, IV, sdata.length()); - return res; - } - - MD5Provider(Module* parent) : HashProvider(parent, "hash/md5", 16, 64) {} + MD5Provider(Module* parent) : HashProvider(parent, "md5", 16, 64) {} }; class ModuleMD5 : public Module @@ -291,10 +261,9 @@ class ModuleMD5 : public Module public: ModuleMD5() : md5(this) { - ServerInstance->Modules->AddService(md5); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements MD5 hashing",VF_VENDOR); } diff --git a/src/modules/m_messageflood.cpp b/src/modules/m_messageflood.cpp index 9ff17924d..1faf3bfb9 100644 --- a/src/modules/m_messageflood.cpp +++ b/src/modules/m_messageflood.cpp @@ -25,8 +25,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +f (message flood protection) */ - /** Holds flood settings and state for mode +f */ class floodsettings @@ -36,7 +34,7 @@ class floodsettings unsigned int secs; unsigned int lines; time_t reset; - std::map<User*, unsigned int> counters; + insp::flat_map<User*, unsigned int> counters; floodsettings(bool a, int b, int c) : ban(a), secs(b), lines(c) { @@ -56,64 +54,50 @@ class floodsettings void clear(User* who) { - std::map<User*, unsigned int>::iterator iter = counters.find(who); - if (iter != counters.end()) - { - counters.erase(iter); - } + counters.erase(who); } }; /** Handles channel mode +f */ -class MsgFlood : public ModeHandler +class MsgFlood : public ParamMode<MsgFlood, SimpleExtItem<floodsettings> > { public: - SimpleExtItem<floodsettings> ext; - MsgFlood(Module* Creator) : ModeHandler(Creator, "flood", 'f', PARAM_SETONLY, MODETYPE_CHANNEL), - ext("messageflood", Creator) { } + MsgFlood(Module* Creator) + : ParamMode<MsgFlood, SimpleExtItem<floodsettings> >(Creator, "flood", 'f') + { + } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) + std::string::size_type colon = parameter.find(':'); + if ((colon == std::string::npos) || (parameter.find('-') != std::string::npos)) { - std::string::size_type colon = parameter.find(':'); - if ((colon == std::string::npos) || (parameter.find('-') != std::string::npos)) - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - return MODEACTION_DENY; - } - - /* Set up the flood parameters for this channel */ - bool ban = (parameter[0] == '*'); - unsigned int nlines = ConvToInt(parameter.substr(ban ? 1 : 0, ban ? colon-1 : colon)); - unsigned int nsecs = ConvToInt(parameter.substr(colon+1)); - - if ((nlines<2) || (nsecs<1)) - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - return MODEACTION_DENY; - } + source->WriteNumeric(608, "%s :Invalid flood parameter", channel->name.c_str()); + return MODEACTION_DENY; + } - floodsettings* f = ext.get(channel); - if ((f) && (nlines == f->lines) && (nsecs == f->secs) && (ban == f->ban)) - // mode params match - return MODEACTION_DENY; + /* Set up the flood parameters for this channel */ + bool ban = (parameter[0] == '*'); + unsigned int nlines = ConvToInt(parameter.substr(ban ? 1 : 0, ban ? colon-1 : colon)); + unsigned int nsecs = ConvToInt(parameter.substr(colon+1)); - ext.set(channel, new floodsettings(ban, nsecs, nlines)); - parameter = std::string(ban ? "*" : "") + ConvToStr(nlines) + ":" + ConvToStr(nsecs); - channel->SetModeParam('f', parameter); - return MODEACTION_ALLOW; - } - else + if ((nlines<2) || (nsecs<1)) { - if (!channel->IsModeSet('f')) - return MODEACTION_DENY; - - ext.unset(channel); - channel->SetModeParam('f', ""); - return MODEACTION_ALLOW; + source->WriteNumeric(608, "%s :Invalid flood parameter", channel->name.c_str()); + return MODEACTION_DENY; } + + ext.set(channel, new floodsettings(ban, nsecs, nlines)); + return MODEACTION_ALLOW; + } + + void SerializeParam(Channel* chan, const floodsettings* fs, std::string& out) + { + if (fs->ban) + out.push_back('*'); + out.append(ConvToStr(fs->lines)).push_back(':'); + out.append(ConvToStr(fs->secs)); } }; @@ -128,17 +112,13 @@ class ModuleMsgFlood : public Module { } - void init() + ModResult OnUserPreMessage(User* user, void* voiddest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(mf); - ServerInstance->Modules->AddService(mf.ext); - Implementation eventlist[] = { I_OnUserPreNotice, I_OnUserPreMessage }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } + if (target_type != TYPE_CHANNEL) + return MOD_RES_PASSTHRU; - ModResult ProcessMessages(User* user,Channel* dest, const std::string &text) - { - if ((!IS_LOCAL(user)) || !dest->IsModeSet('f')) + Channel* dest = static_cast<Channel*>(voiddest); + if ((!IS_LOCAL(user)) || !dest->IsModeSet(mf)) return MOD_RES_PASSTHRU; if (ServerInstance->OnCheckExemption(user,dest,"flood") == MOD_RES_ALLOW) @@ -153,17 +133,15 @@ class ModuleMsgFlood : public Module f->clear(user); if (f->ban) { - std::vector<std::string> parameters; - parameters.push_back(dest->name); - parameters.push_back("+b"); - parameters.push_back(user->MakeWildHost()); - ServerInstance->SendGlobalMode(parameters, ServerInstance->FakeClient); + Modes::ChangeList changelist; + changelist.push_add(ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL), "*!*@" + user->dhost); + ServerInstance->Modes->Process(ServerInstance->FakeClient, dest, NULL, changelist); } - char kickmessage[MAXBUF]; - snprintf(kickmessage, MAXBUF, "Channel flood triggered (limit is %u lines in %u secs)", f->lines, f->secs); + const std::string kickMessage = "Channel flood triggered (limit is " + ConvToStr(f->lines) + + " in " + ConvToStr(f->secs) + " secs)"; - dest->KickUser(ServerInstance->FakeClient, user, kickmessage); + dest->KickUser(ServerInstance->FakeClient, user, kickMessage); return MOD_RES_DENY; } @@ -172,30 +150,13 @@ class ModuleMsgFlood : public Module return MOD_RES_PASSTHRU; } - ModResult OnUserPreMessage(User *user, void *dest, int target_type, std::string &text, char status, CUList &exempt_list) - { - if (target_type == TYPE_CHANNEL) - return ProcessMessages(user,(Channel*)dest,text); - - return MOD_RES_PASSTHRU; - } - - ModResult OnUserPreNotice(User *user, void *dest, int target_type, std::string &text, char status, CUList &exempt_list) - { - if (target_type == TYPE_CHANNEL) - return ProcessMessages(user,(Channel*)dest,text); - - return MOD_RES_PASSTHRU; - } - void Prioritize() { // we want to be after all modules that might deny the message (e.g. m_muteban, m_noctcp, m_blockcolor, etc.) ServerInstance->Modules->SetPriority(this, I_OnUserPreMessage, PRIORITY_LAST); - ServerInstance->Modules->SetPriority(this, I_OnUserPreNotice, PRIORITY_LAST); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +f (message flood protection)", VF_VENDOR); } diff --git a/src/modules/m_mlock.cpp b/src/modules/m_mlock.cpp index d1df81354..9b0fa8dab 100644 --- a/src/modules/m_mlock.cpp +++ b/src/modules/m_mlock.cpp @@ -17,30 +17,24 @@ */ -/* $ModDesc: Implements the ability to have server-side MLOCK enforcement. */ - #include "inspircd.h" class ModuleMLock : public Module { -private: StringExtItem mlock; -public: - ModuleMLock() : mlock("mlock", this) {}; - - void init() + public: + ModuleMLock() + : mlock("mlock", ExtensionItem::EXT_CHANNEL, this) { - ServerInstance->Modules->Attach(I_OnRawMode, this); - ServerInstance->Modules->AddService(this->mlock); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements the ability to have server-side MLOCK enforcement.", VF_VENDOR); } - ModResult OnRawMode(User* source, Channel* channel, const char mode, const std::string& parameter, bool adding, int pcnt) + ModResult OnRawMode(User* source, Channel* channel, ModeHandler* mh, const std::string& parameter, bool adding) { if (!channel) return MOD_RES_PASSTHRU; @@ -52,6 +46,7 @@ public: if (!mlock_str) return MOD_RES_PASSTHRU; + const char mode = mh->GetModeChar(); std::string::size_type p = mlock_str->find(mode); if (p != std::string::npos) { @@ -62,7 +57,6 @@ public: return MOD_RES_PASSTHRU; } - }; MODULE_INIT(ModuleMLock) diff --git a/src/modules/m_modenotice.cpp b/src/modules/m_modenotice.cpp new file mode 100644 index 000000000..056eb4a62 --- /dev/null +++ b/src/modules/m_modenotice.cpp @@ -0,0 +1,72 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class CommandModeNotice : public Command +{ + public: + CommandModeNotice(Module* parent) : Command(parent,"MODENOTICE",2,2) + { + syntax = "<modes> <message>"; + flags_needed = 'o'; + } + + CmdResult Handle(const std::vector<std::string>& parameters, User *src) + { + std::string msg = "*** From " + src->nick + ": " + parameters[1]; + int mlen = parameters[0].length(); + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i) + { + User* user = *i; + for (int n = 0; n < mlen; n++) + { + if (!user->IsModeSet(parameters[0][n])) + goto next_user; + } + user->WriteNotice(msg); +next_user: ; + } + return CMD_SUCCESS; + } + + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) + { + return ROUTE_OPT_BCAST; + } +}; + +class ModuleModeNotice : public Module +{ + CommandModeNotice cmd; + + public: + ModuleModeNotice() + : cmd(this) + { + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides the /MODENOTICE command", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleModeNotice) diff --git a/src/modules/m_muteban.cpp b/src/modules/m_muteban.cpp index 767af2901..72c4acd47 100644 --- a/src/modules/m_muteban.cpp +++ b/src/modules/m_muteban.cpp @@ -20,28 +20,15 @@ #include "inspircd.h" -/* $ModDesc: Implements extban +b m: - mute bans */ - class ModuleQuietBan : public Module { - private: public: - void init() - { - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleQuietBan() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements extban +b m: - mute bans",VF_OPTCOMMON|VF_VENDOR); } - virtual ModResult OnUserPreMessage(User *user, void *dest, int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (!IS_LOCAL(user) || target_type != TYPE_CHANNEL) return MOD_RES_PASSTHRU; @@ -49,24 +36,17 @@ class ModuleQuietBan : public Module Channel* chan = static_cast<Channel*>(dest); if (chan->GetExtBanStatus(user, 'm') == MOD_RES_DENY && chan->GetPrefixValue(user) < VOICE_VALUE) { - user->WriteNumeric(404, "%s %s :Cannot send to channel (you're muted)", user->nick.c_str(), chan->name.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Cannot send to channel (you're muted)", chan->name.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User *user, void *dest, int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user, dest, target_type, text, status, exempt_list); - } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('m'); + tokens["EXTBAN"].push_back('m'); } }; - MODULE_INIT(ModuleQuietBan) - diff --git a/src/modules/m_namedmodes.cpp b/src/modules/m_namedmodes.cpp index 4db1f70b9..1735df924 100644 --- a/src/modules/m_namedmodes.cpp +++ b/src/modules/m_namedmodes.cpp @@ -17,28 +17,24 @@ */ -/* $ModDesc: Provides the ability to manipulate modes via long names. */ - #include "inspircd.h" static void DisplayList(User* user, Channel* channel) { std::stringstream items; - for(char letter = 'A'; letter <= 'z'; letter++) + const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL); + for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i) { - ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_CHANNEL); - if (!mh || mh->IsListMode()) - continue; - if (!channel->IsModeSet(letter)) + ModeHandler* mh = i->second; + if (!channel->IsModeSet(mh)) continue; items << " +" << mh->name; if (mh->GetNumParams(true)) - items << " " << channel->GetModeParameter(letter); + items << " " << channel->GetModeParameter(mh); } - char pfx[MAXBUF]; - snprintf(pfx, MAXBUF, ":%s 961 %s %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), channel->name.c_str()); - user->SendText(std::string(pfx), items); - user->WriteNumeric(960, "%s %s :End of mode list", user->nick.c_str(), channel->name.c_str()); + const std::string line = ":" + ServerInstance->Config->ServerName + " 961 " + user->nick + " " + channel->name; + user->SendText(line, items); + user->WriteNumeric(960, "%s :End of mode list", channel->name.c_str()); } class CommandProp : public Command @@ -51,17 +47,20 @@ class CommandProp : public Command CmdResult Handle(const std::vector<std::string> ¶meters, User *src) { + Channel* const chan = ServerInstance->FindChan(parameters[0]); + if (!chan) + { + src->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); + return CMD_FAILURE; + } + if (parameters.size() == 1) { - Channel* chan = ServerInstance->FindChan(parameters[0]); - if (chan) - DisplayList(src, chan); + DisplayList(src, chan); return CMD_SUCCESS; } unsigned int i = 1; - std::vector<std::string> modes; - modes.push_back(parameters[0]); - modes.push_back(""); + Modes::ChangeList modes; while (i < parameters.size()) { std::string prop = parameters[i++]; @@ -69,21 +68,19 @@ class CommandProp : public Command if (prop[0] == '+' || prop[0] == '-') prop.erase(prop.begin()); - for(char letter = 'A'; letter <= 'z'; letter++) + ModeHandler* mh = ServerInstance->Modes->FindMode(prop, MODETYPE_CHANNEL); + if (mh) { - ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_CHANNEL); - if (mh && mh->name == prop) + if (mh->GetNumParams(plus)) { - modes[1].append((plus ? "+" : "-") + std::string(1, letter)); - if (mh->GetNumParams(plus)) - { - if (i != parameters.size()) - modes.push_back(parameters[i++]); - } + if (i != parameters.size()) + modes.push(mh, plus, parameters[i++]); } + else + modes.push(mh, plus); } } - ServerInstance->SendGlobalMode(modes, src); + ServerInstance->Modes->ProcessSingle(src, chan, NULL, modes, ModeParser::MODE_CHECKACCESS); return CMD_SUCCESS; } }; @@ -95,6 +92,12 @@ class DummyZ : public ModeHandler { list = true; } + + // Handle /MODE #chan Z + void DisplayList(User* user, Channel* chan) + { + ::DisplayList(user, chan); + } }; class ModuleNamedModes : public Module @@ -106,16 +109,7 @@ class ModuleNamedModes : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(dummyZ); - - Implementation eventlist[] = { I_OnPreMode }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the ability to manipulate modes via long names.",VF_VENDOR); } @@ -125,80 +119,59 @@ class ModuleNamedModes : public Module ServerInstance->Modules->SetPriority(this, I_OnPreMode, PRIORITY_FIRST); } - ModResult OnPreMode(User* source, User* dest, Channel* channel, const std::vector<std::string>& parameters) + ModResult OnPreMode(User* source, User* dest, Channel* channel, Modes::ChangeList& modes) CXX11_OVERRIDE { if (!channel) return MOD_RES_PASSTHRU; - if (parameters[1].find('Z') == std::string::npos) - return MOD_RES_PASSTHRU; - if (parameters.size() <= 2) - { - DisplayList(source, channel); - return MOD_RES_DENY; - } - std::vector<std::string> newparms; - newparms.push_back(parameters[0]); - newparms.push_back(parameters[1]); - - std::string modelist = newparms[1]; - bool adding = true; - unsigned int param_at = 2; - for(unsigned int i = 0; i < modelist.length(); i++) + Modes::ChangeList::List& list = modes.getlist(); + for (Modes::ChangeList::List::iterator i = list.begin(); i != list.end(); ) { - unsigned char modechar = modelist[i]; - if (modechar == '+' || modechar == '-') - { - adding = (modechar == '+'); - continue; - } - ModeHandler *mh = ServerInstance->Modes->FindMode(modechar, MODETYPE_CHANNEL); - if (modechar == 'Z') + Modes::Change& curr = *i; + // Replace all namebase (dummyZ) modes being changed with the actual + // mode handler and parameter. The parameter format of the namebase mode is + // <modename>[=<parameter>]. + if (curr.mh == &dummyZ) { - modechar = 0; - std::string name, value; - if (param_at < parameters.size()) - name = parameters[param_at++]; + std::string name = curr.param; + std::string value; std::string::size_type eq = name.find('='); if (eq != std::string::npos) { - value = name.substr(eq + 1); - name = name.substr(0, eq); + value.assign(name, eq + 1, std::string::npos); + name.erase(eq); + } + + ModeHandler* mh = ServerInstance->Modes->FindMode(name, MODETYPE_CHANNEL); + if (!mh) + { + // Mode handler not found + i = list.erase(i); + continue; } - for(char letter = 'A'; modechar == 0 && letter <= 'z'; letter++) + + curr.param.clear(); + if (mh->GetNumParams(curr.adding)) { - mh = ServerInstance->Modes->FindMode(letter, MODETYPE_CHANNEL); - if (mh && mh->name == name) + if (value.empty()) { - if (mh->GetNumParams(adding)) - { - if (!value.empty()) - { - newparms.push_back(value); - modechar = letter; - break; - } - } - else - { - modechar = letter; - break; - } + // Mode needs a parameter but there wasn't one + i = list.erase(i); + continue; } + + // Change parameter to the text after the '=' + curr.param = value; } - if (modechar) - modelist[i] = modechar; - else - modelist.erase(i--, 1); - } - else if (mh && mh->GetNumParams(adding) && param_at < parameters.size()) - { - newparms.push_back(parameters[param_at++]); + + // Put the actual ModeHandler in place of the namebase handler + curr.mh = mh; } + + ++i; } - newparms[1] = modelist; - ServerInstance->Modes->Process(newparms, source, false); - return MOD_RES_DENY; + + return MOD_RES_PASSTHRU; } }; diff --git a/src/modules/m_namesx.cpp b/src/modules/m_namesx.cpp index 82d311773..c701f16bf 100644 --- a/src/modules/m_namesx.cpp +++ b/src/modules/m_namesx.cpp @@ -21,40 +21,27 @@ #include "inspircd.h" -#include "m_cap.h" - -/* $ModDesc: Provides the NAMESX (CAP multi-prefix) capability. */ +#include "modules/cap.h" class ModuleNamesX : public Module { - public: GenericCap cap; + public: ModuleNamesX() : cap(this, "multi-prefix") { } - void init() - { - Implementation eventlist[] = { I_OnPreCommand, I_OnNamesListItem, I_On005Numeric, I_OnEvent, I_OnSendWhoLine }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - - ~ModuleNamesX() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the NAMESX (CAP multi-prefix) capability.",VF_VENDOR); } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" NAMESX"); + tokens["NAMESX"]; } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { /* We don't actually create a proper command handler class for PROTOCTL, * because other modules might want to have PROTOCTL hooks too. @@ -72,21 +59,17 @@ class ModuleNamesX : public Module return MOD_RES_PASSTHRU; } - void OnNamesListItem(User* issuer, Membership* memb, std::string &prefixes, std::string &nick) + ModResult OnNamesListItem(User* issuer, Membership* memb, std::string& prefixes, std::string& nick) CXX11_OVERRIDE { - if (!cap.ext.get(issuer)) - return; - - /* Some module hid this from being displayed, dont bother */ - if (nick.empty()) - return; + if (cap.ext.get(issuer)) + prefixes = memb->GetAllPrefixChars(); - prefixes = memb->chan->GetAllPrefixChars(memb->user); + return MOD_RES_PASSTHRU; } - void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, std::string& line) + void OnSendWhoLine(User* source, const std::vector<std::string>& params, User* user, Membership* memb, std::string& line) CXX11_OVERRIDE { - if (!cap.ext.get(source)) + if ((!memb) || (!cap.ext.get(source))) return; // Channel names can contain ":", and ":" as a 'start-of-token' delimiter is @@ -101,31 +84,16 @@ class ModuleNamesX : public Module return; // 352 21DAAAAAB #chan ident localhost insp21.test 21DAAAAAB H@ :0 a - // a b pos - std::string::size_type a = 4 + source->nick.length() + 1; - std::string::size_type b = line.find(' ', a); - if (b == std::string::npos) - return; - - // Try to find this channel - std::string channame = line.substr(a, b-a); - Channel* chan = ServerInstance->FindChan(channame); - if (!chan) - return; + // pos // Don't do anything if the user has only one prefix - std::string prefixes = chan->GetAllPrefixChars(user); + std::string prefixes = memb->GetAllPrefixChars(); if (prefixes.length() <= 1) return; line.erase(pos, 1); line.insert(pos, prefixes); } - - void OnEvent(Event& ev) - { - cap.HandleEvent(ev); - } }; MODULE_INIT(ModuleNamesX) diff --git a/src/modules/m_nationalchars.cpp b/src/modules/m_nationalchars.cpp index bf95f0f9f..f77899ad4 100644 --- a/src/modules/m_nationalchars.cpp +++ b/src/modules/m_nationalchars.cpp @@ -26,17 +26,12 @@ by Chernov-Phoenix Alexey (Phoenix@RusNet) mailto:phoenix /email address separator/ pravmail.ru */ #include "inspircd.h" -#include "caller.h" #include <fstream> -/* $ModDesc: Provides an ability to have non-RFC1459 nicks & support for national CASEMAPPING */ - -class lwbNickHandler : public HandlerBase2<bool, const char*, size_t> +class lwbNickHandler : public HandlerBase1<bool, const std::string&> { public: - lwbNickHandler() { } - virtual ~lwbNickHandler() { } - virtual bool Call(const char*, size_t); + bool Call(const std::string&); }; /*,m_reverse_additionalUp[256];*/ @@ -71,11 +66,12 @@ char utf8size(unsigned char * mb) /* Conditions added */ -bool lwbNickHandler::Call(const char* n, size_t max) +bool lwbNickHandler::Call(const std::string& nick) { - if (!n || !*n) + if (nick.empty()) return false; + const char* n = nick.c_str(); unsigned int p = 0; for (const char* i = n; *i; i++, p++) { @@ -215,21 +211,29 @@ bool lwbNickHandler::Call(const char* n, size_t max) } /* too long? or not -- pointer arithmetic rocks */ - return (p < max); + return (p < ServerInstance->Config->Limits.NickMax); } class ModuleNationalChars : public Module { - private: lwbNickHandler myhandler; std::string charset, casemapping; unsigned char m_additional[256], m_additionalUp[256], m_lower[256], m_upper[256]; - caller2<bool, const char*, size_t> rememberer; + caller1<bool, const std::string&> rememberer; bool forcequit; const unsigned char * lowermap_rememberer; unsigned char prev_map[256]; + template <typename T> + void RehashHashmap(T& hashmap) + { + T newhash(hashmap.bucket_count()); + for (typename T::const_iterator i = hashmap.begin(); i != hashmap.end(); ++i) + newhash.insert(std::make_pair(i->first, i->second)); + hashmap.swap(newhash); + } + void CheckRehash() { // See if anything changed @@ -238,20 +242,14 @@ class ModuleNationalChars : public Module memcpy(prev_map, national_case_insensitive_map, sizeof(prev_map)); - ServerInstance->RehashUsersAndChans(); + RehashHashmap(ServerInstance->Users.clientlist); + RehashHashmap(ServerInstance->Users.uuidlist); + RehashHashmap(ServerInstance->chanlist); // The OnGarbageCollect() method in m_watch rebuilds the hashmap used by it Module* mod = ServerInstance->Modules->Find("m_watch.so"); if (mod) mod->OnGarbageCollect(); - - // Send a Request to m_spanningtree asking it to rebuild its hashmaps - mod = ServerInstance->Modules->Find("m_spanningtree.so"); - if (mod) - { - Request req(this, mod, "rehash"); - req.Send(); - } } public: @@ -261,26 +259,20 @@ class ModuleNationalChars : public Module memcpy(prev_map, national_case_insensitive_map, sizeof(prev_map)); } - void init() + void init() CXX11_OVERRIDE { memcpy(m_lower, rfc_case_insensitive_map, 256); national_case_insensitive_map = m_lower; ServerInstance->IsNick = &myhandler; - - Implementation eventlist[] = { I_OnRehash, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - std::string tmp(casemapping); - tmp.insert(0, "CASEMAPPING="); - SearchAndReplace(output, std::string("CASEMAPPING=rfc1459"), tmp); + tokens["CASEMAPPING"] = casemapping; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("nationalchars"); charset = tag->getString("file"); @@ -299,16 +291,17 @@ class ModuleNationalChars : public Module if (!forcequit) return; - for (LocalUserList::const_iterator iter = ServerInstance->Users->local_users.begin(); iter != ServerInstance->Users->local_users.end(); ++iter) + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator iter = list.begin(); iter != list.end(); ++iter) { /* Fix by Brain: Dont quit UID users */ User* n = *iter; - if (!isdigit(n->nick[0]) && !ServerInstance->IsNick(n->nick.c_str(), ServerInstance->Config->Limits.NickMax)) + if (!isdigit(n->nick[0]) && !ServerInstance->IsNick(n->nick)) ServerInstance->Users->QuitUser(n, message); } } - virtual ~ModuleNationalChars() + ~ModuleNationalChars() { ServerInstance->IsNick = rememberer; national_case_insensitive_map = lowermap_rememberer; @@ -316,7 +309,7 @@ class ModuleNationalChars : public Module CheckRehash(); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides an ability to have non-RFC1459 nicks & support for national CASEMAPPING", VF_VENDOR | VF_COMMON, charset); } @@ -332,10 +325,10 @@ class ModuleNationalChars : public Module /*so Bynets Unreal distribution stuff*/ void loadtables(std::string filename, unsigned char ** tables, unsigned char cnt, char faillimit) { - std::ifstream ifs(filename.c_str()); + std::ifstream ifs(ServerInstance->Config->Paths.PrependConfig(filename).c_str()); if (ifs.fail()) { - ServerInstance->Logs->Log("m_nationalchars",DEFAULT,"loadtables() called for missing file: %s", filename.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "loadtables() called for missing file: %s", filename.c_str()); return; } @@ -350,7 +343,7 @@ class ModuleNationalChars : public Module { if (loadtable(ifs, tables[n], 255) && (n < faillimit)) { - ServerInstance->Logs->Log("m_nationalchars",DEFAULT,"loadtables() called for illegal file: %s (line %d)", filename.c_str(), n+1); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "loadtables() called for illegal file: %s (line %d)", filename.c_str(), n+1); return; } } diff --git a/src/modules/m_nickflood.cpp b/src/modules/m_nickflood.cpp index 04d7c8b5e..cade0b1db 100644 --- a/src/modules/m_nickflood.cpp +++ b/src/modules/m_nickflood.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +F (nick flood protection) */ - /** Holds settings and state associated with channel mode +F */ class nickfloodsettings @@ -80,53 +78,41 @@ class nickfloodsettings /** Handles channel mode +F */ -class NickFlood : public ModeHandler +class NickFlood : public ParamMode<NickFlood, SimpleExtItem<nickfloodsettings> > { public: - SimpleExtItem<nickfloodsettings> ext; - NickFlood(Module* Creator) : ModeHandler(Creator, "nickflood", 'F', PARAM_SETONLY, MODETYPE_CHANNEL), - ext("nickflood", Creator) { } + NickFlood(Module* Creator) + : ParamMode<NickFlood, SimpleExtItem<nickfloodsettings> >(Creator, "nickflood", 'F') + { + } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) + std::string::size_type colon = parameter.find(':'); + if ((colon == std::string::npos) || (parameter.find('-') != std::string::npos)) { - std::string::size_type colon = parameter.find(':'); - if ((colon == std::string::npos) || (parameter.find('-') != std::string::npos)) - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - return MODEACTION_DENY; - } - - /* Set up the flood parameters for this channel */ - unsigned int nnicks = ConvToInt(parameter.substr(0, colon)); - unsigned int nsecs = ConvToInt(parameter.substr(colon+1)); - - if ((nnicks<1) || (nsecs<1)) - { - source->WriteNumeric(608, "%s %s :Invalid flood parameter",source->nick.c_str(),channel->name.c_str()); - return MODEACTION_DENY; - } + source->WriteNumeric(608, "%s :Invalid flood parameter",channel->name.c_str()); + return MODEACTION_DENY; + } - nickfloodsettings* f = ext.get(channel); - if ((f) && (nnicks == f->nicks) && (nsecs == f->secs)) - // mode params match - return MODEACTION_DENY; + /* Set up the flood parameters for this channel */ + unsigned int nnicks = ConvToInt(parameter.substr(0, colon)); + unsigned int nsecs = ConvToInt(parameter.substr(colon+1)); - ext.set(channel, new nickfloodsettings(nsecs, nnicks)); - parameter = ConvToStr(nnicks) + ":" + ConvToStr(nsecs); - channel->SetModeParam('F', parameter); - return MODEACTION_ALLOW; - } - else + if ((nnicks<1) || (nsecs<1)) { - if (!channel->IsModeSet('F')) - return MODEACTION_DENY; - - ext.unset(channel); - channel->SetModeParam('F', ""); - return MODEACTION_ALLOW; + source->WriteNumeric(608, "%s :Invalid flood parameter",channel->name.c_str()); + return MODEACTION_DENY; } + + ext.set(channel, new nickfloodsettings(nsecs, nnicks)); + return MODEACTION_ALLOW; + } + + void SerializeParam(Channel* chan, const nickfloodsettings* nfs, std::string& out) + { + out.append(ConvToStr(nfs->nicks)).push_back(':'); + out.append(ConvToStr(nfs->secs)); } }; @@ -135,28 +121,16 @@ class ModuleNickFlood : public Module NickFlood nf; public: - ModuleNickFlood() : nf(this) { } - void init() - { - ServerInstance->Modules->AddService(nf); - ServerInstance->Modules->AddService(nf.ext); - Implementation eventlist[] = { I_OnUserPreNick, I_OnUserPostNick }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnUserPreNick(User* user, const std::string &newnick) + ModResult OnUserPreNick(LocalUser* user, const std::string& newnick) CXX11_OVERRIDE { - if (ServerInstance->NICKForced.get(user)) /* Allow forced nick changes */ - return MOD_RES_PASSTHRU; - - for (UCListIter i = user->chans.begin(); i != user->chans.end(); i++) + for (User::ChanList::iterator i = user->chans.begin(); i != user->chans.end(); i++) { - Channel *channel = *i; + Channel* channel = (*i)->chan; ModResult res; nickfloodsettings *f = nf.ext.get(channel); @@ -168,7 +142,7 @@ class ModuleNickFlood : public Module if (f->islocked()) { - user->WriteNumeric(447, "%s :%s has been locked for nickchanges for 60 seconds because there have been more than %u nick changes in %u seconds", user->nick.c_str(), channel->name.c_str(), f->nicks, f->secs); + user->WriteNumeric(ERR_CANTCHANGENICK, ":%s has been locked for nickchanges for 60 seconds because there have been more than %u nick changes in %u seconds", channel->name.c_str(), f->nicks, f->secs); return MOD_RES_DENY; } @@ -188,14 +162,14 @@ class ModuleNickFlood : public Module /* * XXX: HACK: We do the increment on the *POST* event here (instead of all together) because we have no way of knowing whether other modules would block a nickchange. */ - void OnUserPostNick(User* user, const std::string &oldnick) + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE { if (isdigit(user->nick[0])) /* allow switches to UID */ return; - for (UCListIter i = user->chans.begin(); i != user->chans.end(); ++i) + for (User::ChanList::iterator i = user->chans.begin(); i != user->chans.end(); ++i) { - Channel *channel = *i; + Channel* channel = (*i)->chan; ModResult res; nickfloodsettings *f = nf.ext.get(channel); @@ -214,11 +188,7 @@ class ModuleNickFlood : public Module } } - ~ModuleNickFlood() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Channel mode F - nick flood protection", VF_VENDOR); } diff --git a/src/modules/m_nicklock.cpp b/src/modules/m_nicklock.cpp index 4f5e5941c..a99628bf1 100644 --- a/src/modules/m_nicklock.cpp +++ b/src/modules/m_nicklock.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides the NICKLOCK command, allows an oper to change a users nick and lock them to it until they quit */ - /** Handle /NICKLOCK */ class CommandNicklock : public Command @@ -35,7 +33,7 @@ class CommandNicklock : public Command { flags_needed = 'o'; syntax = "<oldnick> <newnick>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle(const std::vector<std::string>& parameters, User *user) @@ -44,20 +42,20 @@ class CommandNicklock : public Command if ((!target) || (target->registered != REG_ALL)) { - user->WriteServ("NOTICE %s :*** No such nickname: '%s'", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** No such nickname: '" + parameters[0] + "'"); return CMD_FAILURE; } /* Do local sanity checks and bails */ if (IS_LOCAL(user)) { - if (!ServerInstance->IsNick(parameters[1].c_str(), ServerInstance->Config->Limits.NickMax)) + if (!ServerInstance->IsNick(parameters[1])) { - user->WriteServ("NOTICE %s :*** Invalid nickname '%s'", user->nick.c_str(), parameters[1].c_str()); + user->WriteNotice("*** Invalid nickname '" + parameters[1] + "'"); return CMD_FAILURE; } - user->WriteServ("947 %s %s :Nickname now locked.", user->nick.c_str(), parameters[1].c_str()); + user->WriteNumeric(947, "%s :Nickname now locked.", parameters[1].c_str()); } /* If we made it this far, extend the user */ @@ -66,7 +64,7 @@ class CommandNicklock : public Command locked.set(target, 1); std::string oldnick = target->nick; - if (target->ForceNickChange(parameters[1].c_str())) + if (target->ChangeNick(parameters[1])) ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used NICKLOCK to change and hold "+oldnick+" to "+parameters[1]); else { @@ -98,7 +96,7 @@ class CommandNickunlock : public Command { flags_needed = 'o'; syntax = "<locked-nick>"; - TRANSLATE2(TR_NICK, TR_END); + TRANSLATE1(TR_NICK); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -107,7 +105,7 @@ class CommandNickunlock : public Command if (!target) { - user->WriteServ("NOTICE %s :*** No such nickname: '%s'", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** No such nickname: '" + parameters[0] + "'"); return CMD_FAILURE; } @@ -139,7 +137,6 @@ class CommandNickunlock : public Command } }; - class ModuleNickLock : public Module { LocalIntExt locked; @@ -147,38 +144,22 @@ class ModuleNickLock : public Module CommandNickunlock cmd2; public: ModuleNickLock() - : locked("nick_locked", this), cmd1(this, locked), cmd2(this, locked) - { - } - - void init() + : locked("nick_locked", ExtensionItem::EXT_USER, this) + , cmd1(this, locked) + , cmd2(this, locked) { - ServerInstance->Modules->AddService(cmd1); - ServerInstance->Modules->AddService(cmd2); - ServerInstance->Modules->AddService(locked); - ServerInstance->Modules->Attach(I_OnUserPreNick, this); } - ~ModuleNickLock() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the NICKLOCK command, allows an oper to change a users nick and lock them to it until they quit", VF_OPTCOMMON | VF_VENDOR); } - ModResult OnUserPreNick(User* user, const std::string &newnick) + ModResult OnUserPreNick(LocalUser* user, const std::string& newnick) CXX11_OVERRIDE { - if (!IS_LOCAL(user)) - return MOD_RES_PASSTHRU; - - if (ServerInstance->NICKForced.get(user)) /* Allow forced nick changes */ - return MOD_RES_PASSTHRU; - if (locked.get(user)) { - user->WriteNumeric(447, "%s :You cannot change your nickname (your nick is locked)",user->nick.c_str()); + user->WriteNumeric(ERR_CANTCHANGENICK, ":You cannot change your nickname (your nick is locked)"); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; @@ -187,7 +168,7 @@ class ModuleNickLock : public Module void Prioritize() { Module *nflood = ServerInstance->Modules->Find("m_nickflood.so"); - ServerInstance->Modules->SetPriority(this, I_OnUserPreNick, PRIORITY_BEFORE, &nflood); + ServerInstance->Modules->SetPriority(this, I_OnUserPreNick, PRIORITY_BEFORE, nflood); } }; diff --git a/src/modules/m_noctcp.cpp b/src/modules/m_noctcp.cpp index 1dd6fe34a..953557d90 100644 --- a/src/modules/m_noctcp.cpp +++ b/src/modules/m_noctcp.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +C to block CTCPs */ - class NoCTCP : public SimpleChannelModeHandler { public: @@ -31,38 +29,20 @@ class NoCTCP : public SimpleChannelModeHandler class ModuleNoCTCP : public Module { - NoCTCP nc; public: - ModuleNoCTCP() : nc(this) { } - void init() - { - ServerInstance->Modules->AddService(nc); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleNoCTCP() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +C to block CTCPs", VF_VENDOR); } - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreNotice(user,dest,target_type,text,status,exempt_list); - } - - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if ((target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) { @@ -74,18 +54,18 @@ class ModuleNoCTCP : public Module if (res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; - if (!c->GetExtBanStatus(user, 'C').check(!c->IsModeSet('C'))) + if (!c->GetExtBanStatus(user, 'C').check(!c->IsModeSet(nc))) { - user->WriteNumeric(ERR_NOCTCPALLOWED, "%s %s :Can't send CTCP to channel (+C set)",user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(ERR_NOCTCPALLOWED, "%s :Can't send CTCP to channel (+C set)", c->name.c_str()); return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('C'); + tokens["EXTBAN"].push_back('C'); } }; diff --git a/src/modules/m_nokicks.cpp b/src/modules/m_nokicks.cpp index 1f58a2e08..0acf84118 100644 --- a/src/modules/m_nokicks.cpp +++ b/src/modules/m_nokicks.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +Q to prevent kicks on the channel. */ - class NoKicks : public SimpleChannelModeHandler { public: @@ -40,38 +38,26 @@ class ModuleNoKicks : public Module { } - void init() - { - ServerInstance->Modules->AddService(nk); - Implementation eventlist[] = { I_OnUserPreKick, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('Q'); + tokens["EXTBAN"].push_back('Q'); } - ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) + ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) CXX11_OVERRIDE { - if (!memb->chan->GetExtBanStatus(source, 'Q').check(!memb->chan->IsModeSet('Q'))) + if (!memb->chan->GetExtBanStatus(source, 'Q').check(!memb->chan->IsModeSet(nk))) { // Can't kick with Q in place, not even opers with override, and founders - source->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :Can't kick user %s from channel (+Q set)",source->nick.c_str(), memb->chan->name.c_str(), memb->user->nick.c_str()); + source->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :Can't kick user %s from channel (+Q set)", memb->chan->name.c_str(), memb->user->nick.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - ~ModuleNoKicks() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +Q to prevent kicks on the channel.", VF_VENDOR); } }; - MODULE_INIT(ModuleNoKicks) diff --git a/src/modules/m_nonicks.cpp b/src/modules/m_nonicks.cpp index 672a48f8d..63815f2bf 100644 --- a/src/modules/m_nonicks.cpp +++ b/src/modules/m_nonicks.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for channel mode +N & extban +b N: which prevents nick changes on channel */ - class NoNicks : public SimpleChannelModeHandler { public: @@ -38,54 +36,34 @@ class ModuleNoNickChange : public Module { } - void init() - { - OnRehash(NULL); - ServerInstance->Modules->AddService(nn); - Implementation eventlist[] = { I_OnUserPreNick, I_On005Numeric, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleNoNickChange() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for channel mode +N & extban +b N: which prevents nick changes on channel", VF_VENDOR); } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('N'); + tokens["EXTBAN"].push_back('N'); } - virtual ModResult OnUserPreNick(User* user, const std::string &newnick) + ModResult OnUserPreNick(LocalUser* user, const std::string& newnick) CXX11_OVERRIDE { - if (!IS_LOCAL(user)) - return MOD_RES_PASSTHRU; - - // Allow forced nick changes. - if (ServerInstance->NICKForced.get(user)) - return MOD_RES_PASSTHRU; - - for (UCListIter i = user->chans.begin(); i != user->chans.end(); i++) + for (User::ChanList::iterator i = user->chans.begin(); i != user->chans.end(); i++) { - Channel* curr = *i; + Channel* curr = (*i)->chan; ModResult res = ServerInstance->OnCheckExemption(user,curr,"nonick"); if (res == MOD_RES_ALLOW) continue; - if (override && IS_OPER(user)) + if (override && user->IsOper()) continue; - if (!curr->GetExtBanStatus(user, 'N').check(!curr->IsModeSet('N'))) + if (!curr->GetExtBanStatus(user, 'N').check(!curr->IsModeSet(nn))) { - user->WriteNumeric(ERR_CANTCHANGENICK, "%s :Can't change nickname while on %s (+N is set)", - user->nick.c_str(), curr->name.c_str()); + user->WriteNumeric(ERR_CANTCHANGENICK, ":Can't change nickname while on %s (+N is set)", + curr->name.c_str()); return MOD_RES_DENY; } } @@ -93,7 +71,7 @@ class ModuleNoNickChange : public Module return MOD_RES_PASSTHRU; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { override = ServerInstance->Config->ConfValue("nonicks")->getBool("operoverride", false); } diff --git a/src/modules/m_nonotice.cpp b/src/modules/m_nonotice.cpp index c5b9f3a1c..cab367ad9 100644 --- a/src/modules/m_nonotice.cpp +++ b/src/modules/m_nonotice.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +T to block notices to the channel */ - class NoNotice : public SimpleChannelModeHandler { public: @@ -39,32 +37,25 @@ class ModuleNoNotice : public Module { } - void init() - { - ServerInstance->Modules->AddService(nt); - Implementation eventlist[] = { I_OnUserPreNotice, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('T'); + tokens["EXTBAN"].push_back('T'); } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { ModResult res; - if ((target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) + if ((msgtype == MSG_NOTICE) && (target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) { Channel* c = (Channel*)dest; - if (!c->GetExtBanStatus(user, 'T').check(!c->IsModeSet('T'))) + if (!c->GetExtBanStatus(user, 'T').check(!c->IsModeSet(nt))) { res = ServerInstance->OnCheckExemption(user,c,"nonotice"); if (res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; else { - user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s %s :Can't send NOTICE to channel (+T set)",user->nick.c_str(), c->name.c_str()); + user->WriteNumeric(ERR_CANNOTSENDTOCHAN, "%s :Can't send NOTICE to channel (+T set)", c->name.c_str()); return MOD_RES_DENY; } } @@ -72,11 +63,7 @@ class ModuleNoNotice : public Module return MOD_RES_PASSTHRU; } - virtual ~ModuleNoNotice() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +T to block notices to the channel", VF_VENDOR); } diff --git a/src/modules/m_nopartmsg.cpp b/src/modules/m_nopartmsg.cpp index ad3413101..7aeb66920 100644 --- a/src/modules/m_nopartmsg.cpp +++ b/src/modules/m_nopartmsg.cpp @@ -19,45 +19,27 @@ #include "inspircd.h" -/* $ModDesc: Implements extban +b p: - part message bans */ - class ModulePartMsgBan : public Module { - private: public: - void init() - { - Implementation eventlist[] = { I_OnUserPart, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModulePartMsgBan() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements extban +b p: - part message bans", VF_OPTCOMMON|VF_VENDOR); } - - virtual void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) + void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) CXX11_OVERRIDE { if (!IS_LOCAL(memb->user)) return; if (memb->chan->GetExtBanStatus(memb->user, 'p') == MOD_RES_DENY) partmessage.clear(); - - return; } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('p'); + tokens["EXTBAN"].push_back('p'); } }; - MODULE_INIT(ModulePartMsgBan) - diff --git a/src/modules/m_ojoin.cpp b/src/modules/m_ojoin.cpp index 026d98f86..1444f93ad 100644 --- a/src/modules/m_ojoin.cpp +++ b/src/modules/m_ojoin.cpp @@ -1,6 +1,7 @@ /* * InspIRCd -- Internet Relay Chat Daemon * + * Copyright (C) 2009 Taros <taros34@hotmail.com> * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org> * * This file is part of InspIRCd. InspIRCd is free software: you can @@ -16,57 +17,39 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - -/* - * Written for InspIRCd-1.2 by Taros on the Tel'Laerad M&D Team - * <http://tellaerad.net> - */ - #include "inspircd.h" -/* $ModConfig: <ojoin prefix="!" notice="yes" op="yes"> - * Specify the prefix that +Y will grant here, it should be unused. - * Leave prefix empty if you do not wish +Y to grant a prefix - * If notice is set to on, upon ojoin, the server will notice - * the channel saying that the oper is joining on network business - * If op is set to on, it will give them +o along with +Y */ -/* $ModDesc: Provides the /ojoin command, which joins a user to a channel on network business, and gives them +Y, which makes them immune to kick / deop and so on. */ -/* $ModAuthor: Taros */ -/* $ModAuthorMail: taros34@hotmail.com */ - -/* A note: This will not protect against kicks from services, - * ulines, or operoverride. */ - #define NETWORK_VALUE 9000000 -char NPrefix; -bool notice; -bool op; - /** Handle /OJOIN */ -class CommandOjoin : public Command +class CommandOjoin : public SplitCommand { public: bool active; - CommandOjoin(Module* parent) : Command(parent,"OJOIN", 1) + bool notice; + bool op; + ModeHandler* npmh; + CommandOjoin(Module* parent, ModeHandler& mode) + : SplitCommand(parent, "OJOIN", 1) + , npmh(&mode) { flags_needed = 'o'; Penalty = 0; syntax = "<channel>"; active = false; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); } - CmdResult Handle (const std::vector<std::string>& parameters, User *user) + CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) { // Make sure the channel name is allowable. - if (!ServerInstance->IsChannel(parameters[0].c_str(), ServerInstance->Config->Limits.ChanMax)) + if (!ServerInstance->IsChannel(parameters[0])) { - user->WriteServ("NOTICE "+user->nick+" :*** Invalid characters in channel name or name too long"); + user->WriteNotice("*** Invalid characters in channel name or name too long"); return CMD_FAILURE; } active = true; - Channel* channel = Channel::JoinUser(user, parameters[0].c_str(), false, "", false); + // override is false because we want OnUserPreJoin to run + Channel* channel = Channel::JoinUser(user, parameters[0], false); active = false; if (channel) @@ -82,15 +65,17 @@ class CommandOjoin : public Command } else { + channel = ServerInstance->FindChan(parameters[0]); + if (!channel) + return CMD_FAILURE; + ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used OJOIN in "+parameters[0]); // they're already in the channel - std::vector<std::string> modes; - modes.push_back(parameters[0]); - modes.push_back(op ? "+Yo" : "+Y"); - modes.push_back(user->nick); + Modes::ChangeList changelist; + changelist.push_add(npmh, user->nick); if (op) - modes.push_back(user->nick); - ServerInstance->SendGlobalMode(modes, ServerInstance->FakeClient); + changelist.push_add(ServerInstance->Modes->FindMode('o', MODETYPE_CHANNEL), user->nick); + ServerInstance->Modes->Process(ServerInstance->FakeClient, channel, NULL, changelist); } return CMD_SUCCESS; } @@ -98,54 +83,13 @@ class CommandOjoin : public Command /** channel mode +Y */ -class NetworkPrefix : public ModeHandler +class NetworkPrefix : public PrefixMode { public: - NetworkPrefix(Module* parent) : ModeHandler(parent, "official-join", 'Y', PARAM_ALWAYS, MODETYPE_CHANNEL) + NetworkPrefix(Module* parent, char NPrefix) + : PrefixMode(parent, "official-join", 'Y', NETWORK_VALUE, NPrefix) { - list = true; - prefix = NPrefix; levelrequired = INT_MAX; - m_paramtype = TR_NICK; - } - - void RemoveMode(Channel* channel, irc::modestacker* stack) - { - const UserMembList* cl = channel->GetUsers(); - std::vector<std::string> mode_junk; - mode_junk.push_back(channel->name); - irc::modestacker modestack(false); - std::deque<std::string> stackresult; - - for (UserMembCIter i = cl->begin(); i != cl->end(); i++) - { - if (i->second->hasMode('Y')) - { - if (stack) - stack->Push(this->GetModeChar(), i->first->nick); - else - modestack.Push(this->GetModeChar(), i->first->nick); - } - } - - if (stack) - return; - - while (modestack.GetStackedLine(stackresult)) - { - mode_junk.insert(mode_junk.end(), stackresult.begin(), stackresult.end()); - ServerInstance->SendMode(mode_junk, ServerInstance->FakeClient); - mode_junk.erase(mode_junk.begin() + 1, mode_junk.end()); - } - } - - unsigned int GetPrefixRank() - { - return NETWORK_VALUE; - } - - void RemoveMode(User* user, irc::modestacker* stack) - { } ModResult AccessCheck(User* source, Channel* channel, std::string ¶meter, bool adding) @@ -157,47 +101,27 @@ class NetworkPrefix : public ModeHandler return MOD_RES_PASSTHRU; } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - return MODEACTION_ALLOW; - } - }; class ModuleOjoin : public Module { - NetworkPrefix* np; + NetworkPrefix np; CommandOjoin mycommand; public: ModuleOjoin() - : np(NULL), mycommand(this) + : np(this, ServerInstance->Config->ConfValue("ojoin")->getString("prefix").c_str()[0]) + , mycommand(this, np) { } - void init() - { - /* Load config stuff */ - OnRehash(NULL); - - /* Initialise module variables */ - np = new NetworkPrefix(this); - - ServerInstance->Modules->AddService(*np); - ServerInstance->Modules->AddService(mycommand); - - Implementation eventlist[] = { I_OnUserPreJoin, I_OnUserPreKick, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnUserPreJoin(User *user, Channel *chan, const char *cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (mycommand.active) { - privs += 'Y'; - if (op) + privs += np.GetModeChar(); + if (mycommand.op) privs += 'o'; return MOD_RES_ALLOW; } @@ -205,53 +129,36 @@ class ModuleOjoin : public Module return MOD_RES_PASSTHRU; } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* Conf = ServerInstance->Config->ConfValue("ojoin"); - - if (!np) - { - // This is done on module load only - std::string npre = Conf->getString("prefix"); - NPrefix = npre.empty() ? 0 : npre[0]; - - if (NPrefix && ServerInstance->Modes->FindPrefix(NPrefix)) - throw ModuleException("Looks like the +Y prefix you picked for m_ojoin is already in use. Pick another."); - } - - notice = Conf->getBool("notice", true); - op = Conf->getBool("op", true); + mycommand.notice = Conf->getBool("notice", true); + mycommand.op = Conf->getBool("op", true); } - ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) + ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) CXX11_OVERRIDE { // Don't do anything if they're not +Y - if (!memb->hasMode('Y')) + if (!memb->hasMode(np.GetModeChar())) return MOD_RES_PASSTHRU; // Let them do whatever they want to themselves. if (source == memb->user) return MOD_RES_PASSTHRU; - source->WriteNumeric(484, source->nick+" "+memb->chan->name+" :Can't kick "+memb->user->nick+" as they're on official network business."); + source->WriteNumeric(ERR_RESTRICTED, memb->chan->name+" :Can't kick "+memb->user->nick+" as they're on official network business."); return MOD_RES_DENY; } - ~ModuleOjoin() - { - delete np; - } - void Prioritize() { ServerInstance->Modules->SetPriority(this, I_OnUserPreJoin, PRIORITY_FIRST); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Network Business Join", VF_VENDOR); } }; MODULE_INIT(ModuleOjoin) - diff --git a/src/modules/m_operchans.cpp b/src/modules/m_operchans.cpp index ca948d95b..3c6b4cd59 100644 --- a/src/modules/m_operchans.cpp +++ b/src/modules/m_operchans.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for oper-only chans via the +O channel mode */ - class OperChans : public SimpleChannelModeHandler { public: @@ -42,44 +40,33 @@ class ModuleOperChans : public Module { } - void init() - { - ServerInstance->Modules->AddService(oc); - Implementation eventlist[] = { I_OnCheckBan, I_On005Numeric, I_OnUserPreJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - if (chan && chan->IsModeSet('O') && !IS_OPER(user)) + if (chan && chan->IsModeSet(oc) && !user->IsOper()) { - user->WriteNumeric(ERR_CANTJOINOPERSONLY, "%s %s :Only IRC operators may join %s (+O is set)", - user->nick.c_str(), chan->name.c_str(), chan->name.c_str()); + user->WriteNumeric(ERR_CANTJOINOPERSONLY, "%s :Only IRC operators may join %s (+O is set)", + chan->name.c_str(), chan->name.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) + ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) CXX11_OVERRIDE { if ((mask.length() > 2) && (mask[0] == 'O') && (mask[1] == ':')) { - if (IS_OPER(user) && InspIRCd::Match(user->oper->name, mask.substr(2))) + if (user->IsOper() && InspIRCd::Match(user->oper->name, mask.substr(2))) return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - void On005Numeric(std::string &output) - { - ServerInstance->AddExtBanChar('O'); - } - - ~ModuleOperChans() + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { + tokens["EXTBAN"].push_back('O'); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for oper-only chans via the +O channel mode and 'O' extban", VF_VENDOR); } diff --git a/src/modules/m_operjoin.cpp b/src/modules/m_operjoin.cpp index bd77384a6..dd80d99ba 100644 --- a/src/modules/m_operjoin.cpp +++ b/src/modules/m_operjoin.cpp @@ -24,84 +24,44 @@ #include "inspircd.h" -/* $ModDesc: Forces opers to join the specified channel(s) on oper-up */ - class ModuleOperjoin : public Module { - private: - std::string operChan; std::vector<std::string> operChans; bool override; - int tokenize(const std::string &str, std::vector<std::string> &tokens) - { - // skip delimiters at beginning. - std::string::size_type lastPos = str.find_first_not_of(",", 0); - // find first "non-delimiter". - std::string::size_type pos = str.find_first_of(",", lastPos); - - while (std::string::npos != pos || std::string::npos != lastPos) - { - // found a token, add it to the vector. - tokens.push_back(str.substr(lastPos, pos - lastPos)); - // skip delimiters. Note the "not_of" - lastPos = str.find_first_not_of(",", pos); - // find next "non-delimiter" - pos = str.find_first_of(",", lastPos); - } - return tokens.size(); - } - public: - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnPostOper, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("operjoin"); - operChan = tag->getString("channel"); override = tag->getBool("override", false); + irc::commasepstream ss(tag->getString("channel")); operChans.clear(); - if (!operChan.empty()) - tokenize(operChan,operChans); - } - virtual ~ModuleOperjoin() - { + for (std::string channame; ss.GetToken(channame); ) + operChans.push_back(channame); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Forces opers to join the specified channel(s) on oper-up", VF_VENDOR); } - virtual void OnPostOper(User* user, const std::string &opertype, const std::string &opername) + void OnPostOper(User* user, const std::string &opertype, const std::string &opername) CXX11_OVERRIDE { - if (!IS_LOCAL(user)) + LocalUser* localuser = IS_LOCAL(user); + if (!localuser) return; - for(std::vector<std::string>::iterator it = operChans.begin(); it != operChans.end(); it++) - if (ServerInstance->IsChannel(it->c_str(), ServerInstance->Config->Limits.ChanMax)) - Channel::JoinUser(user, it->c_str(), override, "", false, ServerInstance->Time()); + for (std::vector<std::string>::const_iterator i = operChans.begin(); i != operChans.end(); ++i) + if (ServerInstance->IsChannel(*i)) + Channel::JoinUser(localuser, *i, override); - std::string chanList = IS_OPER(user)->getConfig("autojoin"); - if (!chanList.empty()) + irc::commasepstream ss(localuser->oper->getConfig("autojoin")); + for (std::string channame; ss.GetToken(channame); ) { - std::vector<std::string> typechans; - tokenize(chanList, typechans); - for (std::vector<std::string>::const_iterator it = typechans.begin(); it != typechans.end(); ++it) - { - if (ServerInstance->IsChannel(it->c_str(), ServerInstance->Config->Limits.ChanMax)) - { - Channel::JoinUser(user, it->c_str(), override, "", false, ServerInstance->Time()); - } - } + if (ServerInstance->IsChannel(channame)) + Channel::JoinUser(localuser, channame, override); } } }; diff --git a/src/modules/m_operlevels.cpp b/src/modules/m_operlevels.cpp index 569defd49..ac7178a93 100644 --- a/src/modules/m_operlevels.cpp +++ b/src/modules/m_operlevels.cpp @@ -20,27 +20,20 @@ */ -/* $ModDesc: Gives each oper type a 'level', cannot kill opers 'above' your level. */ - #include "inspircd.h" class ModuleOperLevels : public Module { public: - void init() - { - ServerInstance->Modules->Attach(I_OnKill, this); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Gives each oper type a 'level', cannot kill opers 'above' your level.", VF_VENDOR); } - virtual ModResult OnKill(User* source, User* dest, const std::string &reason) + ModResult OnKill(User* source, User* dest, const std::string &reason) CXX11_OVERRIDE { // oper killing an oper? - if (IS_OPER(dest) && IS_OPER(source)) + if (dest->IsOper() && source->IsOper()) { std::string level = dest->oper->getConfig("level"); long dest_level = atol(level.c_str()); @@ -50,8 +43,8 @@ class ModuleOperLevels : public Module if (dest_level > source_level) { if (IS_LOCAL(source)) ServerInstance->SNO->WriteGlobalSno('a', "Oper %s (level %ld) attempted to /kill a higher oper: %s (level %ld): Reason: %s",source->nick.c_str(),source_level,dest->nick.c_str(),dest_level,reason.c_str()); - dest->WriteServ("NOTICE %s :*** Oper %s attempted to /kill you!",dest->nick.c_str(),source->nick.c_str()); - source->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper %s is a higher level than you",source->nick.c_str(),dest->nick.c_str()); + dest->WriteNotice("*** Oper " + source->nick + " attempted to /kill you!"); + source->WriteNumeric(ERR_NOPRIVILEGES, ":Permission Denied - Oper %s is a higher level than you", dest->nick.c_str()); return MOD_RES_DENY; } } @@ -60,4 +53,3 @@ class ModuleOperLevels : public Module }; MODULE_INIT(ModuleOperLevels) - diff --git a/src/modules/m_operlog.cpp b/src/modules/m_operlog.cpp index edb9109e8..68f50bf6d 100644 --- a/src/modules/m_operlog.cpp +++ b/src/modules/m_operlog.cpp @@ -21,51 +21,39 @@ #include "inspircd.h" -/* $ModDesc: A module which logs all oper commands to the ircd log at default loglevel. */ - class ModuleOperLog : public Module { bool tosnomask; public: - void init() + void init() CXX11_OVERRIDE { - Implementation eventlist[] = { I_OnPreCommand, I_On005Numeric, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); ServerInstance->SNO->EnableSnomask('r', "OPERLOG"); - OnRehash(NULL); } - virtual ~ModuleOperLog() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("A module which logs all oper commands to the ircd log at default loglevel.", VF_VENDOR); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { tosnomask = ServerInstance->Config->ConfValue("operlog")->getBool("tosnomask", false); } - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { /* If the command doesnt appear to be valid, we dont want to mess with it. */ if (!validated) return MOD_RES_PASSTHRU; - if ((IS_OPER(user)) && (IS_LOCAL(user)) && (user->HasPermission(command))) + if ((user->IsOper()) && (user->HasPermission(command))) { - Command* thiscommand = ServerInstance->Parser->GetHandler(command); + Command* thiscommand = ServerInstance->Parser.GetHandler(command); if ((thiscommand) && (thiscommand->flags_needed == 'o')) { - std::string line; - if (!parameters.empty()) - line = irc::stringjoiner(" ", parameters, 0, parameters.size() - 1).GetJoined(); - std::string msg = "[" + user->GetFullRealHost() + "] " + command + " " + line; - ServerInstance->Logs->Log("m_operlog", DEFAULT, "OPERLOG: " + msg); + std::string msg = "[" + user->GetFullRealHost() + "] " + command + " " + irc::stringjoiner(parameters); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "OPERLOG: " + msg); if (tosnomask) ServerInstance->SNO->WriteGlobalSno('r', msg); } @@ -74,12 +62,11 @@ class ModuleOperLog : public Module return MOD_RES_PASSTHRU; } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" OPERLOG"); + tokens["OPERLOG"]; } }; - MODULE_INIT(ModuleOperLog) diff --git a/src/modules/m_opermodes.cpp b/src/modules/m_opermodes.cpp index 8b49f685e..33ebb57a0 100644 --- a/src/modules/m_opermodes.cpp +++ b/src/modules/m_opermodes.cpp @@ -22,26 +22,15 @@ #include "inspircd.h" -/* $ModDesc: Sets (and unsets) modes on opers when they oper up */ - class ModuleModesOnOper : public Module { public: - void init() - { - ServerInstance->Modules->Attach(I_OnPostOper, this); - } - - virtual ~ModuleModesOnOper() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Sets (and unsets) modes on opers when they oper up", VF_VENDOR); } - virtual void OnPostOper(User* user, const std::string &opertype, const std::string &opername) + void OnPostOper(User* user, const std::string &opertype, const std::string &opername) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return; @@ -71,7 +60,7 @@ class ModuleModesOnOper : public Module while (ss >> buf) modes.push_back(buf); - ServerInstance->SendMode(modes, u); + ServerInstance->Parser.CallHandler("MODE", modes, u); } }; diff --git a/src/modules/m_opermotd.cpp b/src/modules/m_opermotd.cpp index 989f97689..bd1853d43 100644 --- a/src/modules/m_opermotd.cpp +++ b/src/modules/m_opermotd.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Shows a message to opers after oper-up, adds /opermotd */ - /** Handle /OPERMOTD */ class CommandOpermotd : public Command @@ -82,34 +80,32 @@ class ModuleOpermotd : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - OnRehash(NULL); - Implementation eventlist[] = { I_OnRehash, I_OnOper }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Shows a message to opers after oper-up, adds /opermotd", VF_VENDOR | VF_OPTCOMMON); } - virtual void OnOper(User* user, const std::string &opertype) + void OnOper(User* user, const std::string &opertype) CXX11_OVERRIDE { if (onoper && IS_LOCAL(user)) cmd.ShowOperMOTD(user); } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { cmd.opermotd.clear(); ConfigTag* conf = ServerInstance->Config->ConfValue("opermotd"); onoper = conf->getBool("onoper", true); - FileReader f(conf->getString("file", "opermotd")); - for (int i=0, filesize = f.FileSize(); i < filesize; i++) - cmd.opermotd.push_back(f.GetLine(i)); + try + { + FileReader reader(conf->getString("file", "opermotd")); + cmd.opermotd = reader.GetVector(); + } + catch (CoreException&) + { + // Nothing happens here as we do the error handling in ShowOperMOTD. + } if (conf->getBool("processcolors")) InspIRCd::ProcessColors(cmd.opermotd); diff --git a/src/modules/m_operprefix.cpp b/src/modules/m_operprefix.cpp index 9f1f6cc5e..51281a528 100644 --- a/src/modules/m_operprefix.cpp +++ b/src/modules/m_operprefix.cpp @@ -22,148 +22,85 @@ * Originally by Chernov-Phoenix Alexey (Phoenix@RusNet) mailto:phoenix /email address separator/ pravmail.ru */ -/* $ModDesc: Gives opers cmode +y which provides a staff prefix. */ - #include "inspircd.h" #define OPERPREFIX_VALUE 1000000 -class OperPrefixMode : public ModeHandler +class OperPrefixMode : public PrefixMode { public: - OperPrefixMode(Module* Creator) : ModeHandler(Creator, "operprefix", 'y', PARAM_ALWAYS, MODETYPE_CHANNEL) + OperPrefixMode(Module* Creator) + : PrefixMode(Creator, "operprefix", 'y', OPERPREFIX_VALUE) { std::string pfx = ServerInstance->Config->ConfValue("operprefix")->getString("prefix", "!"); - list = true; prefix = pfx.empty() ? '!' : pfx[0]; - levelrequired = OPERPREFIX_VALUE; - m_paramtype = TR_NICK; - } - - unsigned int GetPrefixRank() - { - return OPERPREFIX_VALUE; + levelrequired = INT_MAX; } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - if (IS_SERVER(source) || ServerInstance->ULine(source->server)) - return MODEACTION_ALLOW; - else - { - if (channel) - source->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :Only servers are permitted to change channel mode '%c'", source->nick.c_str(), channel->name.c_str(), 'y'); - return MODEACTION_DENY; - } - } - - bool NeedsOper() { return true; } }; class ModuleOperPrefixMode; class HideOperWatcher : public ModeWatcher { ModuleOperPrefixMode* parentmod; + public: - HideOperWatcher(ModuleOperPrefixMode* parent) : ModeWatcher((Module*) parent, 'H', MODETYPE_USER), parentmod(parent) {} - void AfterMode(User* source, User* dest, Channel* channel, const std::string ¶meter, bool adding, ModeType type); + HideOperWatcher(ModuleOperPrefixMode* parent); + void AfterMode(User* source, User* dest, Channel* channel, const std::string ¶meter, bool adding); }; class ModuleOperPrefixMode : public Module { - private: OperPrefixMode opm; - bool mw_added; HideOperWatcher hideoperwatcher; + UserModeReference hideopermode; + public: ModuleOperPrefixMode() - : opm(this), mw_added(false), hideoperwatcher(this) - { - } - - void init() + : opm(this), hideoperwatcher(this) + , hideopermode(this, "hideoper") { - ServerInstance->Modules->AddService(opm); - - Implementation eventlist[] = { I_OnUserPreJoin, I_OnPostOper, I_OnLoadModule, I_OnUnloadModule, I_OnPostJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - /* To give clients a chance to learn about the new prefix we don't give +y to opers * right now. That means if the module was loaded after opers have joined channels * they need to rejoin them in order to get the oper prefix. */ - - if (ServerInstance->Modules->Find("m_hideoper.so")) - mw_added = ServerInstance->Modes->AddModeWatcher(&hideoperwatcher); } - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string& privs, const std::string& keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - /* The user may have the +H umode on himself, but +H does not necessarily correspond - * to the +H of m_hideoper. - * However we only add the modewatcher when m_hideoper is loaded, so these - * conditions (mw_added and the user being +H) together mean the user is a hidden oper. - */ - - if (IS_OPER(user) && (!mw_added || !user->IsModeSet('H'))) + if ((user->IsOper()) && (!user->IsModeSet(hideopermode))) privs.push_back('y'); return MOD_RES_PASSTHRU; } void OnPostJoin(Membership* memb) { - if ((!IS_LOCAL(memb->user)) || (!IS_OPER(memb->user)) || (((mw_added) && (memb->user->IsModeSet('H'))))) + if ((!IS_LOCAL(memb->user)) || (!memb->user->IsOper()) || (memb->user->IsModeSet(hideopermode))) return; if (memb->hasMode(opm.GetModeChar())) return; // The user was force joined and OnUserPreJoin() did not run. Set the operprefix now. - std::vector<std::string> modechange; - modechange.push_back(memb->chan->name); - modechange.push_back("+y"); - modechange.push_back(memb->user->nick); - ServerInstance->SendGlobalMode(modechange, ServerInstance->FakeClient); + Modes::ChangeList changelist; + changelist.push_add(&opm, memb->user->nick); + ServerInstance->Modes.Process(ServerInstance->FakeClient, memb->chan, NULL, changelist); } void SetOperPrefix(User* user, bool add) { - std::vector<std::string> modechange; - modechange.push_back(""); - modechange.push_back(add ? "+y" : "-y"); - modechange.push_back(user->nick); - for (UCListIter v = user->chans.begin(); v != user->chans.end(); v++) - { - modechange[0] = (*v)->name; - ServerInstance->SendGlobalMode(modechange, ServerInstance->FakeClient); - } + Modes::ChangeList changelist; + changelist.push(&opm, add, user->nick); + for (User::ChanList::iterator v = user->chans.begin(); v != user->chans.end(); v++) + ServerInstance->Modes->Process(ServerInstance->FakeClient, (*v)->chan, NULL, changelist); } - void OnPostOper(User* user, const std::string& opername, const std::string& opertype) + void OnPostOper(User* user, const std::string& opername, const std::string& opertype) CXX11_OVERRIDE { - if (IS_LOCAL(user) && (!mw_added || !user->IsModeSet('H'))) + if (IS_LOCAL(user) && (!user->IsModeSet(hideopermode))) SetOperPrefix(user, true); } - void OnLoadModule(Module* mod) - { - if ((!mw_added) && (mod->ModuleSourceFile == "m_hideoper.so")) - mw_added = ServerInstance->Modes->AddModeWatcher(&hideoperwatcher); - } - - void OnUnloadModule(Module* mod) - { - if ((mw_added) && (mod->ModuleSourceFile == "m_hideoper.so") && (ServerInstance->Modes->DelModeWatcher(&hideoperwatcher))) - mw_added = false; - } - - ~ModuleOperPrefixMode() - { - if (mw_added) - ServerInstance->Modes->DelModeWatcher(&hideoperwatcher); - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Gives opers cmode +y which provides a staff prefix.", VF_VENDOR); } @@ -176,10 +113,16 @@ class ModuleOperPrefixMode : public Module } }; -void HideOperWatcher::AfterMode(User* source, User* dest, Channel* channel, const std::string& parameter, bool adding, ModeType type) +HideOperWatcher::HideOperWatcher(ModuleOperPrefixMode* parent) + : ModeWatcher(parent, "hideoper", MODETYPE_USER) + , parentmod(parent) +{ +} + +void HideOperWatcher::AfterMode(User* source, User* dest, Channel* channel, const std::string& parameter, bool adding) { // If hideoper is being unset because the user is deopering, don't set +y - if (IS_LOCAL(dest) && IS_OPER(dest)) + if (IS_LOCAL(dest) && dest->IsOper()) parentmod->SetOperPrefix(dest, !adding); } diff --git a/src/modules/m_override.cpp b/src/modules/m_override.cpp index 3e42c4f79..69f4b3bca 100644 --- a/src/modules/m_override.cpp +++ b/src/modules/m_override.cpp @@ -26,49 +26,66 @@ #include "inspircd.h" -/* $ModDesc: Provides support for allowing opers to override certain things. */ - class ModuleOverride : public Module { bool RequireKey; bool NoisyOverride; + ChanModeReference topiclock; + ChanModeReference inviteonly; + ChanModeReference key; + ChanModeReference limit; - static bool IsOverride(unsigned int userlevel, const std::string& modeline) + static bool IsOverride(unsigned int userlevel, const Modes::ChangeList::List& list) { - for (std::string::const_iterator i = modeline.begin(); i != modeline.end(); ++i) + for (Modes::ChangeList::List::const_iterator i = list.begin(); i != list.end(); ++i) { - ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL); - if (!mh) - continue; - + ModeHandler* mh = i->mh; if (mh->GetLevelRequired() > userlevel) return true; } return false; } + ModResult HandleJoinOverride(LocalUser* user, Channel* chan, const std::string& keygiven, const char* bypasswhat, const char* mode) + { + if (RequireKey && keygiven != "override") + { + // Can't join normally -- must use a special key to bypass restrictions + user->WriteNotice("*** You may not join normally. You must join with a key of 'override' to oper override."); + return MOD_RES_PASSTHRU; + } + + if (NoisyOverride) + chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s used oper override to bypass %s", chan->name.c_str(), user->nick.c_str(), bypasswhat); + ServerInstance->SNO->WriteGlobalSno('v', user->nick+" used oper override to bypass " + mode + " on " + chan->name); + return MOD_RES_ALLOW; + } + public: + ModuleOverride() + : topiclock(this, "topiclock") + , inviteonly(this, "inviteonly") + , key(this, "key") + , limit(this, "limit") + { + } - void init() + void init() CXX11_OVERRIDE { - // read our config options (main config file) - OnRehash(NULL); ServerInstance->SNO->EnableSnomask('v', "OVERRIDE"); - Implementation eventlist[] = { I_OnRehash, I_OnPreMode, I_On005Numeric, I_OnUserPreJoin, I_OnUserPreKick, I_OnPreTopicChange }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - // re-read our config options on a rehash + // re-read our config options ConfigTag* tag = ServerInstance->Config->ConfValue("override"); NoisyOverride = tag->getBool("noisy"); RequireKey = tag->getBool("requirekey"); } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" OVERRIDE"); + tokens["OVERRIDE"]; } bool CanOverride(User* source, const char* token) @@ -80,11 +97,11 @@ class ModuleOverride : public Module } - ModResult OnPreTopicChange(User *source, Channel *channel, const std::string &topic) + ModResult OnPreTopicChange(User *source, Channel *channel, const std::string &topic) CXX11_OVERRIDE { - if (IS_LOCAL(source) && IS_OPER(source) && CanOverride(source, "TOPIC")) + if (IS_LOCAL(source) && source->IsOper() && CanOverride(source, "TOPIC")) { - if (!channel->HasUser(source) || (channel->IsModeSet('t') && channel->GetPrefixValue(source) < HALFOP_VALUE)) + if (!channel->HasUser(source) || (channel->IsModeSet(topiclock) && channel->GetPrefixValue(source) < HALFOP_VALUE)) { ServerInstance->SNO->WriteGlobalSno('v',source->nick+" used oper override to change a topic on "+channel->name); } @@ -96,9 +113,9 @@ class ModuleOverride : public Module return MOD_RES_PASSTHRU; } - ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) + ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason) CXX11_OVERRIDE { - if (IS_OPER(source) && CanOverride(source,"KICK")) + if (source->IsOper() && CanOverride(source,"KICK")) { // If the kicker's status is less than the target's, or the kicker's status is less than or equal to voice if ((memb->chan->GetPrefixValue(source) < memb->getRank()) || (memb->chan->GetPrefixValue(source) <= VOICE_VALUE)) @@ -110,104 +127,75 @@ class ModuleOverride : public Module return MOD_RES_PASSTHRU; } - ModResult OnPreMode(User* source,User* dest,Channel* channel, const std::vector<std::string>& parameters) + ModResult OnPreMode(User* source, User* dest, Channel* channel, Modes::ChangeList& modes) CXX11_OVERRIDE { - if (!source || !channel) + if (!channel) return MOD_RES_PASSTHRU; - if (!IS_OPER(source) || !IS_LOCAL(source)) + if (!source->IsOper() || !IS_LOCAL(source)) return MOD_RES_PASSTHRU; + const Modes::ChangeList::List& list = modes.getlist(); unsigned int mode = channel->GetPrefixValue(source); - if (!IsOverride(mode, parameters[1])) + if (!IsOverride(mode, list)) return MOD_RES_PASSTHRU; if (CanOverride(source, "MODE")) { - std::string msg = source->nick+" overriding modes:"; - for(unsigned int i=0; i < parameters.size(); i++) - msg += " " + parameters[i]; + std::string msg = source->nick + " overriding modes: "; + + // Construct a MODE string in the old format for sending it as a snotice + std::string params; + char pm = 0; + for (Modes::ChangeList::List::const_iterator i = list.begin(); i != list.end(); ++i) + { + const Modes::Change& item = *i; + if (!item.param.empty()) + params.append(1, ' ').append(item.param); + + char wanted_pm = (item.adding ? '+' : '-'); + if (wanted_pm != pm) + { + pm = wanted_pm; + msg += pm; + } + + msg += item.mh->GetModeChar(); + } + msg += params; ServerInstance->SNO->WriteGlobalSno('v',msg); return MOD_RES_ALLOW; } return MOD_RES_PASSTHRU; } - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - if (IS_LOCAL(user) && IS_OPER(user)) + if (user->IsOper()) { if (chan) { - if (chan->IsModeSet('i') && (CanOverride(user,"INVITE"))) + if (chan->IsModeSet(inviteonly) && (CanOverride(user,"INVITE"))) { - irc::string x(chan->name.c_str()); - if (!IS_LOCAL(user)->IsInvited(x)) - { - if (RequireKey && keygiven != "override") - { - // Can't join normally -- must use a special key to bypass restrictions - user->WriteServ("NOTICE %s :*** You may not join normally. You must join with a key of 'override' to oper override.", user->nick.c_str()); - return MOD_RES_PASSTHRU; - } - - if (NoisyOverride) - chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s used oper override to bypass invite-only", cname, user->nick.c_str()); - ServerInstance->SNO->WriteGlobalSno('v', user->nick+" used oper override to bypass +i on "+std::string(cname)); - } + if (!user->IsInvited(chan)) + return HandleJoinOverride(user, chan, keygiven, "invite-only", "+i"); return MOD_RES_ALLOW; } - if (chan->IsModeSet('k') && (CanOverride(user,"KEY")) && keygiven != chan->GetModeParameter('k')) - { - if (RequireKey && keygiven != "override") - { - // Can't join normally -- must use a special key to bypass restrictions - user->WriteServ("NOTICE %s :*** You may not join normally. You must join with a key of 'override' to oper override.", user->nick.c_str()); - return MOD_RES_PASSTHRU; - } - - if (NoisyOverride) - chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s used oper override to bypass the channel key", cname, user->nick.c_str()); - ServerInstance->SNO->WriteGlobalSno('v', user->nick+" used oper override to bypass +k on "+std::string(cname)); - return MOD_RES_ALLOW; - } + if (chan->IsModeSet(key) && (CanOverride(user,"KEY")) && keygiven != chan->GetModeParameter(key)) + return HandleJoinOverride(user, chan, keygiven, "the channel key", "+k"); - if (chan->IsModeSet('l') && (chan->GetUserCounter() >= ConvToInt(chan->GetModeParameter('l'))) && (CanOverride(user,"LIMIT"))) - { - if (RequireKey && keygiven != "override") - { - // Can't join normally -- must use a special key to bypass restrictions - user->WriteServ("NOTICE %s :*** You may not join normally. You must join with a key of 'override' to oper override.", user->nick.c_str()); - return MOD_RES_PASSTHRU; - } - - if (NoisyOverride) - chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s used oper override to bypass the channel limit", cname, user->nick.c_str()); - ServerInstance->SNO->WriteGlobalSno('v', user->nick+" used oper override to bypass +l on "+std::string(cname)); - return MOD_RES_ALLOW; - } + if (chan->IsModeSet(limit) && (chan->GetUserCounter() >= ConvToInt(chan->GetModeParameter(limit))) && (CanOverride(user,"LIMIT"))) + return HandleJoinOverride(user, chan, keygiven, "the channel limit", "+l"); if (chan->IsBanned(user) && CanOverride(user,"BANWALK")) - { - if (RequireKey && keygiven != "override") - { - // Can't join normally -- must use a special key to bypass restrictions - user->WriteServ("NOTICE %s :*** You may not join normally. You must join with a key of 'override' to oper override.", user->nick.c_str()); - return MOD_RES_PASSTHRU; - } - - if (NoisyOverride) - chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s used oper override to bypass channel ban", cname, user->nick.c_str()); - ServerInstance->SNO->WriteGlobalSno('v',"%s used oper override to bypass channel ban on %s", user->nick.c_str(), cname); - return MOD_RES_ALLOW; - } + return HandleJoinOverride(user, chan, keygiven, "channel ban", "channel ban"); } } return MOD_RES_PASSTHRU; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for allowing opers to override certain things",VF_VENDOR); } diff --git a/src/modules/m_passforward.cpp b/src/modules/m_passforward.cpp index c04b306b1..3050dba0b 100644 --- a/src/modules/m_passforward.cpp +++ b/src/modules/m_passforward.cpp @@ -17,29 +17,19 @@ */ -/* $ModDesc: Forwards a password users can send on connect (for example for NickServ identification). */ - #include "inspircd.h" class ModulePassForward : public Module { - private: std::string nickrequired, forwardmsg, forwardcmd; public: - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnPostConnect, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Sends server password to NickServ", VF_VENDOR); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("passforward"); nickrequired = tag->getString("nick", "NickServ"); @@ -54,22 +44,22 @@ class ModulePassForward : public Module char c = format[i]; if (c == '$') { - if (format.substr(i, 13) == "$nickrequired") + if (!format.compare(i, 13, "$nickrequired", 13)) { result.append(nickrequired); i += 12; } - else if (format.substr(i, 5) == "$nick") + else if (!format.compare(i, 5, "$nick", 5)) { result.append(user->nick); i += 4; } - else if (format.substr(i, 5) == "$user") + else if (!format.compare(i, 5, "$user", 5)) { result.append(user->ident); i += 4; } - else if (format.substr(i,5) == "$pass") + else if (!format.compare(i, 5, "$pass", 5)) { result.append(user->password); i += 4; @@ -82,17 +72,21 @@ class ModulePassForward : public Module } } - virtual void OnPostConnect(User* ruser) + void OnPostConnect(User* ruser) CXX11_OVERRIDE { LocalUser* user = IS_LOCAL(ruser); if (!user || user->password.empty()) return; + // If the connect class requires a password, don't forward it + if (!user->MyClass->config->getString("password").empty()) + return; + if (!nickrequired.empty()) { /* Check if nick exists and its server is ulined */ User* u = ServerInstance->FindNick(nickrequired); - if (!u || !ServerInstance->ULine(u->server)) + if (!u || !u->server->IsULine()) return; } @@ -102,7 +96,7 @@ class ModulePassForward : public Module tmp.clear(); FormatStr(tmp,forwardcmd, user); - ServerInstance->Parser->ProcessBuffer(tmp,user); + ServerInstance->Parser.ProcessBuffer(tmp,user); } }; diff --git a/src/modules/m_password_hash.cpp b/src/modules/m_password_hash.cpp index 98462780b..09cdbb402 100644 --- a/src/modules/m_password_hash.cpp +++ b/src/modules/m_password_hash.cpp @@ -18,10 +18,8 @@ */ -/* $ModDesc: Allows for hashed oper passwords */ - #include "inspircd.h" -#include "hash.h" +#include "modules/hash.h" /* Handle /MKPASSWD */ @@ -36,34 +34,39 @@ class CommandMkpasswd : public Command void MakeHash(User* user, const std::string& algo, const std::string& stuff) { - if (algo.substr(0,5) == "hmac-") + if (!algo.compare(0, 5, "hmac-", 5)) { - std::string type = algo.substr(5); + std::string type(algo, 5); HashProvider* hp = ServerInstance->Modules->FindDataService<HashProvider>("hash/" + type); if (!hp) { - user->WriteServ("NOTICE %s :Unknown hash type", user->nick.c_str()); + user->WriteNotice("Unknown hash type"); + return; + } + + if (hp->IsKDF()) + { + user->WriteNotice(type + " does not support HMAC"); return; } - std::string salt = ServerInstance->GenRandomStr(6, false); + + std::string salt = ServerInstance->GenRandomStr(hp->out_size, false); std::string target = hp->hmac(salt, stuff); std::string str = BinToBase64(salt) + "$" + BinToBase64(target, NULL, 0); - user->WriteServ("NOTICE %s :%s hashed password for %s is %s", - user->nick.c_str(), algo.c_str(), stuff.c_str(), str.c_str()); + user->WriteNotice(algo + " hashed password for " + stuff + " is " + str); return; } HashProvider* hp = ServerInstance->Modules->FindDataService<HashProvider>("hash/" + algo); if (hp) { /* Now attempt to generate a hash */ - std::string hexsum = hp->hexsum(stuff); - user->WriteServ("NOTICE %s :%s hashed password for %s is %s", - user->nick.c_str(), algo.c_str(), stuff.c_str(), hexsum.c_str()); + std::string hexsum = hp->Generate(stuff); + user->WriteNotice(algo + " hashed password for " + stuff + " is " + hexsum); } else { - user->WriteServ("NOTICE %s :Unknown hash type", user->nick.c_str()); + user->WriteNotice("Unknown hash type"); } } @@ -84,24 +87,21 @@ class ModuleOperHash : public Module { } - void init() + ModResult OnPassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype) CXX11_OVERRIDE { - /* Read the config file first */ - OnRehash(NULL); - - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnPassCompare }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ModResult OnPassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype) - { - if (hashtype.substr(0,5) == "hmac-") + if (!hashtype.compare(0, 5, "hmac-", 5)) { - std::string type = hashtype.substr(5); + std::string type(hashtype, 5); HashProvider* hp = ServerInstance->Modules->FindDataService<HashProvider>("hash/" + type); if (!hp) return MOD_RES_PASSTHRU; + + if (hp->IsKDF()) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Tried to use HMAC with %s, which does not support HMAC", type.c_str()); + return MOD_RES_DENY; + } + // this is a valid hash, from here on we either accept or deny std::string::size_type sep = data.find('$'); if (sep == std::string::npos) @@ -120,19 +120,18 @@ class ModuleOperHash : public Module /* Is this a valid hash name? */ if (hp) { - /* Compare the hash in the config to the generated hash */ - if (data == hp->hexsum(input)) + if (hp->Compare(input, data)) return MOD_RES_ALLOW; else /* No match, and must be hashed, forbid */ return MOD_RES_DENY; } - /* Not a hash, fall through to strcmp in core */ + // We don't handle this type, let other mods or the core decide return MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows for hashed oper passwords",VF_VENDOR); } diff --git a/src/modules/m_pbkdf2.cpp b/src/modules/m_pbkdf2.cpp new file mode 100644 index 000000000..314f6b836 --- /dev/null +++ b/src/modules/m_pbkdf2.cpp @@ -0,0 +1,262 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2014 Daniel Vassdal <shutter@canternet.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "modules/hash.h" + +// Format: +// Iterations:B64(Hash):B64(Salt) +// E.g. +// 10200:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +class PBKDF2Hash +{ + public: + unsigned int iterations; + unsigned int length; + std::string salt; + std::string hash; + + PBKDF2Hash(unsigned int itr, unsigned int dkl, const std::string& slt, const std::string& hsh = "") + : iterations(itr), length(dkl), salt(slt), hash(hsh) + { + } + + PBKDF2Hash(const std::string& data) + { + irc::sepstream ss(data, ':'); + std::string tok; + + ss.GetToken(tok); + this->iterations = ConvToInt(tok); + + ss.GetToken(tok); + this->hash = Base64ToBin(tok); + + ss.GetToken(tok); + this->salt = Base64ToBin(tok); + + this->length = this->hash.length(); + } + + std::string ToString() + { + if (!IsValid()) + return ""; + return ConvToStr(this->iterations) + ":" + BinToBase64(this->hash) + ":" + BinToBase64(this->salt); + } + + bool IsValid() + { + if (!this->iterations || !this->length || this->salt.empty() || this->hash.empty()) + return false; + return true; + } +}; + +class PBKDF2Provider : public HashProvider +{ + public: + HashProvider* provider; + unsigned int iterations; + unsigned int dkey_length; + + std::string PBKDF2(const std::string& pass, const std::string& salt, unsigned int itr = 0, unsigned int dkl = 0) + { + size_t blocks = std::ceil((double)dkl / provider->out_size); + + std::string output; + std::string tmphash; + std::string salt_block = salt; + for (size_t block = 1; block <= blocks; block++) + { + char salt_data[4]; + for (size_t i = 0; i < sizeof(salt_data); i++) + salt_data[i] = block >> (24 - i * 8) & 0x0F; + + salt_block.erase(salt.length()); + salt_block.append(salt_data, sizeof(salt_data)); + + std::string blockdata = provider->hmac(pass, salt_block); + std::string lasthash = blockdata; + for (size_t iter = 1; iter < itr; iter++) + { + tmphash = provider->hmac(pass, lasthash); + for (size_t i = 0; i < provider->out_size; i++) + blockdata[i] ^= tmphash[i]; + + lasthash.swap(tmphash); + } + output += blockdata; + } + + output.erase(dkl); + return output; + } + + std::string GenerateRaw(const std::string& data) CXX11_OVERRIDE + { + PBKDF2Hash hs(this->iterations, this->dkey_length, ServerInstance->GenRandomStr(dkey_length, false)); + hs.hash = PBKDF2(data, hs.salt, this->iterations, this->dkey_length); + return hs.ToString(); + } + + bool Compare(const std::string& input, const std::string& hash) CXX11_OVERRIDE + { + PBKDF2Hash hs(hash); + if (!hs.IsValid()) + return false; + + std::string cmp = PBKDF2(input, hs.salt, hs.iterations, hs.length); + return (cmp == hs.hash); + } + + std::string ToPrintable(const std::string& raw) CXX11_OVERRIDE + { + return raw; + } + + PBKDF2Provider(Module* mod, HashProvider* hp) + : HashProvider(mod, "pbkdf2-hmac-" + hp->name.substr(hp->name.find('/') + 1)) + , provider(hp) + { + DisableAutoRegister(); + } +}; + +class ModulePBKDF2 : public Module +{ + std::vector<PBKDF2Provider*> providers; + + void GetConfig() + { + // First set the common values + ConfigTag* tag = ServerInstance->Config->ConfValue("pbkdf2"); + unsigned int global_iterations = tag->getInt("iterations", 12288, 1); + unsigned int global_dkey_length = tag->getInt("length", 32, 1, 1024); + for (std::vector<PBKDF2Provider*>::iterator i = providers.begin(); i != providers.end(); ++i) + { + PBKDF2Provider* pi = *i; + pi->iterations = global_iterations; + pi->dkey_length = global_dkey_length; + } + + // Then the specific values + ConfigTagList tags = ServerInstance->Config->ConfTags("pbkdf2prov"); + for (ConfigIter i = tags.first; i != tags.second; ++i) + { + tag = i->second; + std::string hash_name = "hash/" + tag->getString("hash"); + for (std::vector<PBKDF2Provider*>::iterator j = providers.begin(); j != providers.end(); ++j) + { + PBKDF2Provider* pi = *j; + if (pi->provider->name != hash_name) + continue; + + pi->iterations = tag->getInt("iterations", global_iterations, 1); + pi->dkey_length = tag->getInt("length", global_dkey_length, 1, 1024); + } + } + } + + public: + ~ModulePBKDF2() + { + stdalgo::delete_all(providers); + } + + void Prioritize() CXX11_OVERRIDE + { + OnLoadModule(NULL); + } + + void OnLoadModule(Module* mod) CXX11_OVERRIDE + { + bool newProv = false; + // As the module doesn't tell us what ServiceProviders it has, let's iterate all (yay ...) the ServiceProviders + // Good thing people don't run loading and unloading those all the time + for (std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.begin(); i != ServerInstance->Modules->DataProviders.end(); ++i) + { + ServiceProvider* provider = i->second; + + // Does the service belong to the new mod? + // In the case this is our first run (mod == NULL, continue anyway) + if (mod && provider->creator != mod) + continue; + + // Check if it's a hash provider + if (provider->name.compare(0, 5, "hash/")) + continue; + + HashProvider* hp = static_cast<HashProvider*>(provider); + + if (hp->IsKDF()) + continue; + + bool has_prov = false; + for (std::vector<PBKDF2Provider*>::const_iterator j = providers.begin(); j != providers.end(); ++j) + { + if ((*j)->provider == hp) + { + has_prov = true; + break; + } + } + if (has_prov) + continue; + + newProv = true; + + PBKDF2Provider* prov = new PBKDF2Provider(this, hp); + providers.push_back(prov); + ServerInstance->Modules->AddService(*prov); + } + + if (newProv) + GetConfig(); + } + + void OnUnloadModule(Module* mod) CXX11_OVERRIDE + { + for (std::vector<PBKDF2Provider*>::iterator i = providers.begin(); i != providers.end(); ) + { + PBKDF2Provider* item = *i; + if (item->provider->creator != mod) + { + ++i; + continue; + } + + ServerInstance->Modules->DelService(*item); + delete item; + i = providers.erase(i); + } + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + GetConfig(); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Implements PBKDF2 hashing", VF_VENDOR); + } +}; + +MODULE_INIT(ModulePBKDF2) diff --git a/src/modules/m_permchannels.cpp b/src/modules/m_permchannels.cpp index e86b3cbf6..22513abea 100644 --- a/src/modules/m_permchannels.cpp +++ b/src/modules/m_permchannels.cpp @@ -19,192 +19,144 @@ #include "inspircd.h" +#include "listmode.h" +#include <fstream> -/* $ModDesc: Provides support for channel mode +P to provide permanent channels */ -struct ListModeData +/** Handles the +P channel mode + */ +class PermChannel : public ModeHandler { - std::string modes; - std::string params; + public: + PermChannel(Module* Creator) + : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) + { + oper = true; + } + + ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string& parameter, bool adding) + { + if (adding == channel->IsModeSet(this)) + return MODEACTION_DENY; + + channel->SetMode(this, adding); + if (!adding) + channel->CheckDestroy(); + + return MODEACTION_ALLOW; + } }; // Not in a class due to circular dependancy hell. static std::string permchannelsconf; -static bool WriteDatabase(Module* mod, bool save_listmodes) +static bool WriteDatabase(PermChannel& permchanmode, Module* mod, bool save_listmodes) { - FILE *f; + ChanModeReference ban(mod, "ban"); + /* + * We need to perform an atomic write so as not to fuck things up. + * So, let's write to a temporary file, flush it, then rename the file.. + * -- w00t + */ + // If the user has not specified a configuration file then we don't write one. if (permchannelsconf.empty()) - { - // Fake success. return true; - } - std::string tempname = permchannelsconf + ".tmp"; - - /* - * We need to perform an atomic write so as not to fuck things up. - * So, let's write to a temporary file, flush and sync the FD, then rename the file.. - * -- w00t - */ - f = fopen(tempname.c_str(), "w"); - if (!f) + std::string permchannelsnewconf = permchannelsconf + ".tmp"; + std::ofstream stream(permchannelsnewconf.c_str()); + if (!stream.is_open()) { - ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot create database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot create database \"%s\"! %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new permchan db \"%s\": %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno); return false; } - fputs("# Permchannels DB\n# This file is autogenerated; any changes will be overwritten!\n<config format=\"compat\">\n", f); - // Now, let's write. - std::string line; - for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++) + stream << "# This file is automatically generated by m_permchannels. Any changes will be overwritten." << std::endl + << "<config format=\"xml\">" << std::endl; + + const chan_hash& chans = ServerInstance->GetChans(); + for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i) { Channel* chan = i->second; - if (!chan->IsModeSet('P')) + if (!chan->IsModeSet(permchanmode)) continue; std::string chanmodes = chan->ChanModes(true); if (save_listmodes) { - ListModeData lm; + std::string modes; + std::string params; - // Bans are managed by the core, so we have to process them separately - lm.modes = std::string(chan->bans.size(), 'b'); - for (BanList::const_iterator j = chan->bans.begin(); j != chan->bans.end(); ++j) + const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes(); + for (ModeParser::ListModeList::const_iterator j = listmodes.begin(); j != listmodes.end(); ++j) { - lm.params += j->data; - lm.params += ' '; - } + ListModeBase* lm = *j; + ListModeBase::ModeList* list = lm->GetList(chan); + if (!list || list->empty()) + continue; + + size_t n = 0; + // Append the parameters + for (ListModeBase::ModeList::const_iterator k = list->begin(); k != list->end(); ++k, n++) + { + params += k->mask; + params += ' '; + } - // All other listmodes are managed by modules, so we need to ask them (call their - // OnSyncChannel() handler) to give our ProtoSendMode() a list of modes that are - // set on the channel. The ListModeData struct is passed as an opaque pointer - // that will be passed back to us by the module handling the mode. - FOREACH_MOD(I_OnSyncChannel, OnSyncChannel(chan, mod, &lm)); + // Append the mode letters (for example "IIII", "gg") + modes.append(n, lm->GetModeChar()); + } - if (!lm.modes.empty()) + if (!params.empty()) { // Remove the last space - lm.params.erase(lm.params.end()-1); + params.erase(params.end()-1); // If there is at least a space in chanmodes (that is, a non-listmode has a parameter) // insert the listmode mode letters before the space. Otherwise just append them. std::string::size_type p = chanmodes.find(' '); if (p == std::string::npos) - chanmodes += lm.modes; + chanmodes += modes; else - chanmodes.insert(p, lm.modes); + chanmodes.insert(p, modes); // Append the listmode parameters (the masks themselves) chanmodes += ' '; - chanmodes += lm.params; + chanmodes += params; } } - std::string chants = ConvToStr(chan->age); - std::string topicts = ConvToStr(chan->topicset); - const char* items[] = - { - "<permchannels channel=", - chan->name.c_str(), - " ts=", - chants.c_str(), - " topic=", - chan->topic.c_str(), - " topicts=", - topicts.c_str(), - " topicsetby=", - chan->setby.c_str(), - " modes=", - chanmodes.c_str(), - ">\n" - }; - - line.clear(); - int item = 0, ipos = 0; - while (item < 13) - { - char c = items[item][ipos++]; - if (c == 0) - { - // end of this string; hop to next string, insert a quote - item++; - ipos = 0; - c = '"'; - } - else if (c == '\\' || c == '"') - { - line += '\\'; - } - line += c; - } - - // Erase last '"' - line.erase(line.end()-1); - fputs(line.c_str(), f); + stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name) + << "\" ts=\"" << chan->age + << "\" topic=\"" << ServerConfig::Escape(chan->topic) + << "\" topicts=\"" << chan->topicset + << "\" topicsetby=\"" << ServerConfig::Escape(chan->setby) + << "\" modes=\"" << ServerConfig::Escape(chanmodes) + << "\">" << std::endl; } - int write_error = 0; - write_error = ferror(f); - write_error |= fclose(f); - if (write_error) + if (stream.fail()) { - ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot write to new database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database \"%s\"! %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new permchan db \"%s\": %s (%d)", permchannelsnewconf.c_str(), strerror(errno), errno); return false; } + stream.close(); #ifdef _WIN32 remove(permchannelsconf.c_str()); #endif // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash. - if (rename(tempname.c_str(), permchannelsconf.c_str()) < 0) + if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0) { - ServerInstance->Logs->Log("m_permchannels",DEFAULT, "permchannels: Cannot move new to old database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot replace old database \"%s\" with new database \"%s\"! %s (%d)", permchannelsconf.c_str(), permchannelsnewconf.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old permchan db \"%s\" with new db \"%s\": %s (%d)", permchannelsconf.c_str(), permchannelsnewconf.c_str(), strerror(errno), errno); return false; } return true; } - - -/** Handles the +P channel mode - */ -class PermChannel : public ModeHandler -{ - public: - PermChannel(Module* Creator) : ModeHandler(Creator, "permanent", 'P', PARAM_NONE, MODETYPE_CHANNEL) { oper = true; } - - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) - { - if (adding) - { - if (!channel->IsModeSet('P')) - { - channel->SetMode('P',true); - return MODEACTION_ALLOW; - } - } - else - { - if (channel->IsModeSet('P')) - { - channel->SetMode(this,false); - if (channel->GetUserCounter() == 0) - { - channel->DelUser(ServerInstance->FakeClient); - } - return MODEACTION_ALLOW; - } - } - - return MODEACTION_DENY; - } -}; - class ModulePermanentChannels : public Module { PermChannel p; @@ -218,46 +170,14 @@ public: { } - void init() - { - ServerInstance->Modules->AddService(p); - Implementation eventlist[] = { I_OnChannelPreDelete, I_OnPostTopicChange, I_OnRawMode, I_OnRehash, I_OnBackgroundTimer }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - OnRehash(NULL); - } - - CullResult cull() - { - /* - * DelMode can't remove the +P mode on empty channels, or it will break - * merging modes with remote servers. Remove the empty channels now as - * we know this is not the case. - */ - chan_hash::iterator iter = ServerInstance->chanlist->begin(); - while (iter != ServerInstance->chanlist->end()) - { - Channel* c = iter->second; - if (c->GetUserCounter() == 0) - { - chan_hash::iterator at = iter; - iter++; - FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(c)); - ServerInstance->chanlist->erase(at); - ServerInstance->GlobalCulls.AddItem(c); - } - else - iter++; - } - ServerInstance->Modes->DelMode(&p); - return Module::cull(); - } - - virtual void OnRehash(User *user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("permchanneldb"); permchannelsconf = tag->getString("filename"); save_listmodes = tag->getBool("listmodes"); + + if (!permchannelsconf.empty()) + permchannelsconf = ServerInstance->Config->Paths.PrependConfig(permchannelsconf); } void LoadDatabase() @@ -271,12 +191,11 @@ public: { ConfigTag* tag = i->second; std::string channel = tag->getString("channel"); - std::string topic = tag->getString("topic"); std::string modes = tag->getString("modes"); if ((channel.empty()) || (channel.length() > ServerInstance->Config->Limits.ChanMax)) { - ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")"); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring permchannels tag with empty or too long channel name (\"" + channel + "\")"); continue; } @@ -284,19 +203,23 @@ public: if (!c) { - time_t TS = tag->getInt("ts"); - c = new Channel(channel, ((TS > 0) ? TS : ServerInstance->Time())); + time_t TS = tag->getInt("ts", ServerInstance->Time(), 1); + c = new Channel(channel, TS); - c->SetTopic(NULL, topic, true); - c->setby = tag->getString("topicsetby"); - if (c->setby.empty()) - c->setby = ServerInstance->Config->ServerName; unsigned int topicset = tag->getInt("topicts"); - // SetTopic() sets the topic TS to now, if there was no topicts saved then don't overwrite that with a 0 - if (topicset > 0) + c->topic = tag->getString("topic"); + + if ((topicset != 0) || (!c->topic.empty())) + { + if (topicset == 0) + topicset = ServerInstance->Time(); c->topicset = topicset; + c->setby = tag->getString("topicsetby"); + if (c->setby.empty()) + c->setby = ServerInstance->Config->ServerName; + } - ServerInstance->Logs->Log("m_permchannels", DEBUG, "Added %s with topic %s", channel.c_str(), topic.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Added %s with topic %s", channel.c_str(), c->topic.c_str()); if (modes.empty()) continue; @@ -325,24 +248,24 @@ public: } } - virtual ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string ¶m, bool adding, int pcnt) + ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE { - if (chan && (chan->IsModeSet('P') || mode == 'P')) + if (chan && (chan->IsModeSet(p) || mh == &p)) dirty = true; return MOD_RES_PASSTHRU; } - virtual void OnPostTopicChange(User*, Channel *c, const std::string&) + void OnPostTopicChange(User*, Channel *c, const std::string&) CXX11_OVERRIDE { - if (c->IsModeSet('P')) + if (c->IsModeSet(p)) dirty = true; } - void OnBackgroundTimer(time_t) + void OnBackgroundTimer(time_t) CXX11_OVERRIDE { if (dirty) - WriteDatabase(this, save_listmodes); + WriteDatabase(p, this, save_listmodes); dirty = false; } @@ -361,7 +284,7 @@ public: // Load only when there are no linked servers - we set the TS of the channels we // create to the current time, this can lead to desync because spanningtree has // no way of knowing what we do - ProtoServerList serverlist; + ProtocolInterface::ServerList serverlist; ServerInstance->PI->GetServerList(serverlist); if (serverlist.size() < 2) { @@ -371,38 +294,19 @@ public: } catch (CoreException& e) { - ServerInstance->Logs->Log("m_permchannels", DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason())); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error loading permchannels database: " + std::string(e.GetReason())); } } } - void ProtoSendMode(void* opaque, TargetTypeFlags type, void* target, const std::vector<std::string>& modes, const std::vector<TranslateType>& translate) - { - // We never pass an empty modelist but better be sure - if (modes.empty()) - return; - - ListModeData* lm = static_cast<ListModeData*>(opaque); - - // Append the mode letters without the trailing '+' (for example "IIII", "gg") - lm->modes.append(modes[0].begin()+1, modes[0].end()); - - // Append the parameters - for (std::vector<std::string>::const_iterator i = modes.begin()+1; i != modes.end(); ++i) - { - lm->params += *i; - lm->params += ' '; - } - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for channel mode +P to provide permanent channels",VF_VENDOR); } - virtual ModResult OnChannelPreDelete(Channel *c) + ModResult OnChannelPreDelete(Channel *c) CXX11_OVERRIDE { - if (c->IsModeSet('P')) + if (c->IsModeSet(p)) return MOD_RES_DENY; return MOD_RES_PASSTHRU; diff --git a/src/modules/m_randquote.cpp b/src/modules/m_randquote.cpp index 668eea0e5..1bb28583e 100644 --- a/src/modules/m_randquote.cpp +++ b/src/modules/m_randquote.cpp @@ -21,80 +21,37 @@ */ -/* $ModDesc: Provides random quotes on connect. */ - #include "inspircd.h" -static FileReader *quotes = NULL; - -std::string prefix; -std::string suffix; - -/** Handle /RANDQUOTE - */ -class CommandRandquote : public Command -{ - public: - CommandRandquote(Module* Creator) : Command(Creator,"RANDQUOTE", 0) - { - } - - CmdResult Handle (const std::vector<std::string>& parameters, User *user) - { - int fsize = quotes->FileSize(); - if (fsize) - { - std::string str = quotes->GetLine(ServerInstance->GenRandomInt(fsize)); - if (!str.empty()) - user->WriteServ("NOTICE %s :%s%s%s",user->nick.c_str(),prefix.c_str(),str.c_str(),suffix.c_str()); - } - - return CMD_SUCCESS; - } -}; - class ModuleRandQuote : public Module { private: - CommandRandquote cmd; - public: - ModuleRandQuote() - : cmd(this) - { - } + std::string prefix; + std::string suffix; + std::vector<std::string> quotes; - void init() + public: + void init() CXX11_OVERRIDE { ConfigTag* conf = ServerInstance->Config->ConfValue("randquote"); - - std::string q_file = conf->getString("file","quotes"); prefix = conf->getString("prefix"); suffix = conf->getString("suffix"); - - quotes = new FileReader(q_file); - if (!quotes->Exists()) - { - throw ModuleException("m_randquote: QuoteFile not Found!! Please check your config - module will not function."); - } - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnUserConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + FileReader reader(conf->getString("file", "quotes")); + quotes = reader.GetVector(); } - - virtual ~ModuleRandQuote() + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE { - delete quotes; - } - - virtual Version GetVersion() - { - return Version("Provides random quotes on connect.",VF_VENDOR); + if (!quotes.empty()) + { + unsigned long random = ServerInstance->GenRandomInt(quotes.size()); + user->WriteNotice(prefix + quotes[random] + suffix); + } } - virtual void OnUserConnect(LocalUser* user) + Version GetVersion() CXX11_OVERRIDE { - cmd.Handle(std::vector<std::string>(), user); + return Version("Provides random quotes on connect.", VF_VENDOR); } }; diff --git a/src/modules/m_redirect.cpp b/src/modules/m_redirect.cpp index 26d6b162b..e822676bf 100644 --- a/src/modules/m_redirect.cpp +++ b/src/modules/m_redirect.cpp @@ -24,66 +24,51 @@ #include "inspircd.h" -/* $ModDesc: Provides channel mode +L (limit redirection) and usermode +L (no forced redirection) */ - /** Handle channel mode +L */ -class Redirect : public ModeHandler +class Redirect : public ParamMode<Redirect, LocalStringExt> { public: - Redirect(Module* Creator) : ModeHandler(Creator, "redirect", 'L', PARAM_SETONLY, MODETYPE_CHANNEL) { } + Redirect(Module* Creator) + : ParamMode<Redirect, LocalStringExt>(Creator, "redirect", 'L') { } - ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) { - if (adding) + if (IS_LOCAL(source)) { - if (IS_LOCAL(source)) + if (!ServerInstance->IsChannel(parameter)) { - if (!ServerInstance->IsChannel(parameter.c_str(), ServerInstance->Config->Limits.ChanMax)) - { - source->WriteNumeric(403, "%s %s :Invalid channel name", source->nick.c_str(), parameter.c_str()); - parameter.clear(); - return MODEACTION_DENY; - } + source->WriteNumeric(ERR_NOSUCHCHANNEL, "%s :Invalid channel name", parameter.c_str()); + return MODEACTION_DENY; } + } - if (IS_LOCAL(source) && !IS_OPER(source)) + if (IS_LOCAL(source) && !source->IsOper()) + { + Channel* c = ServerInstance->FindChan(parameter); + if (!c) { - Channel* c = ServerInstance->FindChan(parameter); - if (!c) - { - source->WriteNumeric(690, "%s :Target channel %s must exist to be set as a redirect.",source->nick.c_str(),parameter.c_str()); - parameter.clear(); - return MODEACTION_DENY; - } - else if (c->GetPrefixValue(source) < OP_VALUE) - { - source->WriteNumeric(690, "%s :You must be opped on %s to set it as a redirect.",source->nick.c_str(),parameter.c_str()); - parameter.clear(); - return MODEACTION_DENY; - } - } - - if (channel->GetModeParameter('L') == parameter) + source->WriteNumeric(690, ":Target channel %s must exist to be set as a redirect.",parameter.c_str()); return MODEACTION_DENY; - /* - * We used to do some checking for circular +L here, but there is no real need for this any more especially as we - * now catch +L looping in PreJoin. Remove it, since O(n) logic makes me sad, and we catch it anyway. :) -- w00t - */ - channel->SetModeParam('L', parameter); - return MODEACTION_ALLOW; - } - else - { - if (channel->IsModeSet('L')) + } + else if (c->GetPrefixValue(source) < OP_VALUE) { - channel->SetModeParam('L', ""); - return MODEACTION_ALLOW; + source->WriteNumeric(690, ":You must be opped on %s to set it as a redirect.",parameter.c_str()); + return MODEACTION_DENY; } } - return MODEACTION_DENY; + /* + * We used to do some checking for circular +L here, but there is no real need for this any more especially as we + * now catch +L looping in PreJoin. Remove it, since O(n) logic makes me sad, and we catch it anyway. :) -- w00t + */ + ext.set(channel, parameter); + return MODEACTION_ALLOW; + } + void SerializeParam(Channel* chan, const std::string* str, std::string& out) + { + out += *str; } }; @@ -92,75 +77,62 @@ class Redirect : public ModeHandler class AntiRedirect : public SimpleUserModeHandler { public: - AntiRedirect(Module* Creator) : SimpleUserModeHandler(Creator, "antiredirect", 'L') {} + AntiRedirect(Module* Creator) : SimpleUserModeHandler(Creator, "antiredirect", 'L') + { + if (!ServerInstance->Config->ConfValue("redirect")->getBool("antiredirect")) + DisableAutoRegister(); + } }; class ModuleRedirect : public Module { - Redirect re; AntiRedirect re_u; + ChanModeReference limitmode; bool UseUsermode; public: - ModuleRedirect() - : re(this), re_u(this) + : re(this) + , re_u(this) + , limitmode(this, "limit") { } - void init() + void init() CXX11_OVERRIDE { /* Setting this here so it isn't changable by rehasing the config later. */ UseUsermode = ServerInstance->Config->ConfValue("redirect")->getBool("antiredirect"); - - /* Channel mode */ - ServerInstance->Modules->AddService(re); - - /* Check to see if the usermode is enabled in the config */ - if (UseUsermode) - { - /* Log noting that this breaks compatability. */ - ServerInstance->Logs->Log("m_redirect", DEFAULT, "REDIRECT: Enabled usermode +L. This breaks linking with servers that do not have this enabled. This is disabled by default in the 2.0 branch but will be enabled in the next version."); - - /* Try to add the usermode */ - ServerInstance->Modules->AddService(re_u); - } - - Implementation eventlist[] = { I_OnUserPreJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (chan) { - if (chan->IsModeSet('L') && chan->IsModeSet('l')) + if (chan->IsModeSet(re) && chan->IsModeSet(limitmode)) { - if (chan->GetUserCounter() >= ConvToInt(chan->GetModeParameter('l'))) + if (chan->GetUserCounter() >= ConvToInt(chan->GetModeParameter(limitmode))) { - std::string channel = chan->GetModeParameter('L'); + const std::string& channel = *re.ext.get(chan); /* sometimes broken ulines can make circular or chained +L, avoid this */ - Channel* destchan = NULL; - destchan = ServerInstance->FindChan(channel); - if (destchan && destchan->IsModeSet('L')) + Channel* destchan = ServerInstance->FindChan(channel); + if (destchan && destchan->IsModeSet(re)) { - user->WriteNumeric(470, "%s %s * :You may not join this channel. A redirect is set, but you may not be redirected as it is a circular loop.", user->nick.c_str(), cname); + user->WriteNumeric(470, "%s * :You may not join this channel. A redirect is set, but you may not be redirected as it is a circular loop.", cname.c_str()); return MOD_RES_DENY; } /* We check the bool value here to make sure we have it enabled, if we don't then usermode +L might be assigned to something else. */ - if (UseUsermode && user->IsModeSet('L')) + if (UseUsermode && user->IsModeSet(re_u)) { - user->WriteNumeric(470, "%s %s %s :Force redirection stopped.", - user->nick.c_str(), cname, channel.c_str()); + user->WriteNumeric(470, "%s %s :Force redirection stopped.", cname.c_str(), channel.c_str()); return MOD_RES_DENY; } else { - user->WriteNumeric(470, "%s %s %s :You may not join this channel, so you are automatically being transferred to the redirect channel.", user->nick.c_str(), cname, channel.c_str()); - Channel::JoinUser(user, channel.c_str(), false, "", false, ServerInstance->Time()); + user->WriteNumeric(470, "%s %s :You may not join this channel, so you are automatically being transferred to the redirect channel.", cname.c_str(), channel.c_str()); + Channel::JoinUser(user, channel); return MOD_RES_DENY; } } @@ -169,11 +141,7 @@ class ModuleRedirect : public Module return MOD_RES_PASSTHRU; } - virtual ~ModuleRedirect() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +L (limit redirection) and user mode +L (no forced redirection)", VF_VENDOR); } diff --git a/src/modules/m_regex.h b/src/modules/m_regex.h deleted file mode 100644 index 0233f938a..000000000 --- a/src/modules/m_regex.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef M_REGEX_H -#define M_REGEX_H - -#include "inspircd.h" - -class Regex : public classbase -{ -protected: - std::string regex_string; // The raw uncompiled regex string. - - // Constructor may as well be protected, as this class is abstract. - Regex(const std::string& rx) : regex_string(rx) - { - } - -public: - - virtual ~Regex() - { - } - - virtual bool Matches(const std::string& text) = 0; - - const std::string& GetRegexString() const - { - return regex_string; - } -}; - -class RegexFactory : public DataProvider -{ - public: - RegexFactory(Module* Creator, const std::string& Name) : DataProvider(Creator, Name) {} - - virtual Regex* Create(const std::string& expr) = 0; -}; - -#endif diff --git a/src/modules/m_regex_glob.cpp b/src/modules/m_regex_glob.cpp index 44d1a5898..9c3162885 100644 --- a/src/modules/m_regex_glob.cpp +++ b/src/modules/m_regex_glob.cpp @@ -18,11 +18,9 @@ */ -#include "m_regex.h" +#include "modules/regex.h" #include "inspircd.h" -/* $ModDesc: Regex module using plain wildcard matching. */ - class GlobRegex : public Regex { public: @@ -30,11 +28,7 @@ public: { } - virtual ~GlobRegex() - { - } - - virtual bool Matches(const std::string& text) + bool Matches(const std::string& text) CXX11_OVERRIDE { return InspIRCd::Match(text, this->regex_string); } @@ -43,7 +37,7 @@ public: class GlobFactory : public RegexFactory { public: - Regex* Create(const std::string& expr) + Regex* Create(const std::string& expr) CXX11_OVERRIDE { return new GlobRegex(expr); } @@ -55,11 +49,12 @@ class ModuleRegexGlob : public Module { GlobFactory gf; public: - ModuleRegexGlob() : gf(this) { - ServerInstance->Modules->AddService(gf); + ModuleRegexGlob() + : gf(this) + { } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Regex module using plain wildcard matching.", VF_VENDOR); } diff --git a/src/modules/m_regonlycreate.cpp b/src/modules/m_regonlycreate.cpp index 61f94c0bd..0ffe5e085 100644 --- a/src/modules/m_regonlycreate.cpp +++ b/src/modules/m_regonlycreate.cpp @@ -21,28 +21,27 @@ #include "inspircd.h" -#include "account.h" - -/* $ModDesc: Prevents users whose nicks are not registered from creating new channels */ +#include "modules/account.h" class ModuleRegOnlyCreate : public Module { + UserModeReference regusermode; + public: - void init() + ModuleRegOnlyCreate() + : regusermode(this, "u_registered") { - Implementation eventlist[] = { I_OnUserPreJoin }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { if (chan) return MOD_RES_PASSTHRU; - if (IS_OPER(user)) + if (user->IsOper()) return MOD_RES_PASSTHRU; - if (user->IsModeSet('r')) + if (user->IsModeSet(regusermode)) return MOD_RES_PASSTHRU; const AccountExtItem* ext = GetAccountExtItem(); @@ -50,15 +49,11 @@ class ModuleRegOnlyCreate : public Module return MOD_RES_PASSTHRU; // XXX. there may be a better numeric for this.. - user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must have a registered nickname to create a new channel", user->nick.c_str(), cname); + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You must have a registered nickname to create a new channel", cname.c_str()); return MOD_RES_DENY; } - ~ModuleRegOnlyCreate() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Prevents users whose nicks are not registered from creating new channels", VF_VENDOR); } diff --git a/src/modules/m_remove.cpp b/src/modules/m_remove.cpp index cf139f4a3..30924eb2f 100644 --- a/src/modules/m_remove.cpp +++ b/src/modules/m_remove.cpp @@ -24,8 +24,6 @@ #include "inspircd.h" -/* $ModDesc: Provides a /remove command, this is mostly an alternative to /kick, except makes users appear to have parted the channel */ - /* * This module supports the use of the +q and +a usermodes, but should work without them too. * Usage of the command is restricted to +hoaq, and you cannot remove a user with a "higher" level than yourself. @@ -36,23 +34,27 @@ */ class RemoveBase : public Command { - private: bool& supportnokicks; + ChanModeReference& nokicksmode; public: - RemoveBase(Module* Creator, bool& snk, const char* cmdn) - : Command(Creator, cmdn, 2, 3), supportnokicks(snk) + unsigned int protectedrank; + + RemoveBase(Module* Creator, bool& snk, ChanModeReference& nkm, const char* cmdn) + : Command(Creator, cmdn, 2, 3) + , supportnokicks(snk) + , nokicksmode(nkm) { } - CmdResult HandleRMB(const std::vector<std::string>& parameters, User *user, bool neworder) + CmdResult HandleRMB(const std::vector<std::string>& parameters, User *user, bool fpart) { User* target; Channel* channel; std::string reason; - std::string protectkey; - std::string founderkey; - bool hasnokicks; + + // If the command is a /REMOVE then detect the parameter order + bool neworder = ((fpart) || (parameters[0][0] == '#')); /* Set these to the parameters needed, the new version of this module switches it's parameters around * supplying a new command with the new order while keeping the old /remove with the older order. @@ -74,7 +76,7 @@ class RemoveBase : public Command /* Fix by brain - someone needs to learn to validate their input! */ if ((!target) || (target->registered != REG_ALL) || (!channel)) { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), !channel ? channame.c_str() : username.c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", !channel ? channame.c_str() : username.c_str()); return CMD_FAILURE; } @@ -84,30 +86,38 @@ class RemoveBase : public Command return CMD_FAILURE; } - int ulevel = channel->GetPrefixValue(user); - int tlevel = channel->GetPrefixValue(target); - - hasnokicks = (ServerInstance->Modules->Find("m_nokicks.so") && channel->IsModeSet('Q')); - - if (ServerInstance->ULine(target->server)) + if (target->server->IsULine()) { - user->WriteNumeric(482, "%s %s :Only a u-line may remove a u-line from a channel.", user->nick.c_str(), channame.c_str()); + user->WriteNumeric(482, "%s :Only a u-line may remove a u-line from a channel.", channame.c_str()); return CMD_FAILURE; } /* We support the +Q channel mode via. the m_nokicks module, if the module is loaded and the mode is set then disallow the /remove */ - if ((!IS_LOCAL(user)) || (!supportnokicks || !hasnokicks)) + if ((!IS_LOCAL(user)) || (!supportnokicks) || (!channel->IsModeSet(nokicksmode))) { /* We'll let everyone remove their level and below, eg: * ops can remove ops, halfops, voices, and those with no mode (no moders actually are set to 1) * a ulined target will get a higher level than it's possible for a /remover to get..so they're safe. - * Nobody may remove a founder. + * Nobody may remove people with >= protectedrank rank. */ - if ((!IS_LOCAL(user)) || ((ulevel > VOICE_VALUE) && (ulevel >= tlevel) && (tlevel != 50000))) + unsigned int ulevel = channel->GetPrefixValue(user); + unsigned int tlevel = channel->GetPrefixValue(target); + if ((!IS_LOCAL(user)) || ((ulevel > VOICE_VALUE) && (ulevel >= tlevel) && ((protectedrank == 0) || (tlevel < protectedrank)))) { - // REMOVE/FPART will be sent to the target's server and it will reply with a PART (or do nothing if it doesn't understand the command) + // REMOVE will be sent to the target's server and it will reply with a PART (or do nothing if it doesn't understand the command) if (!IS_LOCAL(target)) + { + // Send an ENCAP REMOVE with parameters being in the old <user> <chan> order which is + // compatible with both 2.0 and 2.2. This also turns FPART into REMOVE. + std::vector<std::string> p; + p.push_back(target->uuid); + p.push_back(channel->name); + if (parameters.size() > 2) + p.push_back(":" + parameters[2]); + ServerInstance->PI->SendEncapsulatedData(target->server->GetName(), "REMOVE", p, user); + return CMD_SUCCESS; + } std::string reasonparam; @@ -121,7 +131,7 @@ class RemoveBase : public Command reason = "Removed by " + user->nick + ": " + reasonparam; channel->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :%s removed %s from the channel", channel->name.c_str(), user->nick.c_str(), target->nick.c_str()); - target->WriteServ("NOTICE %s :*** %s removed you from %s with the message: %s", target->nick.c_str(), user->nick.c_str(), channel->name.c_str(), reasonparam.c_str()); + target->WriteNotice("*** " + user->nick + " removed you from " + channel->name + " with the message: " + reasonparam); channel->PartUser(target, reason); } @@ -134,13 +144,12 @@ class RemoveBase : public Command else { /* m_nokicks.so was loaded and +Q was set, block! */ - user->WriteServ( "484 %s %s :Can't remove user %s from channel (+Q set)", user->nick.c_str(), channel->name.c_str(), target->nick.c_str()); + user->WriteNumeric(ERR_RESTRICTED, "%s :Can't remove user %s from channel (nokicks mode is set)", channel->name.c_str(), target->nick.c_str()); return CMD_FAILURE; } return CMD_SUCCESS; } - virtual RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) = 0; }; /** Handle /REMOVE @@ -148,25 +157,17 @@ class RemoveBase : public Command class CommandRemove : public RemoveBase { public: - CommandRemove(Module* Creator, bool& snk) - : RemoveBase(Creator, snk, "REMOVE") + CommandRemove(Module* Creator, bool& snk, ChanModeReference& nkm) + : RemoveBase(Creator, snk, nkm, "REMOVE") { - syntax = "<nick> <channel> [<reason>]"; - TRANSLATE4(TR_NICK, TR_TEXT, TR_TEXT, TR_END); + syntax = "<channel> <nick> [<reason>]"; + TRANSLATE3(TR_NICK, TR_TEXT, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { return HandleRMB(parameters, user, false); } - - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) - { - User* dest = ServerInstance->FindNick(parameters[0]); - if (dest) - return ROUTE_OPT_UCAST(dest->server); - return ROUTE_LOCALONLY; - } }; /** Handle /FPART @@ -174,67 +175,50 @@ class CommandRemove : public RemoveBase class CommandFpart : public RemoveBase { public: - CommandFpart(Module* Creator, bool& snk) - : RemoveBase(Creator, snk, "FPART") + CommandFpart(Module* Creator, bool& snk, ChanModeReference& nkm) + : RemoveBase(Creator, snk, nkm, "FPART") { syntax = "<channel> <nick> [<reason>]"; - TRANSLATE4(TR_TEXT, TR_NICK, TR_TEXT, TR_END); + TRANSLATE3(TR_TEXT, TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { return HandleRMB(parameters, user, true); } - - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) - { - User* dest = ServerInstance->FindNick(parameters[1]); - if (dest) - return ROUTE_OPT_UCAST(dest->server); - return ROUTE_LOCALONLY; - } }; class ModuleRemove : public Module { + ChanModeReference nokicksmode; CommandRemove cmd1; CommandFpart cmd2; bool supportnokicks; - public: - ModuleRemove() : cmd1(this, supportnokicks), cmd2(this, supportnokicks) - { - } - - void init() + ModuleRemove() + : nokicksmode(this, "nokick") + , cmd1(this, supportnokicks, nokicksmode) + , cmd2(this, supportnokicks, nokicksmode) { - ServerInstance->Modules->AddService(cmd1); - ServerInstance->Modules->AddService(cmd2); - OnRehash(NULL); - Implementation eventlist[] = { I_On005Numeric, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" REMOVE"); + tokens["REMOVE"]; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - supportnokicks = ServerInstance->Config->ConfValue("remove")->getBool("supportnokicks"); + ConfigTag* tag = ServerInstance->Config->ConfValue("remove"); + supportnokicks = tag->getBool("supportnokicks"); + cmd1.protectedrank = cmd2.protectedrank = tag->getInt("protectedrank", 50000); } - virtual ~ModuleRemove() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides a /remove command, this is mostly an alternative to /kick, except makes users appear to have parted the channel", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleRemove) diff --git a/src/modules/m_repeat.cpp b/src/modules/m_repeat.cpp new file mode 100644 index 000000000..820ef702f --- /dev/null +++ b/src/modules/m_repeat.cpp @@ -0,0 +1,401 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class ChannelSettings +{ + public: + enum RepeatAction + { + ACT_KICK, + ACT_BLOCK, + ACT_BAN + }; + + RepeatAction Action; + unsigned int Backlog; + unsigned int Lines; + unsigned int Diff; + unsigned int Seconds; + + void serialize(std::string& out) const + { + if (Action == ACT_BAN) + out.push_back('*'); + else if (Action == ACT_BLOCK) + out.push_back('~'); + + out.append(ConvToStr(Lines)).push_back(':'); + out.append(ConvToStr(Seconds)); + if (Diff) + { + out.push_back(':'); + out.append(ConvToStr(Diff)); + if (Backlog) + { + out.push_back(':'); + out.append(ConvToStr(Backlog)); + } + } + } +}; + +class RepeatMode : public ParamMode<RepeatMode, SimpleExtItem<ChannelSettings> > +{ + private: + struct RepeatItem + { + time_t ts; + std::string line; + RepeatItem(time_t TS, const std::string& Line) : ts(TS), line(Line) { } + }; + + typedef std::deque<RepeatItem> RepeatItemList; + + struct MemberInfo + { + RepeatItemList ItemList; + unsigned int Counter; + MemberInfo() : Counter(0) {} + }; + + struct ModuleSettings + { + unsigned int MaxLines; + unsigned int MaxSecs; + unsigned int MaxBacklog; + unsigned int MaxDiff; + unsigned int MaxMessageSize; + ModuleSettings() : MaxLines(0), MaxSecs(0), MaxBacklog(0), MaxDiff() { } + }; + + std::vector<unsigned int> mx[2]; + ModuleSettings ms; + + bool CompareLines(const std::string& message, const std::string& historyline, unsigned int trigger) + { + if (message == historyline) + return true; + else if (trigger) + return (Levenshtein(message, historyline) <= trigger); + + return false; + } + + unsigned int Levenshtein(const std::string& s1, const std::string& s2) + { + unsigned int l1 = s1.size(); + unsigned int l2 = s2.size(); + + for (unsigned int i = 0; i < l2; i++) + mx[0][i] = i; + for (unsigned int i = 0; i < l1; i++) + { + mx[1][0] = i + 1; + for (unsigned int j = 0; j < l2; j++) + mx[1][j + 1] = std::min(std::min(mx[1][j] + 1, mx[0][j + 1] + 1), mx[0][j] + ((s1[i] == s2[j]) ? 0 : 1)); + + mx[0].swap(mx[1]); + } + return mx[0][l2]; + } + + public: + SimpleExtItem<MemberInfo> MemberInfoExt; + + RepeatMode(Module* Creator) + : ParamMode<RepeatMode, SimpleExtItem<ChannelSettings> >(Creator, "repeat", 'E') + , MemberInfoExt("repeat_memb", ExtensionItem::EXT_MEMBERSHIP, Creator) + { + } + + void OnUnset(User* source, Channel* chan) + { + // Unset the per-membership extension when the mode is removed + const Channel::MemberMap& users = chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = users.begin(); i != users.end(); ++i) + MemberInfoExt.unset(i->second); + } + + ModeAction OnSet(User* source, Channel* channel, std::string& parameter) + { + ChannelSettings settings; + if (!ParseSettings(source, parameter, settings)) + { + source->WriteNotice("*** Invalid syntax. Syntax is {[~*]}[lines]:[time]{:[difference]}{:[backlog]}"); + return MODEACTION_DENY; + } + + if ((settings.Backlog > 0) && (settings.Lines > settings.Backlog)) + { + source->WriteNotice("*** You can't set needed lines higher than backlog"); + return MODEACTION_DENY; + } + + LocalUser* localsource = IS_LOCAL(source); + if ((localsource) && (!ValidateSettings(localsource, settings))) + return MODEACTION_DENY; + + ext.set(channel, settings); + + return MODEACTION_ALLOW; + } + + bool MatchLine(Membership* memb, ChannelSettings* rs, std::string message) + { + // If the message is larger than whatever size it's set to, + // let's pretend it isn't. If the first 512 (def. setting) match, it's probably spam. + if (message.size() > ms.MaxMessageSize) + message.erase(ms.MaxMessageSize); + + MemberInfo* rp = MemberInfoExt.get(memb); + if (!rp) + { + rp = new MemberInfo; + MemberInfoExt.set(memb, rp); + } + + unsigned int matches = 0; + if (!rs->Backlog) + matches = rp->Counter; + + RepeatItemList& items = rp->ItemList; + const unsigned int trigger = (message.size() * rs->Diff / 100); + const time_t now = ServerInstance->Time(); + + std::transform(message.begin(), message.end(), message.begin(), ::tolower); + + for (std::deque<RepeatItem>::iterator it = items.begin(); it != items.end(); ++it) + { + if (it->ts < now) + { + items.erase(it, items.end()); + matches = 0; + break; + } + + if (CompareLines(message, it->line, trigger)) + { + if (++matches >= rs->Lines) + { + if (rs->Action != ChannelSettings::ACT_BLOCK) + rp->Counter = 0; + return true; + } + } + else if ((ms.MaxBacklog == 0) || (rs->Backlog == 0)) + { + matches = 0; + items.clear(); + break; + } + } + + unsigned int max_items = (rs->Backlog ? rs->Backlog : 1); + if (items.size() >= max_items) + items.pop_back(); + + items.push_front(RepeatItem(now + rs->Seconds, message)); + rp->Counter = matches; + return false; + } + + void Resize(size_t size) + { + size_t newsize = size+1; + if (newsize <= mx[0].size()) + return; + ms.MaxMessageSize = size; + mx[0].resize(newsize); + mx[1].resize(newsize); + } + + void ReadConfig() + { + ConfigTag* conf = ServerInstance->Config->ConfValue("repeat"); + ms.MaxLines = conf->getInt("maxlines", 20); + ms.MaxBacklog = conf->getInt("maxbacklog", 20); + ms.MaxSecs = conf->getInt("maxsecs", 0); + + ms.MaxDiff = conf->getInt("maxdistance", 50); + if (ms.MaxDiff > 100) + ms.MaxDiff = 100; + + unsigned int newsize = conf->getInt("size", 512); + if (newsize > ServerInstance->Config->Limits.MaxLine) + newsize = ServerInstance->Config->Limits.MaxLine; + Resize(newsize); + } + + std::string GetModuleSettings() const + { + return ConvToStr(ms.MaxLines) + ":" + ConvToStr(ms.MaxSecs) + ":" + ConvToStr(ms.MaxDiff) + ":" + ConvToStr(ms.MaxBacklog); + } + + void SerializeParam(Channel* chan, const ChannelSettings* chset, std::string& out) + { + chset->serialize(out); + } + + private: + bool ParseSettings(User* source, std::string& parameter, ChannelSettings& settings) + { + irc::sepstream stream(parameter, ':'); + std::string item; + if (!stream.GetToken(item)) + // Required parameter missing + return false; + + if ((item[0] == '*') || (item[0] == '~')) + { + settings.Action = ((item[0] == '*') ? ChannelSettings::ACT_BAN : ChannelSettings::ACT_BLOCK); + item.erase(item.begin()); + } + else + settings.Action = ChannelSettings::ACT_KICK; + + if ((settings.Lines = ConvToInt(item)) == 0) + return false; + + if ((!stream.GetToken(item)) || ((settings.Seconds = InspIRCd::Duration(item)) == 0)) + // Required parameter missing + return false; + + // The diff and backlog parameters are optional + settings.Diff = settings.Backlog = 0; + if (stream.GetToken(item)) + { + // There is a diff parameter, see if it's valid (> 0) + if ((settings.Diff = ConvToInt(item)) == 0) + return false; + + if (stream.GetToken(item)) + { + // There is a backlog parameter, see if it's valid + if ((settings.Backlog = ConvToInt(item)) == 0) + return false; + + // If there are still tokens, then it's invalid because we allow only 4 + if (stream.GetToken(item)) + return false; + } + } + + return true; + } + + bool ValidateSettings(LocalUser* source, const ChannelSettings& settings) + { + if (settings.Backlog && !ms.MaxBacklog) + { + source->WriteNotice("*** The server administrator has disabled backlog matching"); + return false; + } + + if (settings.Diff) + { + if (settings.Diff > ms.MaxDiff) + { + if (ms.MaxDiff == 0) + source->WriteNotice("*** The server administrator has disabled matching on edit distance"); + else + source->WriteNotice("*** The distance you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxDiff)); + return false; + } + + if (ms.MaxLines && settings.Lines > ms.MaxLines) + { + source->WriteNotice("*** The line number you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxLines)); + return false; + } + + if (ms.MaxSecs && settings.Seconds > ms.MaxSecs) + { + source->WriteNotice("*** The seconds you specified is too great. Maximum allowed is " + ConvToStr(ms.MaxSecs)); + return false; + } + } + + return true; + } +}; + +class RepeatModule : public Module +{ + RepeatMode rm; + + public: + RepeatModule() : rm(this) {} + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + rm.ReadConfig(); + } + + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE + { + if (target_type != TYPE_CHANNEL || !IS_LOCAL(user)) + return MOD_RES_PASSTHRU; + + Channel* chan = reinterpret_cast<Channel*>(dest); + ChannelSettings* settings = rm.ext.get(chan); + if (!settings) + return MOD_RES_PASSTHRU; + + Membership* memb = chan->GetUser(user); + if (!memb) + return MOD_RES_PASSTHRU; + + if (ServerInstance->OnCheckExemption(user, chan, "repeat") == MOD_RES_ALLOW) + return MOD_RES_PASSTHRU; + + if (rm.MatchLine(memb, settings, text)) + { + if (settings->Action == ChannelSettings::ACT_BLOCK) + { + user->WriteNotice("*** This line is too similiar to one of your last lines."); + return MOD_RES_DENY; + } + + if (settings->Action == ChannelSettings::ACT_BAN) + { + Modes::ChangeList changelist; + changelist.push_add(ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL), "*!*@" + user->dhost); + ServerInstance->Modes->Process(ServerInstance->FakeClient, chan, NULL, changelist); + } + + memb->chan->KickUser(ServerInstance->FakeClient, user, "Repeat flood"); + return MOD_RES_DENY; + } + return MOD_RES_PASSTHRU; + } + + void Prioritize() CXX11_OVERRIDE + { + ServerInstance->Modules->SetPriority(this, I_OnUserPreMessage, PRIORITY_LAST); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides the +E channel mode - for blocking of similiar messages", VF_COMMON|VF_VENDOR, rm.GetModuleSettings()); + } +}; + +MODULE_INIT(RepeatModule) diff --git a/src/modules/m_restrictchans.cpp b/src/modules/m_restrictchans.cpp index c76b0e79f..9e660e8ed 100644 --- a/src/modules/m_restrictchans.cpp +++ b/src/modules/m_restrictchans.cpp @@ -22,13 +22,12 @@ #include "inspircd.h" -/* $ModDesc: Only opers may create new channels if this module is loaded */ - class ModuleRestrictChans : public Module { - std::set<irc::string> allowchans; + insp::flat_set<std::string, irc::insensitive_swo> allowchans; - void ReadConfig() + public: + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { allowchans.clear(); ConfigTagList tags = ServerInstance->Config->ConfTags("allowchannel"); @@ -36,48 +35,26 @@ class ModuleRestrictChans : public Module { ConfigTag* tag = i->second; std::string txt = tag->getString("name"); - allowchans.insert(txt.c_str()); + allowchans.insert(txt); } } - public: - void init() - { - ReadConfig(); - Implementation eventlist[] = { I_OnUserPreJoin, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void OnRehash(User* user) - { - ReadConfig(); - } - - - virtual ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - irc::string x = cname; - if (!IS_LOCAL(user)) - return MOD_RES_PASSTHRU; - // channel does not yet exist (record is null, about to be created IF we were to allow it) if (!chan) { // user is not an oper and its not in the allow list - if ((!IS_OPER(user)) && (allowchans.find(x) == allowchans.end())) + if ((!user->IsOper()) && (allowchans.find(cname) == allowchans.end())) { - user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s %s :Only IRC operators may create new channels",user->nick.c_str(),cname); + user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Only IRC operators may create new channels", cname.c_str()); return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - virtual ~ModuleRestrictChans() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Only opers may create new channels if this module is loaded",VF_VENDOR); } diff --git a/src/modules/m_restrictmsg.cpp b/src/modules/m_restrictmsg.cpp index 2a9f1dc93..279775d48 100644 --- a/src/modules/m_restrictmsg.cpp +++ b/src/modules/m_restrictmsg.cpp @@ -21,29 +21,10 @@ #include "inspircd.h" -/* $ModDesc: Forbids users from messaging each other. Users may still message opers and opers may message other opers. */ - - class ModuleRestrictMsg : public Module { - private: - bool uline; - public: - - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnRehash, I_OnUserPreMessage, I_OnUserPreNotice }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void OnRehash(User*) - { - uline = ServerInstance->Config->ConfValue("restrictmsg")->getBool("uline", false); - } - - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if ((target_type == TYPE_USER) && (IS_LOCAL(user))) { @@ -54,11 +35,11 @@ class ModuleRestrictMsg : public Module // (2) the recipient is opered // (3) the recipient is on a ulined server // anything else, blocked. - if (IS_OPER(u) || IS_OPER(user) || (uline && ServerInstance->ULine(u->server))) + if (u->IsOper() || user->IsOper() || u->server->IsULine()) { return MOD_RES_PASSTHRU; } - user->WriteNumeric(ERR_CANTSENDTOUSER, "%s %s :You are not permitted to send private messages to this user",user->nick.c_str(),u->nick.c_str()); + user->WriteNumeric(ERR_CANTSENDTOUSER, "%s :You are not permitted to send private messages to this user", u->nick.c_str()); return MOD_RES_DENY; } @@ -66,16 +47,7 @@ class ModuleRestrictMsg : public Module return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return this->OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - virtual ~ModuleRestrictMsg() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Forbids users from messaging each other. Users may still message opers and opers may message other opers.",VF_VENDOR); } diff --git a/src/modules/m_ripemd160.cpp b/src/modules/m_ripemd160.cpp index 04c27e83d..8d3131bc0 100644 --- a/src/modules/m_ripemd160.cpp +++ b/src/modules/m_ripemd160.cpp @@ -56,25 +56,15 @@ */ -/* $ModDesc: Allows for RIPEMD-160 encrypted oper passwords */ - /* macro definitions */ #include "inspircd.h" -#ifdef HAS_STDINT -#include <stdint.h> -#endif -#include "hash.h" +#include "modules/hash.h" #define RMDsize 160 -#ifndef HAS_STDINT -typedef unsigned char byte; -typedef unsigned int dword; -#else -typedef uint8_t byte; -typedef uint32_t dword; -#endif +typedef uint8_t byte; +typedef uint32_t dword; /* collect four bytes into one word: */ #define BYTES_TO_DWORD(strptr) \ @@ -167,7 +157,6 @@ class RIProv : public HashProvider { if (key) { - ServerInstance->Logs->Log("m_ripemd160.so", DEBUG, "initialize with custom mdbuf"); MDbuf[0] = key[0]; MDbuf[1] = key[1]; MDbuf[2] = key[2]; @@ -176,7 +165,6 @@ class RIProv : public HashProvider } else { - ServerInstance->Logs->Log("m_ripemd160.so", DEBUG, "initialize with default mdbuf"); MDbuf[0] = 0x67452301UL; MDbuf[1] = 0xefcdab89UL; MDbuf[2] = 0x98badcfeUL; @@ -417,7 +405,6 @@ class RIProv : public HashProvider byte *RMD(byte *message, dword length, unsigned int* key) { - ServerInstance->Logs->Log("m_ripemd160", DEBUG, "RMD: '%s' length=%u", (const char*)message, length); dword MDbuf[RMDsize/32]; /* contains (A, B, C, D(E)) */ dword X[16]; /* current 16-word chunk */ unsigned int i; /* counter */ @@ -447,18 +434,13 @@ class RIProv : public HashProvider return (byte *)hashcode; } public: - std::string sum(const std::string& data) + std::string GenerateRaw(const std::string& data) { char* rv = (char*)RMD((byte*)data.data(), data.length(), NULL); return std::string(rv, RMDsize / 8); } - std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata) - { - return ""; - } - - RIProv(Module* m) : HashProvider(m, "hash/ripemd160", 20, 64) {} + RIProv(Module* m) : HashProvider(m, "ripemd160", 20, 64) {} }; class ModuleRIPEMD160 : public Module @@ -467,15 +449,12 @@ class ModuleRIPEMD160 : public Module RIProv mr; ModuleRIPEMD160() : mr(this) { - ServerInstance->Modules->AddService(mr); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides RIPEMD-160 hashing", VF_VENDOR); } - }; MODULE_INIT(ModuleRIPEMD160) - diff --git a/src/modules/m_rline.cpp b/src/modules/m_rline.cpp index d1ab5d9ba..2aee89ad2 100644 --- a/src/modules/m_rline.cpp +++ b/src/modules/m_rline.cpp @@ -20,10 +20,8 @@ */ -/* $ModDesc: RLINE: Regexp user banning. */ - #include "inspircd.h" -#include "m_regex.h" +#include "modules/regex.h" #include "xline.h" static bool ZlineOnMatch = false; @@ -60,7 +58,8 @@ class RLine : public XLine bool Matches(User *u) { - if (u->exempt) + LocalUser* lu = IS_LOCAL(u); + if (lu && lu->exempt) return false; std::string compare = u->nick + "!" + u->ident + "@" + u->host + " " + u->fullname; @@ -79,7 +78,7 @@ class RLine : public XLine ZLine* zl = new ZLine(ServerInstance->Time(), duration ? expiry - ServerInstance->Time() : 0, ServerInstance->Config->ServerName.c_str(), reason.c_str(), u->GetIPString()); if (ServerInstance->XLines->AddLine(zl, NULL)) { - std::string timestr = ServerInstance->TimeString(zl->expiry); + std::string timestr = InspIRCd::TimeString(zl->expiry); ServerInstance->SNO->WriteToSnoMask('x', "Z-line added due to R-line match on *@%s%s%s: %s", zl->ipaddr.c_str(), zl->duration ? " to expire on " : "", zl->duration ? timestr.c_str() : "", zl->reason.c_str()); added_zline = true; @@ -90,15 +89,9 @@ class RLine : public XLine DefaultApply(u, "R", false); } - void DisplayExpiry() + const std::string& Displayable() { - ServerInstance->SNO->WriteToSnoMask('x',"Removing expired R-line %s (set by %s %ld seconds ago)", - this->matchtext.c_str(), this->source.c_str(), (long int)(ServerInstance->Time() - this->set_time)); - } - - const char* Displayable() - { - return matchtext.c_str(); + return matchtext; } std::string matchtext; @@ -116,7 +109,7 @@ class RLineFactory : public XLineFactory RLineFactory(dynamic_reference<RegexFactory>& rx) : XLineFactory("R"), rxfactory(rx) { } - + /** Generate a RLine */ XLine* Generate(time_t set_time, long duration, std::string source, std::string reason, std::string xline_specific_mask) @@ -129,10 +122,6 @@ class RLineFactory : public XLineFactory return new RLine(set_time, duration, source, reason, xline_specific_mask, rxfactory); } - - ~RLineFactory() - { - } }; /** Handle /RLINE @@ -156,7 +145,7 @@ class CommandRLine : public Command { // Adding - XXX todo make this respect <insane> tag perhaps.. - long duration = ServerInstance->Duration(parameters[1]); + unsigned long duration = InspIRCd::Duration(parameters[1]); XLine *r = NULL; try @@ -165,7 +154,7 @@ class CommandRLine : public Command } catch (ModuleException &e) { - ServerInstance->SNO->WriteToSnoMask('a',"Could not add RLINE: %s", e.GetReason()); + ServerInstance->SNO->WriteToSnoMask('a',"Could not add RLINE: " + e.GetReason()); } if (r) @@ -179,7 +168,7 @@ class CommandRLine : public Command else { time_t c_requires_crap = duration + ServerInstance->Time(); - std::string timestr = ServerInstance->TimeString(c_requires_crap); + std::string timestr = InspIRCd::TimeString(c_requires_crap); ServerInstance->SNO->WriteToSnoMask('x', "%s added timed R-line for %s to expire on %s: %s", user->nick.c_str(), parameters[0].c_str(), timestr.c_str(), parameters[2].c_str()); } @@ -188,7 +177,7 @@ class CommandRLine : public Command else { delete r; - user->WriteServ("NOTICE %s :*** R-Line for %s already exists", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** R-Line for " + parameters[0] + " already exists"); } } } @@ -200,7 +189,7 @@ class CommandRLine : public Command } else { - user->WriteServ("NOTICE %s :*** R-Line %s not found in list, try /stats R.",user->nick.c_str(),parameters[0].c_str()); + user->WriteNotice("*** R-Line " + parameters[0] + " not found in list, try /stats R."); } } @@ -218,7 +207,6 @@ class CommandRLine : public Command class ModuleRLine : public Module { - private: dynamic_reference<RegexFactory> rxfactory; RLineFactory f; CommandRLine r; @@ -233,29 +221,23 @@ class ModuleRLine : public Module { } - void init() + void init() CXX11_OVERRIDE { - OnRehash(NULL); - - ServerInstance->Modules->AddService(r); ServerInstance->XLines->RegisterFactory(&f); - - Implementation eventlist[] = { I_OnUserRegister, I_OnRehash, I_OnUserPostNick, I_OnStats, I_OnBackgroundTimer, I_OnUnloadModule }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual ~ModuleRLine() + ~ModuleRLine() { ServerInstance->XLines->DelAll("R"); ServerInstance->XLines->UnregisterFactory(&f); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("RLINE: Regexp user banning.", VF_COMMON | VF_VENDOR, rxfactory ? rxfactory->name : ""); } - ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { // Apply lines on user connect XLine *rl = ServerInstance->XLines->MatchesLine("R", user); @@ -269,7 +251,7 @@ class ModuleRLine : public Module return MOD_RES_PASSTHRU; } - virtual void OnRehash(User *user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("rline"); @@ -302,7 +284,7 @@ class ModuleRLine : public Module initing = false; } - virtual ModResult OnStats(char symbol, User* user, string_list &results) + ModResult OnStats(char symbol, User* user, string_list &results) CXX11_OVERRIDE { if (symbol != 'R') return MOD_RES_PASSTHRU; @@ -311,7 +293,7 @@ class ModuleRLine : public Module return MOD_RES_DENY; } - virtual void OnUserPostNick(User *user, const std::string &oldnick) + void OnUserPostNick(User *user, const std::string &oldnick) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return; @@ -328,7 +310,7 @@ class ModuleRLine : public Module } } - virtual void OnBackgroundTimer(time_t curtime) + void OnBackgroundTimer(time_t curtime) CXX11_OVERRIDE { if (added_zline) { @@ -337,7 +319,7 @@ class ModuleRLine : public Module } } - void OnUnloadModule(Module* mod) + void OnUnloadModule(Module* mod) CXX11_OVERRIDE { // If the regex engine became unavailable or has changed, remove all rlines if (!rxfactory) diff --git a/src/modules/m_rmode.cpp b/src/modules/m_rmode.cpp new file mode 100644 index 000000000..feb17383d --- /dev/null +++ b/src/modules/m_rmode.cpp @@ -0,0 +1,110 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "listmode.h" + +/** Handle /RMODE + */ +class CommandRMode : public Command +{ + public: + CommandRMode(Module* Creator) : Command(Creator,"RMODE", 2, 3) + { + allow_empty_last_param = false; + syntax = "<channel> <mode> [pattern]"; + } + + CmdResult Handle(const std::vector<std::string> ¶meters, User *user) + { + ModeHandler* mh; + Channel* chan = ServerInstance->FindChan(parameters[0]); + char modeletter = parameters[1][0]; + + if (chan == NULL) + { + user->WriteNotice("The channel " + parameters[0] + " does not exist."); + return CMD_FAILURE; + } + + mh = ServerInstance->Modes->FindMode(modeletter, MODETYPE_CHANNEL); + if (mh == NULL || parameters[1].size() > 1) + { + user->WriteNotice(parameters[1] + " is not a valid channel mode."); + return CMD_FAILURE; + } + + if (chan->GetPrefixValue(user) < mh->GetLevelRequired()) + { + user->WriteNotice("You do not have access to unset " + ConvToStr(modeletter) + " on " + chan->name + "."); + return CMD_FAILURE; + } + + std::string pattern = parameters.size() > 2 ? parameters[2] : "*"; + PrefixMode* pm; + ListModeBase* lm; + ListModeBase::ModeList* ml; + Modes::ChangeList changelist; + + if ((pm = mh->IsPrefixMode())) + { + // As user prefix modes don't have a GetList() method, let's iterate through the channel's users. + const Channel::MemberMap& users = chan->GetUsers(); + for (Channel::MemberMap::const_iterator it = users.begin(); it != users.end(); ++it) + { + if (!InspIRCd::Match(it->first->nick, pattern)) + continue; + if (it->second->hasMode(modeletter) && !((it->first == user) && (pm->GetPrefixRank() > VOICE_VALUE))) + changelist.push_remove(mh, it->first->nick); + } + } + else if ((lm = mh->IsListModeBase()) && ((ml = lm->GetList(chan)) != NULL)) + { + for (ListModeBase::ModeList::iterator it = ml->begin(); it != ml->end(); ++it) + { + if (!InspIRCd::Match(it->mask, pattern)) + continue; + changelist.push_remove(mh, it->mask); + } + } + else + { + if (chan->IsModeSet(mh)) + changelist.push_remove(mh); + } + + ServerInstance->Modes->Process(user, chan, NULL, changelist); + return CMD_SUCCESS; + } +}; + +class ModuleRMode : public Module +{ + CommandRMode cmd; + + public: + ModuleRMode() : cmd(this) { } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Allows glob-based removal of list modes", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleRMode) diff --git a/src/modules/m_sajoin.cpp b/src/modules/m_sajoin.cpp index 7ac465732..d1321947b 100644 --- a/src/modules/m_sajoin.cpp +++ b/src/modules/m_sajoin.cpp @@ -21,62 +21,71 @@ #include "inspircd.h" -/* $ModDesc: Provides command SAJOIN to allow opers to force-join users to channels */ - /** Handle /SAJOIN */ class CommandSajoin : public Command { public: - CommandSajoin(Module* Creator) : Command(Creator,"SAJOIN", 2) + CommandSajoin(Module* Creator) : Command(Creator,"SAJOIN", 1) { allow_empty_last_param = false; - flags_needed = 'o'; Penalty = 0; syntax = "<nick> <channel>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + flags_needed = 'o'; Penalty = 0; syntax = "[<nick>] <channel>[,<channel>]"; + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { - User* dest = ServerInstance->FindNick(parameters[0]); + const unsigned int channelindex = (parameters.size() > 1) ? 1 : 0; + if (CommandParser::LoopCall(user, this, parameters, channelindex)) + return CMD_FAILURE; + + const std::string& channel = parameters[channelindex]; + const std::string& nickname = parameters.size() > 1 ? parameters[0] : user->nick; + + User* dest = ServerInstance->FindNick(nickname); if ((dest) && (dest->registered == REG_ALL)) { - if (ServerInstance->ULine(dest->server)) + if (user != dest && !user->HasPrivPermission("users/sajoin-others", false)) { - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Cannot use an SA command on a u-lined client",user->nick.c_str()); + user->WriteNotice("*** You are not allowed to /SAJOIN other users (the privilege users/sajoin-others is needed to /SAJOIN others)."); return CMD_FAILURE; } - if (IS_LOCAL(user) && !ServerInstance->IsChannel(parameters[1].c_str(), ServerInstance->Config->Limits.ChanMax)) + + if (dest->server->IsULine()) + { + user->WriteNumeric(ERR_NOPRIVILEGES, ":Cannot use an SA command on a u-lined client"); + return CMD_FAILURE; + } + if (IS_LOCAL(user) && !ServerInstance->IsChannel(channel)) { /* we didn't need to check this for each character ;) */ - user->WriteServ("NOTICE "+user->nick+" :*** Invalid characters in channel name or name too long"); + user->WriteNotice("*** Invalid characters in channel name or name too long"); + return CMD_FAILURE; + } + + Channel* chan = ServerInstance->FindChan(channel); + if ((chan) && (chan->HasUser(dest))) + { + user->SendText(":" + user->server->GetName() + " NOTICE " + user->nick + " :*** " + dest->nick + " is already on " + channel); return CMD_FAILURE; } - /* For local users, we send the JoinUser which may create a channel and set its TS. + /* For local users, we call Channel::JoinUser which may create a channel and set its TS. * For non-local users, we just return CMD_SUCCESS, knowing this will propagate it where it needs to be - * and then that server will generate the users JOIN or FJOIN instead. + * and then that server will handle the command. */ - if (IS_LOCAL(dest)) + LocalUser* localuser = IS_LOCAL(dest); + if (localuser) { - Channel::JoinUser(dest, parameters[1].c_str(), true, "", false, ServerInstance->Time()); - /* Fix for dotslasher and w00t - if the join didnt succeed, return CMD_FAILURE so that it doesnt propagate */ - Channel* n = ServerInstance->FindChan(parameters[1]); - if (n) + chan = Channel::JoinUser(localuser, channel, true); + if (chan) { - if (n->HasUser(dest)) - { - ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAJOIN to make "+dest->nick+" join "+parameters[1]); - return CMD_SUCCESS; - } - else - { - user->WriteServ("NOTICE "+user->nick+" :*** Could not join "+dest->nick+" to "+parameters[1]+" (User is probably banned, or blocking modes)"); - return CMD_FAILURE; - } + ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAJOIN to make "+dest->nick+" join "+channel); + return CMD_SUCCESS; } else { - user->WriteServ("NOTICE "+user->nick+" :*** Could not join "+dest->nick+" to "+parameters[1]); + user->WriteNotice("*** Could not join "+dest->nick+" to "+channel); return CMD_FAILURE; } } @@ -87,7 +96,7 @@ class CommandSajoin : public Command } else { - user->WriteServ("NOTICE "+user->nick+" :*** No such nickname "+parameters[0]); + user->WriteNotice("*** No such nickname "+nickname); return CMD_FAILURE; } } @@ -110,20 +119,10 @@ class ModuleSajoin : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSajoin() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides command SAJOIN to allow opers to force-join users to channels", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleSajoin) diff --git a/src/modules/m_sakick.cpp b/src/modules/m_sakick.cpp index 7dfcd8904..911b826dc 100644 --- a/src/modules/m_sakick.cpp +++ b/src/modules/m_sakick.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides a SAKICK command */ - /** Handle /SAKICK */ class CommandSakick : public Command @@ -30,29 +28,27 @@ class CommandSakick : public Command CommandSakick(Module* Creator) : Command(Creator,"SAKICK", 2, 3) { flags_needed = 'o'; Penalty = 0; syntax = "<channel> <nick> [reason]"; - TRANSLATE4(TR_TEXT, TR_NICK, TR_TEXT, TR_END); + TRANSLATE3(TR_TEXT, TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { User* dest = ServerInstance->FindNick(parameters[1]); Channel* channel = ServerInstance->FindChan(parameters[0]); - const char* reason = ""; if ((dest) && (dest->registered == REG_ALL) && (channel)) { - if (parameters.size() > 2) - { - reason = parameters[2].c_str(); - } - else + const std::string& reason = (parameters.size() > 2) ? parameters[2] : dest->nick; + + if (dest->server->IsULine()) { - reason = dest->nick.c_str(); + user->WriteNumeric(ERR_NOPRIVILEGES, ":Cannot use an SA command on a u-lined client"); + return CMD_FAILURE; } - if (ServerInstance->ULine(dest->server)) + if (!channel->HasUser(dest)) { - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Cannot use an SA command on a u-lined client", user->nick.c_str()); + user->WriteNotice("*** " + dest->nick + " is not on " + channel->name); return CMD_FAILURE; } @@ -62,28 +58,16 @@ class CommandSakick : public Command */ if (IS_LOCAL(dest)) { + // Target is on this server, kick them and send the snotice channel->KickUser(ServerInstance->FakeClient, dest, reason); - - Channel *n = ServerInstance->FindChan(parameters[1]); - if (n && n->HasUser(dest)) - { - /* Sort-of-bug: If the command was issued remotely, this message won't be sent */ - user->WriteServ("NOTICE %s :*** Unable to kick %s from %s", user->nick.c_str(), dest->nick.c_str(), parameters[0].c_str()); - return CMD_FAILURE; - } - } - - if (IS_LOCAL(user)) - { - /* Locally issued command; send the snomasks */ - ServerInstance->SNO->WriteGlobalSno('a', user->nick + " SAKICKed " + dest->nick + " on " + parameters[0]); + ServerInstance->SNO->WriteGlobalSno('a', user->nick + " SAKICKed " + dest->nick + " on " + channel->name); } return CMD_SUCCESS; } else { - user->WriteServ("NOTICE %s :*** Invalid nickname or channel", user->nick.c_str()); + user->WriteNotice("*** Invalid nickname or channel"); } return CMD_FAILURE; @@ -107,21 +91,10 @@ class ModuleSakick : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSakick() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides a SAKICK command", VF_OPTCOMMON|VF_VENDOR); } - }; MODULE_INIT(ModuleSakick) - diff --git a/src/modules/m_samode.cpp b/src/modules/m_samode.cpp index ea2ae24ab..689189229 100644 --- a/src/modules/m_samode.cpp +++ b/src/modules/m_samode.cpp @@ -20,8 +20,6 @@ */ -/* $ModDesc: Provides command SAMODE to allow opers to change modes on channels and users */ - #include "inspircd.h" /** Handle /SAMODE @@ -47,13 +45,32 @@ class CommandSamode : public Command user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); return CMD_FAILURE; } + + // Changing the modes of another user requires a special permission + if ((target != user) && (!user->HasPrivPermission("users/samode-usermodes", true))) + return CMD_FAILURE; } + // XXX: Make ModeParser clear LastParse + Modes::ChangeList emptychangelist; + ServerInstance->Modes->ProcessSingle(ServerInstance->FakeClient, NULL, ServerInstance->FakeClient, emptychangelist); + this->active = true; - ServerInstance->Parser->CallHandler("MODE", parameters, user); - if (ServerInstance->Modes->GetLastParse().length()) - ServerInstance->SNO->WriteGlobalSno('a', user->nick + " used SAMODE: " +ServerInstance->Modes->GetLastParse()); + CmdResult result = ServerInstance->Parser.CallHandler("MODE", parameters, user); this->active = false; + + if (result == CMD_SUCCESS) + { + // If lastparse is empty and the MODE command handler returned CMD_SUCCESS then + // the client queried the list of a listmode (e.g. /SAMODE #chan b), which was + // handled internally by the MODE command handler. + // + // Viewing the modes of a user or a channel can also result in CMD_SUCCESS, but + // that is not possible with /SAMODE because we require at least 2 parameters. + const std::string& lastparse = ServerInstance->Modes.GetLastParse(); + ServerInstance->SNO->WriteGlobalSno('a', user->nick + " used SAMODE: " + (lastparse.empty() ? irc::stringjoiner(parameters) : lastparse)); + } + return CMD_SUCCESS; } }; @@ -67,22 +84,12 @@ class ModuleSaMode : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->Attach(I_OnPreMode, this); - } - - ~ModuleSaMode() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides command SAMODE to allow opers to change modes on channels and users", VF_VENDOR); } - ModResult OnPreMode(User* source,User* dest,Channel* channel, const std::vector<std::string>& parameters) + ModResult OnPreMode(User* source, User* dest, Channel* channel, Modes::ChangeList& modes) CXX11_OVERRIDE { if (cmd.active) return MOD_RES_ALLOW; @@ -92,7 +99,7 @@ class ModuleSaMode : public Module void Prioritize() { Module *override = ServerInstance->Modules->Find("m_override.so"); - ServerInstance->Modules->SetPriority(this, I_OnPreMode, PRIORITY_BEFORE, &override); + ServerInstance->Modules->SetPriority(this, I_OnPreMode, PRIORITY_BEFORE, override); } }; diff --git a/src/modules/m_sanick.cpp b/src/modules/m_sanick.cpp index 4e4be77ae..ba265fddd 100644 --- a/src/modules/m_sanick.cpp +++ b/src/modules/m_sanick.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for SANICK command */ - /** Handle /SANICK */ class CommandSanick : public Command @@ -32,7 +30,7 @@ class CommandSanick : public Command { allow_empty_last_param = false; flags_needed = 'o'; Penalty = 0; syntax = "<nick> <new-nick>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -42,21 +40,21 @@ class CommandSanick : public Command /* Do local sanity checks and bails */ if (IS_LOCAL(user)) { - if (target && ServerInstance->ULine(target->server)) + if (target && target->server->IsULine()) { - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Cannot use an SA command on a u-lined client",user->nick.c_str()); + user->WriteNumeric(ERR_NOPRIVILEGES, ":Cannot use an SA command on a u-lined client"); return CMD_FAILURE; } if ((!target) || (target->registered != REG_ALL)) { - user->WriteServ("NOTICE %s :*** No such nickname: '%s'", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** No such nickname: '" + parameters[0] + "'"); return CMD_FAILURE; } - if (!ServerInstance->IsNick(parameters[1].c_str(), ServerInstance->Config->Limits.NickMax)) + if (!ServerInstance->IsNick(parameters[1])) { - user->WriteServ("NOTICE %s :*** Invalid nickname '%s'", user->nick.c_str(), parameters[1].c_str()); + user->WriteNotice("*** Invalid nickname '" + parameters[1] + "'"); return CMD_FAILURE; } } @@ -66,7 +64,7 @@ class CommandSanick : public Command { std::string oldnick = user->nick; std::string newnick = target->nick; - if (target->ChangeNick(parameters[1], true)) + if (target->ChangeNick(parameters[1])) { ServerInstance->SNO->WriteGlobalSno('a', oldnick+" used SANICK to change "+newnick+" to "+parameters[1]); } @@ -98,20 +96,10 @@ class ModuleSanick : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSanick() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for SANICK command", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleSanick) diff --git a/src/modules/m_sapart.cpp b/src/modules/m_sapart.cpp index 89256e0e4..730bf0823 100644 --- a/src/modules/m_sapart.cpp +++ b/src/modules/m_sapart.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides command SAPART to force-part users from a channel. */ - /** Handle /SAPART */ class CommandSapart : public Command @@ -30,12 +28,15 @@ class CommandSapart : public Command public: CommandSapart(Module* Creator) : Command(Creator,"SAPART", 2, 3) { - flags_needed = 'o'; Penalty = 0; syntax = "<nick> <channel> [reason]"; - TRANSLATE4(TR_NICK, TR_TEXT, TR_TEXT, TR_END); + flags_needed = 'o'; Penalty = 0; syntax = "<nick> <channel>[,<channel>] [reason]"; + TRANSLATE3(TR_NICK, TR_TEXT, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { + if (CommandParser::LoopCall(user, this, parameters, 1)) + return CMD_FAILURE; + User* dest = ServerInstance->FindNick(parameters[0]); Channel* channel = ServerInstance->FindChan(parameters[1]); std::string reason; @@ -45,9 +46,15 @@ class CommandSapart : public Command if (parameters.size() > 2) reason = parameters[2]; - if (ServerInstance->ULine(dest->server)) + if (dest->server->IsULine()) + { + user->WriteNumeric(ERR_NOPRIVILEGES, ":Cannot use an SA command on a u-lined client"); + return CMD_FAILURE; + } + + if (!channel->HasUser(dest)) { - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Cannot use an SA command on a u-lined client",user->nick.c_str()); + user->WriteNotice("*** " + dest->nick + " is not on " + channel->name); return CMD_FAILURE; } @@ -58,33 +65,14 @@ class CommandSapart : public Command if (IS_LOCAL(dest)) { channel->PartUser(dest, reason); - - Channel* n = ServerInstance->FindChan(parameters[1]); - if (!n) - { - ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAPART to make "+dest->nick+" part "+parameters[1]); - return CMD_SUCCESS; - } - else - { - if (!n->HasUser(dest)) - { - ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAPART to make "+dest->nick+" part "+parameters[1]); - return CMD_SUCCESS; - } - else - { - user->WriteServ("NOTICE %s :*** Unable to make %s part %s",user->nick.c_str(), dest->nick.c_str(), parameters[1].c_str()); - return CMD_FAILURE; - } - } + ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAPART to make "+dest->nick+" part "+channel->name); } return CMD_SUCCESS; } else { - user->WriteServ("NOTICE %s :*** Invalid nickname or channel", user->nick.c_str()); + user->WriteNotice("*** Invalid nickname or channel"); } return CMD_FAILURE; @@ -109,21 +97,10 @@ class ModuleSapart : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSapart() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides command SAPART to force-part users from a channel.", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleSapart) - diff --git a/src/modules/m_saquit.cpp b/src/modules/m_saquit.cpp index 909a026ab..aa6aa0180 100644 --- a/src/modules/m_saquit.cpp +++ b/src/modules/m_saquit.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for an SAQUIT command, exits user with a reason */ - /** Handle /SAQUIT */ class CommandSaquit : public Command @@ -31,7 +29,7 @@ class CommandSaquit : public Command CommandSaquit(Module* Creator) : Command(Creator, "SAQUIT", 2, 2) { flags_needed = 'o'; Penalty = 0; syntax = "<nick> <reason>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -39,16 +37,16 @@ class CommandSaquit : public Command User* dest = ServerInstance->FindNick(parameters[0]); if ((dest) && (!IS_SERVER(dest)) && (dest->registered == REG_ALL)) { - if (ServerInstance->ULine(dest->server)) + if (dest->server->IsULine()) { - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Cannot use an SA command on a u-lined client",user->nick.c_str()); + user->WriteNumeric(ERR_NOPRIVILEGES, ":Cannot use an SA command on a u-lined client"); return CMD_FAILURE; } // Pass the command on, so the client's server can quit it properly. if (!IS_LOCAL(dest)) return CMD_SUCCESS; - + ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SAQUIT to make "+dest->nick+" quit with a reason of "+parameters[1]); ServerInstance->Users->QuitUser(dest, parameters[1]); @@ -56,7 +54,7 @@ class CommandSaquit : public Command } else { - user->WriteServ("NOTICE %s :*** Invalid nickname '%s'", user->nick.c_str(), parameters[0].c_str()); + user->WriteNotice("*** Invalid nickname '" + parameters[0] + "'"); return CMD_FAILURE; } } @@ -79,20 +77,10 @@ class ModuleSaquit : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSaquit() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for an SAQUIT command, exits user with a reason", VF_OPTCOMMON | VF_VENDOR); } - }; MODULE_INIT(ModuleSaquit) diff --git a/src/modules/m_sasl.cpp b/src/modules/m_sasl.cpp index 32c9afc79..341b3aea7 100644 --- a/src/modules/m_sasl.cpp +++ b/src/modules/m_sasl.cpp @@ -19,23 +19,22 @@ #include "inspircd.h" -#include "m_cap.h" -#include "account.h" -#include "sasl.h" -#include "ssl.h" - -/* $ModDesc: Provides support for IRC Authentication Layer (aka: atheme SASL) via AUTHENTICATE. */ +#include "modules/cap.h" +#include "modules/account.h" +#include "modules/sasl.h" +#include "modules/ssl.h" enum SaslState { SASL_INIT, SASL_COMM, SASL_DONE }; enum SaslResult { SASL_OK, SASL_FAIL, SASL_ABORT }; static std::string sasl_target = "*"; +static Events::ModuleEventProvider* saslevprov; static void SendSASL(const parameterlist& params) { - if (!ServerInstance->PI->SendEncapsulatedData(params)) + if (!ServerInstance->PI->SendEncapsulatedData(sasl_target, "SASL", params)) { - SASLFallback(NULL, params); + FOREACH_MOD_CUSTOM(*saslevprov, SASLEventListener, OnSASLAuth, (params)); } } @@ -56,17 +55,15 @@ class SaslAuthenticator : 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_)) + LocalUser* localuser = IS_LOCAL(user); + if (method == "EXTERNAL" && localuser) { - SocketCertificateRequest req(&((LocalUser*)user_)->eh, ServerInstance->Modules->Find("m_sasl.so")); - std::string fp = req.GetFingerprint(); + std::string fp = SSLClientCert::GetFingerprint(&localuser->eh); if (fp.size()) params.push_back(fp); @@ -112,13 +109,13 @@ class SaslAuthenticator else if (msg[2] == "M") this->user->WriteNumeric(908, "%s %s :are available SASL mechanisms", this->user->nick.c_str(), msg[3].c_str()); else - ServerInstance->Logs->Log("m_sasl", DEFAULT, "Services sent an unknown SASL message \"%s\" \"%s\"", msg[2].c_str(), msg[3].c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Services sent an unknown SASL message \"%s\" \"%s\"", msg[2].c_str(), msg[3].c_str()); break; case SASL_DONE: break; default: - ServerInstance->Logs->Log("m_sasl", DEFAULT, "WTF: SaslState is not a known state (%d)", this->state); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WTF: SaslState is not a known state (%d)", this->state); break; } @@ -137,8 +134,6 @@ class SaslAuthenticator 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"); @@ -164,13 +159,13 @@ class SaslAuthenticator switch (this->result) { case SASL_OK: - this->user->WriteNumeric(903, "%s :SASL authentication successful", this->user->nick.c_str()); + this->user->WriteNumeric(903, ":SASL authentication successful"); break; case SASL_ABORT: - this->user->WriteNumeric(906, "%s :SASL authentication aborted", this->user->nick.c_str()); + this->user->WriteNumeric(906, ":SASL authentication aborted"); break; case SASL_FAIL: - this->user->WriteNumeric(904, "%s :SASL authentication failed", this->user->nick.c_str()); + this->user->WriteNumeric(904, ":SASL authentication failed"); break; default: break; @@ -226,7 +221,7 @@ class CommandSASL : public Command User* target = ServerInstance->FindNick(parameters[1]); if ((!target) || (IS_SERVER(target))) { - ServerInstance->Logs->Log("m_sasl", DEBUG,"User not found in sasl ENCAP event: %s", parameters[1].c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User not found in sasl ENCAP event: %s", parameters[1].c_str()); return CMD_FAILURE; } @@ -255,31 +250,31 @@ class ModuleSASL : public Module GenericCap cap; CommandAuthenticate auth; CommandSASL sasl; + Events::ModuleEventProvider sasleventprov; + public: ModuleSASL() - : authExt("sasl_auth", this), cap(this, "sasl"), auth(this, authExt, cap), sasl(this, authExt) + : authExt("sasl_auth", ExtensionItem::EXT_USER, this) + , cap(this, "sasl") + , auth(this, authExt, cap) + , sasl(this, authExt) + , sasleventprov(this, "event/sasl") { + saslevprov = &sasleventprov; } - void init() + void init() CXX11_OVERRIDE { - OnRehash(NULL); - Implementation eventlist[] = { I_OnEvent, I_OnUserRegister, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - ServiceProvider* providelist[] = { &auth, &sasl, &authExt }; - ServerInstance->Modules->AddServices(providelist, 3); - if (!ServerInstance->Modules->Find("m_services_account.so") || !ServerInstance->Modules->Find("m_cap.so")) - ServerInstance->Logs->Log("m_sasl", DEFAULT, "WARNING: m_services_account.so and m_cap.so are not loaded! m_sasl.so will NOT function correctly until these two modules are loaded!"); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: m_services_account.so and m_cap.so are not loaded! m_sasl.so will NOT function correctly until these two modules are loaded!"); } - void OnRehash(User*) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { sasl_target = ServerInstance->Config->ConfValue("sasl")->getString("target", "*"); } - ModResult OnUserRegister(LocalUser *user) + ModResult OnUserRegister(LocalUser *user) CXX11_OVERRIDE { SaslAuthenticator *sasl_ = authExt.get(user); if (sasl_) @@ -291,15 +286,10 @@ class ModuleSASL : public Module return MOD_RES_PASSTHRU; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for IRC Authentication Layer (aka: SASL) via AUTHENTICATE.", VF_VENDOR); } - - void OnEvent(Event &ev) - { - cap.HandleEvent(ev); - } }; MODULE_INIT(ModuleSASL) diff --git a/src/modules/m_satopic.cpp b/src/modules/m_satopic.cpp index ae1c19d91..4a6f85536 100644 --- a/src/modules/m_satopic.cpp +++ b/src/modules/m_satopic.cpp @@ -17,8 +17,6 @@ */ -/* $ModDesc: Provides a SATOPIC command */ - #include "inspircd.h" /** Handle /SATOPIC @@ -40,17 +38,15 @@ class CommandSATopic : public Command if(target) { - std::string newTopic = parameters[1]; - - // 3rd parameter overrides access checks - target->SetTopic(user, newTopic, true); + const std::string& newTopic = parameters[1]; + target->SetTopic(user, newTopic); ServerInstance->SNO->WriteGlobalSno('a', user->nick + " used SATOPIC on " + target->name + ", new topic: " + newTopic); return CMD_SUCCESS; } else { - user->WriteNumeric(401, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); return CMD_FAILURE; } } @@ -65,16 +61,7 @@ class ModuleSATopic : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSATopic() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides a SATOPIC command", VF_VENDOR); } diff --git a/src/modules/m_securelist.cpp b/src/modules/m_securelist.cpp index 6013d1fd7..f4042b8f6 100644 --- a/src/modules/m_securelist.cpp +++ b/src/modules/m_securelist.cpp @@ -21,31 +21,18 @@ #include "inspircd.h" -/* $ModDesc: Disallows /LIST for recently connected clients to hinder spam bots */ - class ModuleSecureList : public Module { - private: std::vector<std::string> allowlist; time_t WaitTime; - public: - void init() - { - OnRehash(NULL); - Implementation eventlist[] = { I_OnRehash, I_OnPreCommand, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - virtual ~ModuleSecureList() - { - } - - virtual Version GetVersion() + public: + Version GetVersion() CXX11_OVERRIDE { return Version("Disallows /LIST for recently connected clients to hinder spam bots", VF_VENDOR); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { allowlist.clear(); @@ -61,13 +48,13 @@ class ModuleSecureList : public Module * OnPreCommand() * Intercept the LIST command. */ - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { /* If the command doesnt appear to be valid, we dont want to mess with it. */ if (!validated) return MOD_RES_PASSTHRU; - if ((command == "LIST") && (ServerInstance->Time() < (user->signon+WaitTime)) && (!IS_OPER(user))) + if ((command == "LIST") && (ServerInstance->Time() < (user->signon+WaitTime)) && (!user->IsOper())) { /* Normally wouldnt be allowed here, are they exempt? */ for (std::vector<std::string>::iterator x = allowlist.begin(); x != allowlist.end(); x++) @@ -75,20 +62,20 @@ class ModuleSecureList : public Module return MOD_RES_PASSTHRU; /* Not exempt, BOOK EM DANNO! */ - user->WriteServ("NOTICE %s :*** You cannot list within the first %lu seconds of connecting. Please try again later.",user->nick.c_str(), (unsigned long) WaitTime); + user->WriteNotice("*** You cannot list within the first " + ConvToStr(WaitTime) + " seconds of connecting. Please try again later."); /* Some crap clients (read: mIRC, various java chat applets) muck up if they don't * receive these numerics whenever they send LIST, so give them an empty LIST to mull over. */ - user->WriteNumeric(321, "%s Channel :Users Name",user->nick.c_str()); - user->WriteNumeric(323, "%s :End of channel list.",user->nick.c_str()); + user->WriteNumeric(RPL_LISTSTART, "Channel :Users Name"); + user->WriteNumeric(RPL_LISTEND, ":End of channel list."); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" SECURELIST"); + tokens["SECURELIST"]; } }; diff --git a/src/modules/m_seenicks.cpp b/src/modules/m_seenicks.cpp index 95872b5b2..bff3516f1 100644 --- a/src/modules/m_seenicks.cpp +++ b/src/modules/m_seenicks.cpp @@ -21,24 +21,20 @@ #include "inspircd.h" -/* $ModDesc: Provides support for seeing local and remote nickchanges via snomasks 'n' and 'N'. */ - class ModuleSeeNicks : public Module { public: - void init() + void init() CXX11_OVERRIDE { ServerInstance->SNO->EnableSnomask('n',"NICK"); - Implementation eventlist[] = { I_OnUserPostNick }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for seeing local and remote nickchanges via snomasks", VF_VENDOR); } - virtual void OnUserPostNick(User* user, const std::string &oldnick) + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE { ServerInstance->SNO->WriteToSnoMask(IS_LOCAL(user) ? 'n' : 'N',"User %s changed their nickname to %s", oldnick.c_str(), user->nick.c_str()); } diff --git a/src/modules/m_serverban.cpp b/src/modules/m_serverban.cpp index cf77ae9ba..f51d1d373 100644 --- a/src/modules/m_serverban.cpp +++ b/src/modules/m_serverban.cpp @@ -19,43 +19,28 @@ #include "inspircd.h" -/* $ModDesc: Implements extban +b s: - server name bans */ - class ModuleServerBan : public Module { - private: public: - void init() - { - Implementation eventlist[] = { I_OnCheckBan, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ~ModuleServerBan() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Extban 's' - server ban",VF_OPTCOMMON|VF_VENDOR); } - ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) + ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) CXX11_OVERRIDE { if ((mask.length() > 2) && (mask[0] == 's') && (mask[1] == ':')) { - if (InspIRCd::Match(user->server, mask.substr(2))) + if (InspIRCd::Match(user->server->GetName(), mask.substr(2))) return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('s'); + tokens["EXTBAN"].push_back('s'); } }; - MODULE_INIT(ModuleServerBan) - diff --git a/src/modules/m_services_account.cpp b/src/modules/m_services_account.cpp index 154968e9e..4ad339fcb 100644 --- a/src/modules/m_services_account.cpp +++ b/src/modules/m_services_account.cpp @@ -22,10 +22,8 @@ */ -/* $ModDesc: Provides support for ircu-style services accounts, including chmode +R, etc. */ - #include "inspircd.h" -#include "account.h" +#include "modules/account.h" /** Channel mode +r - mark a channel as identified */ @@ -40,15 +38,15 @@ class Channel_r : public ModeHandler if (!IS_LOCAL(source)) { // Only change the mode if it's not redundant - if ((adding != channel->IsModeSet('r'))) + if ((adding != channel->IsModeSet(this))) { - channel->SetMode('r',adding); + channel->SetMode(this, adding); return MODEACTION_ALLOW; } } else { - source->WriteNumeric(500, "%s :Only a server may modify the +r channel mode", source->nick.c_str()); + source->WriteNumeric(500, ":Only a server may modify the +r channel mode"); } return MODEACTION_DENY; } @@ -66,15 +64,15 @@ class User_r : public ModeHandler { if (!IS_LOCAL(source)) { - if ((adding != dest->IsModeSet('r'))) + if ((adding != dest->IsModeSet(this))) { - dest->SetMode('r',adding); + dest->SetMode(this, adding); return MODEACTION_ALLOW; } } else { - source->WriteNumeric(500, "%s :Only a server may modify the +r user mode", source->nick.c_str()); + source->WriteNumeric(500, ":Only a server may modify the +r user mode"); } return MODEACTION_DENY; } @@ -104,86 +102,84 @@ class AChannel_M : public SimpleChannelModeHandler AChannel_M(Module* Creator) : SimpleChannelModeHandler(Creator, "regmoderated", 'M') { } }; -class ModuleServicesAccount : public Module +class AccountExtItemImpl : public AccountExtItem { - AChannel_R m1; - AChannel_M m2; - AUser_R m3; - Channel_r m4; - User_r m5; - AccountExtItem accountname; - bool checking_ban; + Events::ModuleEventProvider eventprov; - static bool ReadCGIIRCExt(const char* extname, User* user, const std::string*& out) + public: + AccountExtItemImpl(Module* mod) + : AccountExtItem("accountname", ExtensionItem::EXT_USER, mod) + , eventprov(mod, "event/account") { - ExtensionItem* wiext = ServerInstance->Extensions.GetItem(extname); - if (!wiext) - return false; + } - if (wiext->creator->ModuleSourceFile != "m_cgiirc.so") - return false; + void unserialize(SerializeFormat format, Extensible* container, const std::string& value) + { + User* user = static_cast<User*>(container); - StringExtItem* stringext = static_cast<StringExtItem*>(wiext); - std::string* addr = stringext->get(user); - if (!addr) - return false; + StringExtItem::unserialize(format, container, value); + if (!value.empty()) + { + // Logged in + if (IS_LOCAL(user)) + { + user->WriteNumeric(900, "%s %s :You are now logged in as %s", + user->GetFullHost().c_str(), value.c_str(), value.c_str()); + } + } + // If value is empty then logged out - out = addr; - return true; + FOREACH_MOD_CUSTOM(eventprov, AccountEventListener, OnAccountChange, (user, value)); } +}; +class ModuleServicesAccount : public Module +{ + AChannel_R m1; + AChannel_M m2; + AUser_R m3; + Channel_r m4; + User_r m5; + AccountExtItemImpl accountname; + bool checking_ban; public: ModuleServicesAccount() : m1(this), m2(this), m3(this), m4(this), m5(this), - accountname("accountname", this), checking_ban(false) + accountname(this) + , checking_ban(false) { } - void init() + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServiceProvider* providerlist[] = { &m1, &m2, &m3, &m4, &m5, &accountname }; - ServerInstance->Modules->AddServices(providerlist, sizeof(providerlist)/sizeof(ServiceProvider*)); - Implementation eventlist[] = { I_OnWhois, I_OnUserPreMessage, I_OnUserPreNotice, I_OnUserPreJoin, I_OnCheckBan, - I_OnDecodeMetaData, I_On005Numeric, I_OnUserPostNick, I_OnSetConnectClass }; - - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void On005Numeric(std::string &t) - { - ServerInstance->AddExtBanChar('R'); - ServerInstance->AddExtBanChar('U'); + tokens["EXTBAN"].push_back('R'); + tokens["EXTBAN"].push_back('U'); } /* <- :twisted.oscnet.org 330 w00t2 w00t2 w00t :is logged in as */ - void OnWhois(User* source, User* dest) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - std::string *account = accountname.get(dest); + std::string* account = accountname.get(whois.GetTarget()); if (account) { - ServerInstance->SendWhoisLine(source, dest, 330, "%s %s %s :is logged in as", source->nick.c_str(), dest->nick.c_str(), account->c_str()); + whois.SendLine(330, "%s :is logged in as", account->c_str()); } - if (dest->IsModeSet('r')) + if (whois.GetTarget()->IsModeSet(m5)) { /* user is registered */ - ServerInstance->SendWhoisLine(source, dest, 307, "%s %s :is a registered nick", source->nick.c_str(), dest->nick.c_str()); + whois.SendLine(307, ":is a registered nick"); } } - void OnUserPostNick(User* user, const std::string &oldnick) + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE { /* On nickchange, if they have +r, remove it */ - if (user->IsModeSet('r') && assign(user->nick) != oldnick) - { - std::vector<std::string> modechange; - modechange.push_back(user->nick); - modechange.push_back("-r"); - ServerInstance->SendMode(modechange, ServerInstance->FakeClient); - } + if (user->IsModeSet(m5) && assign(user->nick) != oldnick) + m5.RemoveMode(user); } - ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; @@ -196,10 +192,10 @@ class ModuleServicesAccount : public Module Channel* c = (Channel*)dest; ModResult res = ServerInstance->OnCheckExemption(user,c,"regmoderated"); - if (c->IsModeSet('M') && !is_registered && res != MOD_RES_ALLOW) + if (c->IsModeSet(m2) && !is_registered && res != MOD_RES_ALLOW) { // user messaging a +M channel and is not registered - user->WriteNumeric(477, user->nick+" "+c->name+" :You need to be identified to a registered account to message this channel"); + user->WriteNumeric(477, c->name+" :You need to be identified to a registered account to message this channel"); return MOD_RES_DENY; } } @@ -207,17 +203,17 @@ class ModuleServicesAccount : public Module { User* u = (User*)dest; - if (u->IsModeSet('R') && !is_registered) + if (u->IsModeSet(m3) && !is_registered) { // user messaging a +R user and is not registered - user->WriteNumeric(477, ""+ user->nick +" "+ u->nick +" :You need to be identified to a registered account to message this user"); + user->WriteNumeric(477, u->nick +" :You need to be identified to a registered account to message this user"); return MOD_RES_DENY; } } return MOD_RES_PASSTHRU; } - ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) + ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask) CXX11_OVERRIDE { if (checking_ban) return MOD_RES_PASSTHRU; @@ -253,27 +249,19 @@ class ModuleServicesAccount : public Module return MOD_RES_PASSTHRU; } - ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user, dest, target_type, text, status, exempt_list); - } - - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - if (!IS_LOCAL(user)) - return MOD_RES_PASSTHRU; - std::string *account = accountname.get(user); bool is_registered = account && !account->empty(); if (chan) { - if (chan->IsModeSet('R')) + if (chan->IsModeSet(m1)) { if (!is_registered) { // joining a +R channel and not identified - user->WriteNumeric(477, user->nick + " " + chan->name + " :You need to be identified to a registered account to join this channel"); + user->WriteNumeric(477, chan->name + " :You need to be identified to a registered account to join this channel"); return MOD_RES_DENY; } } @@ -281,56 +269,14 @@ class ModuleServicesAccount : public Module return MOD_RES_PASSTHRU; } - // Whenever the linking module receives metadata from another server and doesnt know what - // to do with it (of course, hence the 'meta') it calls this method, and it is up to each - // module in turn to figure out if this metadata key belongs to them, and what they want - // to do with it. - // In our case we're only sending a single string around, so we just construct a std::string. - // Some modules will probably get much more complex and format more detailed structs and classes - // in a textual way for sending over the link. - void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata) - { - User* dest = dynamic_cast<User*>(target); - // check if its our metadata key, and its associated with a user - if (dest && (extname == "accountname")) - { - std::string *account = accountname.get(dest); - if (account && !account->empty()) - { - trim(*account); - - if (IS_LOCAL(dest)) - { - const std::string* host = &dest->dhost; - if (dest->registered != REG_ALL) - { - if (!ReadCGIIRCExt("cgiirc_webirc_hostname", dest, host)) - { - ReadCGIIRCExt("cgiirc_webirc_ip", dest, host); - } - } - - dest->WriteNumeric(900, "%s %s!%s@%s %s :You are now logged in as %s", - dest->nick.c_str(), dest->nick.c_str(), dest->ident.c_str(), host->c_str(), account->c_str(), account->c_str()); - } - - AccountEvent(this, dest, *account).Send(); - } - else - { - AccountEvent(this, dest, "").Send(); - } - } - } - - ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) + ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE { if (myclass->config->getBool("requireaccount") && !accountname.get(user)) return MOD_RES_DENY; return MOD_RES_PASSTHRU; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for ircu-style services accounts, including chmode +R, etc.",VF_OPTCOMMON|VF_VENDOR); } diff --git a/src/modules/m_servprotect.cpp b/src/modules/m_servprotect.cpp index b4f2b5bbd..2ed37b9e4 100644 --- a/src/modules/m_servprotect.cpp +++ b/src/modules/m_servprotect.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides usermode +k to protect services from kicks, kills and mode changes. */ - /** Handles user mode +k */ class ServProtectMode : public ModeHandler @@ -44,46 +42,35 @@ class ServProtectMode : public ModeHandler } }; -class ModuleServProtectMode : public Module +class ModuleServProtectMode : public Module, public Whois::EventListener { ServProtectMode bm; public: ModuleServProtectMode() - : bm(this) + : Whois::EventListener(this) + , bm(this) { } - void init() - { - ServerInstance->Modules->AddService(bm); - Implementation eventlist[] = { I_OnWhois, I_OnKill, I_OnWhoisLine, I_OnRawMode, I_OnUserPreKick }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - - ~ModuleServProtectMode() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides usermode +k to protect services from kicks, kills, and mode changes.", VF_VENDOR); } - void OnWhois(User* src, User* dst) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - if (dst->IsModeSet('k')) + if (whois.GetTarget()->IsModeSet(bm)) { - ServerInstance->SendWhoisLine(src, dst, 310, src->nick+" "+dst->nick+" :is an "+ServerInstance->Config->Network+" Service"); + whois.SendLine(310, ":is a Network Service on " + ServerInstance->Config->Network); } } - ModResult OnRawMode(User* user, Channel* chan, const char mode, const std::string ¶m, bool adding, int pcnt) + ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding) CXX11_OVERRIDE { /* Check that the mode is not a server mode, it is being removed, the user making the change is local, there is a parameter, * and the user making the change is not a uline */ - if (!adding && chan && IS_LOCAL(user) && !param.empty() && !ServerInstance->ULine(user->server)) + if (!adding && chan && IS_LOCAL(user) && !param.empty()) { /* Check if the parameter is a valid nick/uuid */ @@ -95,10 +82,10 @@ class ModuleServProtectMode : public Module * This includes any prefix permission mode, even those registered in other modules, e.g. +qaohv. Using ::ModeString() * here means that the number of modes is restricted to only modes the user has, limiting it to as short a loop as possible. */ - if (u->IsModeSet('k') && memb && memb->modes.find(mode) != std::string::npos) + if (u->IsModeSet(bm) && memb && memb->hasMode(mh->GetModeChar())) { /* BZZZT, Denied! */ - user->WriteNumeric(482, "%s %s :You are not permitted to remove privileges from %s services", user->nick.c_str(), chan->name.c_str(), ServerInstance->Config->Network.c_str()); + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You are not permitted to remove privileges from %s services", chan->name.c_str(), ServerInstance->Config->Network.c_str()); return MOD_RES_DENY; } } @@ -107,37 +94,36 @@ class ModuleServProtectMode : public Module return MOD_RES_PASSTHRU; } - ModResult OnKill(User* src, User* dst, const std::string &reason) + ModResult OnKill(User* src, User* dst, const std::string &reason) CXX11_OVERRIDE { if (src == NULL) return MOD_RES_PASSTHRU; - if (dst->IsModeSet('k')) + if (dst->IsModeSet(bm)) { - src->WriteNumeric(485, "%s :You are not permitted to kill %s services!", src->nick.c_str(), ServerInstance->Config->Network.c_str()); + src->WriteNumeric(485, ":You are not permitted to kill %s services!", ServerInstance->Config->Network.c_str()); ServerInstance->SNO->WriteGlobalSno('a', src->nick+" tried to kill service "+dst->nick+" ("+reason+")"); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - ModResult OnUserPreKick(User *src, Membership* memb, const std::string &reason) + ModResult OnUserPreKick(User *src, Membership* memb, const std::string &reason) CXX11_OVERRIDE { - if (memb->user->IsModeSet('k')) + if (memb->user->IsModeSet(bm)) { - src->WriteNumeric(484, "%s %s :You are not permitted to kick services", - src->nick.c_str(), memb->chan->name.c_str()); + src->WriteNumeric(ERR_RESTRICTED, "%s :You are not permitted to kick services", + memb->chan->name.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - ModResult OnWhoisLine(User* src, User* dst, int &numeric, std::string &text) + ModResult OnWhoisLine(User* src, User* dst, int &numeric, std::string &text) CXX11_OVERRIDE { - return ((src != dst) && (numeric == 319) && dst->IsModeSet('k')) ? MOD_RES_DENY : MOD_RES_PASSTHRU; + return ((numeric == 319) && dst->IsModeSet(bm)) ? MOD_RES_DENY : MOD_RES_PASSTHRU; } }; - MODULE_INIT(ModuleServProtectMode) diff --git a/src/modules/m_sethost.cpp b/src/modules/m_sethost.cpp index 2ef0c0548..75dbe1c6a 100644 --- a/src/modules/m_sethost.cpp +++ b/src/modules/m_sethost.cpp @@ -21,20 +21,17 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the SETHOST command */ - /** Handle /SETHOST */ class CommandSethost : public Command { - private: char* hostmap; + public: CommandSethost(Module* Creator, char* hmap) : Command(Creator,"SETHOST", 1), hostmap(hmap) { allow_empty_last_param = false; flags_needed = 'o'; syntax = "<new-hostname>"; - TRANSLATE2(TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -44,18 +41,18 @@ class CommandSethost : public Command { if (!hostmap[(const unsigned char)*x]) { - user->WriteServ("NOTICE "+user->nick+" :*** SETHOST: Invalid characters in hostname"); + user->WriteNotice("*** SETHOST: Invalid characters in hostname"); return CMD_FAILURE; } } - if (len > 64) + if (len > ServerInstance->Config->Limits.MaxHost) { - user->WriteServ("NOTICE %s :*** SETHOST: Host too long",user->nick.c_str()); + user->WriteNotice("*** SETHOST: Host too long"); return CMD_FAILURE; } - if (user->ChangeDisplayedHost(parameters[0].c_str())) + if (user->ChangeDisplayedHost(parameters[0])) { ServerInstance->SNO->WriteGlobalSno('a', user->nick+" used SETHOST to change their displayed host to "+user->dhost); return CMD_SUCCESS; @@ -70,21 +67,14 @@ class ModuleSetHost : public Module { CommandSethost cmd; char hostmap[256]; + public: ModuleSetHost() : cmd(this, hostmap) { } - void init() - { - OnRehash(NULL); - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { std::string hmap = ServerInstance->Config->ConfValue("hostname")->getString("charmap", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_/0123456789"); @@ -93,15 +83,10 @@ class ModuleSetHost : public Module hostmap[(unsigned char)*n] = 1; } - virtual ~ModuleSetHost() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the SETHOST command", VF_VENDOR); } - }; MODULE_INIT(ModuleSetHost) diff --git a/src/modules/m_setident.cpp b/src/modules/m_setident.cpp index f63be1381..93dd4c332 100644 --- a/src/modules/m_setident.cpp +++ b/src/modules/m_setident.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the SETIDENT command */ - /** Handle /SETIDENT */ class CommandSetident : public Command @@ -33,31 +31,29 @@ class CommandSetident : public Command { allow_empty_last_param = false; flags_needed = 'o'; syntax = "<new-ident>"; - TRANSLATE2(TR_TEXT, TR_END); } CmdResult Handle(const std::vector<std::string>& parameters, User *user) { if (parameters[0].size() > ServerInstance->Config->Limits.IdentMax) { - user->WriteServ("NOTICE %s :*** SETIDENT: Ident is too long", user->nick.c_str()); + user->WriteNotice("*** SETIDENT: Ident is too long"); return CMD_FAILURE; } - if (!ServerInstance->IsIdent(parameters[0].c_str())) + if (!ServerInstance->IsIdent(parameters[0])) { - user->WriteServ("NOTICE %s :*** SETIDENT: Invalid characters in ident", user->nick.c_str()); + user->WriteNotice("*** SETIDENT: Invalid characters in ident"); return CMD_FAILURE; } - user->ChangeIdent(parameters[0].c_str()); + user->ChangeIdent(parameters[0]); ServerInstance->SNO->WriteGlobalSno('a', "%s used SETIDENT to change their ident to '%s'", user->nick.c_str(), user->ident.c_str()); return CMD_SUCCESS; } }; - class ModuleSetIdent : public Module { CommandSetident cmd; @@ -67,21 +63,10 @@ class ModuleSetIdent : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSetIdent() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the SETIDENT command", VF_VENDOR); } - }; - MODULE_INIT(ModuleSetIdent) diff --git a/src/modules/m_setidle.cpp b/src/modules/m_setidle.cpp index fdb29d14f..dd82aef29 100644 --- a/src/modules/m_setidle.cpp +++ b/src/modules/m_setidle.cpp @@ -21,25 +21,22 @@ #include "inspircd.h" -/* $ModDesc: Allows opers to set their idle time */ - /** Handle /SETIDLE */ -class CommandSetidle : public Command +class CommandSetidle : public SplitCommand { public: - CommandSetidle(Module* Creator) : Command(Creator,"SETIDLE", 1) + CommandSetidle(Module* Creator) : SplitCommand(Creator,"SETIDLE", 1) { flags_needed = 'o'; syntax = "<duration>"; - TRANSLATE2(TR_TEXT, TR_END); } - CmdResult Handle (const std::vector<std::string>& parameters, User *user) + CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) { - time_t idle = ServerInstance->Duration(parameters[0]); + int idle = InspIRCd::Duration(parameters[0]); if (idle < 1) { - user->WriteNumeric(948, "%s :Invalid idle time.",user->nick.c_str()); + user->WriteNumeric(948, ":Invalid idle time."); return CMD_FAILURE; } user->idle_lastmsg = (ServerInstance->Time() - idle); @@ -47,7 +44,7 @@ class CommandSetidle : public Command if (user->signon > user->idle_lastmsg) user->signon = user->idle_lastmsg; ServerInstance->SNO->WriteToSnoMask('a', user->nick+" used SETIDLE to set their idle time to "+ConvToStr(idle)+" seconds"); - user->WriteNumeric(944, "%s :Idle time set.",user->nick.c_str()); + user->WriteNumeric(944, ":Idle time set."); return CMD_SUCCESS; } @@ -63,16 +60,7 @@ class ModuleSetIdle : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSetIdle() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows opers to set their idle time", VF_VENDOR); } diff --git a/src/modules/m_setname.cpp b/src/modules/m_setname.cpp index d0610853b..0e71840f7 100644 --- a/src/modules/m_setname.cpp +++ b/src/modules/m_setname.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the SETNAME command */ - class CommandSetname : public Command @@ -32,18 +30,17 @@ class CommandSetname : public Command { allow_empty_last_param = false; syntax = "<new-gecos>"; - TRANSLATE2(TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) { if (parameters[0].size() > ServerInstance->Config->Limits.MaxGecos) { - user->WriteServ("NOTICE %s :*** SETNAME: GECOS too long", user->nick.c_str()); + user->WriteNotice("*** SETNAME: GECOS too long"); return CMD_FAILURE; } - if (user->ChangeName(parameters[0].c_str())) + if (user->ChangeName(parameters[0])) { ServerInstance->SNO->WriteGlobalSno('a', "%s used SETNAME to change their GECOS to '%s'", user->nick.c_str(), parameters[0].c_str()); } @@ -62,16 +59,7 @@ class ModuleSetName : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleSetName() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the SETNAME command", VF_VENDOR); } diff --git a/src/modules/m_sha256.cpp b/src/modules/m_sha256.cpp index 86970968a..48bfc0041 100644 --- a/src/modules/m_sha256.cpp +++ b/src/modules/m_sha256.cpp @@ -56,17 +56,8 @@ * SUCH DAMAGE. */ -/* $ModDesc: Allows for SHA-256 encrypted oper passwords */ - #include "inspircd.h" -#ifdef HAS_STDINT -#include <stdint.h> -#endif -#include "hash.h" - -#ifndef HAS_STDINT -typedef unsigned int uint32_t; -#endif +#include "modules/hash.h" #define SHA256_DIGEST_SIZE (256 / 8) #define SHA256_BLOCK_SIZE (512 / 8) @@ -256,19 +247,14 @@ class HashSHA256 : public HashProvider } public: - std::string sum(const std::string& data) + std::string GenerateRaw(const std::string& data) { unsigned char bytes[SHA256_DIGEST_SIZE]; SHA256(data.data(), bytes, data.length()); return std::string((char*)bytes, SHA256_DIGEST_SIZE); } - std::string sumIV(unsigned int* IV, const char* HexMap, const std::string &sdata) - { - return ""; - } - - HashSHA256(Module* parent) : HashProvider(parent, "hash/sha256", 32, 64) {} + HashSHA256(Module* parent) : HashProvider(parent, "sha256", 32, 64) {} }; class ModuleSHA256 : public Module @@ -277,10 +263,9 @@ class ModuleSHA256 : public Module public: ModuleSHA256() : sha(this) { - ServerInstance->Modules->AddService(sha); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements SHA-256 hashing", VF_VENDOR); } diff --git a/src/modules/m_showfile.cpp b/src/modules/m_showfile.cpp new file mode 100644 index 000000000..cb51c4387 --- /dev/null +++ b/src/modules/m_showfile.cpp @@ -0,0 +1,169 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +class CommandShowFile : public Command +{ + enum Method + { + SF_MSG, + SF_NOTICE, + SF_NUMERIC + }; + + std::string introtext; + std::string endtext; + unsigned int intronumeric; + unsigned int textnumeric; + unsigned int endnumeric; + file_cache contents; + Method method; + + public: + CommandShowFile(Module* parent, const std::string& cmdname) + : Command(parent, cmdname) + { + } + + CmdResult Handle(const std::vector<std::string>& parameters, User* user) CXX11_OVERRIDE + { + const std::string& sn = ServerInstance->Config->ServerName; + if (method == SF_NUMERIC) + { + if (!introtext.empty()) + user->SendText(":%s %03d %s :%s %s", sn.c_str(), intronumeric, user->nick.c_str(), sn.c_str(), introtext.c_str()); + + for (file_cache::const_iterator i = contents.begin(); i != contents.end(); ++i) + user->SendText(":%s %03d %s :- %s", sn.c_str(), textnumeric, user->nick.c_str(), i->c_str()); + + user->SendText(":%s %03d %s :%s", sn.c_str(), endnumeric, user->nick.c_str(), endtext.c_str()); + } + else + { + const char* msgcmd = (method == SF_MSG ? "PRIVMSG" : "NOTICE"); + std::string header = InspIRCd::Format(":%s %s %s :", sn.c_str(), msgcmd, user->nick.c_str()); + for (file_cache::const_iterator i = contents.begin(); i != contents.end(); ++i) + user->SendText(header + *i); + } + return CMD_SUCCESS; + } + + void UpdateSettings(ConfigTag* tag, const std::vector<std::string>& filecontents) + { + introtext = tag->getString("introtext", "Showing " + name); + endtext = tag->getString("endtext", "End of " + name); + intronumeric = tag->getInt("intronumeric", RPL_RULESTART, 0, 999); + textnumeric = tag->getInt("numeric", RPL_RULES, 0, 999); + endnumeric = tag->getInt("endnumeric", RPL_RULESEND, 0, 999); + std::string smethod = tag->getString("method"); + + method = SF_NUMERIC; + if (smethod == "msg") + method = SF_MSG; + else if (smethod == "notice") + method = SF_NOTICE; + + contents = filecontents; + if (tag->getBool("colors")) + InspIRCd::ProcessColors(contents); + } +}; + +class ModuleShowFile : public Module +{ + std::vector<CommandShowFile*> cmds; + + void ReadTag(ConfigTag* tag, std::vector<CommandShowFile*>& newcmds) + { + std::string cmdname = tag->getString("name"); + if (cmdname.empty()) + throw ModuleException("Empty value for 'name'"); + + std::transform(cmdname.begin(), cmdname.end(), cmdname.begin(), ::toupper); + + const std::string file = tag->getString("file", cmdname); + if (file.empty()) + throw ModuleException("Empty value for 'file'"); + FileReader reader(file); + + CommandShowFile* sfcmd; + Command* handler = ServerInstance->Parser.GetHandler(cmdname); + if (handler) + { + // Command exists, check if it is ours + if (handler->creator != this) + throw ModuleException("Command " + cmdname + " already exists"); + + // This is our command, make sure we don't have the same entry twice + sfcmd = static_cast<CommandShowFile*>(handler); + if (stdalgo::isin(newcmds, sfcmd)) + throw ModuleException("Command " + cmdname + " is already used in a <showfile> tag"); + } + else + { + // Command doesn't exist, create it + sfcmd = new CommandShowFile(this, cmdname); + ServerInstance->Modules->AddService(*sfcmd); + } + + sfcmd->UpdateSettings(tag, reader.GetVector()); + newcmds.push_back(sfcmd); + } + + public: + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + std::vector<CommandShowFile*> newcmds; + + ConfigTagList tags = ServerInstance->Config->ConfTags("showfile"); + for (ConfigIter i = tags.first; i != tags.second; ++i) + { + ConfigTag* tag = i->second; + try + { + ReadTag(tag, newcmds); + } + catch (CoreException& ex) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error: " + ex.GetReason() + " at " + tag->getTagLocation()); + } + } + + // Remove all commands that were removed from the config + std::vector<CommandShowFile*> removed(cmds.size()); + std::sort(newcmds.begin(), newcmds.end()); + std::set_difference(cmds.begin(), cmds.end(), newcmds.begin(), newcmds.end(), removed.begin()); + + stdalgo::delete_all(removed); + cmds.swap(newcmds); + } + + ~ModuleShowFile() + { + stdalgo::delete_all(cmds); + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides support for showing text files to users", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleShowFile) diff --git a/src/modules/m_showwhois.cpp b/src/modules/m_showwhois.cpp index 398ebf571..3cb85f3fb 100644 --- a/src/modules/m_showwhois.cpp +++ b/src/modules/m_showwhois.cpp @@ -23,16 +23,19 @@ #include "inspircd.h" -/* $ModDesc: Allows opers to set +W to see when a user uses WHOIS on them */ - /** Handle user mode +W */ class SeeWhois : public SimpleUserModeHandler { public: - SeeWhois(Module* Creator, bool IsOpersOnly) : SimpleUserModeHandler(Creator, "showwhois", 'W') + SeeWhois(Module* Creator) + : SimpleUserModeHandler(Creator, "showwhois", 'W') { - oper = IsOpersOnly; + } + + void SetOperOnly(bool operonly) + { + oper = operonly; } }; @@ -46,9 +49,9 @@ class WhoisNoticeCmd : public Command void HandleFast(User* dest, User* src) { - dest->WriteServ("NOTICE %s :*** %s (%s@%s) did a /whois on you", - dest->nick.c_str(), src->nick.c_str(), src->ident.c_str(), - dest->HasPrivPermission("users/auspex") ? src->host.c_str() : src->dhost.c_str()); + dest->WriteNotice("*** " + src->nick + " (" + src->ident + "@" + + (dest->HasPrivPermission("users/auspex") ? src->host : src->dhost) + + ") did a /whois on you"); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) @@ -66,49 +69,42 @@ class WhoisNoticeCmd : public Command } }; -class ModuleShowwhois : public Module +class ModuleShowwhois : public Module, public Whois::EventListener { bool ShowWhoisFromOpers; - SeeWhois* sw; + SeeWhois sw; WhoisNoticeCmd cmd; public: ModuleShowwhois() - : sw(NULL), cmd(this) + : Whois::EventListener(this) + , sw(this) + , cmd(this) { } - void init() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("showwhois"); - bool OpersOnly = tag->getBool("opersonly", true); + sw.SetOperOnly(tag->getBool("opersonly", true)); ShowWhoisFromOpers = tag->getBool("showfromopers", true); - - sw = new SeeWhois(this, OpersOnly); - ServerInstance->Modules->AddService(*sw); - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnWhois }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - ~ModuleShowwhois() - { - delete sw; - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows opers to set +W to see when a user uses WHOIS on them",VF_OPTCOMMON|VF_VENDOR); } - void OnWhois(User* source, User* dest) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - if (!dest->IsModeSet('W') || source == dest) + User* const source = whois.GetSource(); + User* const dest = whois.GetTarget(); + if (!dest->IsModeSet(sw) || whois.IsSelfWhois()) return; - if (!ShowWhoisFromOpers && IS_OPER(source)) + if (!ShowWhoisFromOpers && source->IsOper()) return; if (IS_LOCAL(dest)) @@ -118,14 +114,11 @@ class ModuleShowwhois : public Module else { std::vector<std::string> params; - params.push_back(dest->server); - params.push_back("WHOISNOTICE"); params.push_back(dest->uuid); params.push_back(source->uuid); - ServerInstance->PI->SendEncapsulatedData(params); + ServerInstance->PI->SendEncapsulatedData(dest->server->GetName(), cmd.name, params); } } - }; MODULE_INIT(ModuleShowwhois) diff --git a/src/modules/m_shun.cpp b/src/modules/m_shun.cpp index 8bf4d30e7..a3a2909a0 100644 --- a/src/modules/m_shun.cpp +++ b/src/modules/m_shun.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" #include "xline.h" -/* $ModDesc: Provides the /SHUN command, which stops a user from executing all except configured commands. */ - class Shun : public XLine { public: @@ -36,14 +34,11 @@ public: { } - ~Shun() - { - } - bool Matches(User *u) { // E: overrides shun - if (u->exempt) + LocalUser* lu = IS_LOCAL(u); + if (lu && lu->exempt) return false; if (InspIRCd::Match(u->GetFullHost(), matchtext) || InspIRCd::Match(u->GetFullRealHost(), matchtext) || InspIRCd::Match(u->nick+"!"+u->ident+"@"+u->GetIPString(), matchtext)) @@ -59,15 +54,9 @@ public: return false; } - void DisplayExpiry() + const std::string& Displayable() { - ServerInstance->SNO->WriteToSnoMask('x',"Removing expired shun %s (set by %s %ld seconds ago)", - this->matchtext.c_str(), this->source.c_str(), (long int)(ServerInstance->Time() - this->set_time)); - } - - const char* Displayable() - { - return matchtext.c_str(); + return matchtext; } }; @@ -107,7 +96,7 @@ class CommandShun : public Command /* 'time' is a human-readable timestring, like 2d3h2s. */ std::string target = parameters[0]; - + User *find = ServerInstance->FindNick(target); if ((find) && (find->registered == REG_ALL)) target = std::string("*!*@") + find->GetIPString(); @@ -120,18 +109,18 @@ class CommandShun : public Command } else { - user->WriteServ("NOTICE %s :*** Shun %s not found in list, try /stats H.",user->nick.c_str(),target.c_str()); + user->WriteNotice("*** Shun " + target + " not found in list, try /stats H."); return CMD_FAILURE; } } else { // Adding - XXX todo make this respect <insane> tag perhaps.. - long duration; + unsigned long duration; std::string expr; if (parameters.size() > 2) { - duration = ServerInstance->Duration(parameters[1]); + duration = InspIRCd::Duration(parameters[1]); expr = parameters[2]; } else @@ -151,7 +140,7 @@ class CommandShun : public Command else { time_t c_requires_crap = duration + ServerInstance->Time(); - std::string timestr = ServerInstance->TimeString(c_requires_crap); + std::string timestr = InspIRCd::TimeString(c_requires_crap); ServerInstance->SNO->WriteToSnoMask('x', "%s added timed SHUN for %s to expire on %s: %s", user->nick.c_str(), target.c_str(), timestr.c_str(), expr.c_str()); } @@ -159,7 +148,7 @@ class CommandShun : public Command else { delete r; - user->WriteServ("NOTICE %s :*** Shun for %s already exists", user->nick.c_str(), target.c_str()); + user->WriteNotice("*** Shun for " + target + " already exists"); return CMD_FAILURE; } } @@ -179,7 +168,7 @@ class ModuleShun : public Module { CommandShun cmd; ShunFactory f; - std::set<std::string> ShunEnabledCommands; + insp::flat_set<std::string> ShunEnabledCommands; bool NotifyOfShun; bool affectopers; @@ -188,17 +177,12 @@ class ModuleShun : public Module { } - void init() + void init() CXX11_OVERRIDE { ServerInstance->XLines->RegisterFactory(&f); - ServerInstance->Modules->AddService(cmd); - - Implementation eventlist[] = { I_OnStats, I_OnPreCommand, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); } - virtual ~ModuleShun() + ~ModuleShun() { ServerInstance->XLines->DelAll("SHUN"); ServerInstance->XLines->UnregisterFactory(&f); @@ -207,10 +191,10 @@ class ModuleShun : public Module void Prioritize() { Module* alias = ServerInstance->Modules->Find("m_alias.so"); - ServerInstance->Modules->SetPriority(this, I_OnPreCommand, PRIORITY_BEFORE, &alias); + ServerInstance->Modules->SetPriority(this, I_OnPreCommand, PRIORITY_BEFORE, alias); } - virtual ModResult OnStats(char symbol, User* user, string_list& out) + ModResult OnStats(char symbol, User* user, string_list& out) CXX11_OVERRIDE { if (symbol != 'H') return MOD_RES_PASSTHRU; @@ -219,7 +203,7 @@ class ModuleShun : public Module return MOD_RES_DENY; } - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("shun"); std::string cmds = tag->getString("enabledcommands"); @@ -242,7 +226,7 @@ class ModuleShun : public Module affectopers = tag->getBool("affectopers", false); } - virtual ModResult OnPreCommand(std::string &command, std::vector<std::string>& parameters, LocalUser* user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string>& parameters, LocalUser* user, bool validated, const std::string &original_line) CXX11_OVERRIDE { if (validated) return MOD_RES_PASSTHRU; @@ -253,18 +237,16 @@ class ModuleShun : public Module return MOD_RES_PASSTHRU; } - if (!affectopers && IS_OPER(user)) + if (!affectopers && user->IsOper()) { /* Don't do anything if the user is an operator and affectopers isn't set */ return MOD_RES_PASSTHRU; } - std::set<std::string>::iterator i = ShunEnabledCommands.find(command); - - if (i == ShunEnabledCommands.end()) + if (!ShunEnabledCommands.count(command)) { if (NotifyOfShun) - user->WriteServ("NOTICE %s :*** Command %s not processed, as you have been blocked from issuing commands (SHUN)", user->nick.c_str(), command.c_str()); + user->WriteNotice("*** Command " + command + " not processed, as you have been blocked from issuing commands (SHUN)"); return MOD_RES_DENY; } @@ -283,11 +265,10 @@ class ModuleShun : public Module return MOD_RES_PASSTHRU; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the /SHUN command, which stops a user from executing all except configured commands.",VF_VENDOR|VF_COMMON); } }; MODULE_INIT(ModuleShun) - diff --git a/src/modules/m_silence.cpp b/src/modules/m_silence.cpp index c82ab3f9d..502f947f4 100644 --- a/src/modules/m_silence.cpp +++ b/src/modules/m_silence.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the /SILENCE command */ - /* Improved drop-in replacement for the /SILENCE command * syntax: /SILENCE [+|-]<mask> <p|c|i|n|t|a|x> as in <privatemessage|channelmessage|invites|privatenotice|channelnotice|all|exclude> * @@ -66,7 +64,7 @@ class CommandSVSSilence : public Command CommandSVSSilence(Module* Creator) : Command(Creator,"SVSSILENCE", 2) { syntax = "<target> {[+|-]<mask> <p|c|i|n|t|a|x>}"; - TRANSLATE4(TR_NICK, TR_TEXT, TR_TEXT, TR_END); /* we watch for a nick. not a UID. */ + TRANSLATE3(TR_NICK, TR_TEXT, TR_TEXT); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -78,7 +76,7 @@ class CommandSVSSilence : public Command * style command so services can modify lots of entries at once. * leaving it backwards compatible for now as it's late. -- w */ - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) return CMD_FAILURE; User *u = ServerInstance->FindNick(parameters[0]); @@ -87,7 +85,7 @@ class CommandSVSSilence : public Command if (IS_LOCAL(u)) { - ServerInstance->Parser->CallHandler("SILENCE", std::vector<std::string>(parameters.begin() + 1, parameters.end()), u); + ServerInstance->Parser.CallHandler("SILENCE", std::vector<std::string>(parameters.begin() + 1, parameters.end()), u); } return CMD_SUCCESS; @@ -108,11 +106,11 @@ class CommandSilence : public Command public: SimpleExtItem<silencelist> ext; CommandSilence(Module* Creator, unsigned int &max) : Command(Creator, "SILENCE", 0), - maxsilence(max), ext("silence_list", Creator) + maxsilence(max) + , ext("silence_list", ExtensionItem::EXT_USER, Creator) { allow_empty_last_param = false; syntax = "{[+|-]<mask> <p|c|i|n|t|a|x>}"; - TRANSLATE3(TR_TEXT, TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string>& parameters, User *user) @@ -127,17 +125,17 @@ class CommandSilence : public Command for (silencelist::const_iterator c = sl->begin(); c != sl->end(); c++) { std::string decomppattern = DecompPattern(c->second); - user->WriteNumeric(271, "%s %s %s %s",user->nick.c_str(), user->nick.c_str(),c->first.c_str(), decomppattern.c_str()); + user->WriteNumeric(271, "%s %s %s", user->nick.c_str(),c->first.c_str(), decomppattern.c_str()); } } - user->WriteNumeric(272, "%s :End of Silence List",user->nick.c_str()); + user->WriteNumeric(272, ":End of Silence List"); return CMD_SUCCESS; } else if (parameters.size() > 0) { // one or more parameters, add or delete entry from the list (only the first parameter is used) - std::string mask = parameters[0].substr(1); + std::string mask(parameters[0], 1); char action = parameters[0][0]; // Default is private and notice so clients do not break int pattern = CompilePattern("pn"); @@ -149,7 +147,7 @@ class CommandSilence : public Command if (pattern == 0) { - user->WriteServ("NOTICE %s :Bad SILENCE pattern",user->nick.c_str()); + user->WriteNotice("Bad SILENCE pattern"); return CMD_INVALID; } @@ -176,7 +174,7 @@ class CommandSilence : public Command if (listitem == mask && i->second == pattern) { sl->erase(i); - user->WriteNumeric(950, "%s %s :Removed %s %s from silence list",user->nick.c_str(), user->nick.c_str(), mask.c_str(), decomppattern.c_str()); + user->WriteNumeric(950, "%s :Removed %s %s from silence list", user->nick.c_str(), mask.c_str(), decomppattern.c_str()); if (!sl->size()) { ext.unset(user); @@ -185,7 +183,7 @@ class CommandSilence : public Command } } } - user->WriteNumeric(952, "%s %s :%s %s does not exist on your silence list",user->nick.c_str(), user->nick.c_str(), mask.c_str(), decomppattern.c_str()); + user->WriteNumeric(952, "%s :%s %s does not exist on your silence list", user->nick.c_str(), mask.c_str(), decomppattern.c_str()); } else if (action == '+') { @@ -198,7 +196,7 @@ class CommandSilence : public Command } if (sl->size() > maxsilence) { - user->WriteNumeric(952, "%s %s :Your silence list is full",user->nick.c_str(), user->nick.c_str()); + user->WriteNumeric(952, "%s :Your silence list is full",user->nick.c_str()); return CMD_FAILURE; } @@ -208,7 +206,7 @@ class CommandSilence : public Command irc::string listitem = n->first.c_str(); if (listitem == mask && n->second == pattern) { - user->WriteNumeric(952, "%s %s :%s %s is already on your silence list",user->nick.c_str(), user->nick.c_str(), mask.c_str(), decomppattern.c_str()); + user->WriteNumeric(952, "%s :%s %s is already on your silence list", user->nick.c_str(), mask.c_str(), decomppattern.c_str()); return CMD_FAILURE; } } @@ -220,7 +218,7 @@ class CommandSilence : public Command { sl->push_back(silenceset(mask,pattern)); } - user->WriteNumeric(951, "%s %s :Added %s %s to silence list",user->nick.c_str(), user->nick.c_str(), mask.c_str(), decomppattern.c_str()); + user->WriteNumeric(951, "%s :Added %s %s to silence list", user->nick.c_str(), mask.c_str(), decomppattern.c_str()); return CMD_SUCCESS; } } @@ -293,6 +291,7 @@ class CommandSilence : public Command class ModuleSilence : public Module { unsigned int maxsilence; + bool ExemptULine; CommandSilence cmdsilence; CommandSVSSilence cmdsvssilence; public: @@ -302,36 +301,29 @@ class ModuleSilence : public Module { } - void init() + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { - OnRehash(NULL); - ServerInstance->Modules->AddService(cmdsilence); - ServerInstance->Modules->AddService(cmdsvssilence); - ServerInstance->Modules->AddService(cmdsilence.ext); - - Implementation eventlist[] = { I_OnRehash, I_On005Numeric, I_OnUserPreNotice, I_OnUserPreMessage, I_OnUserPreInvite }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } + ConfigTag* tag = ServerInstance->Config->ConfValue("silence"); - void OnRehash(User* user) - { - maxsilence = ServerInstance->Config->ConfValue("silence")->getInt("maxentries", 32); + maxsilence = tag->getInt("maxentries", 32); if (!maxsilence) maxsilence = 32; + + ExemptULine = tag->getBool("exemptuline", true); } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - // we don't really have a limit... - output = output + " ESILENCE SILENCE=" + ConvToStr(maxsilence); + tokens["ESILENCE"]; + tokens["SILENCE"] = ConvToStr(maxsilence); } void OnBuildExemptList(MessageType message_type, Channel* chan, User* sender, char status, CUList &exempt_list, const std::string &text) { int public_silence = (message_type == MSG_PRIVMSG ? SILENCE_CHANNEL : SILENCE_CNOTICE); - const UserMembList *ulist = chan->GetUsers(); - for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++) + const Channel::MemberMap& ulist = chan->GetUsers(); + for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i) { if (IS_LOCAL(i->first)) { @@ -343,43 +335,29 @@ class ModuleSilence : public Module } } - ModResult PreText(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list, int silence_type) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (target_type == TYPE_USER && IS_LOCAL(((User*)dest))) { - return MatchPattern((User*)dest, user, silence_type); + return MatchPattern((User*)dest, user, ((msgtype == MSG_PRIVMSG) ? SILENCE_PRIVATE : SILENCE_NOTICE)); } else if (target_type == TYPE_CHANNEL) { Channel* chan = (Channel*)dest; - if (chan) - { - this->OnBuildExemptList((silence_type == SILENCE_PRIVATE ? MSG_PRIVMSG : MSG_NOTICE), chan, user, status, exempt_list, ""); - } + this->OnBuildExemptList(msgtype, chan, user, status, exempt_list, ""); } return MOD_RES_PASSTHRU; } - ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return PreText(user, dest, target_type, text, status, exempt_list, SILENCE_PRIVATE); - } - - ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return PreText(user, dest, target_type, text, status, exempt_list, SILENCE_NOTICE); - } - - ModResult OnUserPreInvite(User* source,User* dest,Channel* channel, time_t timeout) + ModResult OnUserPreInvite(User* source,User* dest,Channel* channel, time_t timeout) CXX11_OVERRIDE { return MatchPattern(dest, source, SILENCE_INVITE); } ModResult MatchPattern(User* dest, User* source, int pattern) { - /* Server source */ - if (!source || !dest) - return MOD_RES_ALLOW; + if (ExemptULine && source->server->IsULine()) + return MOD_RES_PASSTHRU; silencelist* sl = cmdsilence.ext.get(dest); if (sl) @@ -393,11 +371,7 @@ class ModuleSilence : public Module return MOD_RES_PASSTHRU; } - ~ModuleSilence() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the /SILENCE command", VF_OPTCOMMON | VF_VENDOR); } diff --git a/src/modules/m_spanningtree/addline.cpp b/src/modules/m_spanningtree/addline.cpp index 16043b2aa..1bf847604 100644 --- a/src/modules/m_spanningtree/addline.cpp +++ b/src/modules/m_spanningtree/addline.cpp @@ -20,60 +20,37 @@ #include "inspircd.h" #include "xline.h" -#include "treesocket.h" #include "treeserver.h" #include "utils.h" +#include "commands.h" -/* $ModDep: m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - -bool TreeSocket::AddLine(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandAddLine::Handle(User* usr, std::vector<std::string>& params) { - if (params.size() < 6) - { - std::string servername = MyRoot->GetName(); - ServerInstance->SNO->WriteToSnoMask('d', "%s sent me a malformed ADDLINE", servername.c_str()); - return true; - } - XLineFactory* xlf = ServerInstance->XLines->GetFactory(params[0]); - - std::string setter = "<unknown>"; - User* usr = ServerInstance->FindNick(prefix); - if (usr) - setter = usr->nick; - else - { - TreeServer* t = Utils->FindServer(prefix); - if (t) - setter = t->GetName(); - } + const std::string& setter = usr->nick; if (!xlf) { ServerInstance->SNO->WriteToSnoMask('d',"%s sent me an unknown ADDLINE type (%s).",setter.c_str(),params[0].c_str()); - return true; + return CMD_FAILURE; } - long created = atol(params[3].c_str()), expires = atol(params[4].c_str()); - if (created < 0 || expires < 0) - return true; - XLine* xl = NULL; try { - xl = xlf->Generate(ServerInstance->Time(), expires, params[2], params[5], params[1]); + xl = xlf->Generate(ServerInstance->Time(), ConvToInt(params[4]), params[2], params[5], params[1]); } catch (ModuleException &e) { - ServerInstance->SNO->WriteToSnoMask('d',"Unable to ADDLINE type %s from %s: %s", params[0].c_str(), setter.c_str(), e.GetReason()); - return true; + ServerInstance->SNO->WriteToSnoMask('d',"Unable to ADDLINE type %s from %s: %s", params[0].c_str(), setter.c_str(), e.GetReason().c_str()); + return CMD_FAILURE; } - xl->SetCreateTime(created); + xl->SetCreateTime(ConvToInt(params[3])); if (ServerInstance->XLines->AddLine(xl, NULL)) { if (xl->duration) { - std::string timestr = ServerInstance->TimeString(xl->expiry); + std::string timestr = InspIRCd::TimeString(xl->expiry); ServerInstance->SNO->WriteToSnoMask('X',"%s added %s%s on %s to expire on %s: %s",setter.c_str(),params[0].c_str(),params[0].length() == 1 ? "-line" : "", params[1].c_str(), timestr.c_str(), params[5].c_str()); } @@ -82,20 +59,29 @@ bool TreeSocket::AddLine(const std::string &prefix, parameterlist ¶ms) ServerInstance->SNO->WriteToSnoMask('X',"%s added permanent %s%s on %s: %s",setter.c_str(),params[0].c_str(),params[0].length() == 1 ? "-line" : "", params[1].c_str(),params[5].c_str()); } - params[5] = ":" + params[5]; - User* u = ServerInstance->FindNick(prefix); - Utils->DoOneToAllButSender(prefix, "ADDLINE", params, u ? u->server : prefix); - TreeServer *remoteserver = Utils->FindServer(u ? u->server : prefix); + TreeServer* remoteserver = TreeServer::Get(usr); - if (!remoteserver->bursting) + if (!remoteserver->IsBursting()) { ServerInstance->XLines->ApplyLines(); } + return CMD_SUCCESS; } else + { delete xl; - - return true; + return CMD_FAILURE; + } } +CommandAddLine::Builder::Builder(XLine* xline, User* user) + : CmdBuilder(user, "ADDLINE") +{ + push(xline->type); + push(xline->Displayable()); + push(xline->source); + push_int(xline->set_time); + push_int(xline->duration); + push_last(xline->reason); +} diff --git a/src/modules/m_spanningtree/away.cpp b/src/modules/m_spanningtree/away.cpp index ed97c48cd..f14c8ac98 100644 --- a/src/modules/m_spanningtree/away.cpp +++ b/src/modules/m_spanningtree/away.cpp @@ -21,32 +21,38 @@ #include "main.h" #include "utils.h" -#include "treeserver.h" -#include "treesocket.h" +#include "commands.h" -bool TreeSocket::Away(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandAway::HandleRemote(RemoteUser* u, std::vector<std::string>& params) { - User* u = ServerInstance->FindNick(prefix); - if ((!u) || (IS_SERVER(u))) - return true; if (params.size()) { - FOREACH_MOD(I_OnSetAway, OnSetAway(u, params[params.size() - 1])); + FOREACH_MOD(OnSetAway, (u, params.back())); if (params.size() > 1) - u->awaytime = atoi(params[0].c_str()); + u->awaytime = ConvToInt(params[0]); else u->awaytime = ServerInstance->Time(); - u->awaymsg = params[params.size() - 1]; - - params[params.size() - 1] = ":" + params[params.size() - 1]; + u->awaymsg = params.back(); } else { - FOREACH_MOD(I_OnSetAway, OnSetAway(u, "")); + FOREACH_MOD(OnSetAway, (u, "")); u->awaymsg.clear(); } - Utils->DoOneToAllButSender(prefix,"AWAY",params,u->server); - return true; + return CMD_SUCCESS; +} + +CommandAway::Builder::Builder(User* user) + : CmdBuilder(user, "AWAY") +{ + push_int(user->awaytime).push_last(user->awaymsg); +} + +CommandAway::Builder::Builder(User* user, const std::string& msg) + : CmdBuilder(user, "AWAY") +{ + if (!msg.empty()) + push_int(ServerInstance->Time()).push_last(msg); } diff --git a/src/modules/m_spanningtree/cachetimer.cpp b/src/modules/m_spanningtree/cachetimer.cpp deleted file mode 100644 index be438651d..000000000 --- a/src/modules/m_spanningtree/cachetimer.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "inspircd.h" -#include "socket.h" -#include "xline.h" - -#include "cachetimer.h" -#include "main.h" -#include "utils.h" -#include "treeserver.h" -#include "link.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/cachetimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */ - -CacheRefreshTimer::CacheRefreshTimer(SpanningTreeUtilities *Util) : Timer(3600, ServerInstance->Time(), true), Utils(Util) -{ -} - -void CacheRefreshTimer::Tick(time_t TIME) -{ - Utils->RefreshIPCache(); -} - diff --git a/src/modules/m_spanningtree/cachetimer.h b/src/modules/m_spanningtree/cachetimer.h index bad1b7419..89933cc4b 100644 --- a/src/modules/m_spanningtree/cachetimer.h +++ b/src/modules/m_spanningtree/cachetimer.h @@ -17,13 +17,7 @@ */ -#ifndef M_SPANNINGTREE_CACHETIMER_H -#define M_SPANNINGTREE_CACHETIMER_H - -#include "timer.h" - -class ModuleSpanningTree; -class SpanningTreeUtilities; +#pragma once /** Create a timer which recurs every second, we inherit from Timer. * Timer is only one-shot however, so at the end of each Tick() we simply @@ -31,11 +25,7 @@ class SpanningTreeUtilities; */ class CacheRefreshTimer : public Timer { - private: - SpanningTreeUtilities *Utils; public: - CacheRefreshTimer(SpanningTreeUtilities* Util); - virtual void Tick(time_t TIME); + CacheRefreshTimer(); + bool Tick(time_t TIME); }; - -#endif diff --git a/src/modules/m_spanningtree/capab.cpp b/src/modules/m_spanningtree/capab.cpp index 7b6435898..9035d89c9 100644 --- a/src/modules/m_spanningtree/capab.cpp +++ b/src/modules/m_spanningtree/capab.cpp @@ -20,9 +20,7 @@ #include "inspircd.h" -#include "xline.h" -#include "treesocket.h" #include "treeserver.h" #include "utils.h" #include "link.h" @@ -30,27 +28,27 @@ std::string TreeSocket::MyModules(int filter) { - std::vector<std::string> modlist = ServerInstance->Modules->GetAllModuleNames(filter); - - if (filter == VF_COMMON && proto_version != ProtocolVersion) - CompatAddModules(modlist); + const ModuleManager::ModuleMap& modlist = ServerInstance->Modules->GetModules(); std::string capabilities; - sort(modlist.begin(),modlist.end()); - for (std::vector<std::string>::const_iterator i = modlist.begin(); i != modlist.end(); ++i) + for (ModuleManager::ModuleMap::const_iterator i = modlist.begin(); i != modlist.end(); ++i) { + // 2.2 advertises its settings for the benefit of services + // 2.0 would bork on this + if (proto_version < 1205 && i->second->ModuleSourceFile == "m_kicknorejoin.so") + continue; + + Version v = i->second->GetVersion(); + if (!(v.Flags & filter)) + continue; + if (i != modlist.begin()) - capabilities.push_back(proto_version > 1201 ? ' ' : ','); - capabilities.append(*i); - Module* m = ServerInstance->Modules->Find(*i); - if (m && proto_version > 1201) + capabilities.push_back(' '); + capabilities.append(i->first); + if (!v.link_data.empty()) { - Version v = m->GetVersion(); - if (!v.link_data.empty()) - { - capabilities.push_back('='); - capabilities.append(v.link_data); - } + capabilities.push_back('='); + capabilities.append(v.link_data); } } return capabilities; @@ -66,16 +64,18 @@ static std::string BuildModeList(ModeType type) { std::string mdesc = mh->name; mdesc.push_back('='); - if (mh->GetPrefix()) - mdesc.push_back(mh->GetPrefix()); - if (mh->GetModeChar()) - mdesc.push_back(mh->GetModeChar()); + PrefixMode* pm = mh->IsPrefixMode(); + if (pm) + { + if (pm->GetPrefix()) + mdesc.push_back(pm->GetPrefix()); + } + mdesc.push_back(mh->GetModeChar()); modes.push_back(mdesc); } } - sort(modes.begin(), modes.end()); - irc::stringjoiner line(" ", modes, 0, modes.size() - 1); - return line.GetJoined(); + std::sort(modes.begin(), modes.end()); + return irc::stringjoiner(modes); } void TreeSocket::SendCapabilities(int phase) @@ -90,7 +90,7 @@ void TreeSocket::SendCapabilities(int phase) if (phase < 2) return; - char sep = proto_version > 1201 ? ' ' : ','; + const char sep = ' '; irc::sepstream modulelist(MyModules(VF_COMMON), sep); irc::sepstream optmodulelist(MyModules(VF_OPTCOMMON), sep); /* Send module names, split at 509 length */ @@ -134,13 +134,15 @@ void TreeSocket::SendCapabilities(int phase) std::string extra; /* Do we have sha256 available? If so, we send a challenge */ - if (Utils->ChallengeResponse && (ServerInstance->Modules->Find("m_sha256.so"))) + if (ServerInstance->Modules->FindService(SERVICE_DATA, "hash/sha256")) { SetOurChallenge(ServerInstance->GenRandomStr(20)); extra = " CHALLENGE=" + this->GetOurChallenge(); } - if (proto_version < 1202) - extra += ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL) ? " HALFOP=1" : " HALFOP=0"; + + // 2.0 needs this key + if (proto_version == 1202) + extra.append(" PROTOCOL="+ConvToStr(ProtocolVersion)); this->WriteLine("CAPAB CAPABILITIES " /* Preprocessor does this one. */ ":NICKMAX="+ConvToStr(ServerInstance->Config->Limits.NickMax)+ @@ -152,18 +154,18 @@ void TreeSocket::SendCapabilities(int phase) " MAXKICK="+ConvToStr(ServerInstance->Config->Limits.MaxKick)+ " MAXGECOS="+ConvToStr(ServerInstance->Config->Limits.MaxGecos)+ " MAXAWAY="+ConvToStr(ServerInstance->Config->Limits.MaxAway)+ - " IP6SUPPORT=1"+ - " PROTOCOL="+ConvToStr(ProtocolVersion)+extra+ + " MAXHOST="+ConvToStr(ServerInstance->Config->Limits.MaxHost)+ + extra+ " PREFIX="+ServerInstance->Modes->BuildPrefixes()+ - " CHANMODES="+ServerInstance->Modes->GiveModeList(MASK_CHANNEL)+ - " USERMODES="+ServerInstance->Modes->GiveModeList(MASK_USER)+ + " CHANMODES="+ServerInstance->Modes->GiveModeList(MODETYPE_CHANNEL)+ + " USERMODES="+ServerInstance->Modes->GiveModeList(MODETYPE_USER)+ // XXX: Advertise the presence or absence of m_globops in CAPAB CAPABILITIES. // Services want to know about it, and since m_globops was not marked as VF_(OPT)COMMON // in 2.0, we advertise it here to not break linking to previous versions. // Protocol version 1201 (1.2) does not have this issue because we advertise m_globops // to 1201 protocol servers irrespectively of its module flags. - (ServerInstance->Modules->Find("m_globops.so") != NULL ? " GLOBOPS=1" : " GLOBOPS=0")+ - " SVSPART=1"); + (ServerInstance->Modules->Find("m_globops.so") != NULL ? " GLOBOPS=1" : " GLOBOPS=0") + ); this->WriteLine("CAPAB END"); } @@ -208,7 +210,23 @@ bool TreeSocket::Capab(const parameterlist ¶ms) capab->OptModuleList.clear(); capab->CapKeys.clear(); if (params.size() > 1) - proto_version = atoi(params[1].c_str()); + proto_version = ConvToInt(params[1]); + + if (proto_version < MinCompatProtocol) + { + SendError("CAPAB negotiation failed: Server is using protocol version " + (proto_version ? ConvToStr(proto_version) : "1201 or older") + + " which is too old to link with this server (version " + ConvToStr(ProtocolVersion) + + (ProtocolVersion != MinCompatProtocol ? ", links with " + ConvToStr(MinCompatProtocol) + " and above)" : ")")); + return false; + } + + // Special case, may be removed in the future + if (proto_version == 1203 || proto_version == 1204) + { + SendError("CAPAB negotiation failed: InspIRCd 2.1 beta is not supported"); + return false; + } + SendCapabilities(2); } else if (params[0] == "END") @@ -218,7 +236,7 @@ bool TreeSocket::Capab(const parameterlist ¶ms) if ((this->capab->ModuleList != this->MyModules(VF_COMMON)) && (this->capab->ModuleList.length())) { std::string diffIneed, diffUneed; - ListDifference(this->capab->ModuleList, this->MyModules(VF_COMMON), proto_version > 1201 ? ' ' : ',', diffIneed, diffUneed); + ListDifference(this->capab->ModuleList, this->MyModules(VF_COMMON), ' ', diffIneed, diffUneed); if (diffIneed.length() || diffUneed.length()) { reason = "Modules incorrectly matched on these servers."; @@ -256,21 +274,6 @@ bool TreeSocket::Capab(const parameterlist ¶ms) } } - if (this->capab->CapKeys.find("PROTOCOL") == this->capab->CapKeys.end()) - { - reason = "Protocol version not specified"; - } - else - { - proto_version = atoi(capab->CapKeys.find("PROTOCOL")->second.c_str()); - if (proto_version < MinCompatProtocol) - { - reason = "Server is using protocol version " + ConvToStr(proto_version) + - " which is too old to link with this server (version " + ConvToStr(ProtocolVersion) - + (ProtocolVersion != MinCompatProtocol ? ", links with " + ConvToStr(MinCompatProtocol) + " and above)" : ")"); - } - } - if(this->capab->CapKeys.find("PREFIX") != this->capab->CapKeys.end() && this->capab->CapKeys.find("PREFIX")->second != ServerInstance->Modes->BuildPrefixes()) reason = "One or more of the prefixes on the remote server are invalid on this server."; @@ -292,7 +295,7 @@ bool TreeSocket::Capab(const parameterlist ¶ms) } else if (this->capab->CapKeys.find("CHANMODES") != this->capab->CapKeys.end()) { - if (this->capab->CapKeys.find("CHANMODES")->second != ServerInstance->Modes->GiveModeList(MASK_CHANNEL)) + if (this->capab->CapKeys.find("CHANMODES")->second != ServerInstance->Modes->GiveModeList(MODETYPE_CHANNEL)) reason = "One or more of the channel modes on the remote server are invalid on this server."; } @@ -314,13 +317,13 @@ bool TreeSocket::Capab(const parameterlist ¶ms) } else if (this->capab->CapKeys.find("USERMODES") != this->capab->CapKeys.end()) { - if (this->capab->CapKeys.find("USERMODES")->second != ServerInstance->Modes->GiveModeList(MASK_USER)) + if (this->capab->CapKeys.find("USERMODES")->second != ServerInstance->Modes->GiveModeList(MODETYPE_USER)) reason = "One or more of the user modes on the remote server are invalid on this server."; } /* Challenge response, store their challenge for our password */ std::map<std::string,std::string>::iterator n = this->capab->CapKeys.find("CHALLENGE"); - if (Utils->ChallengeResponse && (n != this->capab->CapKeys.end()) && (ServerInstance->Modules->Find("m_sha256.so"))) + if ((n != this->capab->CapKeys.end()) && (ServerInstance->Modules->FindService(SERVICE_DATA, "hash/sha256"))) { /* Challenge-response is on now */ this->SetTheirChallenge(n->second); @@ -332,7 +335,7 @@ bool TreeSocket::Capab(const parameterlist ¶ms) } else { - /* They didnt specify a challenge or we don't have m_sha256.so, we use plaintext */ + // They didn't specify a challenge or we don't have sha256, we use plaintext if (this->LinkState == CONNECTING) { this->SendCapabilities(2); @@ -354,7 +357,7 @@ bool TreeSocket::Capab(const parameterlist ¶ms) } else { - capab->ModuleList.push_back(proto_version > 1201 ? ' ' : ','); + capab->ModuleList.push_back(' '); capab->ModuleList.append(params[1]); } } @@ -388,12 +391,11 @@ bool TreeSocket::Capab(const parameterlist ¶ms) std::string::size_type equals = item.find('='); if (equals != std::string::npos) { - std::string var = item.substr(0, equals); - std::string value = item.substr(equals+1, item.length()); + std::string var(item, 0, equals); + std::string value(item, equals+1); capab->CapKeys[var] = value; } } } return true; } - diff --git a/src/modules/m_spanningtree/commandbuilder.h b/src/modules/m_spanningtree/commandbuilder.h new file mode 100644 index 000000000..26eb4587f --- /dev/null +++ b/src/modules/m_spanningtree/commandbuilder.h @@ -0,0 +1,154 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#pragma once + +#include "utils.h" + +class TreeServer; + +class CmdBuilder +{ + protected: + std::string content; + + public: + CmdBuilder(const char* cmd) + : content(1, ':') + { + content.append(ServerInstance->Config->GetSID()); + push(cmd); + } + + CmdBuilder(const std::string& src, const char* cmd) + : content(1, ':') + { + content.append(src); + push(cmd); + } + + CmdBuilder(User* src, const char* cmd) + : content(1, ':') + { + content.append(src->uuid); + push(cmd); + } + + CmdBuilder& push_raw(const std::string& s) + { + content.append(s); + return *this; + } + + CmdBuilder& push_raw(const char* s) + { + content.append(s); + return *this; + } + + CmdBuilder& push_raw(char c) + { + content.push_back(c); + return *this; + } + + template <typename T> + CmdBuilder& push_raw_int(T i) + { + content.append(ConvToStr(i)); + return *this; + } + + template <typename InputIterator> + CmdBuilder& push_raw(InputIterator first, InputIterator last) + { + content.append(first, last); + return *this; + } + + CmdBuilder& push(const std::string& s) + { + content.push_back(' '); + content.append(s); + return *this; + } + + CmdBuilder& push(const char* s) + { + content.push_back(' '); + content.append(s); + return *this; + } + + CmdBuilder& push(char c) + { + content.push_back(' '); + content.push_back(c); + return *this; + } + + template <typename T> + CmdBuilder& push_int(T i) + { + content.push_back(' '); + content.append(ConvToStr(i)); + return *this; + } + + CmdBuilder& push_last(const std::string& s) + { + content.push_back(' '); + content.push_back(':'); + content.append(s); + return *this; + } + + template<typename T> + CmdBuilder& insert(const T& cont) + { + for (typename T::const_iterator i = cont.begin(); i != cont.end(); ++i) + push(*i); + return *this; + } + + void push_back(const std::string& s) { push(s); } + + const std::string& str() const { return content; } + operator const std::string&() const { return str(); } + + void Broadcast() const + { + Utils->DoOneToMany(*this); + } + + void Forward(TreeServer* omit) const + { + Utils->DoOneToAllButSender(*this, omit); + } + + bool Unicast(const std::string& target) const + { + return Utils->DoOneToOne(*this, target); + } + + void Unicast(User* target) const + { + Utils->DoOneToOne(*this, target->server); + } +}; diff --git a/src/modules/m_spanningtree/commands.h b/src/modules/m_spanningtree/commands.h index 3b5b499c1..1f7456426 100644 --- a/src/modules/m_spanningtree/commands.h +++ b/src/modules/m_spanningtree/commands.h @@ -17,126 +17,361 @@ */ -#ifndef M_SPANNINGTREE_COMMANDS_H -#define M_SPANNINGTREE_COMMANDS_H +#pragma once -#include "main.h" +#include "servercommand.h" +#include "commandbuilder.h" /** Handle /RCONNECT */ class CommandRConnect : public Command { - SpanningTreeUtilities* Utils; /* Utility class */ public: - CommandRConnect (Module* Callback, SpanningTreeUtilities* Util); - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); + CommandRConnect(Module* Creator); + CmdResult Handle(const std::vector<std::string>& parameters, User* user); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; class CommandRSQuit : public Command { - SpanningTreeUtilities* Utils; /* Utility class */ public: - CommandRSQuit(Module* Callback, SpanningTreeUtilities* Util); - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); - void NoticeUser(User* user, const std::string &msg); + CommandRSQuit(Module* Creator); + CmdResult Handle(const std::vector<std::string>& parameters, User* user); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; -class CommandSVSJoin : public Command +class CommandMap : public Command { public: - CommandSVSJoin(Module* Creator) : Command(Creator, "SVSJOIN", 2) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); + CommandMap(Module* Creator); + CmdResult Handle(const std::vector<std::string>& parameters, User* user); RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; -class CommandSVSPart : public Command + +class CommandSVSJoin : public ServerCommand { public: - CommandSVSPart(Module* Creator) : Command(Creator, "SVSPART", 2) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); + CommandSVSJoin(Module* Creator) : ServerCommand(Creator, "SVSJOIN", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& params); RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; -class CommandSVSNick : public Command + +class CommandSVSPart : public ServerCommand { public: - CommandSVSNick(Module* Creator) : Command(Creator, "SVSNICK", 3) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); + CommandSVSPart(Module* Creator) : ServerCommand(Creator, "SVSPART", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& params); RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; -class CommandMetadata : public Command + +class CommandSVSNick : public ServerCommand { public: - CommandMetadata(Module* Creator) : Command(Creator, "METADATA", 2) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandSVSNick(Module* Creator) : ServerCommand(Creator, "SVSNICK", 3) { } + CmdResult Handle(User* user, std::vector<std::string>& params); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); }; -class CommandUID : public Command + +class CommandMetadata : public ServerCommand { public: - CommandUID(Module* Creator) : Command(Creator, "UID", 10) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandMetadata(Module* Creator) : ServerCommand(Creator, "METADATA", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& params); + + class Builder : public CmdBuilder + { + public: + Builder(User* user, const std::string& key, const std::string& val); + Builder(Channel* chan, const std::string& key, const std::string& val); + Builder(const std::string& key, const std::string& val); + }; }; -class CommandOpertype : public Command + +class CommandUID : public ServerOnlyServerCommand<CommandUID> { public: - CommandOpertype(Module* Creator) : Command(Creator, "OPERTYPE", 1) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandUID(Module* Creator) : ServerOnlyServerCommand<CommandUID>(Creator, "UID", 10) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& params); + + class Builder : public CmdBuilder + { + public: + Builder(User* user); + }; }; -class CommandFJoin : public Command + +class CommandOpertype : public UserOnlyServerCommand<CommandOpertype> { public: - CommandFJoin(Module* Creator) : Command(Creator, "FJOIN", 3) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandOpertype(Module* Creator) : UserOnlyServerCommand<CommandOpertype>(Creator, "OPERTYPE", 1) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& params); + + class Builder : public CmdBuilder + { + public: + Builder(User* user); + }; +}; + +class TreeSocket; +class FwdFJoinBuilder; +class CommandFJoin : public ServerCommand +{ /** Remove all modes from a channel, including statusmodes (+qaovh etc), simplemodes, parameter modes. * This does not update the timestamp of the target channel, this must be done seperately. */ - void RemoveStatus(User* source, parameterlist ¶ms); + static void RemoveStatus(Channel* c); + + /** + * Lowers the TS on the given channel: removes all modes, unsets all extensions, + * clears the topic and removes all pending invites. + * @param chan The target channel whose TS to lower + * @param TS The new TS to set + * @param newname The new name of the channel; must be the same or a case change of the current name + */ + static void LowerTS(Channel* chan, time_t TS, const std::string& newname); + void ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin); + public: + CommandFJoin(Module* Creator) : ServerCommand(Creator, "FJOIN", 3) { } + CmdResult Handle(User* user, std::vector<std::string>& params); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_LOCALONLY; } + + class Builder : public CmdBuilder + { + /** Maximum possible Membership::Id length in decimal digits, used for determining whether a user will fit into + * a message or not + */ + static const size_t membid_max_digits = 20; + static const size_t maxline = 510; + std::string::size_type pos; + + protected: + void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend); + bool has_room(std::string::size_type nummodes) const; + + public: + Builder(Channel* chan, TreeServer* source = Utils->TreeRoot); + void add(Membership* memb) + { + add(memb, memb->modes.begin(), memb->modes.end()); + } + + bool has_room(Membership* memb) const + { + return has_room(memb->modes.size()); + } + + void clear(); + const std::string& finalize(); + }; +}; + +class CommandFMode : public ServerCommand +{ + public: + CommandFMode(Module* Creator) : ServerCommand(Creator, "FMODE", 3) { } + CmdResult Handle(User* user, std::vector<std::string>& params); +}; + +class CommandFTopic : public ServerCommand +{ + public: + CommandFTopic(Module* Creator) : ServerCommand(Creator, "FTOPIC", 4, 5) { } + CmdResult Handle(User* user, std::vector<std::string>& params); + + class Builder : public CmdBuilder + { + public: + Builder(Channel* chan); + Builder(User* user, Channel* chan); + }; +}; + +class CommandFHost : public UserOnlyServerCommand<CommandFHost> +{ + public: + CommandFHost(Module* Creator) : UserOnlyServerCommand<CommandFHost>(Creator, "FHOST", 1) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& params); +}; + +class CommandFIdent : public UserOnlyServerCommand<CommandFIdent> +{ + public: + CommandFIdent(Module* Creator) : UserOnlyServerCommand<CommandFIdent>(Creator, "FIDENT", 1) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& params); +}; + +class CommandFName : public UserOnlyServerCommand<CommandFName> +{ + public: + CommandFName(Module* Creator) : UserOnlyServerCommand<CommandFName>(Creator, "FNAME", 1) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& params); +}; + +class CommandIJoin : public UserOnlyServerCommand<CommandIJoin> +{ + public: + CommandIJoin(Module* Creator) : UserOnlyServerCommand<CommandIJoin>(Creator, "IJOIN", 2) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& params); +}; + +class CommandResync : public ServerOnlyServerCommand<CommandResync> +{ + public: + CommandResync(Module* Creator) : ServerOnlyServerCommand<CommandResync>(Creator, "RESYNC", 1) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_LOCALONLY; } +}; + +class CommandAway : public UserOnlyServerCommand<CommandAway> +{ + public: + CommandAway(Module* Creator) : UserOnlyServerCommand<CommandAway>(Creator, "AWAY", 0, 2) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& parameters); + + class Builder : public CmdBuilder + { + public: + Builder(User* user); + Builder(User* user, const std::string& msg); + }; +}; + +class XLine; +class CommandAddLine : public ServerCommand +{ + public: + CommandAddLine(Module* Creator) : ServerCommand(Creator, "ADDLINE", 6, 6) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); + + class Builder : public CmdBuilder + { + public: + Builder(XLine* xline, User* user = ServerInstance->FakeClient); + }; +}; + +class CommandDelLine : public ServerCommand +{ + public: + CommandDelLine(Module* Creator) : ServerCommand(Creator, "DELLINE", 2, 2) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); +}; + +class CommandEncap : public ServerCommand +{ + public: + CommandEncap(Module* Creator) : ServerCommand(Creator, "ENCAP", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); +}; + +class CommandIdle : public UserOnlyServerCommand<CommandIdle> +{ + public: + CommandIdle(Module* Creator) : UserOnlyServerCommand<CommandIdle>(Creator, "IDLE", 1) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_UNICAST(parameters[0]); } +}; + +class CommandNick : public UserOnlyServerCommand<CommandNick> +{ + public: + CommandNick(Module* Creator) : UserOnlyServerCommand<CommandNick>(Creator, "NICK", 2) { } + CmdResult HandleRemote(RemoteUser* user, std::vector<std::string>& parameters); +}; + +class CommandPing : public ServerCommand +{ + public: + CommandPing(Module* Creator) : ServerCommand(Creator, "PING", 1) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_UNICAST(parameters[0]); } +}; + +class CommandPong : public ServerOnlyServerCommand<CommandPong> +{ + public: + CommandPong(Module* Creator) : ServerOnlyServerCommand<CommandPong>(Creator, "PONG", 1) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_UNICAST(parameters[0]); } +}; + +class CommandPush : public ServerCommand +{ + public: + CommandPush(Module* Creator) : ServerCommand(Creator, "PUSH", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); + RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_UNICAST(parameters[0]); } +}; + +class CommandSave : public ServerCommand +{ + public: + /** Timestamp of the uuid nick of all users who collided and got their nick changed to uuid + */ + static const time_t SavedTimestamp = 100; + + CommandSave(Module* Creator) : ServerCommand(Creator, "SAVE", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); }; -class CommandFMode : public Command + +class CommandServer : public ServerOnlyServerCommand<CommandServer> { + static void HandleExtra(TreeServer* newserver, const std::vector<std::string>& params); + public: - CommandFMode(Module* Creator) : Command(Creator, "FMODE", 3) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandServer(Module* Creator) : ServerOnlyServerCommand<CommandServer>(Creator, "SERVER", 3) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); + + class Builder : public CmdBuilder + { + void push_property(const char* key, const std::string& val) + { + push(key).push_raw('=').push_raw(val); + } + public: + Builder(TreeServer* server); + }; }; -class CommandFTopic : public Command + +class CommandSQuit : public ServerOnlyServerCommand<CommandSQuit> { public: - CommandFTopic(Module* Creator) : Command(Creator, "FTOPIC", 4) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandSQuit(Module* Creator) : ServerOnlyServerCommand<CommandSQuit>(Creator, "SQUIT", 2) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); }; -class CommandFHost : public Command + +class CommandSNONotice : public ServerCommand { public: - CommandFHost(Module* Creator) : Command(Creator, "FHOST", 1) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandSNONotice(Module* Creator) : ServerCommand(Creator, "SNONOTICE", 2) { } + CmdResult Handle(User* user, std::vector<std::string>& parameters); }; -class CommandFIdent : public Command + +class CommandEndBurst : public ServerOnlyServerCommand<CommandEndBurst> { public: - CommandFIdent(Module* Creator) : Command(Creator, "FIDENT", 1) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandEndBurst(Module* Creator) : ServerOnlyServerCommand<CommandEndBurst>(Creator, "ENDBURST") { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); }; -class CommandFName : public Command + +class CommandSInfo : public ServerOnlyServerCommand<CommandSInfo> { public: - CommandFName(Module* Creator) : Command(Creator, "FNAME", 1) { flags_needed = FLAG_SERVERONLY; } - CmdResult Handle (const std::vector<std::string>& parameters, User *user); - RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters) { return ROUTE_BROADCAST; } + CommandSInfo(Module* Creator) : ServerOnlyServerCommand<CommandSInfo>(Creator, "SINFO", 2) { } + CmdResult HandleServer(TreeServer* server, std::vector<std::string>& parameters); + + class Builder : public CmdBuilder + { + public: + Builder(TreeServer* server, const char* type, const std::string& value); + }; }; class SpanningTreeCommands { public: - CommandRConnect rconnect; - CommandRSQuit rsquit; CommandSVSJoin svsjoin; CommandSVSPart svspart; CommandSVSNick svsnick; @@ -144,12 +379,27 @@ class SpanningTreeCommands CommandUID uid; CommandOpertype opertype; CommandFJoin fjoin; + CommandIJoin ijoin; + CommandResync resync; CommandFMode fmode; CommandFTopic ftopic; CommandFHost fhost; CommandFIdent fident; CommandFName fname; + CommandAway away; + CommandAddLine addline; + CommandDelLine delline; + CommandEncap encap; + CommandIdle idle; + CommandNick nick; + CommandPing ping; + CommandPong pong; + CommandPush push; + CommandSave save; + CommandServer server; + CommandSQuit squit; + CommandSNONotice snonotice; + CommandEndBurst endburst; + CommandSInfo sinfo; SpanningTreeCommands(ModuleSpanningTree* module); }; - -#endif diff --git a/src/modules/m_spanningtree/compat.cpp b/src/modules/m_spanningtree/compat.cpp index ec0cdb036..c2ee940fc 100644 --- a/src/modules/m_spanningtree/compat.cpp +++ b/src/modules/m_spanningtree/compat.cpp @@ -20,177 +20,466 @@ #include "inspircd.h" #include "main.h" #include "treesocket.h" +#include "treeserver.h" -static const char* const forge_common_1201[] = { - "m_allowinvite.so", - "m_alltime.so", - "m_auditorium.so", - "m_banexception.so", - "m_blockcaps.so", - "m_blockcolor.so", - "m_botmode.so", - "m_censor.so", - "m_chanfilter.so", - "m_chanhistory.so", - "m_channelban.so", - "m_chanprotect.so", - "m_chghost.so", - "m_chgname.so", - "m_commonchans.so", - "m_customtitle.so", - "m_deaf.so", - "m_delayjoin.so", - "m_delaymsg.so", - "m_exemptchanops.so", - "m_gecosban.so", - "m_globops.so", - "m_helpop.so", - "m_hidechans.so", - "m_hideoper.so", - "m_invisible.so", - "m_inviteexception.so", - "m_joinflood.so", - "m_kicknorejoin.so", - "m_knock.so", - "m_messageflood.so", - "m_muteban.so", - "m_nickflood.so", - "m_nicklock.so", - "m_noctcp.so", - "m_nokicks.so", - "m_nonicks.so", - "m_nonotice.so", - "m_nopartmsg.so", - "m_ojoin.so", - "m_operprefix.so", - "m_permchannels.so", - "m_redirect.so", - "m_regex_glob.so", - "m_regex_pcre.so", - "m_regex_posix.so", - "m_regex_tre.so", - "m_remove.so", - "m_sajoin.so", - "m_sakick.so", - "m_sanick.so", - "m_sapart.so", - "m_saquit.so", - "m_serverban.so", - "m_services_account.so", - "m_servprotect.so", - "m_setident.so", - "m_showwhois.so", - "m_silence.so", - "m_sslmodes.so", - "m_stripcolor.so", - "m_swhois.so", - "m_uninvite.so", - "m_watch.so" -}; - -static std::string wide_newline("\r\n"); static std::string newline("\n"); -void TreeSocket::CompatAddModules(std::vector<std::string>& modlist) +void TreeSocket::WriteLineNoCompat(const std::string& line) { - if (proto_version < 1202) - { - // you MUST have chgident loaded in order to be able to translate FIDENT - modlist.push_back("m_chgident.so"); - for(int i=0; i * sizeof(char*) < sizeof(forge_common_1201); i++) - { - if (ServerInstance->Modules->Find(forge_common_1201[i])) - modlist.push_back(forge_common_1201[i]); - } - // module was merged - if (ServerInstance->Modules->Find("m_operchans.so")) - { - modlist.push_back("m_operchans.so"); - modlist.push_back("m_operinvex.so"); - } - } + ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] O %s", this->GetFd(), line.c_str()); + this->WriteData(line); + this->WriteData(newline); } -void TreeSocket::WriteLine(std::string line) +void TreeSocket::WriteLine(const std::string& original_line) { if (LinkState == CONNECTED) { - if (line[0] != ':') + if (original_line.c_str()[0] != ':') { - ServerInstance->Logs->Log("m_spanningtree", DEFAULT, "Sending line without server prefix!"); - line = ":" + ServerInstance->Config->GetSID() + " " + line; + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Sending line without server prefix!"); + WriteLine(":" + ServerInstance->Config->GetSID() + " " + original_line); + return; } if (proto_version != ProtocolVersion) { + std::string line = original_line; std::string::size_type a = line.find(' '); std::string::size_type b = line.find(' ', a + 1); - std::string command = line.substr(a + 1, b-a-1); + std::string command(line, a + 1, b-a-1); // now try to find a translation entry // TODO a more efficient lookup method will be needed later - if (proto_version < 1202 && command == "FIDENT") - { - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Rewriting FIDENT for 1201-protocol server"); - line = ":" + ServerInstance->Config->GetSID() + " CHGIDENT " + line.substr(1,a-1) + line.substr(b); - } - else if (proto_version < 1202 && command == "SAVE") + if (proto_version < 1205) { - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Rewriting SAVE for 1201-protocol server"); - std::string::size_type c = line.find(' ', b + 1); - std::string uid = line.substr(b, c - b); - line = ":" + ServerInstance->Config->GetSID() + " SVSNICK" + uid + line.substr(b); - } - else if (proto_version < 1202 && command == "AWAY") - { - if (b != std::string::npos) + if (command == "IJOIN") { - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Stripping AWAY timestamp for 1201-protocol server"); + // Convert + // :<uid> IJOIN <chan> <membid> [<ts> [<flags>]] + // to + // :<sid> FJOIN <chan> <ts> + [<flags>],<uuid> std::string::size_type c = line.find(' ', b + 1); - line.erase(b,c-b); + if (c == std::string::npos) + return; + + std::string::size_type d = line.find(' ', c + 1); + // Erase membership id first + line.erase(c, d-c); + if (d == std::string::npos) + { + // No TS or modes in the command + // :22DAAAAAB IJOIN #chan + const std::string channame(line, b+1, c-b-1); + Channel* chan = ServerInstance->FindChan(channame); + if (!chan) + return; + + line.push_back(' '); + line.append(ConvToStr(chan->age)); + line.append(" + ,"); + } + else + { + d = line.find(' ', c + 1); + if (d == std::string::npos) + { + // TS present, no modes + // :22DAAAAAC IJOIN #chan 12345 + line.append(" + ,"); + } + else + { + // Both TS and modes are present + // :22DAAAAAC IJOIN #chan 12345 ov + std::string::size_type e = line.find(' ', d + 1); + if (e != std::string::npos) + line.erase(e); + + line.insert(d, " +"); + line.push_back(','); + } + } + + // Move the uuid to the end and replace the I with an F + line.append(line.substr(1, 9)); + line.erase(4, 6); + line[5] = 'F'; } - } - else if (proto_version < 1202 && command == "ENCAP") - { - // :src ENCAP target command [args...] - // A B C D - // Therefore B and C cannot be npos in a valid command - if (b == std::string::npos) + else if (command == "RESYNC") return; - std::string::size_type c = line.find(' ', b + 1); - if (c == std::string::npos) - return; - std::string::size_type d = line.find(' ', c + 1); - std::string subcmd = line.substr(c + 1, d - c - 1); + else if (command == "METADATA") + { + // Drop TS for channel METADATA, translate METADATA operquit into an OPERQUIT command + // :sid METADATA #target TS extname ... + // A B C D + if (b == std::string::npos) + return; - if (subcmd == "CHGIDENT" && d != std::string::npos) + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; + + std::string::size_type d = line.find(' ', c + 1); + if (d == std::string::npos) + return; + + if (line[b + 1] == '#') + { + // We're sending channel metadata + line.erase(c, d-c); + } + else if (!line.compare(c, d-c, " operquit", 9)) + { + // ":22D METADATA 22DAAAAAX operquit :message" -> ":22DAAAAAX OPERQUIT :message" + line = ":" + line.substr(b+1, c-b) + "OPERQUIT" + line.substr(d); + } + } + else if (command == "FTOPIC") { + // Drop channel TS for FTOPIC + // :sid FTOPIC #target TS TopicTS setter :newtopic + // A B C D E F + // :uid FTOPIC #target TS TopicTS :newtopic + // A B C D E + if (b == std::string::npos) + return; + + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; + + std::string::size_type d = line.find(' ', c + 1); + if (d == std::string::npos) + return; + std::string::size_type e = line.find(' ', d + 1); - if (e == std::string::npos) - return; // not valid - std::string target = line.substr(d + 1, e - d - 1); + if (line[e+1] == ':') + { + line.erase(c, e-c); + line.erase(a+1, 1); + } + else + line.erase(c, d-c); + } + else if ((command == "PING") || (command == "PONG")) + { + // :22D PING 20D + if (line.length() < 13) + return; + + // Insert the source SID (and a space) between the command and the first parameter + line.insert(10, line.substr(1, 4)); + } + else if (command == "OPERTYPE") + { + std::string::size_type colon = line.find(':', b); + if (colon != std::string::npos) + { + for (std::string::iterator i = line.begin()+colon; i != line.end(); ++i) + { + if (*i == ' ') + *i = '_'; + } + line.erase(colon, 1); + } + } + else if (command == "INVITE") + { + // :22D INVITE 22DAAAAAN #chan TS ExpirationTime + // A B C D E + if (b == std::string::npos) + return; + + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; + + std::string::size_type d = line.find(' ', c + 1); + if (d == std::string::npos) + return; + + std::string::size_type e = line.find(' ', d + 1); + // If there is no expiration time then everything will be erased from 'd' + line.erase(d, e-d); + } + else if (command == "FJOIN") + { + // Strip membership ids + // :22D FJOIN #chan 1234 +f 4:3 :o,22DAAAAAB:15 o,22DAAAAAA:15 + // :22D FJOIN #chan 1234 +f 4:3 o,22DAAAAAB:15 + // :22D FJOIN #chan 1234 +Pf 4:3 : - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Forging acceptance of CHGIDENT from 1201-protocol server"); - recvq.insert(0, ":" + target + " FIDENT " + line.substr(e) + "\n"); + // If the last parameter is prefixed by a colon then it's a userlist which may have 0 or more users; + // if it isn't, then it is a single member + std::string::size_type spcolon = line.find(" :"); + if (spcolon != std::string::npos) + { + spcolon++; + // Loop while there is a ':' in the userlist, this is never true if the channel is empty + std::string::size_type pos = std::string::npos; + while ((pos = line.rfind(':', pos-1)) > spcolon) + { + // Find the next space after the ':' + std::string::size_type sp = line.find(' ', pos); + // Erase characters between the ':' and the next space after it, including the ':' but not the space; + // if there is no next space, everything will be erased between pos and the end of the line + line.erase(pos, sp-pos); + } + } + else + { + // Last parameter is a single member + std::string::size_type sp = line.rfind(' '); + std::string::size_type colon = line.find(':', sp); + line.erase(colon); + } } + else if (command == "KICK") + { + // Strip membership id if the KICK has one + if (b == std::string::npos) + return; + + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; - Command* thiscmd = ServerInstance->Parser->GetHandler(subcmd); - if (thiscmd && subcmd != "WHOISNOTICE") + std::string::size_type d = line.find(' ', c + 1); + if ((d < line.size()-1) && (original_line[d+1] != ':')) + { + // There is a third parameter which doesn't begin with a colon, erase it + std::string::size_type e = line.find(' ', d + 1); + line.erase(d, e-d); + } + } + else if (command == "SINFO") + { + // :22D SINFO version :InspIRCd-2.2 + // A B C + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; + + // Only translating SINFO version, discard everything else + if (line.compare(b, 9, " version ", 9)) + return; + + line = line.substr(0, 5) + "VERSION" + line.substr(c); + } + else if (command == "SERVER") { - Version ver = thiscmd->creator->GetVersion(); - if (ver.Flags & VF_OPTCOMMON) + // :001 SERVER inspircd.test 002 [<anything> ...] :gecos + // A B C + std::string::size_type c = line.find(' ', b + 1); + if (c == std::string::npos) + return; + + std::string::size_type d = c + 4; + std::string::size_type spcolon = line.find(" :", d); + if (spcolon == std::string::npos) + return; + + line.erase(d, spcolon-d); + line.insert(c, " * 0"); + + if (burstsent) { - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Removing ENCAP on '%s' for 1201-protocol server", - subcmd.c_str()); - line.erase(a, c-a); + WriteLineNoCompat(line); + + // Synthesize a :<newserver> BURST <time> message + spcolon = line.find(" :"); + line = CmdBuilder(line.substr(spcolon-3, 3), "BURST").push_int(ServerInstance->Time()).str(); } } } + WriteLineNoCompat(line); + return; } } - ServerInstance->Logs->Log("m_spanningtree", RAWIO, "S[%d] O %s", this->GetFd(), line.c_str()); - this->WriteData(line); - if (proto_version < 1202) - this->WriteData(wide_newline); - else - this->WriteData(newline); + WriteLineNoCompat(original_line); +} + +namespace +{ + bool InsertCurrentChannelTS(std::vector<std::string>& params, unsigned int chanindex = 0, unsigned int pos = 1) + { + Channel* chan = ServerInstance->FindChan(params[chanindex]); + if (!chan) + return false; + + // Insert the current TS of the channel after the pos-th parameter + params.insert(params.begin()+pos, ConvToStr(chan->age)); + return true; + } +} + +bool TreeSocket::PreProcessOldProtocolMessage(User*& who, std::string& cmd, std::vector<std::string>& params) +{ + if ((cmd == "METADATA") && (params.size() >= 3) && (params[0][0] == '#')) + { + // :20D METADATA #channel extname :extdata + return InsertCurrentChannelTS(params); + } + else if ((cmd == "FTOPIC") && (params.size() >= 4)) + { + // :20D FTOPIC #channel 100 Attila :topic text + return InsertCurrentChannelTS(params); + } + else if ((cmd == "PING") || (cmd == "PONG")) + { + if (params.size() == 1) + { + // If it's a PING with 1 parameter, reply with a PONG now, if it's a PONG with 1 parameter (weird), do nothing + if (cmd[1] == 'I') + this->WriteData(":" + ServerInstance->Config->GetSID() + " PONG " + params[0] + newline); + + // Don't process this message further + return false; + } + + // :20D PING 20D 22D + // :20D PONG 20D 22D + // Drop the first parameter + params.erase(params.begin()); + + // If the target is a server name, translate it to a SID + if (!InspIRCd::IsSID(params[0])) + { + TreeServer* server = Utils->FindServer(params[0]); + if (!server) + { + // We've no idea what this is, log and stop processing + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Received a " + cmd + " with an unknown target: \"" + params[0] + "\", command dropped"); + return false; + } + + params[0] = server->GetID(); + } + } + else if ((cmd == "GLINE") || (cmd == "KLINE") || (cmd == "ELINE") || (cmd == "ZLINE") || (cmd == "QLINE")) + { + // Fix undocumented protocol usage: translate GLINE, ZLINE, etc. into ADDLINE or DELLINE + if ((params.size() != 1) && (params.size() != 3)) + return false; + + parameterlist p; + p.push_back(cmd.substr(0, 1)); + p.push_back(params[0]); + + if (params.size() == 3) + { + cmd = "ADDLINE"; + p.push_back(who->nick); + p.push_back(ConvToStr(ServerInstance->Time())); + p.push_back(ConvToStr(InspIRCd::Duration(params[1]))); + p.push_back(params[2]); + } + else + cmd = "DELLINE"; + + params.swap(p); + } + else if (cmd == "SVSMODE") + { + cmd = "MODE"; + } + else if (cmd == "OPERQUIT") + { + // Translate OPERQUIT into METADATA + if (params.empty()) + return false; + + cmd = "METADATA"; + params.insert(params.begin(), who->uuid); + params.insert(params.begin()+1, "operquit"); + who = MyRoot->ServerUser; + } + else if ((cmd == "TOPIC") && (params.size() >= 2)) + { + // :20DAAAAAC TOPIC #chan :new topic + cmd = "FTOPIC"; + if (!InsertCurrentChannelTS(params)) + return false; + + params.insert(params.begin()+2, ConvToStr(ServerInstance->Time())); + } + else if (cmd == "MODENOTICE") + { + // MODENOTICE is always supported by 2.0 but it's optional in 2.2. + params.insert(params.begin(), "*"); + params.insert(params.begin()+1, cmd); + cmd = "ENCAP"; + } + else if (cmd == "RULES") + { + return false; + } + else if (cmd == "INVITE") + { + // :20D INVITE 22DAAABBB #chan + // :20D INVITE 22DAAABBB #chan 123456789 + // Insert channel timestamp after the channel name; the 3rd parameter, if there, is the invite expiration time + return InsertCurrentChannelTS(params, 1, 2); + } + else if (cmd == "VERSION") + { + // :20D VERSION :InspIRCd-2.0 + // change to + // :20D SINFO version :InspIRCd-2.0 + cmd = "SINFO"; + params.insert(params.begin(), "version"); + } + else if (cmd == "JOIN") + { + // 2.0 allows and forwards legacy JOINs but we don't, so translate them to FJOINs before processing + if ((params.size() != 1) || (IS_SERVER(who))) + return false; // Huh? + + cmd = "FJOIN"; + Channel* chan = ServerInstance->FindChan(params[0]); + params.push_back(ConvToStr(chan ? chan->age : ServerInstance->Time())); + params.push_back("+"); + params.push_back(","); + params.back().append(who->uuid); + who = TreeServer::Get(who)->ServerUser; + } + else if ((cmd == "FMODE") && (params.size() >= 2)) + { + // Translate user mode changes with timestamp to MODE + if (params[0][0] != '#') + { + User* user = ServerInstance->FindUUID(params[0]); + if (!user) + return false; + + // Emulate the old nonsensical behavior + if (user->age < ServerCommand::ExtractTS(params[1])) + return false; + + cmd = "MODE"; + params.erase(params.begin()+1); + } + } + else if ((cmd == "SERVER") && (params.size() > 4)) + { + // This does not affect the initial SERVER line as it is sent before the link state is CONNECTED + // :20D SERVER <name> * 0 <sid> <desc> + // change to + // :20D SERVER <name> <sid> <desc> + + params[1].swap(params[3]); + params.erase(params.begin()+2, params.begin()+4); + + // If the source of this SERVER message is not bursting, then new servers it introduces are bursting + TreeServer* server = TreeServer::Get(who); + if (!server->IsBursting()) + params.insert(params.begin()+2, "burst=" + ConvToStr(ServerInstance->Time()*1000)); + } + else if (cmd == "BURST") + { + // A server is introducing another one, drop unnecessary BURST + return false; + } + + return true; // Passthru } diff --git a/src/modules/m_spanningtree/delline.cpp b/src/modules/m_spanningtree/delline.cpp index 540ca5079..c76af2fb7 100644 --- a/src/modules/m_spanningtree/delline.cpp +++ b/src/modules/m_spanningtree/delline.cpp @@ -20,38 +20,18 @@ #include "inspircd.h" #include "xline.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" +#include "commands.h" -/* $ModDep: m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - - -bool TreeSocket::DelLine(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandDelLine::Handle(User* user, std::vector<std::string>& params) { - if (params.size() < 2) - return true; - - std::string setter = "<unknown>"; - - User* user = ServerInstance->FindNick(prefix); - if (user) - setter = user->nick; - else - { - TreeServer* t = Utils->FindServer(prefix); - if (t) - setter = t->GetName(); - } - + const std::string& setter = user->nick; /* NOTE: No check needed on 'user', this function safely handles NULL */ if (ServerInstance->XLines->DelLine(params[1].c_str(), params[0], user)) { ServerInstance->SNO->WriteToSnoMask('X',"%s removed %s%s on %s", setter.c_str(), params[0].c_str(), params[0].length() == 1 ? "-line" : "", params[1].c_str()); - Utils->DoOneToAllButSender(prefix,"DELLINE", params, prefix); + return CMD_SUCCESS; } - return true; + return CMD_FAILURE; } - diff --git a/src/modules/m_spanningtree/encap.cpp b/src/modules/m_spanningtree/encap.cpp index dabfc086b..95f8f4e4a 100644 --- a/src/modules/m_spanningtree/encap.cpp +++ b/src/modules/m_spanningtree/encap.cpp @@ -18,32 +18,28 @@ #include "inspircd.h" -#include "xline.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" +#include "commands.h" /** ENCAP */ -void TreeSocket::Encap(User* who, parameterlist ¶ms) +CmdResult CommandEncap::Handle(User* user, std::vector<std::string>& params) { - if (params.size() > 1) + if (ServerInstance->Config->GetSID() == params[0] || InspIRCd::Match(ServerInstance->Config->ServerName, params[0])) { - if (ServerInstance->Config->GetSID() == params[0] || InspIRCd::Match(ServerInstance->Config->ServerName, params[0])) - { - parameterlist plist(params.begin() + 2, params.end()); - ServerInstance->Parser->CallHandler(params[1], plist, who); - // discard return value, ENCAP shall succeed even if the command does not exist - } - - params[params.size() - 1] = ":" + params[params.size() - 1]; + parameterlist plist(params.begin() + 2, params.end()); + Command* cmd = NULL; + ServerInstance->Parser.CallHandler(params[1], plist, user, &cmd); + // Discard return value, ENCAP shall succeed even if the command does not exist - if (params[0].find_first_of("*?") != std::string::npos) - { - Utils->DoOneToAllButSender(who->uuid, "ENCAP", params, who->server); - } - else - Utils->DoOneToOne(who->uuid, "ENCAP", params, params[0]); + if ((cmd) && (cmd->force_manual_route)) + return CMD_FAILURE; } + return CMD_SUCCESS; } +RouteDescriptor CommandEncap::GetRouting(User* user, const std::vector<std::string>& params) +{ + if (params[0].find_first_of("*?") != std::string::npos) + return ROUTE_BROADCAST; + return ROUTE_UNICAST(params[0]); +} diff --git a/src/modules/m_spanningtree/fjoin.cpp b/src/modules/m_spanningtree/fjoin.cpp index 47b394522..e29aa09d7 100644 --- a/src/modules/m_spanningtree/fjoin.cpp +++ b/src/modules/m_spanningtree/fjoin.cpp @@ -25,11 +25,26 @@ #include "treeserver.h" #include "treesocket.h" +/** FJOIN builder for rebuilding incoming FJOINs and splitting them up into multiple messages if necessary + */ +class FwdFJoinBuilder : public CommandFJoin::Builder +{ + TreeServer* const sourceserver; + + public: + FwdFJoinBuilder(Channel* chan, TreeServer* server) + : CommandFJoin::Builder(chan, server) + , sourceserver(server) + { + } + + void add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend); +}; + /** FJOIN, almost identical to TS6 SJOIN, except for nicklist handling. */ -CmdResult CommandFJoin::Handle(const std::vector<std::string>& params, User *srcuser) +CmdResult CommandFJoin::Handle(User* srcuser, std::vector<std::string>& params) { - SpanningTreeUtilities* Utils = ((ModuleSpanningTree*)(Module*)creator)->Utils; - /* 1.1 FJOIN works as follows: + /* 1.1+ FJOIN works as follows: * * Each FJOIN is sent along with a timestamp, and the side with the lowest * timestamp 'wins'. From this point on we will refer to this side as the @@ -54,204 +69,277 @@ CmdResult CommandFJoin::Handle(const std::vector<std::string>& params, User *src * The winning side on the other hand will ignore all user modes from the * losing side, so only its own modes get applied. Life is simple for those * who succeed at internets. :-) + * + * Syntax: + * :<sid> FJOIN <chan> <TS> <modes> :[<member> [<member> ...]] + * The last parameter is a list consisting of zero or more channel members + * (permanent channels may have zero users). Each entry on the list is in the + * following format: + * [[<modes>,]<uuid>[:<membid>] + * <modes> is a concatenation of the mode letters the user has on the channel + * (e.g.: "ov" if the user is opped and voiced). The order of the mode letters + * are not important but if a server ecounters an unknown mode letter, it will + * drop the link to avoid desync. + * + * InspIRCd 2.0 and older required a comma before the uuid even if the user + * had no prefix modes on the channel, InspIRCd 2.2 and later does not require + * a comma in this case anymore. + * + * <membid> is a positive integer representing the id of the membership. + * If not present (in FJOINs coming from pre-1205 servers), 0 is assumed. + * + * Forwarding: + * FJOIN messages are forwarded with the new TS and modes. Prefix modes of + * members on the losing side are not forwarded. + * This is required to only have one server on each side of the network who + * decides the fate of a channel during a network merge. Otherwise, if the + * clock of a server is slightly off it may make a different decision than + * the rest of the network and desync. + * The prefix modes are always forwarded as-is, or not at all. + * One incoming FJOIN may result in more than one FJOIN being generated + * and forwarded mainly due to compatibility reasons with non-InspIRCd + * servers that don't handle more than 512 char long lines. + * + * Forwarding examples: + * Existing channel #chan with TS 1000, modes +n. + * Incoming: :220 FJOIN #chan 1000 +t :o,220AAAAAB:0 + * Forwarded: :220 FJOIN #chan 1000 +nt :o,220AAAAAB:0 + * Merge modes and forward the result. Forward their prefix modes as well. + * + * Existing channel #chan with TS 1000, modes +nt. + * Incoming: :220 FJOIN #CHAN 2000 +i :ov,220AAAAAB:0 o,220AAAAAC:20 + * Forwarded: :220 FJOIN #chan 1000 +nt :,220AAAAAB:0 ,220AAAAAC:20 + * Drop their modes, forward our modes and TS, use our channel name + * capitalization. Don't forward prefix modes. + * */ - irc::modestacker modestack(true); /* Modes to apply from the users in the user list */ - User* who = NULL; /* User we are currently checking */ - std::string channel = params[0]; /* Channel name, as a string */ - time_t TS = atoi(params[1].c_str()); /* Timestamp given to us for remote side */ - irc::tokenstream users((params.size() > 3) ? params[params.size() - 1] : ""); /* users from the user list */ - bool apply_other_sides_modes = true; /* True if we are accepting the other side's modes */ - Channel* chan = ServerInstance->FindChan(channel); /* The channel we're sending joins to */ - bool created = !chan; /* True if the channel doesnt exist here yet */ - std::string item; /* One item in the list of nicks */ - - TreeServer* src_server = Utils->FindServer(srcuser->server); - TreeSocket* src_socket = src_server->GetRoute()->GetSocket(); + time_t TS = ServerCommand::ExtractTS(params[1]); - if (!TS) - { - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"*** BUG? *** TS of 0 sent to FJOIN. Are some services authors smoking craq, or is it 1970 again?. Dropped."); - ServerInstance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending FJOIN with a TS of zero. Total craq. Command was dropped.", srcuser->server.c_str()); - return CMD_INVALID; - } + const std::string& channel = params[0]; + Channel* chan = ServerInstance->FindChan(channel); + bool apply_other_sides_modes = true; - if (created) + if (!chan) { chan = new Channel(channel, TS); - ServerInstance->SNO->WriteToSnoMask('d', "Creation FJOIN received for %s, timestamp: %lu", chan->name.c_str(), (unsigned long)TS); } else { time_t ourTS = chan->age; - if (TS != ourTS) + { ServerInstance->SNO->WriteToSnoMask('d', "Merge FJOIN received for %s, ourTS: %lu, TS: %lu, difference: %ld", chan->name.c_str(), (unsigned long)ourTS, (unsigned long)TS, (long)(ourTS - TS)); - /* If our TS is less than theirs, we dont accept their modes */ - if (ourTS < TS) - { - ServerInstance->SNO->WriteToSnoMask('d', "NOT Applying modes from other side"); - apply_other_sides_modes = false; - } - else if (ourTS > TS) - { - /* Our TS greater than theirs, clear all our modes from the channel, accept theirs. */ - ServerInstance->SNO->WriteToSnoMask('d', "Removing our modes, accepting remote"); - parameterlist param_list; - if (Utils->AnnounceTSChange) - chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :TS for %s changed from %lu to %lu", chan->name.c_str(), channel.c_str(), (unsigned long) ourTS, (unsigned long) TS); - // while the name is equal in case-insensitive compare, it might differ in case; use the remote version - chan->name = channel; - chan->age = TS; - chan->ClearInvites(); - param_list.push_back(channel); - this->RemoveStatus(ServerInstance->FakeClient, param_list); - - // XXX: If the channel does not exist in the chan hash at this point, create it so the remote modes can be applied on it. - // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then - // deleted later) as soon as the permchan mode is removed from them. - if (ServerInstance->FindChan(channel) == NULL) + /* If our TS is less than theirs, we dont accept their modes */ + if (ourTS < TS) + { + apply_other_sides_modes = false; + } + else if (ourTS > TS) { - chan = new Channel(channel, TS); + // Our TS is greater than theirs, remove all modes, extensions, etc. from the channel + LowerTS(chan, TS, channel); + + // XXX: If the channel does not exist in the chan hash at this point, create it so the remote modes can be applied on it. + // This happens to 0-user permanent channels on the losing side, because those are removed (from the chan hash, then + // deleted later) as soon as the permchan mode is removed from them. + if (ServerInstance->FindChan(channel) == NULL) + { + chan = new Channel(channel, TS); + } } } - // The silent case here is ourTS == TS, we don't need to remove modes here, just to merge them later on. } - /* First up, apply their modes if they won the TS war */ + /* First up, apply their channel modes if they won the TS war */ + Modes::ChangeList modechangelist; if (apply_other_sides_modes) { - // Need to use a modestacker here due to maxmodes - irc::modestacker stack(true); - std::vector<std::string>::const_iterator paramit = params.begin() + 3; - const std::vector<std::string>::const_iterator lastparamit = ((params.size() > 3) ? (params.end() - 1) : params.end()); - for (std::string::const_iterator i = params[2].begin(); i != params[2].end(); ++i) - { - ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL); - if (!mh) - continue; + ServerInstance->Modes.ModeParamsToChangeList(srcuser, MODETYPE_CHANNEL, params, modechangelist, 2, params.size() - 1); + ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY | ModeParser::MODE_MERGE); + // Reuse for prefix modes + modechangelist.clear(); + } - std::string modeparam; - if ((paramit != lastparamit) && (mh->GetNumParams(true))) - { - modeparam = *paramit; - ++paramit; - } + TreeServer* const sourceserver = TreeServer::Get(srcuser); - stack.Push(*i, modeparam); - } + // Build a new FJOIN for forwarding. Put the correct TS in it and the current modes of the channel + // after applying theirs. If they lost, the prefix modes from their message are not forwarded. + FwdFJoinBuilder fwdfjoin(chan, sourceserver); - std::vector<std::string> modelist; + /* Now, process every 'modes,uuid' pair */ + irc::tokenstream users(params.back()); + std::string item; + Modes::ChangeList* modechangelistptr = (apply_other_sides_modes ? &modechangelist : NULL); + while (users.GetToken(item)) + { + ProcessModeUUIDPair(item, sourceserver, chan, modechangelistptr, fwdfjoin); + } - // Mode parser needs to know what channel to act on. - modelist.push_back(params[0]); + fwdfjoin.finalize(); + fwdfjoin.Forward(sourceserver); - while (stack.GetStackedLine(modelist)) - { - ServerInstance->Modes->Process(modelist, srcuser, true); - modelist.erase(modelist.begin() + 1, modelist.end()); - } + // Set prefix modes on their users if we lost the FJOIN or had equal TS + if (apply_other_sides_modes) + ServerInstance->Modes->Process(srcuser, chan, NULL, modechangelist, ModeParser::MODE_LOCALONLY); + + return CMD_SUCCESS; +} - ServerInstance->Modes->Process(modelist, srcuser, true); +void CommandFJoin::ProcessModeUUIDPair(const std::string& item, TreeServer* sourceserver, Channel* chan, Modes::ChangeList* modechangelist, FwdFJoinBuilder& fwdfjoin) +{ + std::string::size_type comma = item.find(','); + + // Comma not required anymore if the user has no modes + const std::string::size_type ubegin = (comma == std::string::npos ? 0 : comma+1); + std::string uuid(item, ubegin, UIDGenerator::UUID_LENGTH); + User* who = ServerInstance->FindUUID(uuid); + if (!who) + { + // Probably KILLed, ignore + return; } - /* Now, process every 'modes,nick' pair */ - while (users.GetToken(item)) + TreeSocket* src_socket = sourceserver->GetSocket(); + /* Check that the user's 'direction' is correct */ + TreeServer* route_back_again = TreeServer::Get(who); + if (route_back_again->GetSocket() != src_socket) + { + return; + } + + std::string::const_iterator modeendit = item.begin(); // End of the "ov" mode string + /* Check if the user received at least one mode */ + if ((modechangelist) && (comma != std::string::npos)) { - const char* usr = item.c_str(); - if (usr && *usr) + modeendit += comma; + /* Iterate through the modes and see if they are valid here, if so, apply */ + for (std::string::const_iterator i = item.begin(); i != modeendit; ++i) { - const char* unparsedmodes = usr; - std::string modes; + ModeHandler* mh = ServerInstance->Modes->FindMode(*i, MODETYPE_CHANNEL); + if (!mh) + throw ProtocolException("Unrecognised mode '" + std::string(1, *i) + "'"); + /* Add any modes this user had to the mode stack */ + modechangelist->push_add(mh, who->nick); + } + } - /* Iterate through all modes for this user and check they are valid. */ - while ((*unparsedmodes) && (*unparsedmodes != ',')) - { - ModeHandler *mh = ServerInstance->Modes->FindMode(*unparsedmodes, MODETYPE_CHANNEL); - if (!mh) - { - ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Unrecognised mode %c, dropping link", *unparsedmodes); - return CMD_INVALID; - } + Membership* memb = chan->ForceJoin(who, NULL, sourceserver->IsBursting()); + if (!memb) + { + // User was already on the channel, forward because of the modes they potentially got + memb = chan->GetUser(who); + if (memb) + fwdfjoin.add(memb, item.begin(), modeendit); + return; + } - modes += *unparsedmodes; - usr++; - unparsedmodes++; - } + // Assign the id to the new Membership + Membership::Id membid = 0; + const std::string::size_type colon = item.rfind(':'); + if (colon != std::string::npos) + membid = Membership::IdFromString(item.substr(colon+1)); + memb->id = membid; - /* Advance past the comma, to the nick */ - usr++; + // Add member to fwdfjoin with prefix modes + fwdfjoin.add(memb, item.begin(), modeendit); +} - /* Check the user actually exists */ - who = ServerInstance->FindUUID(usr); - if (who) - { - /* Check that the user's 'direction' is correct */ - TreeServer* route_back_again = Utils->BestRouteTo(who->server); - if ((!route_back_again) || (route_back_again->GetSocket() != src_socket)) - continue; +void CommandFJoin::RemoveStatus(Channel* c) +{ + Modes::ChangeList changelist; - /* Add any modes this user had to the mode stack */ - for (std::string::iterator x = modes.begin(); x != modes.end(); ++x) - modestack.Push(*x, who->nick); + const ModeParser::ModeHandlerMap& mhs = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL); + for (ModeParser::ModeHandlerMap::const_iterator i = mhs.begin(); i != mhs.end(); ++i) + { + ModeHandler* mh = i->second; - Channel::JoinUser(who, channel.c_str(), true, "", src_server->bursting, TS); - } - else - { - ServerInstance->Logs->Log("m_spanningtree",SPARSE, "Ignored nonexistant user %s in fjoin to %s (probably quit?)", usr, channel.c_str()); - continue; - } - } + /* Passing a pointer to a modestacker here causes the mode to be put onto the mode stack, + * rather than applied immediately. Module unloads require this to be done immediately, + * for this function we require tidyness instead. Fixes bug #493 + */ + mh->RemoveMode(c, changelist); } - /* Flush mode stacker if we lost the FJOIN or had equal TS */ - if (apply_other_sides_modes) - { - parameterlist stackresult; - stackresult.push_back(channel); + ServerInstance->Modes->Process(ServerInstance->FakeClient, c, NULL, changelist, ModeParser::MODE_LOCALONLY); +} - while (modestack.GetStackedLine(stackresult)) - { - ServerInstance->SendMode(stackresult, srcuser); - stackresult.erase(stackresult.begin() + 1, stackresult.end()); - } +void CommandFJoin::LowerTS(Channel* chan, time_t TS, const std::string& newname) +{ + if (Utils->AnnounceTSChange) + chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE %s :TS for %s changed from %lu to %lu", chan->name.c_str(), newname.c_str(), (unsigned long) chan->age, (unsigned long) TS); + + // While the name is equal in case-insensitive compare, it might differ in case; use the remote version + chan->name = newname; + chan->age = TS; + + // Remove all pending invites + chan->ClearInvites(); + + // Clear all modes + CommandFJoin::RemoveStatus(chan); + + // Unset all extensions + chan->FreeAllExtItems(); + + // Clear the topic, if it isn't empty then send a topic change message to local users + if (!chan->topic.empty()) + { + chan->topic.clear(); + chan->WriteChannelWithServ(ServerInstance->Config->ServerName, "TOPIC %s :", chan->name.c_str()); } - return CMD_SUCCESS; + chan->setby.clear(); + chan->topicset = 0; } -void CommandFJoin::RemoveStatus(User* srcuser, parameterlist ¶ms) +CommandFJoin::Builder::Builder(Channel* chan, TreeServer* source) + : CmdBuilder(source->GetID(), "FJOIN") { - if (params.size() < 1) - return; + push(chan->name).push_int(chan->age).push_raw(" +"); + pos = str().size(); + push_raw(chan->ChanModes(true)).push_raw(" :"); +} - Channel* c = ServerInstance->FindChan(params[0]); +void CommandFJoin::Builder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend) +{ + push_raw(mbegin, mend).push_raw(',').push_raw(memb->user->uuid); + push_raw(':').push_raw_int(memb->id); + push_raw(' '); +} - if (c) - { - irc::modestacker stack(false); - parameterlist stackresult; - stackresult.push_back(c->name); +bool CommandFJoin::Builder::has_room(std::string::size_type nummodes) const +{ + return ((str().size() + nummodes + UIDGenerator::UUID_LENGTH + 2 + membid_max_digits + 1) <= maxline); +} - for (char modeletter = 'A'; modeletter <= 'z'; ++modeletter) - { - ModeHandler* mh = ServerInstance->Modes->FindMode(modeletter, MODETYPE_CHANNEL); - - /* Passing a pointer to a modestacker here causes the mode to be put onto the mode stack, - * rather than applied immediately. Module unloads require this to be done immediately, - * for this function we require tidyness instead. Fixes bug #493 - */ - if (mh) - mh->RemoveMode(c, &stack); - } +void CommandFJoin::Builder::clear() +{ + content.erase(pos); + push_raw(" :"); +} - while (stack.GetStackedLine(stackresult)) - { - ServerInstance->SendMode(stackresult, srcuser); - stackresult.erase(stackresult.begin() + 1, stackresult.end()); - } - } +const std::string& CommandFJoin::Builder::finalize() +{ + if (*content.rbegin() == ' ') + content.erase(content.size()-1); + return str(); } +void FwdFJoinBuilder::add(Membership* memb, std::string::const_iterator mbegin, std::string::const_iterator mend) +{ + // Pseudoserver compatibility: + // Some pseudoservers do not handle lines longer than 512 so we split long FJOINs into multiple messages. + // The forwarded FJOIN can end up being longer than the original one if we have more modes set and won, for example. + + // Check if the member fits into the current message. If not, send it and prepare a new one. + if (!has_room(std::distance(mbegin, mend))) + { + finalize(); + Forward(sourceserver); + clear(); + } + // Add the member and their modes exactly as they sent them + CommandFJoin::Builder::add(memb, mbegin, mend); +} diff --git a/src/modules/m_spanningtree/fmode.cpp b/src/modules/m_spanningtree/fmode.cpp index c1e452db6..52e512d92 100644 --- a/src/modules/m_spanningtree/fmode.cpp +++ b/src/modules/m_spanningtree/fmode.cpp @@ -21,73 +21,35 @@ #include "inspircd.h" #include "commands.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" - /** FMODE command - server mode with timestamp checks */ -CmdResult CommandFMode::Handle(const std::vector<std::string>& params, User *who) +CmdResult CommandFMode::Handle(User* who, std::vector<std::string>& params) { - std::string sourceserv = who->server; - - std::vector<std::string> modelist; - time_t TS = 0; - for (unsigned int q = 0; (q < params.size()) && (q < 64); q++) - { - if (q == 1) - { - /* The timestamp is in this position. - * We don't want to pass that up to the - * server->client protocol! - */ - TS = atoi(params[q].c_str()); - } - else - { - /* Everything else is fine to append to the modelist */ - modelist.push_back(params[q]); - } + time_t TS = ServerCommand::ExtractTS(params[1]); - } - /* Extract the TS value of the object, either User or Channel */ - User* dst = ServerInstance->FindNick(params[0]); - Channel* chan = NULL; - time_t ourTS = 0; + Channel* const chan = ServerInstance->FindChan(params[0]); + if (!chan) + // Channel doesn't exist + return CMD_FAILURE; - if (dst) - { - ourTS = dst->age; - } - else - { - chan = ServerInstance->FindChan(params[0]); - if (chan) - { - ourTS = chan->age; - } - else - /* Oops, channel doesnt exist! */ - return CMD_FAILURE; - } + // Extract the TS of the channel in question + time_t ourTS = chan->age; - if (!TS) - { - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"*** BUG? *** TS of 0 sent to FMODE. Are some services authors smoking craq, or is it 1970 again?. Dropped."); - ServerInstance->SNO->WriteToSnoMask('d', "WARNING: The server %s is sending FMODE with a TS of zero. Total craq. Mode was dropped.", sourceserv.c_str()); - return CMD_INVALID; - } + /* If the TS is greater than ours, we drop the mode and don't pass it anywhere. + */ + if (TS > ourTS) + return CMD_FAILURE; /* TS is equal or less: Merge the mode changes into ours and pass on. */ - if (TS <= ourTS) - { - bool merge = (TS == ourTS) && IS_SERVER(who); - ServerInstance->Modes->Process(modelist, who, merge); - return CMD_SUCCESS; - } - /* If the TS is greater than ours, we drop the mode and dont pass it anywhere. - */ - return CMD_FAILURE; -} + // Turn modes into a Modes::ChangeList; may have more elements than max modes + Modes::ChangeList changelist; + ServerInstance->Modes.ModeParamsToChangeList(who, MODETYPE_CHANNEL, params, changelist, 2); + + ModeParser::ModeProcessFlag flags = ModeParser::MODE_LOCALONLY; + if ((TS == ourTS) && IS_SERVER(who)) + flags |= ModeParser::MODE_MERGE; + ServerInstance->Modes->Process(who, chan, NULL, changelist, flags); + return CMD_SUCCESS; +} diff --git a/src/modules/m_spanningtree/ftopic.cpp b/src/modules/m_spanningtree/ftopic.cpp index d559c6ae5..3c76c928a 100644 --- a/src/modules/m_spanningtree/ftopic.cpp +++ b/src/modules/m_spanningtree/ftopic.cpp @@ -21,31 +21,81 @@ #include "inspircd.h" #include "commands.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" - /** FTOPIC command */ -CmdResult CommandFTopic::Handle(const std::vector<std::string>& params, User *user) +CmdResult CommandFTopic::Handle(User* user, std::vector<std::string>& params) { - time_t ts = atoi(params[1].c_str()); Channel* c = ServerInstance->FindChan(params[0]); - if (c) + if (!c) + return CMD_FAILURE; + + if (c->age < ServerCommand::ExtractTS(params[1])) + // Our channel TS is older, nothing to do + return CMD_FAILURE; + + // Channel::topicset is initialized to 0 on channel creation, so their ts will always win if we never had a topic + time_t ts = ServerCommand::ExtractTS(params[2]); + if (ts < c->topicset) + return CMD_FAILURE; + + // The topic text is always the last parameter + const std::string& newtopic = params.back(); + + // If there is a setter in the message use that, otherwise use the message source + const std::string& setter = ((params.size() > 4) ? params[3] : (ServerInstance->Config->FullHostInTopic ? user->GetFullHost() : user->nick)); + + /* + * If the topics were updated at the exact same second, accept + * the remote only when it's "bigger" than ours as defined by + * string comparision, so non-empty topics always overridde + * empty topics if their timestamps are equal + * + * Similarly, if the topic texts are equal too, keep one topic + * setter and discard the other + */ + if (ts == c->topicset) + { + // Discard if their topic text is "smaller" + if (c->topic > newtopic) + return CMD_FAILURE; + + // If the texts are equal in addition to the timestamps, decide which setter to keep + if ((c->topic == newtopic) && (c->setby >= setter)) + return CMD_FAILURE; + } + + if (c->topic != newtopic) { - if ((ts >= c->topicset) || (c->topic.empty())) - { - if (c->topic != params[3]) - { - // Update topic only when it differs from current topic - c->topic.assign(params[3], 0, ServerInstance->Config->Limits.MaxTopic); - c->WriteChannel(user, "TOPIC %s :%s", c->name.c_str(), c->topic.c_str()); - } - - // Always update setter and settime. - c->setby.assign(params[2], 0, 127); - c->topicset = ts; - } + // Update topic only when it differs from current topic + c->topic.assign(newtopic, 0, ServerInstance->Config->Limits.MaxTopic); + c->WriteChannel(user, "TOPIC %s :%s", c->name.c_str(), c->topic.c_str()); } + + // Update setter and settime + c->setby.assign(setter, 0, 128); + c->topicset = ts; + + FOREACH_MOD(OnPostTopicChange, (user, c, c->topic)); + return CMD_SUCCESS; } +// Used when bursting and in reply to RESYNC, contains topic setter as the 4th parameter +CommandFTopic::Builder::Builder(Channel* chan) + : CmdBuilder("FTOPIC") +{ + push(chan->name); + push_int(chan->age); + push_int(chan->topicset); + push(chan->setby); + push_last(chan->topic); +} + +// Used when changing the topic, the setter is the message source +CommandFTopic::Builder::Builder(User* user, Channel* chan) + : CmdBuilder(user, "FTOPIC") +{ + push(chan->name); + push_int(chan->age); + push_int(chan->topicset); + push_last(chan->topic); +} diff --git a/src/modules/m_spanningtree/hmac.cpp b/src/modules/m_spanningtree/hmac.cpp index d990e1fbf..2001d560d 100644 --- a/src/modules/m_spanningtree/hmac.cpp +++ b/src/modules/m_spanningtree/hmac.cpp @@ -19,18 +19,12 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "../hash.h" -#include "../ssl.h" -#include "socketengine.h" +#include "modules/hash.h" +#include "modules/ssl.h" #include "main.h" -#include "utils.h" -#include "treeserver.h" #include "link.h" #include "treesocket.h" -#include "resolvers.h" const std::string& TreeSocket::GetOurChallenge() { @@ -57,44 +51,15 @@ std::string TreeSocket::MakePass(const std::string &password, const std::string /* This is a simple (maybe a bit hacky?) HMAC algorithm, thanks to jilles for * suggesting the use of HMAC to secure the password against various attacks. * - * Note: If m_sha256.so is not loaded, we MUST fall back to plaintext with no + * Note: If an sha256 provider is not available, we MUST fall back to plaintext with no * HMAC challenge/response. */ HashProvider* sha256 = ServerInstance->Modules->FindDataService<HashProvider>("hash/sha256"); - if (Utils->ChallengeResponse && sha256 && !challenge.empty()) - { - if (proto_version < 1202) - { - /* This is how HMAC is done in InspIRCd 1.2: - * - * sha256( (pass xor 0x5c) + sha256((pass xor 0x36) + m) ) - * - * 5c and 36 were chosen as part of the HMAC standard, because they - * flip the bits in a way likely to strengthen the function. - */ - std::string hmac1, hmac2; - - for (size_t n = 0; n < password.length(); n++) - { - hmac1.push_back(static_cast<char>(password[n] ^ 0x5C)); - hmac2.push_back(static_cast<char>(password[n] ^ 0x36)); - } - - hmac2.append(challenge); - hmac2 = sha256->hexsum(hmac2); - - std::string hmac = hmac1 + hmac2; - hmac = sha256->hexsum(hmac); - - return "HMAC-SHA256:"+ hmac; - } - else - { - return "AUTH:" + BinToBase64(sha256->hmac(password, challenge)); - } - } - else if (!challenge.empty() && !sha256) - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Not authenticating to server using SHA256/HMAC because we don't have m_sha256 loaded!"); + if (sha256 && !challenge.empty()) + return "AUTH:" + BinToBase64(sha256->hmac(password, challenge)); + + if (!challenge.empty() && !sha256) + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Not authenticating to server using SHA256/HMAC because we don't have an SHA256 provider (e.g. m_sha256) loaded!"); return password; } @@ -104,13 +69,16 @@ bool TreeSocket::ComparePass(const Link& link, const std::string &theirs) capab->auth_fingerprint = !link.Fingerprint.empty(); capab->auth_challenge = !capab->ourchallenge.empty() && !capab->theirchallenge.empty(); - std::string fp; - if (GetIOHook()) + std::string fp = SSLClientCert::GetFingerprint(this); + if (capab->auth_fingerprint) { - SocketCertificateRequest req(this, Utils->Creator); - if (req.cert) + /* Require fingerprint to exist and match */ + if (link.Fingerprint != fp) { - fp = req.cert->GetFingerprint(); + ServerInstance->SNO->WriteToSnoMask('l',"Invalid SSL certificate fingerprint on link %s: need \"%s\" got \"%s\"", + link.Name.c_str(), link.Fingerprint.c_str(), fp.c_str()); + SendError("Invalid SSL certificate fingerprint " + fp + " - expected " + link.Fingerprint); + return false; } } @@ -118,32 +86,24 @@ bool TreeSocket::ComparePass(const Link& link, const std::string &theirs) { std::string our_hmac = MakePass(link.RecvPass, capab->ourchallenge); - /* Straight string compare of hashes */ - if (our_hmac != theirs) + // Use the timing-safe compare function to compare the hashes + if (!InspIRCd::TimingSafeCompare(our_hmac, theirs)) return false; } else { - /* Straight string compare of plaintext */ - if (link.RecvPass != theirs) + // Use the timing-safe compare function to compare the passwords + if (!InspIRCd::TimingSafeCompare(link.RecvPass, theirs)) return false; } - if (capab->auth_fingerprint) + // Tell opers to set up fingerprint verification if it's not already set up and the SSL mod gave us a fingerprint + // this time + if ((!capab->auth_fingerprint) && (!fp.empty())) { - /* Require fingerprint to exist and match */ - if (link.Fingerprint != fp) - { - ServerInstance->SNO->WriteToSnoMask('l',"Invalid SSL fingerprint on link %s: need \"%s\" got \"%s\"", - link.Name.c_str(), link.Fingerprint.c_str(), fp.c_str()); - SendError("Provided invalid SSL fingerprint " + fp + " - expected " + link.Fingerprint); - return false; - } - } - else if (!fp.empty()) - { - ServerInstance->SNO->WriteToSnoMask('l', "SSL fingerprint for link %s is \"%s\". " + ServerInstance->SNO->WriteToSnoMask('l', "SSL certificate fingerprint for link %s is \"%s\". " "You can improve security by specifying this in <link:fingerprint>.", link.Name.c_str(), fp.c_str()); } + return true; } diff --git a/src/modules/m_spanningtree/idle.cpp b/src/modules/m_spanningtree/idle.cpp index 18aeb0ad5..06af4d0fd 100644 --- a/src/modules/m_spanningtree/idle.cpp +++ b/src/modules/m_spanningtree/idle.cpp @@ -18,67 +18,53 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" - -#include "main.h" #include "utils.h" -#include "treeserver.h" -#include "treesocket.h" +#include "commands.h" -bool TreeSocket::Whois(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandIdle::HandleRemote(RemoteUser* issuer, std::vector<std::string>& params) { - if (params.size() < 1) - return true; - User* u = ServerInstance->FindNick(prefix); - if (u) + /** + * There are two forms of IDLE: request and reply. Requests have one parameter, + * replies have more than one. + * + * If this is a request, 'issuer' did a /whois and its server wants to learn the + * idle time of the user in params[0]. + * + * If this is a reply, params[0] is the user who did the whois and params.back() is + * the number of seconds 'issuer' has been idle. + */ + + User* target = ServerInstance->FindUUID(params[0]); + if ((!target) || (IS_SERVER(target) || (target->registered != REG_ALL))) + return CMD_FAILURE; + + LocalUser* localtarget = IS_LOCAL(target); + if (!localtarget) { - // an incoming request - if (params.size() == 1) - { - User* x = ServerInstance->FindNick(params[0]); - if ((x) && (IS_LOCAL(x))) - { - long idle = labs((long)((x->idle_lastmsg) - ServerInstance->Time())); - parameterlist par; - par.push_back(prefix); - par.push_back(ConvToStr(x->signon)); - par.push_back(ConvToStr(idle)); - // ours, we're done, pass it BACK - Utils->DoOneToOne(params[0], "IDLE", par, u->server); - } - else - { - // not ours pass it on - if (x) - Utils->DoOneToOne(prefix, "IDLE", params, x->server); - } - } - else if (params.size() == 3) - { - std::string who_did_the_whois = params[0]; - User* who_to_send_to = ServerInstance->FindNick(who_did_the_whois); - if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)) && (who_to_send_to->registered == REG_ALL)) - { - // an incoming reply to a whois we sent out - std::string nick_whoised = prefix; - unsigned long signon = atoi(params[1].c_str()); - unsigned long idle = atoi(params[2].c_str()); - if ((who_to_send_to) && (IS_LOCAL(who_to_send_to))) - { - ServerInstance->DoWhois(who_to_send_to, u, signon, idle, nick_whoised.c_str()); - } - } - else - { - // not ours, pass it on - if (who_to_send_to) - Utils->DoOneToOne(prefix, "IDLE", params, who_to_send_to->server); - } - } + // Forward to target's server + return CMD_SUCCESS; } - return true; -} + if (params.size() >= 2) + { + ServerInstance->Parser.CallHandler("WHOIS", params, issuer); + } + else + { + // A server is asking us the idle time of our user + unsigned int idle; + if (localtarget->idle_lastmsg >= ServerInstance->Time()) + // Possible case when our clock ticked backwards + idle = 0; + else + idle = ((unsigned int) (ServerInstance->Time() - localtarget->idle_lastmsg)); + + CmdBuilder reply(params[0], "IDLE"); + reply.push_back(issuer->uuid); + reply.push_back(ConvToStr(target->signon)); + reply.push_back(ConvToStr(idle)); + reply.Unicast(issuer); + } + return CMD_SUCCESS; +} diff --git a/src/modules/m_spanningtree/ijoin.cpp b/src/modules/m_spanningtree/ijoin.cpp new file mode 100644 index 000000000..78e05db93 --- /dev/null +++ b/src/modules/m_spanningtree/ijoin.cpp @@ -0,0 +1,77 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2012-2013 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "commands.h" +#include "utils.h" +#include "treeserver.h" +#include "treesocket.h" + +CmdResult CommandIJoin::HandleRemote(RemoteUser* user, std::vector<std::string>& params) +{ + Channel* chan = ServerInstance->FindChan(params[0]); + if (!chan) + { + // Desync detected, recover + // Ignore the join and send RESYNC, this will result in the remote server sending all channel data to us + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received IJOIN for non-existant channel: " + params[0]); + + CmdBuilder("RESYNC").push(params[0]).Unicast(user); + + return CMD_FAILURE; + } + + bool apply_modes; + if (params.size() > 2) + { + time_t RemoteTS = ServerCommand::ExtractTS(params[2]); + if (RemoteTS < chan->age) + throw ProtocolException("Attempted to lower TS via IJOIN. LocalTS=" + ConvToStr(chan->age)); + apply_modes = ((params.size() > 3) && (RemoteTS == chan->age)); + } + else + apply_modes = false; + + // Join the user and set the membership id to what they sent + Membership* memb = chan->ForceJoin(user, apply_modes ? ¶ms[3] : NULL); + if (!memb) + return CMD_FAILURE; + + memb->id = Membership::IdFromString(params[1]); + return CMD_SUCCESS; +} + +CmdResult CommandResync::HandleServer(TreeServer* server, std::vector<std::string>& params) +{ + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Resyncing " + params[0]); + Channel* chan = ServerInstance->FindChan(params[0]); + if (!chan) + { + // This can happen for a number of reasons, safe to ignore + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Channel does not exist"); + return CMD_FAILURE; + } + + if (!server->IsLocal()) + throw ProtocolException("RESYNC from a server that is not directly connected"); + + // Send all known information about the channel + server->GetSocket()->SyncChannel(chan); + return CMD_SUCCESS; +} diff --git a/src/modules/m_spanningtree/link.h b/src/modules/m_spanningtree/link.h index 797f108d8..21213fb3e 100644 --- a/src/modules/m_spanningtree/link.h +++ b/src/modules/m_spanningtree/link.h @@ -18,8 +18,7 @@ */ -#ifndef M_SPANNINGTREE_LINK_H -#define M_SPANNINGTREE_LINK_H +#pragma once class Link : public refcountbase { @@ -31,7 +30,7 @@ class Link : public refcountbase std::string SendPass; std::string RecvPass; std::string Fingerprint; - std::string AllowMask; + std::vector<std::string> AllowMasks; bool HiddenFromStats; std::string Hook; int Timeout; @@ -51,5 +50,3 @@ class Autoconnect : public refcountbase int position; Autoconnect(ConfigTag* Tag) : tag(Tag) {} }; - -#endif diff --git a/src/modules/m_spanningtree/main.cpp b/src/modules/m_spanningtree/main.cpp index 967b577b1..e5e6e522b 100644 --- a/src/modules/m_spanningtree/main.cpp +++ b/src/modules/m_spanningtree/main.cpp @@ -21,13 +21,11 @@ */ -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" #include "socket.h" #include "xline.h" +#include "iohook.h" -#include "cachetimer.h" #include "resolvers.h" #include "main.h" #include "utils.h" @@ -35,60 +33,68 @@ #include "link.h" #include "treesocket.h" #include "commands.h" -#include "protocolinterface.h" +#include "translate.h" ModuleSpanningTree::ModuleSpanningTree() - : KeepNickTS(false) + : rconnect(this), rsquit(this), map(this) + , commands(NULL) + , currmembid(0) + , eventprov(this, "event/spanningtree") + , DNS(this, "DNS") + , loopCall(false) { - Utils = new SpanningTreeUtilities(this); - commands = new SpanningTreeCommands(this); - RefreshTimer = NULL; } SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module) - : rconnect(module, module->Utils), rsquit(module, module->Utils), - svsjoin(module), svspart(module), svsnick(module), metadata(module), - uid(module), opertype(module), fjoin(module), fmode(module), ftopic(module), - fhost(module), fident(module), fname(module) + : svsjoin(module), svspart(module), svsnick(module), metadata(module), + uid(module), opertype(module), fjoin(module), ijoin(module), resync(module), + fmode(module), ftopic(module), fhost(module), fident(module), fname(module), + away(module), addline(module), delline(module), encap(module), idle(module), + nick(module), ping(module), pong(module), push(module), save(module), + server(module), squit(module), snonotice(module), + endburst(module), sinfo(module) { } +namespace +{ + void SetLocalUsersServer(Server* newserver) + { + // Does not change the server of quitting users because those are not in the list + + ServerInstance->FakeClient->server = newserver; + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i) + (*i)->server = newserver; + } + + void ResetMembershipIds() + { + // Set all membership ids to 0 + const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers(); + for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i) + { + LocalUser* user = *i; + for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j) + (*j)->id = 0; + } + } +} + void ModuleSpanningTree::init() { - ServerInstance->Modules->AddService(commands->rconnect); - ServerInstance->Modules->AddService(commands->rsquit); - ServerInstance->Modules->AddService(commands->svsjoin); - ServerInstance->Modules->AddService(commands->svspart); - ServerInstance->Modules->AddService(commands->svsnick); - ServerInstance->Modules->AddService(commands->metadata); - ServerInstance->Modules->AddService(commands->uid); - ServerInstance->Modules->AddService(commands->opertype); - ServerInstance->Modules->AddService(commands->fjoin); - ServerInstance->Modules->AddService(commands->fmode); - ServerInstance->Modules->AddService(commands->ftopic); - ServerInstance->Modules->AddService(commands->fhost); - ServerInstance->Modules->AddService(commands->fident); - ServerInstance->Modules->AddService(commands->fname); - RefreshTimer = new CacheRefreshTimer(Utils); - ServerInstance->Timers->AddTimer(RefreshTimer); - - Implementation eventlist[] = - { - I_OnPreCommand, I_OnGetServerDescription, I_OnUserInvite, I_OnPostTopicChange, - I_OnWallops, I_OnUserNotice, I_OnUserMessage, I_OnBackgroundTimer, I_OnUserJoin, - I_OnChangeHost, I_OnChangeName, I_OnChangeIdent, I_OnUserPart, I_OnUnloadModule, - I_OnUserQuit, I_OnUserPostNick, I_OnUserKick, I_OnRemoteKill, I_OnRehash, I_OnPreRehash, - I_OnOper, I_OnAddLine, I_OnDelLine, I_OnMode, I_OnLoadModule, I_OnStats, - I_OnSetAway, I_OnPostCommand, I_OnUserConnect, I_OnAcceptConnection - }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - - delete ServerInstance->PI; - ServerInstance->PI = new SpanningTreeProtocolInterface(Utils); - loopCall = false; - - // update our local user count - Utils->TreeRoot->SetUserCount(ServerInstance->Users->LocalUserCount()); + ServerInstance->SNO->EnableSnomask('l', "LINK"); + + ResetMembershipIds(); + + Utils = new SpanningTreeUtilities(this); + Utils->TreeRoot = new TreeServer; + commands = new SpanningTreeCommands(this); + + ServerInstance->PI = &protocolinterface; + + delete ServerInstance->FakeClient->server; + SetLocalUsersServer(Utils->TreeRoot); } void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops) @@ -98,44 +104,40 @@ void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops) { Parent = Current->GetParent()->GetName(); } - for (unsigned int q = 0; q < Current->ChildCount(); q++) + + const TreeServer::ChildServers& children = Current->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i) { - if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName())))) + TreeServer* server = *i; + if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine()))) { - if (IS_OPER(user)) + if (user->IsOper()) { - ShowLinks(Current->GetChild(q),user,hops+1); + ShowLinks(server, user, hops+1); } } else { - ShowLinks(Current->GetChild(q),user,hops+1); + ShowLinks(server, user, hops+1); } } /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */ - if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName())) && (!IS_OPER(user))) + if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper())) return; /* Or if the server is hidden and they're not an oper */ - else if ((Current->Hidden) && (!IS_OPER(user))) + else if ((Current->Hidden) && (!user->IsOper())) return; - std::string servername = Current->GetName(); - user->WriteNumeric(364, "%s %s %s :%d %s", user->nick.c_str(), servername.c_str(), - (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(), - (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops, + user->WriteNumeric(RPL_LINKS, "%s %s :%d %s", Current->GetName().c_str(), + (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(), + (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops, Current->GetDesc().c_str()); } -int ModuleSpanningTree::CountServs() -{ - return Utils->serverlist.size(); -} - void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user) { ShowLinks(Utils->TreeRoot,user,0); - user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick.c_str()); - return; + user->WriteNumeric(RPL_ENDOFLINKS, "* :End of /LINKS list."); } std::string ModuleSpanningTree::TimeToStr(time_t secs) @@ -152,79 +154,6 @@ std::string ModuleSpanningTree::TimeToStr(time_t secs) + ConvToStr(secs) + "s"); } -void ModuleSpanningTree::DoPingChecks(time_t curtime) -{ - /* - * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data. - * This prevents lost REMOTECONNECT notices - */ - long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); - -restart: - for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++) - { - TreeServer *s = i->second; - - if (s->GetSocket() && s->GetSocket()->GetLinkState() == DYING) - { - s->GetSocket()->Close(); - goto restart; - } - - // Fix for bug #792, do not ping servers that are not connected yet! - // Remote servers have Socket == NULL and local connected servers have - // Socket->LinkState == CONNECTED - if (s->GetSocket() && s->GetSocket()->GetLinkState() != CONNECTED) - continue; - - // Now do PING checks on all servers - TreeServer *mts = Utils->BestRouteTo(s->GetID()); - - if (mts) - { - // Only ping if this server needs one - if (curtime >= s->NextPingTime()) - { - // And if they answered the last - if (s->AnsweredLastPing()) - { - // They did, send a ping to them - s->SetNextPingTime(curtime + Utils->PingFreq); - TreeSocket *tsock = mts->GetSocket(); - - // ... if we can find a proper route to them - if (tsock) - { - tsock->WriteLine(":" + ServerInstance->Config->GetSID() + " PING " + - ServerInstance->Config->GetSID() + " " + s->GetID()); - s->LastPingMsec = ts; - } - } - else - { - // They didn't answer the last ping, if they are locally connected, get rid of them. - TreeSocket *sock = s->GetSocket(); - if (sock) - { - sock->SendError("Ping timeout"); - sock->Close(); - goto restart; - } - } - } - - // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping... - if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing())) - { - /* The server hasnt responded, send a warning to opers */ - std::string servername = s->GetName(); - ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", servername.c_str(), Utils->PingWarnTime); - s->Warned = true; - } - } - } -} - void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer) { if (!a) @@ -272,7 +201,7 @@ void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y) return; } - QueryType start_type = DNS_QUERY_AAAA; + DNS::QueryType start_type = DNS::QUERY_AAAA; if (strchr(x->IPAddr.c_str(),':')) { in6_addr n; @@ -290,7 +219,7 @@ void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y) if (ipvalid) { /* Gave a hook, but it wasnt one we know */ - TreeSocket* newsocket = new TreeSocket(Utils, x, y, x->IPAddr); + TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr); if (newsocket->GetFd() > -1) { /* Handled automatically on success */ @@ -302,17 +231,21 @@ void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y) ServerInstance->GlobalCulls.AddItem(newsocket); } } + else if (!DNS) + { + ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and m_dns.so is not loaded, unable to resolve.", x->Name.c_str()); + } else { + ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y); try { - bool cached = false; - ServernameResolver* snr = new ServernameResolver(Utils, x->IPAddr, x, cached, start_type, y); - ServerInstance->AddResolver(snr, cached); + DNS->Process(snr); } - catch (ModuleException& e) + catch (DNS::Exception& e) { - ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason()); + delete snr; + ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str()); ConnectServer(y, false); } } @@ -360,16 +293,23 @@ ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& para TreeServer* found = Utils->FindServerMask(parameters[0]); if (found) { - std::string Version = found->GetVersion(); - user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str()); if (found == Utils->TreeRoot) { - ServerInstance->Config->Send005(user); + // Pass to default VERSION handler. + return MOD_RES_PASSTHRU; } + + // If an oper wants to see the version then show the full version string instead of the normal, + // but only if it is non-empty. + // If it's empty it might be that the server is still syncing (full version hasn't arrived yet) + // or the server is a 2.0 server and does not send a full version. + bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty())); + const std::string& Version = (showfull ? found->GetFullVersion() : found->GetVersion()); + user->WriteNumeric(RPL_VERSION, ":%s", Version.c_str()); } else { - user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str()); } return MOD_RES_DENY; } @@ -378,15 +318,11 @@ ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& para */ void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...) { - char text[MAXBUF]; - va_list argsPtr; - - va_start(argsPtr, format); - vsnprintf(text, MAXBUF, format, argsPtr); - va_end(argsPtr); + std::string text; + VAFORMAT(text, format, format); if (IS_LOCAL(user)) - user->WriteServ("NOTICE %s :%s", user->nick.c_str(), text); + user->WriteNotice(text); else ServerInstance->PI->SendUserNotice(user, text); } @@ -413,8 +349,7 @@ ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& para } else { - std::string servername = CheckDupe->GetParent()->GetName(); - RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002", x->Name.c_str(), servername.c_str()); + RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002", x->Name.c_str(), CheckDupe->GetParent()->GetName().c_str()); return MOD_RES_DENY; } } @@ -423,24 +358,16 @@ ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& para return MOD_RES_DENY; } -void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description) -{ - TreeServer* s = Utils->FindServer(servername); - if (s) - { - description = s->GetDesc(); - } -} - void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry) { if (IS_LOCAL(source)) { - parameterlist params; + CmdBuilder params(source, "INVITE"); params.push_back(dest->uuid); params.push_back(channel->name); + params.push_int(channel->age); params.push_back(ConvToStr(expiry)); - Utils->DoOneToMany(source->uuid,"INVITE",params); + params.Broadcast(); } } @@ -450,130 +377,43 @@ void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std: if (!IS_LOCAL(user)) return; - parameterlist params; - params.push_back(chan->name); - params.push_back(":"+topic); - Utils->DoOneToMany(user->uuid,"TOPIC",params); -} - -void ModuleSpanningTree::OnWallops(User* user, const std::string &text) -{ - if (IS_LOCAL(user)) - { - parameterlist params; - params.push_back(":"+text); - Utils->DoOneToMany(user->uuid,"WALLOPS",params); - } + CommandFTopic::Builder(user, chan).Broadcast(); } -void ModuleSpanningTree::OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) +void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype) { - /* Server origin */ - if (user == NULL) + if (!IS_LOCAL(user)) return; + const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE"); if (target_type == TYPE_USER) { - User* d = (User*)dest; - if (!IS_LOCAL(d) && IS_LOCAL(user)) + User* d = (User*) dest; + if (!IS_LOCAL(d)) { - parameterlist params; + CmdBuilder params(user, message_type); params.push_back(d->uuid); - params.push_back(":"+text); - Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server); + params.push_last(text); + params.Unicast(d); } } else if (target_type == TYPE_CHANNEL) { - if (IS_LOCAL(user)) - { - Channel *c = (Channel*)dest; - if (c) - { - std::string cname = c->name; - if (status) - cname = status + cname; - TreeServerList list; - Utils->GetListOfServersForChannel(c,list,status,exempt_list); - for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) - { - TreeSocket* Sock = i->second->GetSocket(); - if (Sock) - Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text); - } - } - } + Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type); } else if (target_type == TYPE_SERVER) { - if (IS_LOCAL(user)) - { - char* target = (char*)dest; - parameterlist par; - par.push_back(target); - par.push_back(":"+text); - Utils->DoOneToMany(user->uuid,"NOTICE",par); - } - } -} - -void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) -{ - /* Server origin */ - if (user == NULL) - return; - - if (target_type == TYPE_USER) - { - // route private messages which are targetted at clients only to the server - // which needs to receive them - User* d = (User*)dest; - if (!IS_LOCAL(d) && (IS_LOCAL(user))) - { - parameterlist params; - params.push_back(d->uuid); - params.push_back(":"+text); - Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server); - } - } - else if (target_type == TYPE_CHANNEL) - { - if (IS_LOCAL(user)) - { - Channel *c = (Channel*)dest; - if (c) - { - std::string cname = c->name; - if (status) - cname = status + cname; - TreeServerList list; - Utils->GetListOfServersForChannel(c,list,status,exempt_list); - for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) - { - TreeSocket* Sock = i->second->GetSocket(); - if (Sock) - Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text); - } - } - } - } - else if (target_type == TYPE_SERVER) - { - if (IS_LOCAL(user)) - { - char* target = (char*)dest; - parameterlist par; - par.push_back(target); - par.push_back(":"+text); - Utils->DoOneToMany(user->uuid,"PRIVMSG",par); - } + char* target = (char*) dest; + CmdBuilder par(user, message_type); + par.push_back(target); + par.push_last(text); + par.Broadcast(); } } void ModuleSpanningTree::OnBackgroundTimer(time_t curtime) { AutoConnectServers(curtime); - DoPingChecks(curtime); DoConnectTimeout(curtime); } @@ -582,25 +422,10 @@ void ModuleSpanningTree::OnUserConnect(LocalUser* user) if (user->quitting) return; - parameterlist params; - params.push_back(user->uuid); - params.push_back(ConvToStr(user->age)); - params.push_back(user->nick); - params.push_back(user->host); - params.push_back(user->dhost); - params.push_back(user->ident); - params.push_back(user->GetIPString()); - params.push_back(ConvToStr(user->signon)); - params.push_back("+"+std::string(user->FormatModes(true))); - params.push_back(":"+user->fullname); - Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params); + CommandUID::Builder(user).Broadcast(); - if (IS_OPER(user)) - { - params.clear(); - params.push_back(user->oper->name); - Utils->DoOneToMany(user->uuid,"OPERTYPE",params); - } + if (user->IsOper()) + CommandOpertype::Builder(user).Broadcast(); for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++) { @@ -610,23 +435,36 @@ void ModuleSpanningTree::OnUserConnect(LocalUser* user) ServerInstance->PI->SendMetaData(user, item->name, value); } - Utils->TreeRoot->SetUserCount(1); // increment by 1 + Utils->TreeRoot->UserCount++; } -void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) +void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts) { // Only do this for local users - if (IS_LOCAL(memb->user)) + if (!IS_LOCAL(memb->user)) + return; + + // Assign the current membership id to the new Membership and increase it + memb->id = currmembid++; + + if (created_by_local) { - parameterlist params; - // set up their permissions and the channel TS with FJOIN. - // All users are FJOINed now, because a module may specify - // new joining permissions for the user. + CommandFJoin::Builder params(memb->chan); + params.add(memb); + params.finalize(); + params.Broadcast(); + } + else + { + CmdBuilder params(memb->user, "IJOIN"); params.push_back(memb->chan->name); - params.push_back(ConvToStr(memb->chan->age)); - params.push_back(std::string("+") + memb->chan->ChanModes(true)); - params.push_back(memb->modes+","+memb->user->uuid); - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params); + params.push_int(memb->id); + if (!memb->modes.empty()) + { + params.push_back(ConvToStr(memb->chan->age)); + params.push_back(memb->modes); + } + params.Broadcast(); } } @@ -635,9 +473,7 @@ void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost) if (user->registered != REG_ALL || !IS_LOCAL(user)) return; - parameterlist params; - params.push_back(newhost); - Utils->DoOneToMany(user->uuid,"FHOST",params); + CmdBuilder(user, "FHOST").push(newhost).Broadcast(); } void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos) @@ -645,9 +481,7 @@ void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos) if (user->registered != REG_ALL || !IS_LOCAL(user)) return; - parameterlist params; - params.push_back(":" + gecos); - Utils->DoOneToMany(user->uuid,"FNAME",params); + CmdBuilder(user, "FNAME").push_last(gecos).Broadcast(); } void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident) @@ -655,101 +489,77 @@ void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident) if ((user->registered != REG_ALL) || (!IS_LOCAL(user))) return; - parameterlist params; - params.push_back(ident); - Utils->DoOneToMany(user->uuid,"FIDENT",params); + CmdBuilder(user, "FIDENT").push(ident).Broadcast(); } void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) { if (IS_LOCAL(memb->user)) { - parameterlist params; + CmdBuilder params(memb->user, "PART"); params.push_back(memb->chan->name); if (!partmessage.empty()) - params.push_back(":"+partmessage); - Utils->DoOneToMany(memb->user->uuid,"PART",params); + params.push_last(partmessage); + params.Broadcast(); } } void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) { - if ((IS_LOCAL(user)) && (user->registered == REG_ALL)) + if (IS_LOCAL(user)) { - parameterlist params; - if (oper_message != reason) + ServerInstance->PI->SendMetaData(user, "operquit", oper_message); + + CmdBuilder(user, "QUIT").push_last(reason).Broadcast(); + } + else + { + // Hide the message if one of the following is true: + // - User is being quit due to a netsplit and quietbursts is on + // - Server is a silent uline + TreeServer* server = TreeServer::Get(user); + bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine())); + if (!hide) { - params.push_back(":"+oper_message); - Utils->DoOneToMany(user->uuid,"OPERQUIT",params); + ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]", + user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str()); } - params.clear(); - params.push_back(":"+reason); - Utils->DoOneToMany(user->uuid,"QUIT",params); } // Regardless, We need to modify the user Counts.. - TreeServer* SourceServer = Utils->FindServer(user->server); - if (SourceServer) - { - SourceServer->SetUserCount(-1); // decrement by 1 - } + TreeServer::Get(user)->UserCount--; } void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick) { if (IS_LOCAL(user)) { - parameterlist params; + // The nick TS is updated by the core, we don't do it + CmdBuilder params(user, "NICK"); params.push_back(user->nick); - - /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick! - */ - if ((irc::string(user->nick.c_str()) != assign(oldnick)) && (!this->KeepNickTS)) - user->age = ServerInstance->Time(); - params.push_back(ConvToStr(user->age)); - Utils->DoOneToMany(user->uuid,"NICK",params); - this->KeepNickTS = false; + params.Broadcast(); } - else if (!loopCall && user->nick == user->uuid) + else if (!loopCall) { - parameterlist params; - params.push_back(user->uuid); - params.push_back(ConvToStr(user->age)); - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Changed nick of remote user %s from %s to %s TS %lu by ourselves!", user->uuid.c_str(), oldnick.c_str(), user->nick.c_str(), (unsigned long) user->age); } } void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) { - parameterlist params; + if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient)) + return; + + CmdBuilder params(source, "KICK"); params.push_back(memb->chan->name); params.push_back(memb->user->uuid); - params.push_back(":"+reason); - if (IS_LOCAL(source)) - { - Utils->DoOneToMany(source->uuid,"KICK",params); - } - else if (source == ServerInstance->FakeClient) - { - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params); - } -} - -void ModuleSpanningTree::OnRemoteKill(User* source, User* dest, const std::string &reason, const std::string &operreason) -{ - if (!IS_LOCAL(source)) - return; // Only start routing if we're origin. - - ServerInstance->OperQuit.set(dest, operreason); - parameterlist params; - params.push_back(":"+operreason); - Utils->DoOneToMany(dest->uuid,"OPERQUIT",params); - params.clear(); - params.push_back(dest->uuid); - params.push_back(":"+reason); - Utils->DoOneToMany(source->uuid,"KILL",params); + // If a remote user is being kicked by us then send the membership id in the kick too + if (!IS_LOCAL(memb->user)) + params.push_int(memb->id); + params.push_last(reason); + params.Broadcast(); } void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter) @@ -757,19 +567,29 @@ void ModuleSpanningTree::OnPreRehash(User* user, const std::string ¶meter) if (loopCall) return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one - ServerInstance->Logs->Log("remoterehash", DEBUG, "called with param %s", parameter.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str()); // Send out to other servers if (!parameter.empty() && parameter[0] != '-') { - parameterlist params; + CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH"); params.push_back(parameter); - Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName); + params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL); } } -void ModuleSpanningTree::OnRehash(User* user) +void ModuleSpanningTree::ReadConfig(ConfigStatus& status) { + // Did this rehash change the description of this server? + const std::string& newdesc = ServerInstance->Config->ServerDesc; + if (newdesc != Utils->TreeRoot->GetDesc()) + { + // Broadcast a SINFO desc message to let the network know about the new description. This is the description + // string that is sent in the SERVER message initially and shown for example in WHOIS. + // We don't need to update the field itself in the Server object - the core does that. + CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast(); + } + // Re-read config stuff try { @@ -783,8 +603,8 @@ void ModuleSpanningTree::OnRehash(User* user) std::string msg = "Error in configuration: "; msg.append(e.GetReason()); ServerInstance->SNO->WriteToSnoMask('l', msg); - if (user && !IS_LOCAL(user)) - ServerInstance->PI->SendSNONotice("L", msg); + if (status.srcuser && !IS_LOCAL(status.srcuser)) + ServerInstance->PI->SendSNONotice('L', msg); } } @@ -799,24 +619,26 @@ void ModuleSpanningTree::OnLoadModule(Module* mod) data.push_back('='); data.append(v.link_data); } - ServerInstance->PI->SendMetaData(NULL, "modules", data); + ServerInstance->PI->SendMetaData("modules", data); } void ModuleSpanningTree::OnUnloadModule(Module* mod) { - ServerInstance->PI->SendMetaData(NULL, "modules", "-" + mod->ModuleSourceFile); + if (!Utils) + return; + ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile); restart: - unsigned int items = Utils->TreeRoot->ChildCount(); - for(unsigned int x = 0; x < items; x++) + // Close all connections which use an IO hook provided by this module + const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i) { - TreeServer* srv = Utils->TreeRoot->GetChild(x); - TreeSocket* sock = srv->GetSocket(); - if (sock && sock->GetIOHook() == mod) + TreeSocket* sock = (*i)->GetSocket(); + if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod) { sock->SendError("SSL module unloaded"); sock->Close(); - // XXX: The list we're iterating is modified by TreeSocket::Squit() which is called by Close() + // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close() goto restart; } } @@ -824,7 +646,7 @@ restart: for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i) { TreeSocket* sock = i->first; - if (sock->GetIOHook() == mod) + if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod) sock->Close(); } } @@ -836,152 +658,82 @@ void ModuleSpanningTree::OnOper(User* user, const std::string &opertype) { if (user->registered != REG_ALL || !IS_LOCAL(user)) return; - parameterlist params; - params.push_back(opertype); - Utils->DoOneToMany(user->uuid,"OPERTYPE",params); + CommandOpertype::Builder(user).Broadcast(); } void ModuleSpanningTree::OnAddLine(User* user, XLine *x) { - if (!x->IsBurstable() || loopCall) + if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user))) return; - parameterlist params; - params.push_back(x->type); - params.push_back(x->Displayable()); - params.push_back(ServerInstance->Config->ServerName); - params.push_back(ConvToStr(x->set_time)); - params.push_back(ConvToStr(x->duration)); - params.push_back(":" + x->reason); - if (!user) - { - /* Server-set lines */ - Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params); - } - else if (IS_LOCAL(user)) - { - /* User-set lines */ - Utils->DoOneToMany(user->uuid, "ADDLINE", params); - } + user = ServerInstance->FakeClient; + + CommandAddLine::Builder(x, user).Broadcast(); } void ModuleSpanningTree::OnDelLine(User* user, XLine *x) { - if (!x->IsBurstable() || loopCall) + if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user))) return; - parameterlist params; - params.push_back(x->type); - params.push_back(x->Displayable()); - if (!user) - { - /* Server-unset lines */ - Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params); - } - else if (IS_LOCAL(user)) - { - /* User-unset lines */ - Utils->DoOneToMany(user->uuid, "DELLINE", params); - } -} - -void ModuleSpanningTree::OnMode(User* user, void* dest, int target_type, const parameterlist &text, const std::vector<TranslateType> &translate) -{ - if ((IS_LOCAL(user)) && (user->registered == REG_ALL)) - { - parameterlist params; - std::string output_text; - - ServerInstance->Parser->TranslateUIDs(translate, text, output_text); + user = ServerInstance->FakeClient; - if (target_type == TYPE_USER) - { - User* u = (User*)dest; - params.push_back(u->uuid); - params.push_back(output_text); - Utils->DoOneToMany(user->uuid, "MODE", params); - } - else - { - Channel* c = (Channel*)dest; - params.push_back(c->name); - params.push_back(ConvToStr(c->age)); - params.push_back(output_text); - Utils->DoOneToMany(user->uuid, "FMODE", params); - } - } + CmdBuilder params(user, "DELLINE"); + params.push_back(x->type); + params.push_back(x->Displayable()); + params.Broadcast(); } ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg) { if (IS_LOCAL(user)) - { - parameterlist params; - if (!awaymsg.empty()) - { - params.push_back(ConvToStr(ServerInstance->Time())); - params.push_back(":" + awaymsg); - } - Utils->DoOneToMany(user->uuid, "AWAY", params); - } + CommandAway::Builder(user, awaymsg).Broadcast(); return MOD_RES_PASSTHRU; } -void ModuleSpanningTree::OnRequest(Request& request) +void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags, const std::string& output_mode) { - if (!strcmp(request.id, "rehash")) - Utils->Rehash(); -} - -void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const parameterlist &modeline, const std::vector<TranslateType> &translate) -{ - TreeSocket* s = (TreeSocket*)opaque; - std::string output_text; + if (processflags & ModeParser::MODE_LOCALONLY) + return; - ServerInstance->Parser->TranslateUIDs(translate, modeline, output_text); + if (u) + { + if (u->registered != REG_ALL) + return; - if (target) + CmdBuilder params(source, "MODE"); + params.push(u->uuid); + params.push(output_mode); + params.push_raw(Translate::ModeChangeListToParams(modes.getlist())); + params.Broadcast(); + } + else { - if (target_type == TYPE_USER) - { - User* u = (User*)target; - s->WriteLine(":"+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text); - } - else if (target_type == TYPE_CHANNEL) - { - Channel* c = (Channel*)target; - s->WriteLine(":"+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text); - } + CmdBuilder params(source, "FMODE"); + params.push(c->name); + params.push_int(c->age); + params.push(output_mode); + params.push_raw(Translate::ModeChangeListToParams(modes.getlist())); + params.Broadcast(); } } -void ModuleSpanningTree::ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata) -{ - TreeSocket* s = static_cast<TreeSocket*>(opaque); - User* u = dynamic_cast<User*>(target); - Channel* c = dynamic_cast<Channel*>(target); - if (u) - s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata); - else if (c) - s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata); - else if (!target) - s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata); -} - CullResult ModuleSpanningTree::cull() { - Utils->cull(); - ServerInstance->Timers->DelTimer(RefreshTimer); + if (Utils) + Utils->cull(); return this->Module::cull(); } ModuleSpanningTree::~ModuleSpanningTree() { - delete ServerInstance->PI; - ServerInstance->PI = new ProtocolInterface; + ServerInstance->PI = &ServerInstance->DefaultProtocolInterface; + + Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc); + SetLocalUsersServer(newsrv); /* This will also free the listeners */ delete Utils; diff --git a/src/modules/m_spanningtree/main.h b/src/modules/m_spanningtree/main.h index 17adc9287..9fde32cad 100644 --- a/src/modules/m_spanningtree/main.h +++ b/src/modules/m_spanningtree/main.h @@ -21,11 +21,14 @@ */ -#ifndef M_SPANNINGTREE_MAIN_H -#define M_SPANNINGTREE_MAIN_H +#pragma once #include "inspircd.h" -#include <stdarg.h> +#include "event.h" +#include "modules/dns.h" +#include "servercommand.h" +#include "commands.h" +#include "protocolinterface.h" /** If you make a change which breaks the protocol, increment this. * If you completely change the protocol, completely change the number. @@ -36,8 +39,8 @@ * Failure to document your protocol changes will result in a painfully * painful death by pain. You have been warned. */ -const long ProtocolVersion = 1202; -const long MinCompatProtocol = 1201; +const long ProtocolVersion = 1205; +const long MinCompatProtocol = 1202; /** Forward declarations */ @@ -52,47 +55,51 @@ class Autoconnect; */ class ModuleSpanningTree : public Module { + /** Client to server commands, registered in the core + */ + CommandRConnect rconnect; + CommandRSQuit rsquit; + CommandMap map; + + /** Server to server only commands, not registered in the core + */ SpanningTreeCommands* commands; + /** Next membership id assigned when a local user joins a channel + */ + Membership::Id currmembid; + + /** The specialized ProtocolInterface that is assigned to ServerInstance->PI on load + */ + SpanningTreeProtocolInterface protocolinterface; + + /** Event provider for our events + */ + Events::ModuleEventProvider eventprov; + public: - SpanningTreeUtilities* Utils; + dynamic_reference<DNS::Manager> DNS; + + ServerCommandManager CmdManager; - CacheRefreshTimer *RefreshTimer; /** Set to true if inside a spanningtree call, to prevent sending * xlines and other things back to their source */ bool loopCall; - /** If true OnUserPostNick() won't update the nick TS before sending the NICK, - * used when handling SVSNICK. - */ - bool KeepNickTS; - /** Constructor */ ModuleSpanningTree(); - void init(); + void init() CXX11_OVERRIDE; /** Shows /LINKS */ void ShowLinks(TreeServer* Current, User* user, int hops); - /** Counts local and remote servers - */ - int CountServs(); - /** Handle LINKS command */ void HandleLinks(const std::vector<std::string>& parameters, User* user); - /** Show MAP output to a user (recursive) - */ - void ShowMap(TreeServer* Current, User* user, int depth, int &line, char* names, int &maxnamew, char* stats); - - /** Handle MAP command - */ - bool HandleMap(const std::vector<std::string>& parameters, User* user); - /** Handle SQUIT */ ModResult HandleSquit(const std::vector<std::string>& parameters, User* user); @@ -101,10 +108,6 @@ class ModuleSpanningTree : public Module */ ModResult HandleRemoteWhois(const std::vector<std::string>& parameters, User* user); - /** Ping all local servers - */ - void DoPingChecks(time_t curtime); - /** Connect a server locally */ void ConnectServer(Link* x, Autoconnect* y = NULL); @@ -133,56 +136,44 @@ class ModuleSpanningTree : public Module */ void RemoteMessage(User* user, const char* format, ...) CUSTOM_PRINTF(3, 4); - /** Returns oper-specific MAP information - */ - const std::string MapOperInfo(TreeServer* Current); - /** Display a time as a human readable string */ - std::string TimeToStr(time_t secs); + static std::string TimeToStr(time_t secs); + + const Events::ModuleEventProvider& GetEventProvider() const { return eventprov; } /** ** *** MODULE EVENTS *** **/ - ModResult OnPreCommand(std::string &command, std::vector<std::string>& parameters, LocalUser *user, bool validated, const std::string &original_line); - void OnPostCommand(const std::string &command, const std::vector<std::string>& parameters, LocalUser *user, CmdResult result, const std::string &original_line); - void OnGetServerDescription(const std::string &servername,std::string &description); - void OnUserConnect(LocalUser* source); - void OnUserInvite(User* source,User* dest,Channel* channel, time_t); - void OnPostTopicChange(User* user, Channel* chan, const std::string &topic); - void OnWallops(User* user, const std::string &text); - void OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list); - void OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list); - void OnBackgroundTimer(time_t curtime); - void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts); - void OnChangeHost(User* user, const std::string &newhost); - void OnChangeName(User* user, const std::string &gecos); - void OnChangeIdent(User* user, const std::string &ident); - void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts); - void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message); - void OnUserPostNick(User* user, const std::string &oldnick); - void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts); - void OnRemoteKill(User* source, User* dest, const std::string &reason, const std::string &operreason); - void OnPreRehash(User* user, const std::string ¶meter); - void OnRehash(User* user); - void OnOper(User* user, const std::string &opertype); - void OnLine(User* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason); - void OnAddLine(User *u, XLine *x); - void OnDelLine(User *u, XLine *x); - void OnMode(User* user, void* dest, int target_type, const std::vector<std::string> &text, const std::vector<TranslateType> &translate); - ModResult OnStats(char statschar, User* user, string_list &results); - ModResult OnSetAway(User* user, const std::string &awaymsg); - void ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const std::vector<std::string> &modeline, const std::vector<TranslateType> &translate); - void ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata); - void OnLoadModule(Module* mod); - void OnUnloadModule(Module* mod); - ModResult OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server); - void OnRequest(Request& request); + ModResult OnPreCommand(std::string &command, std::vector<std::string>& parameters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE; + void OnPostCommand(Command*, const std::vector<std::string>& parameters, LocalUser* user, CmdResult result, const std::string& original_line) CXX11_OVERRIDE; + void OnUserConnect(LocalUser* source) CXX11_OVERRIDE; + void OnUserInvite(User* source,User* dest,Channel* channel, time_t) CXX11_OVERRIDE; + void OnPostTopicChange(User* user, Channel* chan, const std::string &topic) CXX11_OVERRIDE; + void OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE; + void OnBackgroundTimer(time_t curtime) CXX11_OVERRIDE; + void OnUserJoin(Membership* memb, bool sync, bool created, CUList& excepts) CXX11_OVERRIDE; + void OnChangeHost(User* user, const std::string &newhost) CXX11_OVERRIDE; + void OnChangeName(User* user, const std::string &gecos) CXX11_OVERRIDE; + void OnChangeIdent(User* user, const std::string &ident) CXX11_OVERRIDE; + void OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts) CXX11_OVERRIDE; + void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) CXX11_OVERRIDE; + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE; + void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts) CXX11_OVERRIDE; + void OnPreRehash(User* user, const std::string ¶meter) CXX11_OVERRIDE; + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE; + void OnOper(User* user, const std::string &opertype) CXX11_OVERRIDE; + void OnAddLine(User *u, XLine *x) CXX11_OVERRIDE; + void OnDelLine(User *u, XLine *x) CXX11_OVERRIDE; + ModResult OnStats(char statschar, User* user, string_list &results) CXX11_OVERRIDE; + ModResult OnSetAway(User* user, const std::string &awaymsg) CXX11_OVERRIDE; + void OnLoadModule(Module* mod) CXX11_OVERRIDE; + void OnUnloadModule(Module* mod) CXX11_OVERRIDE; + ModResult OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE; + void OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags, const std::string& output_mode) CXX11_OVERRIDE; CullResult cull(); ~ModuleSpanningTree(); - Version GetVersion(); + Version GetVersion() CXX11_OVERRIDE; void Prioritize(); }; - -#endif diff --git a/src/modules/m_spanningtree/metadata.cpp b/src/modules/m_spanningtree/metadata.cpp index a584f8fa8..f758754b4 100644 --- a/src/modules/m_spanningtree/metadata.cpp +++ b/src/modules/m_spanningtree/metadata.cpp @@ -21,39 +21,76 @@ #include "inspircd.h" #include "commands.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" - -CmdResult CommandMetadata::Handle(const std::vector<std::string>& params, User *srcuser) +CmdResult CommandMetadata::Handle(User* srcuser, std::vector<std::string>& params) { - std::string value = params.size() < 3 ? "" : params[2]; - ExtensionItem* item = ServerInstance->Extensions.GetItem(params[1]); if (params[0] == "*") { - FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(NULL,params[1],value)); + std::string value = params.size() < 3 ? "" : params[2]; + FOREACH_MOD(OnDecodeMetaData, (NULL,params[1],value)); + return CMD_SUCCESS; } - else if (*(params[0].c_str()) == '#') + + if (params[0][0] == '#') { + // Channel METADATA has an additional parameter: the channel TS + // :22D METADATA #channel 12345 extname :extdata + if (params.size() < 3) + throw ProtocolException("Insufficient parameters for channel METADATA"); + Channel* c = ServerInstance->FindChan(params[0]); - if (c) - { - if (item) - item->unserialize(FORMAT_NETWORK, c, value); - FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(c,params[1],value)); - } + if (!c) + return CMD_FAILURE; + + time_t ChanTS = ServerCommand::ExtractTS(params[1]); + if (c->age < ChanTS) + // Their TS is newer than ours, discard this command and do not propagate + return CMD_FAILURE; + + std::string value = params.size() < 4 ? "" : params[3]; + + ExtensionItem* item = ServerInstance->Extensions.GetItem(params[2]); + if ((item) && (item->type == ExtensionItem::EXT_CHANNEL)) + item->unserialize(FORMAT_NETWORK, c, value); + FOREACH_MOD(OnDecodeMetaData, (c,params[2],value)); } - else if (*(params[0].c_str()) != '#') + else { User* u = ServerInstance->FindUUID(params[0]); if ((u) && (!IS_SERVER(u))) { - if (item) + ExtensionItem* item = ServerInstance->Extensions.GetItem(params[1]); + std::string value = params.size() < 3 ? "" : params[2]; + + if ((item) && (item->type == ExtensionItem::EXT_USER)) item->unserialize(FORMAT_NETWORK, u, value); - FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(u,params[1],value)); + FOREACH_MOD(OnDecodeMetaData, (u,params[1],value)); } } return CMD_SUCCESS; } +CommandMetadata::Builder::Builder(User* user, const std::string& key, const std::string& val) + : CmdBuilder("METADATA") +{ + push(user->uuid); + push(key); + push_last(val); +} + +CommandMetadata::Builder::Builder(Channel* chan, const std::string& key, const std::string& val) + : CmdBuilder("METADATA") +{ + push(chan->name); + push_int(chan->age); + push(key); + push_last(val); +} + +CommandMetadata::Builder::Builder(const std::string& key, const std::string& val) + : CmdBuilder("METADATA") +{ + push("*"); + push(key); + push_last(val); +} diff --git a/src/modules/m_spanningtree/misccommands.cpp b/src/modules/m_spanningtree/misccommands.cpp new file mode 100644 index 000000000..00f31d668 --- /dev/null +++ b/src/modules/m_spanningtree/misccommands.cpp @@ -0,0 +1,42 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net> + * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org> + * Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc> + * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> + * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org> + * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +#include "main.h" +#include "commands.h" +#include "treeserver.h" + +CmdResult CommandSNONotice::Handle(User* user, std::vector<std::string>& params) +{ + ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + user->nick + ": " + params[1]); + return CMD_SUCCESS; +} + +CmdResult CommandEndBurst::HandleServer(TreeServer* server, std::vector<std::string>& params) +{ + server->FinishBurst(); + return CMD_SUCCESS; +} diff --git a/src/modules/m_spanningtree/netburst.cpp b/src/modules/m_spanningtree/netburst.cpp index d508c092d..b81a285b5 100644 --- a/src/modules/m_spanningtree/netburst.cpp +++ b/src/modules/m_spanningtree/netburst.cpp @@ -21,11 +21,79 @@ #include "inspircd.h" #include "xline.h" +#include "listmode.h" #include "treesocket.h" #include "treeserver.h" -#include "utils.h" #include "main.h" +#include "commands.h" + +/** + * Creates FMODE messages, used only when syncing channels + */ +class FModeBuilder : public CmdBuilder +{ + static const size_t maxline = 480; + std::string params; + unsigned int modes; + std::string::size_type startpos; + + public: + FModeBuilder(Channel* chan) + : CmdBuilder("FMODE"), modes(0) + { + push(chan->name).push_int(chan->age).push_raw(" +"); + startpos = str().size(); + } + + /** Add a mode to the message + */ + void push_mode(const char modeletter, const std::string& mask) + { + push_raw(modeletter); + params.push_back(' '); + params.append(mask); + modes++; + } + + /** Remove all modes from the message + */ + void clear() + { + content.erase(startpos); + params.clear(); + modes = 0; + } + + /** Prepare the message for sending, next mode can only be added after clear() + */ + const std::string& finalize() + { + return push_raw(params); + } + + /** Returns true if the given mask can be added to the message, false if the message + * has no room for the mask + */ + bool has_room(const std::string& mask) const + { + return ((str().size() + params.size() + mask.size() + 2 <= maxline) && + (modes < ServerInstance->Config->Limits.MaxModes)); + } + + /** Returns true if this message is empty (has no modes) + */ + bool empty() const + { + return (modes == 0); + } +}; + +struct TreeSocket::BurstState +{ + SpanningTreeProtocolInterface::Server server; + BurstState(TreeSocket* sock) : server(sock) { } +}; /** This function is called when we want to send a netburst to a local * server. There is a set order we must do this, because for example @@ -34,52 +102,59 @@ */ void TreeSocket::DoBurst(TreeServer* s) { - std::string servername = s->GetName(); ServerInstance->SNO->WriteToSnoMask('l',"Bursting to \2%s\2 (Authentication: %s%s).", - servername.c_str(), - capab->auth_fingerprint ? "SSL Fingerprint and " : "", + s->GetName().c_str(), + capab->auth_fingerprint ? "SSL certificate fingerprint and " : "", capab->auth_challenge ? "challenge-response" : "plaintext password"); this->CleanNegotiationInfo(); - this->WriteLine(":" + ServerInstance->Config->GetSID() + " BURST " + ConvToStr(ServerInstance->Time())); - /* send our version string */ - this->WriteLine(":" + ServerInstance->Config->GetSID() + " VERSION :"+ServerInstance->GetVersionString()); + this->WriteLine(CmdBuilder("BURST").push_int(ServerInstance->Time())); /* Send server tree */ - this->SendServers(Utils->TreeRoot,s,1); + this->SendServers(Utils->TreeRoot, s); + + BurstState bs(this); /* Send users and their oper status */ - this->SendUsers(); - /* Send everything else (channel modes, xlines etc) */ - this->SendChannelModes(); + this->SendUsers(bs); + + const chan_hash& chans = ServerInstance->GetChans(); + for (chan_hash::const_iterator i = chans.begin(); i != chans.end(); ++i) + SyncChannel(i->second, bs); + this->SendXLines(); - FOREACH_MOD(I_OnSyncNetwork,OnSyncNetwork(Utils->Creator,(void*)this)); - this->WriteLine(":" + ServerInstance->Config->GetSID() + " ENDBURST"); + FOREACH_MOD(OnSyncNetwork, (bs.server)); + this->WriteLine(CmdBuilder("ENDBURST")); ServerInstance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+ s->GetName()+"\2."); + + this->burstsent = true; } -/** Recursively send the server tree with distances as hops. +void TreeSocket::SendServerInfo(TreeServer* from) +{ + // Send public version string + this->WriteLine(CommandSInfo::Builder(from, "version", from->GetVersion())); + + // Send full version string that contains more information and is shown to opers + this->WriteLine(CommandSInfo::Builder(from, "fullversion", from->GetFullVersion())); +} + +/** Recursively send the server tree. * This is used during network burst to inform the other server * (and any of ITS servers too) of what servers we know about. * If at any point any of these servers already exist on the other - * end, our connection may be terminated. The hopcounts given - * by this function are relative, this doesn't matter so long as - * they are all >1, as all the remote servers re-calculate them - * to be relative too, with themselves as hop 0. + * end, our connection may be terminated. */ -void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops) +void TreeSocket::SendServers(TreeServer* Current, TreeServer* s) { - char command[MAXBUF]; - for (unsigned int q = 0; q < Current->ChildCount(); q++) + SendServerInfo(Current); + + const TreeServer::ChildServers& children = Current->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i) { - TreeServer* recursive_server = Current->GetChild(q); + TreeServer* recursive_server = *i; if (recursive_server != s) { - std::string recursive_servername = recursive_server->GetName(); - snprintf(command, MAXBUF, ":%s SERVER %s * %d %s :%s", Current->GetID().c_str(), recursive_servername.c_str(), hops, - recursive_server->GetID().c_str(), - recursive_server->GetDesc().c_str()); - this->WriteLine(command); - this->WriteLine(":"+recursive_server->GetID()+" VERSION :"+recursive_server->GetVersion()); + this->WriteLine(CommandServer::Builder(recursive_server)); /* down to next level */ - this->SendServers(recursive_server, s, hops+1); + this->SendServers(recursive_server, s); } } } @@ -87,101 +162,39 @@ void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops) /** Send one or more FJOINs for a channel of users. * If the length of a single line is more than 480-NICKMAX * in length, it is split over multiple lines. + * Send one or more FMODEs for a channel with the + * channel bans, if there's any. */ void TreeSocket::SendFJoins(Channel* c) { - std::string buffer; - char list[MAXBUF]; - - size_t curlen, headlen; - curlen = headlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu +%s :", - ServerInstance->Config->GetSID().c_str(), c->name.c_str(), (unsigned long)c->age, c->ChanModes(true)); - int numusers = 0; - char* ptr = list + curlen; - bool looped_once = false; - - const UserMembList *ulist = c->GetUsers(); - std::string modes; - std::string params; - - for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++) - { - size_t ptrlen = 0; - std::string modestr = i->second->modes; - - if ((curlen + modestr.length() + i->first->uuid.length() + 4) > 480) - { - // remove the final space - if (ptr[-1] == ' ') - ptr[-1] = '\0'; - buffer.append(list).append("\r\n"); - curlen = headlen; - ptr = list + headlen; - numusers = 0; - } - - ptrlen = snprintf(ptr, MAXBUF-curlen, "%s,%s ", modestr.c_str(), i->first->uuid.c_str()); - - looped_once = true; - - curlen += ptrlen; - ptr += ptrlen; - - numusers++; - } - - // Okay, permanent channels will (of course) need this \r\n anyway, numusers check is if there - // actually were people in the channel (looped_once == true) - if (!looped_once || numusers > 0) - { - // remove the final space - if (ptr[-1] == ' ') - ptr[-1] = '\0'; - buffer.append(list).append("\r\n"); - } + CommandFJoin::Builder fjoin(c); - int linesize = 1; - for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++) + const Channel::MemberMap& ulist = c->GetUsers(); + for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i) { - int size = b->data.length() + 2; - int currsize = linesize + size; - if (currsize <= 350) - { - modes.append("b"); - params.append(" ").append(b->data); - linesize += size; - } - if ((modes.length() >= ServerInstance->Config->Limits.MaxModes) || (currsize > 350)) + Membership* memb = i->second; + if (!fjoin.has_room(memb)) { - /* Wrap at MAXMODES */ - buffer.append(":").append(ServerInstance->Config->GetSID()).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n"); - modes.clear(); - params.clear(); - linesize = 1; + // No room for this user, send the line and prepare a new one + this->WriteLine(fjoin.finalize()); + fjoin.clear(); } + fjoin.add(memb); } - - /* Only send these if there are any */ - if (!modes.empty()) - buffer.append(":").append(ServerInstance->Config->GetSID()).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params); - - this->WriteLine(buffer); + this->WriteLine(fjoin.finalize()); } /** Send all XLines we know about */ void TreeSocket::SendXLines() { - char data[MAXBUF]; - std::string n = ServerInstance->Config->GetSID(); - const char* sn = n.c_str(); - std::vector<std::string> types = ServerInstance->XLines->GetAllTypes(); - time_t current = ServerInstance->Time(); - for (std::vector<std::string>::iterator it = types.begin(); it != types.end(); ++it) + for (std::vector<std::string>::const_iterator it = types.begin(); it != types.end(); ++it) { + /* Expired lines are removed in XLineManager::GetAll() */ XLineLookup* lookup = ServerInstance->XLines->GetAll(*it); + /* lookup cannot be NULL in this case but a check won't hurt */ if (lookup) { for (LookupIter i = lookup->begin(); i != lookup->end(); ++i) @@ -192,96 +205,101 @@ void TreeSocket::SendXLines() if (!i->second->IsBurstable()) break; - /* If it's expired, don't bother to burst it - */ - if (i->second->duration && current > i->second->expiry) - continue; - - snprintf(data,MAXBUF,":%s ADDLINE %s %s %s %lu %lu :%s",sn, it->c_str(), i->second->Displayable(), - i->second->source.c_str(), - (unsigned long)i->second->set_time, - (unsigned long)i->second->duration, - i->second->reason.c_str()); - this->WriteLine(data); + this->WriteLine(CommandAddLine::Builder(i->second)); } } } } -/** Send channel topic, modes and metadata */ -void TreeSocket::SendChannelModes() +void TreeSocket::SendListModes(Channel* chan) { - char data[MAXBUF]; - std::string n = ServerInstance->Config->GetSID(); - const char* sn = n.c_str(); - - for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++) + FModeBuilder fmode(chan); + const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes(); + for (ModeParser::ListModeList::const_iterator i = listmodes.begin(); i != listmodes.end(); ++i) { - SendFJoins(c->second); - if (!c->second->topic.empty()) + ListModeBase* mh = *i; + ListModeBase::ModeList* list = mh->GetList(chan); + if (!list) + continue; + + // Add all items on the list to the FMODE, send it whenever it becomes too long + const char modeletter = mh->GetModeChar(); + for (ListModeBase::ModeList::const_iterator j = list->begin(); j != list->end(); ++j) { - snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s", sn, c->second->name.c_str(), (unsigned long)c->second->topicset, c->second->setby.c_str(), c->second->topic.c_str()); - this->WriteLine(data); + const std::string& mask = j->mask; + if (!fmode.has_room(mask)) + { + // No room for this mask, send the current line as-is then add the mask to a + // new, empty FMODE message + this->WriteLine(fmode.finalize()); + fmode.clear(); + } + fmode.push_mode(modeletter, mask); } + } - for(Extensible::ExtensibleStore::const_iterator i = c->second->GetExtList().begin(); i != c->second->GetExtList().end(); i++) - { - ExtensionItem* item = i->first; - std::string value = item->serialize(FORMAT_NETWORK, c->second, i->second); - if (!value.empty()) - Utils->Creator->ProtoSendMetaData(this, c->second, item->name, value); - } + if (!fmode.empty()) + this->WriteLine(fmode.finalize()); +} - FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,Utils->Creator,this)); +/** Send channel topic, modes and metadata */ +void TreeSocket::SyncChannel(Channel* chan, BurstState& bs) +{ + SendFJoins(chan); + + // If the topic was ever set, send it, even if it's empty now + // because a new empty topic should override an old non-empty topic + if (chan->topicset != 0) + this->WriteLine(CommandFTopic::Builder(chan)); + + SendListModes(chan); + + for (Extensible::ExtensibleStore::const_iterator i = chan->GetExtList().begin(); i != chan->GetExtList().end(); i++) + { + ExtensionItem* item = i->first; + std::string value = item->serialize(FORMAT_NETWORK, chan, i->second); + if (!value.empty()) + this->WriteLine(CommandMetadata::Builder(chan, item->name, value)); } + + FOREACH_MOD(OnSyncChannel, (chan, bs.server)); +} + +void TreeSocket::SyncChannel(Channel* chan) +{ + BurstState bs(this); + SyncChannel(chan, bs); } /** send all users and their oper state/modes */ -void TreeSocket::SendUsers() +void TreeSocket::SendUsers(BurstState& bs) { - char data[MAXBUF]; - for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++) + ProtocolInterface::Server& piserver = bs.server; + + const user_hash& users = ServerInstance->Users->GetUsers(); + for (user_hash::const_iterator u = users.begin(); u != users.end(); ++u) { - if (u->second->registered == REG_ALL) - { - TreeServer* theirserver = Utils->FindServer(u->second->server); - if (theirserver) - { - snprintf(data,MAXBUF,":%s UID %s %lu %s %s %s %s %s %lu +%s :%s", - theirserver->GetID().c_str(), /* Prefix: SID */ - u->second->uuid.c_str(), /* 0: UUID */ - (unsigned long)u->second->age, /* 1: TS */ - u->second->nick.c_str(), /* 2: Nick */ - u->second->host.c_str(), /* 3: Displayed Host */ - u->second->dhost.c_str(), /* 4: Real host */ - u->second->ident.c_str(), /* 5: Ident */ - u->second->GetIPString(), /* 6: IP string */ - (unsigned long)u->second->signon, /* 7: Signon time for WHOWAS */ - u->second->FormatModes(true), /* 8...n: Modes and params */ - u->second->fullname.c_str()); /* size-1: GECOS */ - this->WriteLine(data); - if (IS_OPER(u->second)) - { - snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->uuid.c_str(), u->second->oper->name.c_str()); - this->WriteLine(data); - } - if (IS_AWAY(u->second)) - { - snprintf(data,MAXBUF,":%s AWAY %ld :%s", u->second->uuid.c_str(), (long)u->second->awaytime, u->second->awaymsg.c_str()); - this->WriteLine(data); - } - } + User* user = u->second; + if (user->registered != REG_ALL) + continue; - for(Extensible::ExtensibleStore::const_iterator i = u->second->GetExtList().begin(); i != u->second->GetExtList().end(); i++) - { - ExtensionItem* item = i->first; - std::string value = item->serialize(FORMAT_NETWORK, u->second, i->second); - if (!value.empty()) - Utils->Creator->ProtoSendMetaData(this, u->second, item->name, value); - } + this->WriteLine(CommandUID::Builder(user)); + + if (user->IsOper()) + this->WriteLine(CommandOpertype::Builder(user)); + + if (user->IsAway()) + this->WriteLine(CommandAway::Builder(user)); - FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,Utils->Creator,this)); + const Extensible::ExtensibleStore& exts = user->GetExtList(); + for (Extensible::ExtensibleStore::const_iterator i = exts.begin(); i != exts.end(); ++i) + { + ExtensionItem* item = i->first; + std::string value = item->serialize(FORMAT_NETWORK, u->second, i->second); + if (!value.empty()) + this->WriteLine(CommandMetadata::Builder(user, item->name, value)); } + + FOREACH_MOD(OnSyncUser, (user, piserver)); } } - diff --git a/src/modules/m_spanningtree/nick.cpp b/src/modules/m_spanningtree/nick.cpp new file mode 100644 index 000000000..9496c2874 --- /dev/null +++ b/src/modules/m_spanningtree/nick.cpp @@ -0,0 +1,64 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net> + * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org> + * Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc> + * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com> + * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org> + * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +#include "main.h" +#include "utils.h" +#include "commands.h" +#include "treeserver.h" + +CmdResult CommandNick::HandleRemote(RemoteUser* user, std::vector<std::string>& params) +{ + if ((isdigit(params[0][0])) && (params[0] != user->uuid)) + throw ProtocolException("Attempted to change nick to an invalid or non-matching UUID"); + + // Timestamp of the new nick + time_t newts = ServerCommand::ExtractTS(params[1]); + + /* + * On nick messages, check that the nick doesn't already exist here. + * If it does, perform collision logic. + */ + User* x = ServerInstance->FindNickOnly(params[0]); + if ((x) && (x != user) && (x->registered == REG_ALL)) + { + // 'x' is the already existing user using the same nick as params[0] + // 'user' is the user trying to change nick to the in use nick + bool they_change = Utils->DoCollision(x, TreeServer::Get(user), newts, user->ident, user->GetIPString(), user->uuid); + if (they_change) + { + // Remote client lost, or both lost, rewrite this nick change as a change to uuid before + // calling ChangeNick() and forwarding the message + params[0] = user->uuid; + params[1] = ConvToStr(CommandSave::SavedTimestamp); + newts = CommandSave::SavedTimestamp; + } + } + + user->ChangeNick(params[0], newts); + + return CMD_SUCCESS; +} diff --git a/src/modules/m_spanningtree/nickcollide.cpp b/src/modules/m_spanningtree/nickcollide.cpp index 38d59affb..3401041aa 100644 --- a/src/modules/m_spanningtree/nickcollide.cpp +++ b/src/modules/m_spanningtree/nickcollide.cpp @@ -19,23 +19,25 @@ #include "inspircd.h" -#include "xline.h" #include "treesocket.h" #include "treeserver.h" #include "utils.h" - -/* $ModDep: m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - +#include "commandbuilder.h" +#include "commands.h" /* * Yes, this function looks a little ugly. * However, in some circumstances we may not have a User, so we need to do things this way. - * Returns 1 if colliding local client, 2 if colliding remote, 3 if colliding both. - * Sends SAVEs as appropriate and forces nickchanges too. + * Returns true if remote or both lost, false otherwise. + * Sends SAVEs as appropriate and forces nick change of the user 'u' if our side loses or if both lose. + * Does not change the nick of the user that is trying to claim the nick of 'u', i.e. the "remote" user. */ -int TreeSocket::DoCollision(User *u, time_t remotets, const std::string &remoteident, const std::string &remoteip, const std::string &remoteuid) +bool SpanningTreeUtilities::DoCollision(User* u, TreeServer* server, time_t remotets, const std::string& remoteident, const std::string& remoteip, const std::string& remoteuid) { + // At this point we're sure that a collision happened, increment the counter regardless of who wins + ServerInstance->stats.Collisions++; + /* * Under old protocol rules, we would have had to kill both clients. * Really, this sucks. @@ -56,21 +58,14 @@ int TreeSocket::DoCollision(User *u, time_t remotets, const std::string &remotei bool bChangeLocal = true; bool bChangeRemote = true; - /* for brevity, don't use the User - use defines to avoid any copy */ - #define localts u->age - #define localident u->ident - #define localip u->GetIPString() - - /* mmk. let's do this again. */ - if (remotets == localts) + // If the timestamps are not equal only one of the users has to change nick, + // otherwise both have to change + const time_t localts = u->age; + if (remotets != localts) { - /* equal. fuck them both! do nada, let the handler at the bottom figure this out. */ - } - else - { - /* fuck. now it gets complex. */ - /* first, let's see if ident@host matches. */ + const std::string& localident = u->ident; + const std::string& localip = u->GetIPString(); bool SamePerson = (localident == remoteident) && (localip == remoteip); @@ -81,19 +76,18 @@ int TreeSocket::DoCollision(User *u, time_t remotets, const std::string &remotei if((SamePerson && remotets < localts) || (!SamePerson && remotets > localts)) { - /* remote needs to change */ + // Only remote needs to change bChangeLocal = false; } else { - /* ours needs to change */ + // Only ours needs to change bChangeRemote = false; } } /* - * Cheat a little here. Instead of a dedicated command to change UID, - * use SAVE and accept the losing client with its UID (as we know the SAVE will + * Send SAVE and accept the losing client with its UID (as we know the SAVE will * not fail under any circumstances -- UIDs are netwide exclusive). * * This means that each side of a collide will generate one extra NICK back to where @@ -107,38 +101,23 @@ int TreeSocket::DoCollision(User *u, time_t remotets, const std::string &remotei { /* * Local-side nick needs to change. Just in case we are hub, and - * this "local" nick is actually behind us, send an SAVE out. + * this "local" nick is actually behind us, send a SAVE out. */ - parameterlist params; + CmdBuilder params("SAVE"); params.push_back(u->uuid); params.push_back(ConvToStr(u->age)); - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params); + params.Broadcast(); - u->ForceNickChange(u->uuid.c_str()); - - if (!bChangeRemote) - return 1; + u->ChangeNick(u->uuid, CommandSave::SavedTimestamp); } if (bChangeRemote) { - User *remote = ServerInstance->FindUUID(remoteuid); /* - * remote side needs to change. If this happens, we will modify - * the UID or halt the propagation of the nick change command, - * so other servers don't need to see the SAVE + * Remote side needs to change. If this happens, we modify the UID or NICK and + * send back a SAVE to the source. */ - WriteLine(":"+ServerInstance->Config->GetSID()+" SAVE "+remoteuid+" "+ ConvToStr(remotets)); - - if (remote) - { - /* nick change collide. Force change their nick. */ - remote->ForceNickChange(remoteuid.c_str()); - } - - if (!bChangeLocal) - return 2; + CmdBuilder("SAVE").push(remoteuid).push_int(remotets).Unicast(server->ServerUser); } - return 3; + return bChangeRemote; } - diff --git a/src/modules/m_spanningtree/opertype.cpp b/src/modules/m_spanningtree/opertype.cpp index 97a4de8c2..ab531c171 100644 --- a/src/modules/m_spanningtree/opertype.cpp +++ b/src/modules/m_spanningtree/opertype.cpp @@ -26,15 +26,17 @@ /** Because the core won't let users or even SERVERS set +o, * we use the OPERTYPE command to do this. */ -CmdResult CommandOpertype::Handle(const std::vector<std::string>& params, User *u) +CmdResult CommandOpertype::HandleRemote(RemoteUser* u, std::vector<std::string>& params) { - SpanningTreeUtilities* Utils = ((ModuleSpanningTree*)(Module*)creator)->Utils; - std::string opertype = params[0]; - if (!IS_OPER(u)) + const std::string& opertype = params[0]; + if (!u->IsOper()) ServerInstance->Users->all_opers.push_back(u); - u->modes[UM_OPERATOR] = 1; - OperIndex::iterator iter = ServerInstance->Config->oper_blocks.find(" " + opertype); - if (iter != ServerInstance->Config->oper_blocks.end()) + + ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER); + u->SetMode(opermh, true); + + ServerConfig::OperIndex::const_iterator iter = ServerInstance->Config->OperTypes.find(opertype); + if (iter != ServerInstance->Config->OperTypes.end()) u->oper = iter->second; else { @@ -48,12 +50,17 @@ CmdResult CommandOpertype::Handle(const std::vector<std::string>& params, User * * If quiet bursts are enabled, and server is bursting or silent uline (i.e. services), * then do nothing. -- w00t */ - TreeServer* remoteserver = Utils->FindServer(u->server); - if (remoteserver->bursting || ServerInstance->SilentULine(u->server)) + TreeServer* remoteserver = TreeServer::Get(u); + if (remoteserver->IsBehindBursting() || remoteserver->IsSilentULine()) return CMD_SUCCESS; } - ServerInstance->SNO->WriteToSnoMask('O',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server.c_str(), u->nick.c_str(),u->ident.c_str(), u->host.c_str(), irc::Spacify(opertype.c_str())); + ServerInstance->SNO->WriteToSnoMask('O',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server->GetName().c_str(), u->nick.c_str(),u->ident.c_str(), u->host.c_str(), opertype.c_str()); return CMD_SUCCESS; } +CommandOpertype::Builder::Builder(User* user) + : CmdBuilder(user, "OPERTYPE") +{ + push_last(user->oper->name); +} diff --git a/src/modules/m_spanningtree/override_map.cpp b/src/modules/m_spanningtree/override_map.cpp index 04fa4bcab..68551e84f 100644 --- a/src/modules/m_spanningtree/override_map.cpp +++ b/src/modules/m_spanningtree/override_map.cpp @@ -1,6 +1,7 @@ /* * InspIRCd -- Internet Relay Chat Daemon * + * Copyright (C) 2014 Adam <Adam@anope.org> * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> * Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc> * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net> @@ -19,178 +20,203 @@ */ -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" #include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ +#include "commands.h" -const std::string ModuleSpanningTree::MapOperInfo(TreeServer* Current) +CommandMap::CommandMap(Module* Creator) + : Command(Creator, "MAP", 0, 1) { - time_t secs_up = ServerInstance->Time() - Current->age; - return " [Up: " + TimeToStr(secs_up) + (Current->rtt == 0 ? "]" : " Lag: " + ConvToStr(Current->rtt) + "ms]"); + Penalty = 2; } -void ModuleSpanningTree::ShowMap(TreeServer* Current, User* user, int depth, int &line, char* names, int &maxnamew, char* stats) +static inline bool IsHidden(User* user, TreeServer* server) { - ServerInstance->Logs->Log("map",DEBUG,"ShowMap depth %d on line %d", depth, line); - float percent; - - if (ServerInstance->Users->clientlist->size() == 0) + if (!user->IsOper()) { - // If there are no users, WHO THE HELL DID THE /MAP?!?!?! - percent = 0; + if (server->Hidden) + return true; + if (Utils->HideULines && server->IsULine()) + return true; } - else + + return false; +} + +// Calculate the map depth the servers go, and the longest server name +static void GetDepthAndLen(TreeServer* current, unsigned int depth, unsigned int& max_depth, unsigned int& max_len) +{ + if (depth > max_depth) + max_depth = depth; + if (current->GetName().length() > max_len) + max_len = current->GetName().length(); + + const TreeServer::ChildServers& servers = current->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = servers.begin(); i != servers.end(); ++i) { - percent = Current->GetUserCount() * 100.0 / ServerInstance->Users->clientlist->size(); + TreeServer* child = *i; + GetDepthAndLen(child, depth + 1, max_depth, max_len); } +} - const std::string operdata = IS_OPER(user) ? MapOperInfo(Current) : ""; - - char* myname = names + 100 * line; - char* mystat = stats + 50 * line; - memset(myname, ' ', depth); - int w = depth; +static std::vector<std::string> GetMap(User* user, TreeServer* current, unsigned int max_len, unsigned int depth) +{ + float percent = 0; - std::string servername = Current->GetName(); - if (IS_OPER(user)) + const user_hash& users = ServerInstance->Users->GetUsers(); + if (!users.empty()) { - w += snprintf(myname + depth, 99 - depth, "%s (%s)", servername.c_str(), Current->GetID().c_str()); + // If there are no users, WHO THE HELL DID THE /MAP?!?!?! + percent = current->UserCount * 100.0 / users.size(); } - else + + std::string buffer = current->GetName(); + if (user->IsOper()) { - w += snprintf(myname + depth, 99 - depth, "%s", servername.c_str()); + buffer += " (" + current->GetID() + ")"; } - memset(myname + w, ' ', 100 - w); - if (w > maxnamew) - maxnamew = w; - snprintf(mystat, 49, "%5d [%5.2f%%]%s", Current->GetUserCount(), percent, operdata.c_str()); - line++; + // Pad with spaces until its at max len, max_len must always be >= my names length + buffer.append(max_len - current->GetName().length(), ' '); - if (IS_OPER(user) || !Utils->FlatLinks) - depth = depth + 2; - for (unsigned int q = 0; q < Current->ChildCount(); q++) + char buf[16]; + snprintf(buf, sizeof(buf), "%5d [%5.2f%%]", current->UserCount, percent); + buffer += buf; + + if (user->IsOper()) { - TreeServer* child = Current->GetChild(q); - if (!IS_OPER(user)) { - if (child->Hidden) - continue; - if ((Utils->HideULines) && (ServerInstance->ULine(child->GetName()))) - continue; - } - ShowMap(child, user, depth, line, names, maxnamew, stats); + time_t secs_up = ServerInstance->Time() - current->age; + buffer += " [Up: " + ModuleSpanningTree::TimeToStr(secs_up) + (current->rtt == 0 ? "]" : " Lag: " + ConvToStr(current->rtt) + "ms]"); } -} + std::vector<std::string> map; + map.push_back(buffer); -// Ok, prepare to be confused. -// After much mulling over how to approach this, it struck me that -// the 'usual' way of doing a /MAP isnt the best way. Instead of -// keeping track of a ton of ascii characters, and line by line -// under recursion working out where to place them using multiplications -// and divisons, we instead render the map onto a backplane of characters -// (a character matrix), then draw the branches as a series of "L" shapes -// from the nodes. This is not only friendlier on CPU it uses less stack. -bool ModuleSpanningTree::HandleMap(const std::vector<std::string>& parameters, User* user) -{ - if (parameters.size() > 0) + const TreeServer::ChildServers& servers = current->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = servers.begin(); i != servers.end(); ++i) { - /* Remote MAP, the server is within the 1st parameter */ - TreeServer* s = Utils->FindServerMask(parameters[0]); - bool ret = false; - if (!s) + TreeServer* child = *i; + + if (IsHidden(user, child)) + continue; + + bool last = true; + for (TreeServer::ChildServers::const_iterator j = i + 1; last && j != servers.end(); ++j) + if (!IsHidden(user, *j)) + last = false; + + unsigned int next_len; + + if (user->IsOper() || !Utils->FlatLinks) { - user->WriteNumeric(ERR_NOSUCHSERVER, "%s %s :No such server", user->nick.c_str(), parameters[0].c_str()); - ret = true; + // This child is indented by us, so remove the depth from the max length to align the users properly + next_len = max_len - 2; } - else if (s && s != Utils->TreeRoot) + else { - parameterlist params; - params.push_back(parameters[0]); - - params[0] = s->GetName(); - Utils->DoOneToOne(user->uuid, "MAP", params, s->GetName()); - ret = true; + // This user can not see depth, so max_len remains constant + next_len = max_len; } - // Don't return if s == Utils->TreeRoot (us) - if (ret) - return true; - } + // Build the map for this child + std::vector<std::string> child_map = GetMap(user, child, next_len, depth + 1); - // These arrays represent a virtual screen which we will - // "scratch" draw to, as the console device of an irc - // client does not provide for a proper terminal. - int totusers = ServerInstance->Users->clientlist->size(); - int totservers = this->CountServs(); - int maxnamew = 0; - int line = 0; - char* names = new char[totservers * 100]; - char* stats = new char[totservers * 50]; - - // The only recursive bit is called here. - ShowMap(Utils->TreeRoot,user,0,line,names,maxnamew,stats); - - // Process each line one by one. - for (int l = 1; l < line; l++) - { - char* myname = names + 100 * l; - // scan across the line looking for the start of the - // servername (the recursive part of the algorithm has placed - // the servers at indented positions depending on what they - // are related to) - int first_nonspace = 0; - - while (myname[first_nonspace] == ' ') + for (std::vector<std::string>::const_iterator j = child_map.begin(); j != child_map.end(); ++j) { - first_nonspace++; + const char* prefix; + + if (user->IsOper() || !Utils->FlatLinks) + { + // If this server is not the root child + if (j != child_map.begin()) + { + // If this child is not my last child, then add | + // to be able to "link" the next server in my list to me, and to indent this childs servers + if (!last) + prefix = "| "; + // Otherwise this is my last child, so just use a space as theres nothing else linked to me below this + else + prefix = " "; + } + // If we get here, this server must be the root child + else + { + // If this is the last child, it gets a `- + if (last) + prefix = "`-"; + // Otherwise this isn't the last child, so it gets |- + else + prefix = "|-"; + } + } + else + // User can't see depth, so use no prefix + prefix = ""; + + // Add line to the map + map.push_back(prefix + *j); } + } - first_nonspace--; - - // Draw the `- (corner) section: this may be overwritten by - // another L shape passing along the same vertical pane, becoming - // a |- (branch) section instead. - - myname[first_nonspace] = '-'; - myname[first_nonspace-1] = '`'; - int l2 = l - 1; + return map; +} - // Draw upwards until we hit the parent server, causing possibly - // other corners (`-) to become branches (|-) - while ((names[l2 * 100 + first_nonspace-1] == ' ') || (names[l2 * 100 + first_nonspace-1] == '`')) +CmdResult CommandMap::Handle(const std::vector<std::string>& parameters, User* user) +{ + if (parameters.size() > 0) + { + /* Remote MAP, the server is within the 1st parameter */ + TreeServer* s = Utils->FindServerMask(parameters[0]); + if (!s) { - names[l2 * 100 + first_nonspace-1] = '|'; - l2--; + user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str()); + return CMD_FAILURE; } + + if (!s->IsRoot()) + return CMD_SUCCESS; } - float avg_users = totusers * 1.0 / line; + // Max depth and max server name length + unsigned int max_depth = 0; + unsigned int max_len = 0; + GetDepthAndLen(Utils->TreeRoot, 0, max_depth, max_len); - ServerInstance->Logs->Log("map",DEBUG,"local"); - for (int t = 0; t < line; t++) + unsigned int max; + if (user->IsOper() || !Utils->FlatLinks) + { + // Each level of the map is indented by 2 characters, making the max possible line (max_depth * 2) + max_len + max = (max_depth * 2) + max_len; + } + else { - // terminate the string at maxnamew characters - names[100 * t + maxnamew] = '\0'; - user->SendText(":%s %03d %s :%s %s", ServerInstance->Config->ServerName.c_str(), - RPL_MAP, user->nick.c_str(), names + 100 * t, stats + 50 * t); + // This user can't see any depth + max = max_len; } - user->SendText(":%s %03d %s :%d server%s and %d user%s, average %.2f users per server", + + std::vector<std::string> map = GetMap(user, Utils->TreeRoot, max, 0); + for (std::vector<std::string>::const_iterator i = map.begin(); i != map.end(); ++i) + user->SendText(":%s %03d %s :%s", ServerInstance->Config->ServerName.c_str(), + RPL_MAP, user->nick.c_str(), i->c_str()); + + size_t totusers = ServerInstance->Users->GetUsers().size(); + float avg_users = (float) totusers / Utils->serverlist.size(); + + user->SendText(":%s %03d %s :%u server%s and %u user%s, average %.2f users per server", ServerInstance->Config->ServerName.c_str(), RPL_MAPUSERS, user->nick.c_str(), - line, (line > 1 ? "s" : ""), totusers, (totusers > 1 ? "s" : ""), avg_users); + (unsigned int)Utils->serverlist.size(), (Utils->serverlist.size() > 1 ? "s" : ""), (unsigned int)totusers, (totusers > 1 ? "s" : ""), avg_users); user->SendText(":%s %03d %s :End of /MAP", ServerInstance->Config->ServerName.c_str(), RPL_ENDMAP, user->nick.c_str()); - delete[] names; - delete[] stats; - - return true; + return CMD_SUCCESS; } +RouteDescriptor CommandMap::GetRouting(User* user, const std::vector<std::string>& parameters) +{ + if (!parameters.empty()) + return ROUTE_UNICAST(parameters[0]); + return ROUTE_LOCALONLY; +} diff --git a/src/modules/m_spanningtree/override_squit.cpp b/src/modules/m_spanningtree/override_squit.cpp index 7d01c8149..9cec527d3 100644 --- a/src/modules/m_spanningtree/override_squit.cpp +++ b/src/modules/m_spanningtree/override_squit.cpp @@ -17,48 +17,38 @@ */ -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" #include "socket.h" -#include "xline.h" #include "main.h" #include "utils.h" #include "treeserver.h" #include "treesocket.h" -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - ModResult ModuleSpanningTree::HandleSquit(const std::vector<std::string>& parameters, User* user) { TreeServer* s = Utils->FindServerMask(parameters[0]); if (s) { - if (s == Utils->TreeRoot) + if (s->IsRoot()) { - user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick.c_str(),parameters[0].c_str()); + user->WriteNotice("*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (" + parameters[0] + " matches local server name)"); return MOD_RES_DENY; } - TreeSocket* sock = s->GetSocket(); - - if (sock) + if (s->IsLocal()) { ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0].c_str(),user->nick.c_str()); - sock->Squit(s,"Server quit by " + user->GetFullRealHost()); - ServerInstance->SE->DelFd(sock); - sock->Close(); + s->SQuit("Server quit by " + user->GetFullRealHost()); } else { - user->WriteServ("NOTICE %s :*** SQUIT may not be used to remove remote servers. Please use RSQUIT instead.",user->nick.c_str()); + user->WriteNotice("*** SQUIT may not be used to remove remote servers. Please use RSQUIT instead."); } } else { - user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick.c_str(),parameters[0].c_str()); + user->WriteNotice("*** SQUIT: The server \002" + parameters[0] + "\002 does not exist on the network."); } return MOD_RES_DENY; } - diff --git a/src/modules/m_spanningtree/override_stats.cpp b/src/modules/m_spanningtree/override_stats.cpp index 688661b80..14b3f5ef7 100644 --- a/src/modules/m_spanningtree/override_stats.cpp +++ b/src/modules/m_spanningtree/override_stats.cpp @@ -18,16 +18,11 @@ */ -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" -#include "socket.h" #include "main.h" #include "utils.h" -#include "treeserver.h" #include "link.h" -#include "treesocket.h" ModResult ModuleSpanningTree::OnStats(char statschar, User* user, string_list &results) { @@ -36,12 +31,22 @@ ModResult ModuleSpanningTree::OnStats(char statschar, User* user, string_list &r for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i != Utils->LinkBlocks.end(); ++i) { Link* L = *i; - results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" "+statschar+" *@"+(L->HiddenFromStats ? "<hidden>" : L->IPAddr)+" * "+(*i)->Name.c_str()+" "+ConvToStr(L->Port)+" "+(L->Hook.empty() ? "plaintext" : L->Hook)); + results.push_back("213 "+user->nick+" "+statschar+" *@"+(L->HiddenFromStats ? "<hidden>" : L->IPAddr)+" * "+(*i)->Name.c_str()+" "+ConvToStr(L->Port)+" "+(L->Hook.empty() ? "plaintext" : L->Hook)); if (statschar == 'c') - results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+L->Name.c_str()); + results.push_back("244 "+user->nick+" H * * "+L->Name.c_str()); + } + return MOD_RES_DENY; + } + else if (statschar == 'U') + { + ConfigTagList tags = ServerInstance->Config->ConfTags("uline"); + for (ConfigIter i = tags.first; i != tags.second; ++i) + { + std::string name = i->second->getString("server"); + if (!name.empty()) + results.push_back("248 "+user->nick+" U "+name); } return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - diff --git a/src/modules/m_spanningtree/override_whois.cpp b/src/modules/m_spanningtree/override_whois.cpp index ad8c6a6ef..430467dc7 100644 --- a/src/modules/m_spanningtree/override_whois.cpp +++ b/src/modules/m_spanningtree/override_whois.cpp @@ -16,39 +16,24 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" -#include "socket.h" -#include "xline.h" #include "main.h" -#include "utils.h" -#include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ +#include "commandbuilder.h" ModResult ModuleSpanningTree::HandleRemoteWhois(const std::vector<std::string>& parameters, User* user) { - if ((IS_LOCAL(user)) && (parameters.size() > 1)) + User* remote = ServerInstance->FindNickOnly(parameters[1]); + if (remote && !IS_LOCAL(remote)) { - User* remote = ServerInstance->FindNickOnly(parameters[1]); - if (remote && !IS_LOCAL(remote)) - { - parameterlist params; - params.push_back(remote->uuid); - Utils->DoOneToOne(user->uuid,"IDLE",params,remote->server); - return MOD_RES_DENY; - } - else if (!remote) - { - user->WriteNumeric(401, "%s %s :No such nick/channel",user->nick.c_str(), parameters[1].c_str()); - user->WriteNumeric(318, "%s %s :End of /WHOIS list.",user->nick.c_str(), parameters[1].c_str()); - return MOD_RES_DENY; - } + CmdBuilder(user, "IDLE").push(remote->uuid).Unicast(remote); + return MOD_RES_DENY; + } + else if (!remote) + { + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[1].c_str()); + user->WriteNumeric(RPL_ENDOFWHOIS, "%s :End of /WHOIS list.", parameters[1].c_str()); + return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - diff --git a/src/modules/m_spanningtree/ping.cpp b/src/modules/m_spanningtree/ping.cpp index aec680b23..878f8af3a 100644 --- a/src/modules/m_spanningtree/ping.cpp +++ b/src/modules/m_spanningtree/ping.cpp @@ -18,44 +18,24 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ +#include "commands.h" +#include "utils.h" -bool TreeSocket::LocalPing(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandPing::Handle(User* user, std::vector<std::string>& params) { - if (params.size() < 1) - return true; - if (params.size() == 1) - { - std::string stufftobounce = params[0]; - this->WriteLine(":"+ServerInstance->Config->GetSID()+" PONG "+stufftobounce); - return true; - } - else + if (params[0] == ServerInstance->Config->GetSID()) { - std::string forwardto = params[1]; - if (forwardto == ServerInstance->Config->ServerName || forwardto == ServerInstance->Config->GetSID()) - { - // this is a ping for us, send back PONG to the requesting server - params[1] = params[0]; - params[0] = forwardto; - Utils->DoOneToOne(ServerInstance->Config->GetSID(),"PONG",params,params[1]); - } - else - { - // not for us, pass it on :) - Utils->DoOneToOne(prefix,"PING",params,forwardto); - } - return true; + // PING for us, reply with a PONG + CmdBuilder reply("PONG"); + reply.push_back(user->uuid); + if (params.size() >= 2) + // If there is a second parameter, append it + reply.push_back(params[1]); + + reply.Unicast(user); } + return CMD_SUCCESS; } - - diff --git a/src/modules/m_spanningtree/pingtimer.cpp b/src/modules/m_spanningtree/pingtimer.cpp new file mode 100644 index 000000000..1c96259bf --- /dev/null +++ b/src/modules/m_spanningtree/pingtimer.cpp @@ -0,0 +1,102 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2015 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" + +#include "pingtimer.h" +#include "treeserver.h" +#include "commandbuilder.h" + +PingTimer::PingTimer(TreeServer* ts) + : Timer(Utils->PingFreq) + , server(ts) + , state(PS_SENDPING) +{ +} + +PingTimer::State PingTimer::TickInternal() +{ + // Timer expired, take next action based on what happened last time + if (state == PS_SENDPING) + { + // Last ping was answered, send next ping + server->GetSocket()->WriteLine(CmdBuilder("PING").push(server->GetID())); + LastPingMsec = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); + // Warn next unless warnings are disabled. If they are, jump straight to timeout. + if (Utils->PingWarnTime) + return PS_WARN; + else + return PS_TIMEOUT; + } + else if (state == PS_WARN) + { + // No pong arrived in PingWarnTime seconds, send a warning to opers + ServerInstance->SNO->WriteToSnoMask('l', "Server \002%s\002 has not responded to PING for %d seconds, high latency.", server->GetName().c_str(), GetInterval()); + return PS_TIMEOUT; + } + else // PS_TIMEOUT + { + // They didn't answer the last ping, if they are locally connected, get rid of them + if (server->IsLocal()) + { + TreeSocket* sock = server->GetSocket(); + sock->SendError("Ping timeout"); + sock->Close(); + } + + // If the server is non-locally connected, don't do anything until we get a PONG. + // This is to avoid pinging the server and warning opers more than once. + // If they do answer eventually, we will move to the PS_SENDPING state and ping them again. + return PS_IDLE; + } +} + +void PingTimer::SetState(State newstate) +{ + state = newstate; + + // Set when should the next Tick() happen based on the state + if (state == PS_SENDPING) + SetInterval(Utils->PingFreq); + else if (state == PS_WARN) + SetInterval(Utils->PingWarnTime); + else if (state == PS_TIMEOUT) + SetInterval(Utils->PingFreq - Utils->PingWarnTime); + + // If state == PS_IDLE, do not set the timer, see above why +} + +bool PingTimer::Tick(time_t currtime) +{ + if (server->IsDead()) + return false; + + SetState(TickInternal()); + return false; +} + +void PingTimer::OnPong() +{ + // Calculate RTT + long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); + server->rtt = ts - LastPingMsec; + + // Change state to send ping next, also reschedules the timer appropriately + SetState(PS_SENDPING); +} diff --git a/src/modules/m_spanningtree/pingtimer.h b/src/modules/m_spanningtree/pingtimer.h new file mode 100644 index 000000000..753558689 --- /dev/null +++ b/src/modules/m_spanningtree/pingtimer.h @@ -0,0 +1,77 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2015 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#pragma once + +class TreeServer; + +/** Handles PINGing servers and killing them on timeout + */ +class PingTimer : public Timer +{ + enum State + { + /** Send PING next */ + PS_SENDPING, + /** Warn opers next */ + PS_WARN, + /** Kill the server next due to ping timeout */ + PS_TIMEOUT, + /** Do nothing */ + PS_IDLE + }; + + /** Server the timer is interacting with + */ + TreeServer* const server; + + /** What to do when the timer ticks next + */ + State state; + + /** Last ping time in milliseconds, used to calculate round trip time + */ + unsigned long LastPingMsec; + + /** Update internal state and reschedule timer according to the new state + * @param newstate State to change to + */ + void SetState(State newstate); + + /** Process timer tick event + * @return State to change to + */ + State TickInternal(); + + /** Called by the TimerManager when the timer expires + * @param currtime Time now + * @return Always false, we reschedule ourselves instead + */ + bool Tick(time_t currtime) CXX11_OVERRIDE; + + public: + /** Construct the timer. This doesn't schedule the timer. + * @param server TreeServer to interact with + */ + PingTimer(TreeServer* server); + + /** Register a PONG from the server + */ + void OnPong(); +}; diff --git a/src/modules/m_spanningtree/pong.cpp b/src/modules/m_spanningtree/pong.cpp index 5966d05d9..5d97f2af2 100644 --- a/src/modules/m_spanningtree/pong.cpp +++ b/src/modules/m_spanningtree/pong.cpp @@ -18,65 +18,24 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ +#include "commands.h" +#include "utils.h" -bool TreeSocket::LocalPong(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandPong::HandleServer(TreeServer* server, std::vector<std::string>& params) { - if (params.size() < 1) - return true; - - if (params.size() == 1) + if (server->IsBursting()) { - TreeServer* ServerSource = Utils->FindServer(prefix); - if (ServerSource) - { - ServerSource->SetPingFlag(); - long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); - ServerSource->rtt = ts - ServerSource->LastPingMsec; - } + ServerInstance->SNO->WriteGlobalSno('l', "Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", server->GetName().c_str()); + server->FinishBurst(); } - else - { - std::string forwardto = params[1]; - if (forwardto == ServerInstance->Config->GetSID() || forwardto == ServerInstance->Config->ServerName) - { - /* - * this is a PONG for us - * if the prefix is a user, check theyre local, and if they are, - * dump the PONG reply back to their fd. If its a server, do nowt. - * Services might want to send these s->s, but we dont need to yet. - */ - User* u = ServerInstance->FindNick(prefix); - if (u) - { - u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str()); - } - TreeServer *ServerSource = Utils->FindServer(params[0]); - - if (ServerSource) - { - long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); - ServerSource->rtt = ts - ServerSource->LastPingMsec; - ServerSource->SetPingFlag(); - } - } - else - { - // not for us, pass it on :) - Utils->DoOneToOne(prefix,"PONG",params,forwardto); - } + if (params[0] == ServerInstance->Config->GetSID()) + { + // PONG for us + server->OnPong(); } - - return true; + return CMD_SUCCESS; } - diff --git a/src/modules/m_spanningtree/postcommand.cpp b/src/modules/m_spanningtree/postcommand.cpp index 471bbfcb9..ae98be946 100644 --- a/src/modules/m_spanningtree/postcommand.cpp +++ b/src/modules/m_spanningtree/postcommand.cpp @@ -17,69 +17,53 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" -#include "socket.h" -#include "xline.h" #include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" +#include "commandbuilder.h" -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - -void ModuleSpanningTree::OnPostCommand(const std::string &command, const std::vector<std::string>& parameters, LocalUser *user, CmdResult result, const std::string &original_line) +void ModuleSpanningTree::OnPostCommand(Command* command, const std::vector<std::string>& parameters, LocalUser* user, CmdResult result, const std::string& original_line) { if (result == CMD_SUCCESS) Utils->RouteCommand(NULL, command, parameters, user); } -void SpanningTreeUtilities::RouteCommand(TreeServer* origin, const std::string &command, const parameterlist& parameters, User *user) +void SpanningTreeUtilities::RouteCommand(TreeServer* origin, CommandBase* thiscmd, const parameterlist& parameters, User* user) { - if (!ServerInstance->Parser->IsValidCommand(command, parameters.size(), user)) - return; - - /* We know it's non-null because IsValidCommand returned true */ - Command* thiscmd = ServerInstance->Parser->GetHandler(command); - + const std::string& command = thiscmd->name; RouteDescriptor routing = thiscmd->GetRouting(user, parameters); - - std::string sent_cmd = command; - parameterlist params; - if (routing.type == ROUTE_TYPE_LOCALONLY) - { - /* Broadcast when it's a core command with the default route descriptor and the source is a - * remote user or a remote server - */ + return; - Version ver = thiscmd->creator->GetVersion(); - if ((!(ver.Flags & VF_CORE)) || (IS_LOCAL(user)) || (IS_SERVER(user) == ServerInstance->FakeClient)) - return; + const bool encap = ((routing.type == ROUTE_TYPE_OPT_BCAST) || (routing.type == ROUTE_TYPE_OPT_UCAST)); + CmdBuilder params(user, encap ? "ENCAP" : command.c_str()); + TreeServer* sdest = NULL; - routing = ROUTE_BROADCAST; - } - else if (routing.type == ROUTE_TYPE_OPT_BCAST) + if (routing.type == ROUTE_TYPE_OPT_BCAST) { - params.push_back("*"); + params.push('*'); params.push_back(command); - sent_cmd = "ENCAP"; } - else if (routing.type == ROUTE_TYPE_OPT_UCAST) + else if (routing.type == ROUTE_TYPE_UNICAST || routing.type == ROUTE_TYPE_OPT_UCAST) { - TreeServer* sdest = FindServer(routing.serverdest); + sdest = static_cast<TreeServer*>(routing.server); if (!sdest) { - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Trying to route ENCAP to nonexistant server %s", - routing.serverdest.c_str()); - return; + sdest = FindServer(routing.serverdest); + if (!sdest) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Trying to route %s%s to nonexistant server %s", (encap ? "ENCAP " : ""), command.c_str(), routing.serverdest.c_str()); + return; + } + } + + if (encap) + { + params.push_back(sdest->GetID()); + params.push_back(command); } - params.push_back(sdest->GetID()); - params.push_back(command); - sent_cmd = "ENCAP"; } else { @@ -88,14 +72,13 @@ void SpanningTreeUtilities::RouteCommand(TreeServer* origin, const std::string & if (!(ver.Flags & (VF_COMMON | VF_CORE)) && srcmodule != Creator) { - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Routed command %s from non-VF_COMMON module %s", + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Routed command %s from non-VF_COMMON module %s", command.c_str(), srcmodule->ModuleSourceFile.c_str()); return; } } - std::string output_text; - ServerInstance->Parser->TranslateUIDs(thiscmd->translation, parameters, output_text, true, thiscmd); + std::string output_text = CommandParser::TranslateUIDs(thiscmd->translation, parameters, true, thiscmd); params.push_back(output_text); @@ -106,59 +89,40 @@ void SpanningTreeUtilities::RouteCommand(TreeServer* origin, const std::string & if (ServerInstance->Modes->FindPrefix(dest[0])) { pfx = dest[0]; - dest = dest.substr(1); + dest.erase(dest.begin()); } if (dest[0] == '#') { Channel* c = ServerInstance->FindChan(dest); if (!c) return; - TreeServerList list; // TODO OnBuildExemptList hook was here - GetListOfServersForChannel(c,list,pfx, CUList()); - std::string data = ":" + user->uuid + " " + sent_cmd; - for (unsigned int x = 0; x < params.size(); x++) - data += " " + params[x]; - for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) - { - TreeSocket* Sock = i->second->GetSocket(); - if (origin && origin->GetSocket() == Sock) - continue; - if (Sock) - Sock->WriteLine(data); - } + CUList exempts; + SendChannelMessage(user->uuid, c, parameters[1], pfx, exempts, command.c_str(), origin ? origin->GetSocket() : NULL); } else if (dest[0] == '$') { - if (origin) - DoOneToAllButSender(user->uuid, sent_cmd, params, origin->GetName()); - else - DoOneToMany(user->uuid, sent_cmd, params); + params.Forward(origin); } else { // user target? User* d = ServerInstance->FindNick(dest); - if (!d) + if (!d || IS_LOCAL(d)) return; - TreeServer* tsd = BestRouteTo(d->server); + TreeServer* tsd = TreeServer::Get(d)->GetRoute(); if (tsd == origin) // huh? no routing stuff around in a circle, please. return; - DoOneToOne(user->uuid, sent_cmd, params, d->server); + params.Unicast(d); } } else if (routing.type == ROUTE_TYPE_BROADCAST || routing.type == ROUTE_TYPE_OPT_BCAST) { - if (origin) - DoOneToAllButSender(user->uuid, sent_cmd, params, origin->GetName()); - else - DoOneToMany(user->uuid, sent_cmd, params); + params.Forward(origin); } else if (routing.type == ROUTE_TYPE_UNICAST || routing.type == ROUTE_TYPE_OPT_UCAST) { - if (origin && routing.serverdest == origin->GetName()) - return; - DoOneToOne(user->uuid, sent_cmd, params, routing.serverdest); + params.Unicast(sdest->ServerUser); } } diff --git a/src/modules/m_spanningtree/precommand.cpp b/src/modules/m_spanningtree/precommand.cpp index b331571ca..4733d0071 100644 --- a/src/modules/m_spanningtree/precommand.cpp +++ b/src/modules/m_spanningtree/precommand.cpp @@ -18,18 +18,9 @@ */ -/* $ModDesc: Provides a spanning tree server link protocol */ - #include "inspircd.h" -#include "socket.h" -#include "xline.h" #include "main.h" -#include "utils.h" -#include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ ModResult ModuleSpanningTree::OnPreCommand(std::string &command, std::vector<std::string>& parameters, LocalUser *user, bool validated, const std::string &original_line) { @@ -45,10 +36,6 @@ ModResult ModuleSpanningTree::OnPreCommand(std::string &command, std::vector<std { return this->HandleSquit(parameters,user); } - else if (command == "MAP") - { - return this->HandleMap(parameters,user) ? MOD_RES_DENY : MOD_RES_PASSTHRU; - } else if (command == "LINKS") { this->HandleLinks(parameters,user); @@ -64,9 +51,7 @@ ModResult ModuleSpanningTree::OnPreCommand(std::string &command, std::vector<std } else if ((command == "VERSION") && (parameters.size() > 0)) { - this->HandleVersion(parameters,user); - return MOD_RES_DENY; + return this->HandleVersion(parameters,user); } return MOD_RES_PASSTHRU; } - diff --git a/src/modules/m_spanningtree/protocolinterface.cpp b/src/modules/m_spanningtree/protocolinterface.cpp index 3ab5dae9d..786f8b74b 100644 --- a/src/modules/m_spanningtree/protocolinterface.cpp +++ b/src/modules/m_spanningtree/protocolinterface.cpp @@ -19,161 +19,115 @@ #include "inspircd.h" -#include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" #include "protocolinterface.h" +#include "commands.h" /* * For documentation on this class, see include/protocol.h. */ -void SpanningTreeProtocolInterface::GetServerList(ProtoServerList &sl) +void SpanningTreeProtocolInterface::GetServerList(ServerList& sl) { - sl.clear(); for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++) { - ProtoServer ps; + ServerInfo ps; ps.servername = i->second->GetName(); TreeServer* s = i->second->GetParent(); ps.parentname = s ? s->GetName() : ""; - ps.usercount = i->second->GetUserCount(); - ps.opercount = i->second->GetOperCount(); + ps.usercount = i->second->UserCount; + ps.opercount = i->second->OperCount; ps.gecos = i->second->GetDesc(); ps.latencyms = i->second->rtt; sl.push_back(ps); } } -bool SpanningTreeProtocolInterface::SendEncapsulatedData(const parameterlist &encap) +bool SpanningTreeProtocolInterface::SendEncapsulatedData(const std::string& targetmask, const std::string& cmd, const parameterlist& params, User* source) { - if (encap[0].find_first_of("*?") != std::string::npos) + if (!source) + source = ServerInstance->FakeClient; + + CmdBuilder encap(source, "ENCAP"); + + // Are there any wildcards in the target string? + if (targetmask.find_first_of("*?") != std::string::npos) { - Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ENCAP", encap); - return true; + // Yes, send the target string as-is; servers will decide whether or not it matches them + encap.push(targetmask).push(cmd).insert(params).Broadcast(); } - return Utils->DoOneToOne(ServerInstance->Config->GetSID(), "ENCAP", encap, encap[0]); -} - -void SpanningTreeProtocolInterface::SendMetaData(Extensible* target, const std::string &key, const std::string &data) -{ - parameterlist params; - - User* u = dynamic_cast<User*>(target); - Channel* c = dynamic_cast<Channel*>(target); - if (u) - params.push_back(u->uuid); - else if (c) - params.push_back(c->name); else - params.push_back("*"); + { + // No wildcards which means the target string has to be the name of a known server + TreeServer* server = Utils->FindServer(targetmask); + if (!server) + return false; - params.push_back(key); - params.push_back(":" + data); + // Use the SID of the target in the message instead of the server name + encap.push(server->GetID()).push(cmd).insert(params).Unicast(server->ServerUser); + } - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"METADATA",params); + return true; } -void SpanningTreeProtocolInterface::SendTopic(Channel* channel, std::string &topic) +void SpanningTreeProtocolInterface::BroadcastEncap(const std::string& cmd, const parameterlist& params, User* source, User* omit) { - parameterlist params; + if (!source) + source = ServerInstance->FakeClient; - params.push_back(channel->name); - params.push_back(ConvToStr(ServerInstance->Time())); - params.push_back(ServerInstance->Config->ServerName); - params.push_back(":" + topic); - - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FTOPIC", params); + // If omit is non-NULL we pass the route belonging to the user to Forward(), + // otherwise we pass NULL, which is equivalent to Broadcast() + TreeServer* server = (omit ? TreeServer::Get(omit)->GetRoute() : NULL); + CmdBuilder(source, "ENCAP * ").push_raw(cmd).insert(params).Forward(server); } -void SpanningTreeProtocolInterface::SendMode(const std::string &target, const parameterlist &modedata, const std::vector<TranslateType> &translate) +void SpanningTreeProtocolInterface::SendMetaData(User* u, const std::string& key, const std::string& data) { - if (modedata.empty()) - return; - - std::string outdata; - ServerInstance->Parser->TranslateUIDs(translate, modedata, outdata); - - std::string uidtarget; - ServerInstance->Parser->TranslateUIDs(TR_NICK, target, uidtarget); - - parameterlist outlist; - outlist.push_back(uidtarget); - outlist.push_back(outdata); - - User* a = ServerInstance->FindNick(uidtarget); - if (a) - { - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",outlist); - return; - } - else - { - Channel* c = ServerInstance->FindChan(target); - if (c) - { - outlist.insert(outlist.begin() + 1, ConvToStr(c->age)); - Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",outlist); - } - } + CommandMetadata::Builder(u, key, data).Broadcast(); } -void SpanningTreeProtocolInterface::SendSNONotice(const std::string &snomask, const std::string &text) +void SpanningTreeProtocolInterface::SendMetaData(Channel* c, const std::string& key, const std::string& data) { - parameterlist p; - p.push_back(snomask); - p.push_back(":" + text); - Utils->DoOneToMany(ServerInstance->Config->GetSID(), "SNONOTICE", p); + CommandMetadata::Builder(c, key, data).Broadcast(); } -void SpanningTreeProtocolInterface::PushToClient(User* target, const std::string &rawline) +void SpanningTreeProtocolInterface::SendMetaData(const std::string& key, const std::string& data) { - parameterlist p; - p.push_back(target->uuid); - p.push_back(":" + rawline); - Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", p, target->server); + CommandMetadata::Builder(key, data).Broadcast(); } -void SpanningTreeProtocolInterface::SendChannel(Channel* target, char status, const std::string &text) +void SpanningTreeProtocolInterface::Server::SendMetaData(const std::string& key, const std::string& data) { - std::string cname = target->name; - if (status) - cname = status + cname; - TreeServerList list; - CUList exempt_list; - Utils->GetListOfServersForChannel(target,list,status,exempt_list); - for (TreeServerList::iterator i = list.begin(); i != list.end(); i++) - { - TreeSocket* Sock = i->second->GetSocket(); - if (Sock) - Sock->WriteLine(text); - } + sock->WriteLine(CommandMetadata::Builder(key, data)); } +void SpanningTreeProtocolInterface::SendTopic(Channel* channel, std::string &topic) +{ + CommandFTopic::Builder(ServerInstance->FakeClient, channel).Broadcast(); +} -void SpanningTreeProtocolInterface::SendChannelPrivmsg(Channel* target, char status, const std::string &text) +void SpanningTreeProtocolInterface::SendSNONotice(char snomask, const std::string &text) { - SendChannel(target, status, ":" + ServerInstance->Config->GetSID()+" PRIVMSG "+target->name+" :"+text); + CmdBuilder("SNONOTICE").push(snomask).push_last(text).Broadcast(); } -void SpanningTreeProtocolInterface::SendChannelNotice(Channel* target, char status, const std::string &text) +void SpanningTreeProtocolInterface::PushToClient(User* target, const std::string &rawline) { - SendChannel(target, status, ":" + ServerInstance->Config->GetSID()+" NOTICE "+target->name+" :"+text); + CmdBuilder("PUSH").push(target->uuid).push_last(rawline).Unicast(target); } -void SpanningTreeProtocolInterface::SendUserPrivmsg(User* target, const std::string &text) +void SpanningTreeProtocolInterface::SendMessage(Channel* target, char status, const std::string& text, MessageType msgtype) { - parameterlist p; - p.push_back(target->uuid); - p.push_back(":" + text); - Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PRIVMSG", p, target->server); + const char* cmd = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE"); + CUList exempt_list; + Utils->SendChannelMessage(ServerInstance->Config->GetSID(), target, text, status, exempt_list, cmd); } -void SpanningTreeProtocolInterface::SendUserNotice(User* target, const std::string &text) +void SpanningTreeProtocolInterface::SendMessage(User* target, const std::string& text, MessageType msgtype) { - parameterlist p; + CmdBuilder p(msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE"); p.push_back(target->uuid); - p.push_back(":" + text); - Utils->DoOneToOne(ServerInstance->Config->GetSID(), "NOTICE", p, target->server); + p.push_last(text); + p.Unicast(target); } diff --git a/src/modules/m_spanningtree/protocolinterface.h b/src/modules/m_spanningtree/protocolinterface.h index 297366893..45742e9ea 100644 --- a/src/modules/m_spanningtree/protocolinterface.h +++ b/src/modules/m_spanningtree/protocolinterface.h @@ -17,32 +17,29 @@ */ -#ifndef M_SPANNINGTREE_PROTOCOLINTERFACE_H -#define M_SPANNINGTREE_PROTOCOLINTERFACE_H - -class SpanningTreeUtilities; -class ModuleSpanningTree; +#pragma once class SpanningTreeProtocolInterface : public ProtocolInterface { - SpanningTreeUtilities* Utils; - void SendChannel(Channel* target, char status, const std::string &text); public: - SpanningTreeProtocolInterface(SpanningTreeUtilities* util) : Utils(util) { } - virtual ~SpanningTreeProtocolInterface() { } - - virtual bool SendEncapsulatedData(const parameterlist &encap); - virtual void SendMetaData(Extensible* target, const std::string &key, const std::string &data); - virtual void SendTopic(Channel* channel, std::string &topic); - virtual void SendMode(const std::string &target, const parameterlist &modedata, const std::vector<TranslateType> &types); - virtual void SendSNONotice(const std::string &snomask, const std::string &text); - virtual void PushToClient(User* target, const std::string &rawline); - virtual void SendChannelPrivmsg(Channel* target, char status, const std::string &text); - virtual void SendChannelNotice(Channel* target, char status, const std::string &text); - virtual void SendUserPrivmsg(User* target, const std::string &text); - virtual void SendUserNotice(User* target, const std::string &text); - virtual void GetServerList(ProtoServerList &sl); -}; + class Server : public ProtocolInterface::Server + { + TreeSocket* const sock; -#endif + public: + Server(TreeSocket* s) : sock(s) { } + void SendMetaData(const std::string& key, const std::string& data) CXX11_OVERRIDE; + }; + bool SendEncapsulatedData(const std::string& targetmask, const std::string& cmd, const parameterlist& params, User* source) CXX11_OVERRIDE; + void BroadcastEncap(const std::string& cmd, const parameterlist& params, User* source, User* omit) CXX11_OVERRIDE; + void SendMetaData(User* user, const std::string& key, const std::string& data) CXX11_OVERRIDE; + void SendMetaData(Channel* chan, const std::string& key, const std::string& data) CXX11_OVERRIDE; + void SendMetaData(const std::string& key, const std::string& data) CXX11_OVERRIDE; + void SendTopic(Channel* channel, std::string &topic); + void SendSNONotice(char snomask, const std::string& text) CXX11_OVERRIDE; + void PushToClient(User* target, const std::string &rawline); + void SendMessage(Channel* target, char status, const std::string& text, MessageType msgtype); + void SendMessage(User* target, const std::string& text, MessageType msgtype); + void GetServerList(ServerList& sl); +}; diff --git a/src/modules/m_spanningtree/push.cpp b/src/modules/m_spanningtree/push.cpp index b791376ea..b29b780c8 100644 --- a/src/modules/m_spanningtree/push.cpp +++ b/src/modules/m_spanningtree/push.cpp @@ -18,34 +18,18 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" #include "utils.h" -#include "treeserver.h" -#include "treesocket.h" +#include "commands.h" -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - -bool TreeSocket::Push(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandPush::Handle(User* user, std::vector<std::string>& params) { - if (params.size() < 2) - return true; User* u = ServerInstance->FindNick(params[0]); if (!u) - return true; + return CMD_FAILURE; if (IS_LOCAL(u)) { u->Write(params[1]); } - else - { - // continue the raw onwards - params[1] = ":" + params[1]; - Utils->DoOneToOne(prefix,"PUSH",params,u->server); - } - return true; + return CMD_SUCCESS; } - diff --git a/src/modules/m_spanningtree/rconnect.cpp b/src/modules/m_spanningtree/rconnect.cpp index d4254cac6..c5d3a5b52 100644 --- a/src/modules/m_spanningtree/rconnect.cpp +++ b/src/modules/m_spanningtree/rconnect.cpp @@ -19,19 +19,13 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "resolvers.h" #include "main.h" #include "utils.h" -#include "treeserver.h" -#include "link.h" -#include "treesocket.h" #include "commands.h" -CommandRConnect::CommandRConnect (Module* Creator, SpanningTreeUtilities* Util) - : Command(Creator, "RCONNECT", 2), Utils(Util) +CommandRConnect::CommandRConnect (Module* Creator) + : Command(Creator, "RCONNECT", 2) { flags_needed = 'o'; syntax = "<remote-server-mask> <target-server-mask>"; @@ -39,14 +33,11 @@ CommandRConnect::CommandRConnect (Module* Creator, SpanningTreeUtilities* Util) CmdResult CommandRConnect::Handle (const std::vector<std::string>& parameters, User *user) { - if (IS_LOCAL(user)) + /* First see if the server which is being asked to connect to another server in fact exists */ + if (!Utils->FindServerMask(parameters[0])) { - if (!Utils->FindServerMask(parameters[0])) - { - user->WriteServ("NOTICE %s :*** RCONNECT: Server \002%s\002 isn't connected to the network!", user->nick.c_str(), parameters[0].c_str()); - return CMD_FAILURE; - } - user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick.c_str(),parameters[0].c_str(),parameters[1].c_str()); + ((ModuleSpanningTree*)(Module*)creator)->RemoteMessage(user, "*** RCONNECT: Server \002%s\002 isn't connected to the network!", parameters[0].c_str()); + return CMD_FAILURE; } /* Is this aimed at our server? */ @@ -58,6 +49,21 @@ CmdResult CommandRConnect::Handle (const std::vector<std::string>& parameters, U para.push_back(parameters[1]); ((ModuleSpanningTree*)(Module*)creator)->HandleConnect(para, user); } + else + { + /* It's not aimed at our server, but if the request originates from our user + * acknowledge that we sent the request. + * + * It's possible that we're asking a server for something that makes no sense + * (e.g. connect to itself or to an already connected server), but we don't check + * for those conditions here, as ModuleSpanningTree::HandleConnect() (which will run + * on the target) does all the checking and error reporting. + */ + if (IS_LOCAL(user)) + { + user->WriteNotice("*** RCONNECT: Sending remote connect to \002 " + parameters[0] + "\002 to connect server \002" + parameters[1] + "\002."); + } + } return CMD_SUCCESS; } diff --git a/src/modules/m_spanningtree/resolvers.cpp b/src/modules/m_spanningtree/resolvers.cpp index d7c4c5227..3d04a5085 100644 --- a/src/modules/m_spanningtree/resolvers.cpp +++ b/src/modules/m_spanningtree/resolvers.cpp @@ -19,9 +19,8 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" +#include "cachetimer.h" #include "resolvers.h" #include "main.h" #include "utils.h" @@ -29,21 +28,22 @@ #include "link.h" #include "treesocket.h" -/* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */ - /** This class is used to resolve server hostnames during /connect and autoconnect. * As of 1.1, the resolver system is seperated out from BufferedSocket, so we must do this * resolver step first ourselves if we need it. This is totally nonblocking, and will * callback to OnLookupComplete or OnError when completed. Once it has completed we * will have an IP address which we can then use to continue our connection. */ -ServernameResolver::ServernameResolver(SpanningTreeUtilities* Util, const std::string &hostname, Link* x, bool &cached, QueryType qt, Autoconnect* myac) - : Resolver(hostname, qt, cached, Util->Creator), Utils(Util), query(qt), host(hostname), MyLink(x), myautoconnect(myac) +ServernameResolver::ServernameResolver(DNS::Manager* mgr, const std::string& hostname, Link* x, DNS::QueryType qt, Autoconnect* myac) + : DNS::Request(mgr, Utils->Creator, hostname, qt) + , query(qt), host(hostname), MyLink(x), myautoconnect(myac) { } -void ServernameResolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) +void ServernameResolver::OnLookupComplete(const DNS::Query *r) { + const DNS::ResourceRecord &ans_record = r->answers[0]; + /* Initiate the connection, now that we have an IP to use. * Passing a hostname directly to BufferedSocket causes it to * just bail and set its FD to -1. @@ -51,7 +51,7 @@ void ServernameResolver::OnLookupComplete(const std::string &result, unsigned in TreeServer* CheckDupe = Utils->FindServer(MyLink->Name.c_str()); if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */ { - TreeSocket* newsocket = new TreeSocket(Utils, MyLink, myautoconnect, result); + TreeSocket* newsocket = new TreeSocket(MyLink, myautoconnect, ans_record.rdata); if (newsocket->GetFd() > -1) { /* We're all OK */ @@ -66,47 +66,74 @@ void ServernameResolver::OnLookupComplete(const std::string &result, unsigned in } } -void ServernameResolver::OnError(ResolverError e, const std::string &errormessage) +void ServernameResolver::OnError(const DNS::Query *r) { /* Ooops! */ - if (query == DNS_QUERY_AAAA) + if (query == DNS::QUERY_AAAA) { - bool cached = false; - ServernameResolver* snr = new ServernameResolver(Utils, host, MyLink, cached, DNS_QUERY_A, myautoconnect); - ServerInstance->AddResolver(snr, cached); - return; + ServernameResolver* snr = new ServernameResolver(this->manager, host, MyLink, DNS::QUERY_A, myautoconnect); + try + { + this->manager->Process(snr); + return; + } + catch (DNS::Exception &) + { + delete snr; + } } - ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s", MyLink->Name.c_str(), errormessage.c_str() ); + + ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s", MyLink->Name.c_str(), this->manager->GetErrorStr(r->error).c_str()); Utils->Creator->ConnectServer(myautoconnect, false); } -SecurityIPResolver::SecurityIPResolver(Module* me, SpanningTreeUtilities* U, const std::string &hostname, Link* x, bool &cached, QueryType qt) - : Resolver(hostname, qt, cached, me), MyLink(x), Utils(U), mine(me), host(hostname), query(qt) +SecurityIPResolver::SecurityIPResolver(Module* me, DNS::Manager* mgr, const std::string& hostname, Link* x, DNS::QueryType qt) + : DNS::Request(mgr, me, hostname, qt) + , MyLink(x), mine(me), host(hostname), query(qt) { } -void SecurityIPResolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) +void SecurityIPResolver::OnLookupComplete(const DNS::Query *r) { + const DNS::ResourceRecord &ans_record = r->answers[0]; + for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i != Utils->LinkBlocks.end(); ++i) { Link* L = *i; if (L->IPAddr == host) { - Utils->ValidIPs.push_back(result); + Utils->ValidIPs.push_back(ans_record.rdata); break; } } } -void SecurityIPResolver::OnError(ResolverError e, const std::string &errormessage) +void SecurityIPResolver::OnError(const DNS::Query *r) { - if (query == DNS_QUERY_AAAA) + if (query == DNS::QUERY_AAAA) { - bool cached = false; - SecurityIPResolver* res = new SecurityIPResolver(mine, Utils, host, MyLink, cached, DNS_QUERY_A); - ServerInstance->AddResolver(res, cached); - return; + SecurityIPResolver* res = new SecurityIPResolver(mine, this->manager, host, MyLink, DNS::QUERY_A); + try + { + this->manager->Process(res); + return; + } + catch (DNS::Exception &) + { + delete res; + } } - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Could not resolve IP associated with Link '%s': %s", - MyLink->Name.c_str(),errormessage.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Could not resolve IP associated with Link '%s': %s", + MyLink->Name.c_str(), this->manager->GetErrorStr(r->error).c_str()); +} + +CacheRefreshTimer::CacheRefreshTimer() + : Timer(3600, true) +{ +} + +bool CacheRefreshTimer::Tick(time_t TIME) +{ + Utils->RefreshIPCache(); + return true; } diff --git a/src/modules/m_spanningtree/resolvers.h b/src/modules/m_spanningtree/resolvers.h index 65b9e7249..782ac86ef 100644 --- a/src/modules/m_spanningtree/resolvers.h +++ b/src/modules/m_spanningtree/resolvers.h @@ -18,30 +18,27 @@ */ -#ifndef M_SPANNINGTREE_RESOLVERS_H -#define M_SPANNINGTREE_RESOLVERS_H +#pragma once -#include "socket.h" #include "inspircd.h" -#include "xline.h" +#include "modules/dns.h" #include "utils.h" #include "link.h" /** Handle resolving of server IPs for the cache */ -class SecurityIPResolver : public Resolver +class SecurityIPResolver : public DNS::Request { private: reference<Link> MyLink; - SpanningTreeUtilities* Utils; Module* mine; std::string host; - QueryType query; + DNS::QueryType query; public: - SecurityIPResolver(Module* me, SpanningTreeUtilities* U, const std::string &hostname, Link* x, bool &cached, QueryType qt); - void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached); - void OnError(ResolverError e, const std::string &errormessage); + SecurityIPResolver(Module* me, DNS::Manager* mgr, const std::string& hostname, Link* x, DNS::QueryType qt); + void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE; + void OnError(const DNS::Query *q) CXX11_OVERRIDE; }; /** This class is used to resolve server hostnames during /connect and autoconnect. @@ -50,18 +47,15 @@ class SecurityIPResolver : public Resolver * callback to OnLookupComplete or OnError when completed. Once it has completed we * will have an IP address which we can then use to continue our connection. */ -class ServernameResolver : public Resolver +class ServernameResolver : public DNS::Request { private: - SpanningTreeUtilities* Utils; - QueryType query; + DNS::QueryType query; std::string host; reference<Link> MyLink; reference<Autoconnect> myautoconnect; public: - ServernameResolver(SpanningTreeUtilities* Util, const std::string &hostname, Link* x, bool &cached, QueryType qt, Autoconnect* myac); - void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached); - void OnError(ResolverError e, const std::string &errormessage); + ServernameResolver(DNS::Manager* mgr, const std::string& hostname, Link* x, DNS::QueryType qt, Autoconnect* myac); + void OnLookupComplete(const DNS::Query *r) CXX11_OVERRIDE; + void OnError(const DNS::Query *q) CXX11_OVERRIDE; }; - -#endif diff --git a/src/modules/m_spanningtree/rsquit.cpp b/src/modules/m_spanningtree/rsquit.cpp index 027ae02ab..45413c33f 100644 --- a/src/modules/m_spanningtree/rsquit.cpp +++ b/src/modules/m_spanningtree/rsquit.cpp @@ -19,17 +19,14 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" #include "main.h" #include "utils.h" #include "treeserver.h" -#include "treesocket.h" #include "commands.h" -CommandRSQuit::CommandRSQuit (Module* Creator, SpanningTreeUtilities* Util) - : Command(Creator, "RSQUIT", 1), Utils(Util) +CommandRSQuit::CommandRSQuit(Module* Creator) + : Command(Creator, "RSQUIT", 1) { flags_needed = 'o'; syntax = "<target-server-mask> [reason]"; @@ -38,34 +35,26 @@ CommandRSQuit::CommandRSQuit (Module* Creator, SpanningTreeUtilities* Util) CmdResult CommandRSQuit::Handle (const std::vector<std::string>& parameters, User *user) { TreeServer *server_target; // Server to squit - TreeServer *server_linked; // Server target is linked to server_target = Utils->FindServerMask(parameters[0]); if (!server_target) { - user->WriteServ("NOTICE %s :*** RSQUIT: Server \002%s\002 isn't connected to the network!", user->nick.c_str(), parameters[0].c_str()); + ((ModuleSpanningTree*)(Module*)creator)->RemoteMessage(user, "*** RSQUIT: Server \002%s\002 isn't connected to the network!", parameters[0].c_str()); return CMD_FAILURE; } - if (server_target == Utils->TreeRoot) + if (server_target->IsRoot()) { - NoticeUser(user, "*** RSQUIT: Foolish mortal, you cannot make a server SQUIT itself! ("+parameters[0]+" matches local server name)"); + ((ModuleSpanningTree*)(Module*)creator)->RemoteMessage(user, "*** RSQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)", parameters[0].c_str()); return CMD_FAILURE; } - server_linked = server_target->GetParent(); - - if (server_linked == Utils->TreeRoot) + if (server_target->IsLocal()) { // We have been asked to remove server_target. - TreeSocket* sock = server_target->GetSocket(); - if (sock) - { - const char *reason = parameters.size() == 2 ? parameters[1].c_str() : "No reason"; - ServerInstance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s (%s)", parameters[0].c_str(), user->nick.c_str(), reason); - sock->Squit(server_target, "Server quit by " + user->GetFullRealHost() + " (" + reason + ")"); - sock->Close(); - } + const char* reason = parameters.size() == 2 ? parameters[1].c_str() : "No reason"; + ServerInstance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s (%s)", parameters[0].c_str(), user->nick.c_str(), reason); + server_target->SQuit("Server quit by " + user->GetFullRealHost() + " (" + reason + ")"); } return CMD_SUCCESS; @@ -75,20 +64,3 @@ RouteDescriptor CommandRSQuit::GetRouting(User* user, const std::vector<std::str { return ROUTE_UNICAST(parameters[0]); } - -// XXX use protocol interface instead of rolling our own :) -void CommandRSQuit::NoticeUser(User* user, const std::string &msg) -{ - if (IS_LOCAL(user)) - { - user->WriteServ("NOTICE %s :%s",user->nick.c_str(),msg.c_str()); - } - else - { - parameterlist params; - params.push_back(user->nick); - params.push_back("NOTICE "+ConvToStr(user->nick)+" :"+msg); - Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", params, user->server); - } -} - diff --git a/src/modules/m_spanningtree/save.cpp b/src/modules/m_spanningtree/save.cpp index 92999b422..a382b8d66 100644 --- a/src/modules/m_spanningtree/save.cpp +++ b/src/modules/m_spanningtree/save.cpp @@ -18,38 +18,24 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" #include "utils.h" -#include "treeserver.h" #include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ +#include "commands.h" /** * SAVE command - force nick change to UID on timestamp match */ -bool TreeSocket::ForceNick(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandSave::Handle(User* user, std::vector<std::string>& params) { - if (params.size() < 2) - return true; + User* u = ServerInstance->FindUUID(params[0]); + if ((!u) || (IS_SERVER(u))) + return CMD_FAILURE; - User* u = ServerInstance->FindNick(params[0]); time_t ts = atol(params[1].c_str()); - if ((u) && (!IS_SERVER(u)) && (u->age == ts)) - { - Utils->DoOneToAllButSender(prefix,"SAVE",params,prefix); - - if (!u->ForceNickChange(u->uuid.c_str())) - { - ServerInstance->Users->QuitUser(u, "Nickname collision"); - } - } + if (u->age == ts) + u->ChangeNick(u->uuid, SavedTimestamp); - return true; + return CMD_SUCCESS; } - diff --git a/src/modules/m_spanningtree/server.cpp b/src/modules/m_spanningtree/server.cpp index d3033799e..1c624f5c4 100644 --- a/src/modules/m_spanningtree/server.cpp +++ b/src/modules/m_spanningtree/server.cpp @@ -19,107 +19,96 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" #include "main.h" #include "utils.h" #include "link.h" #include "treeserver.h" #include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h m_spanningtree/link.h */ +#include "commands.h" /* * Some server somewhere in the network introducing another server. * -- w */ -bool TreeSocket::RemoteServer(const std::string &prefix, parameterlist ¶ms) +CmdResult CommandServer::HandleServer(TreeServer* ParentOfThis, std::vector<std::string>& params) { - if (params.size() < 5) - { - SendError("Protocol error - Not enough parameters for SERVER command"); - return false; - } - - std::string servername = params[0]; - // password is not used for a remote server - // hopcount is not used (ever) - std::string sid = params[3]; - std::string description = params[4]; - TreeServer* ParentOfThis = Utils->FindServer(prefix); + const std::string& servername = params[0]; + const std::string& sid = params[1]; + const std::string& description = params.back(); + TreeSocket* socket = ParentOfThis->GetSocket(); - if (!ParentOfThis) + if (!InspIRCd::IsSID(sid)) { - this->SendError("Protocol error - Introduced remote server from unknown server "+prefix); - return false; - } - if (!ServerInstance->IsSID(sid)) - { - this->SendError("Invalid format server ID: "+sid+"!"); - return false; + socket->SendError("Invalid format server ID: "+sid+"!"); + return CMD_FAILURE; } TreeServer* CheckDupe = Utils->FindServer(servername); if (CheckDupe) { - this->SendError("Server "+servername+" already exists!"); + socket->SendError("Server "+servername+" already exists!"); ServerInstance->SNO->WriteToSnoMask('L', "Server \2"+CheckDupe->GetName()+"\2 being introduced from \2" + ParentOfThis->GetName() + "\2 denied, already exists. Closing link with " + ParentOfThis->GetName()); - return false; + return CMD_FAILURE; } CheckDupe = Utils->FindServer(sid); if (CheckDupe) { - this->SendError("Server ID "+sid+" already exists! You may want to specify the server ID for the server manually with <server:id> so they do not conflict."); + socket->SendError("Server ID "+sid+" already exists! You may want to specify the server ID for the server manually with <server:id> so they do not conflict."); ServerInstance->SNO->WriteToSnoMask('L', "Server \2"+servername+"\2 being introduced from \2" + ParentOfThis->GetName() + "\2 denied, server ID already exists on the network. Closing link with " + ParentOfThis->GetName()); - return false; + return CMD_FAILURE; } Link* lnk = Utils->FindLink(servername); - TreeServer *Node = new TreeServer(Utils, servername, description, sid, ParentOfThis,NULL, lnk ? lnk->Hidden : false); + TreeServer* Node = new TreeServer(servername, description, sid, ParentOfThis, ParentOfThis->GetSocket(), lnk ? lnk->Hidden : false); + + HandleExtra(Node, params); - ParentOfThis->AddChild(Node); - params[4] = ":" + params[4]; - Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix); ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+ParentOfThis->GetName()+"\002 introduced server \002"+servername+"\002 ("+description+")"); - return true; + return CMD_SUCCESS; } +void CommandServer::HandleExtra(TreeServer* newserver, const std::vector<std::string>& params) +{ + for (std::vector<std::string>::const_iterator i = params.begin() + 2; i != params.end() - 1; ++i) + { + const std::string& prop = *i; + std::string::size_type p = prop.find('='); -/* - * This is used after the other side of a connection has accepted our credentials. - * They are then introducing themselves to us, BEFORE either of us burst. -- w - */ -bool TreeSocket::Outbound_Reply_Server(parameterlist ¶ms) + std::string key = prop; + std::string val; + if (p != std::string::npos) + { + key.erase(p); + val.assign(prop, p+1, std::string::npos); + } + + if (key == "burst") + newserver->BeginBurst(ConvToInt(val)); + } +} + +Link* TreeSocket::AuthRemote(const parameterlist& params) { if (params.size() < 5) { SendError("Protocol error - Not enough parameters for SERVER command"); - return false; + return NULL; } irc::string servername = params[0].c_str(); - std::string sname = params[0]; - std::string password = params[1]; - std::string sid = params[3]; - std::string description = params[4]; - int hops = atoi(params[2].c_str()); + const std::string& sname = params[0]; + const std::string& password = params[1]; + const std::string& sid = params[3]; + const std::string& description = params.back(); this->SendCapabilities(2); - if (hops) - { - this->SendError("Server too far away for authentication"); - ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication"); - return false; - } - if (!ServerInstance->IsSID(sid)) { this->SendError("Invalid format server ID: "+sid+"!"); - return false; + return NULL; } for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++) @@ -134,22 +123,27 @@ bool TreeSocket::Outbound_Reply_Server(parameterlist ¶ms) continue; } - TreeServer* CheckDupe = Utils->FindServer(sname); - if (CheckDupe) - { - std::string pname = CheckDupe->GetParent() ? CheckDupe->GetParent()->GetName() : "<ourself>"; - SendError("Server "+sname+" already exists on server "+pname+"!"); - ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+pname); - return false; - } - CheckDupe = Utils->FindServer(sid); - if (CheckDupe) - { - this->SendError("Server ID "+sid+" already exists on the network! You may want to specify the server ID for the server manually with <server:id> so they do not conflict."); - ServerInstance->SNO->WriteToSnoMask('l',"Server \2"+assign(servername)+"\2 being introduced denied, server ID already exists on the network. Closing link."); - return false; - } + if (!CheckDuplicate(sname, sid)) + return NULL; + + ServerInstance->SNO->WriteToSnoMask('l',"Verified server connection " + linkID + " ("+description+")"); + return x; + } + this->SendError("Mismatched server name or password (check the other server's snomask output for details - e.g. umode +s +Ll)"); + ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials"); + return NULL; +} + +/* + * This is used after the other side of a connection has accepted our credentials. + * They are then introducing themselves to us, BEFORE either of us burst. -- w + */ +bool TreeSocket::Outbound_Reply_Server(parameterlist ¶ms) +{ + const Link* x = AuthRemote(params); + if (x) + { /* * They're in WAIT_AUTH_2 (having accepted our credentials). * Set our state to CONNECTED (since everything's peachy so far) and send our @@ -158,26 +152,11 @@ bool TreeSocket::Outbound_Reply_Server(parameterlist ¶ms) * While we're at it, create a treeserver object so we know about them. * -- w */ - this->LinkState = CONNECTED; - - Utils->timeoutlist.erase(this); - linkID = sname; - - MyRoot = new TreeServer(Utils, sname, description, sid, Utils->TreeRoot, this, x->Hidden); - Utils->TreeRoot->AddChild(MyRoot); - this->DoBurst(MyRoot); - - params[4] = ":" + params[4]; - - /* IMPORTANT: Take password/hmac hash OUT of here before we broadcast the introduction! */ - params[1] = "*"; - Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",params,sname); + FinishAuth(params[0], params[3], params.back(), x->Hidden); return true; } - this->SendError("Mismatched server name or password (check the other server's snomask output for details - e.g. umode +s +Ll)"); - ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials"); return false; } @@ -194,7 +173,7 @@ bool TreeSocket::CheckDuplicate(const std::string& sname, const std::string& sid } /* Check for fully initialized instances of the server by id */ - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Looking for dupe SID %s", sid.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Looking for dupe SID %s", sid.c_str()); CheckDupe = Utils->FindServerID(sid); if (CheckDupe) @@ -214,58 +193,14 @@ bool TreeSocket::CheckDuplicate(const std::string& sname, const std::string& sid */ bool TreeSocket::Inbound_Server(parameterlist ¶ms) { - if (params.size() < 5) - { - SendError("Protocol error - Missing SID"); - return false; - } - - irc::string servername = params[0].c_str(); - std::string sname = params[0]; - std::string password = params[1]; - std::string sid = params[3]; - std::string description = params[4]; - int hops = atoi(params[2].c_str()); - - this->SendCapabilities(2); - - if (hops) - { - this->SendError("Server too far away for authentication"); - ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication"); - return false; - } - - if (!ServerInstance->IsSID(sid)) + const Link* x = AuthRemote(params); + if (x) { - this->SendError("Invalid format server ID: "+sid+"!"); - return false; - } - - for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++) - { - Link* x = *i; - if (x->Name != servername && x->Name != "*") // open link allowance - continue; - - if (!ComparePass(*x, password)) - { - ServerInstance->SNO->WriteToSnoMask('l',"Invalid password on link: %s", x->Name.c_str()); - continue; - } - - if (!CheckDuplicate(sname, sid)) - return false; - - ServerInstance->SNO->WriteToSnoMask('l',"Verified incoming server connection " + linkID + " ("+description+")"); - - this->SendCapabilities(2); - // Save these for later, so when they accept our credentials (indicated by BURST) we remember them this->capab->hidden = x->Hidden; - this->capab->sid = sid; - this->capab->description = description; - this->capab->name = sname; + this->capab->sid = params[3]; + this->capab->description = params.back(); + this->capab->name = params[0]; // Send our details: Our server name and description and hopcount of 0, // along with the sendpass from this block. @@ -276,8 +211,15 @@ bool TreeSocket::Inbound_Server(parameterlist ¶ms) return true; } - this->SendError("Mismatched server name or password (check the other server's snomask output for details - e.g. umode +s +Ll)"); - ServerInstance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials"); return false; } +CommandServer::Builder::Builder(TreeServer* server) + : CmdBuilder(server->GetParent()->GetID(), "SERVER") +{ + push(server->GetName()); + push(server->GetID()); + if (server->IsBursting()) + push_property("burst", ConvToStr(server->StartBurst)); + push_last(server->GetDesc()); +} diff --git a/src/modules/m_spanningtree/servercommand.cpp b/src/modules/m_spanningtree/servercommand.cpp new file mode 100644 index 000000000..3034eee7a --- /dev/null +++ b/src/modules/m_spanningtree/servercommand.cpp @@ -0,0 +1,57 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "main.h" +#include "servercommand.h" + +ServerCommand::ServerCommand(Module* Creator, const std::string& Name, unsigned int MinParams, unsigned int MaxParams) + : CommandBase(Creator, Name, MinParams, MaxParams) +{ + this->ServiceProvider::DisableAutoRegister(); + ModuleSpanningTree* st = static_cast<ModuleSpanningTree*>(Creator); + st->CmdManager.AddCommand(this); +} + +RouteDescriptor ServerCommand::GetRouting(User* user, const std::vector<std::string>& parameters) +{ + // Broadcast server-to-server commands unless overridden + return ROUTE_BROADCAST; +} + +time_t ServerCommand::ExtractTS(const std::string& tsstr) +{ + time_t TS = ConvToInt(tsstr); + if (!TS) + throw ProtocolException("Invalid TS"); + return TS; +} + +ServerCommand* ServerCommandManager::GetHandler(const std::string& command) const +{ + ServerCommandMap::const_iterator it = commands.find(command); + if (it != commands.end()) + return it->second; + return NULL; +} + +bool ServerCommandManager::AddCommand(ServerCommand* cmd) +{ + return commands.insert(std::make_pair(cmd->name, cmd)).second; +} diff --git a/src/modules/m_spanningtree/servercommand.h b/src/modules/m_spanningtree/servercommand.h new file mode 100644 index 000000000..524520a88 --- /dev/null +++ b/src/modules/m_spanningtree/servercommand.h @@ -0,0 +1,100 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2013 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#pragma once + +#include "utils.h" +#include "treeserver.h" + +class ProtocolException : public ModuleException +{ + public: + ProtocolException(const std::string& msg) + : ModuleException("Protocol violation: " + msg) + { + } +}; + +/** Base class for server-to-server commands that may have a (remote) user source or server source. + */ +class ServerCommand : public CommandBase +{ + public: + ServerCommand(Module* Creator, const std::string& Name, unsigned int MinPara = 0, unsigned int MaxPara = 0); + + virtual CmdResult Handle(User* user, std::vector<std::string>& parameters) = 0; + virtual RouteDescriptor GetRouting(User* user, const std::vector<std::string>& parameters); + + /** + * Extract the TS from a string. + * @param tsstr The string containing the TS. + * @return The raw timestamp value. + * This function throws a ProtocolException if it considers the TS invalid. Note that the detection of + * invalid timestamps is not designed to be bulletproof, only some cases - like "0" - trigger an exception. + */ + static time_t ExtractTS(const std::string& tsstr); +}; + +/** Base class for server-to-server command handlers which are only valid if their source is a user. + * When a server sends a command of this type and the source is a server (sid), the link is aborted. + */ +template <class T> +class UserOnlyServerCommand : public ServerCommand +{ + public: + UserOnlyServerCommand(Module* Creator, const std::string& Name, unsigned int MinPara = 0, unsigned int MaxPara = 0) + : ServerCommand(Creator, Name, MinPara, MaxPara) { } + + CmdResult Handle(User* user, std::vector<std::string>& parameters) + { + RemoteUser* remoteuser = IS_REMOTE(user); + if (!remoteuser) + throw ProtocolException("Invalid source"); + return static_cast<T*>(this)->HandleRemote(remoteuser, parameters); + } +}; + +/** Base class for server-to-server command handlers which are only valid if their source is a server. + * When a server sends a command of this type and the source is a user (uuid), the link is aborted. + */ +template <class T> +class ServerOnlyServerCommand : public ServerCommand +{ + public: + ServerOnlyServerCommand(Module* Creator, const std::string& Name, unsigned int MinPara = 0, unsigned int MaxPara = 0) + : ServerCommand(Creator, Name, MinPara, MaxPara) { } + + CmdResult Handle(User* user, std::vector<std::string>& parameters) + { + if (!IS_SERVER(user)) + throw ProtocolException("Invalid source"); + TreeServer* server = TreeServer::Get(user); + return static_cast<T*>(this)->HandleServer(server, parameters); + } +}; + +class ServerCommandManager +{ + typedef TR1NS::unordered_map<std::string, ServerCommand*> ServerCommandMap; + ServerCommandMap commands; + + public: + ServerCommand* GetHandler(const std::string& command) const; + bool AddCommand(ServerCommand* cmd); +}; diff --git a/src/modules/m_spanningtree/sinfo.cpp b/src/modules/m_spanningtree/sinfo.cpp new file mode 100644 index 000000000..0989ea9a5 --- /dev/null +++ b/src/modules/m_spanningtree/sinfo.cpp @@ -0,0 +1,51 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2014 Attila Molnar <attilamolnar@hush.com> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "inspircd.h" + +#include "treeserver.h" +#include "commands.h" + +CmdResult CommandSInfo::HandleServer(TreeServer* server, std::vector<std::string>& params) +{ + const std::string& key = params.front(); + const std::string& value = params.back(); + + if (key == "fullversion") + { + server->SetFullVersion(value); + } + else if (key == "version") + { + server->SetVersion(value); + } + else if (key == "desc") + { + // Only sent when the description of a server changes because of a rehash; not sent on burst + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Server description of " + server->GetName() + " changed: " + value); + server->SetDesc(value); + } + + return CMD_SUCCESS; +} + +CommandSInfo::Builder::Builder(TreeServer* server, const char* key, const std::string& val) + : CmdBuilder(server->GetID(), "SINFO") +{ + push(key).push_last(val); +} diff --git a/src/modules/m_spanningtree/svsjoin.cpp b/src/modules/m_spanningtree/svsjoin.cpp index 416502369..98443409a 100644 --- a/src/modules/m_spanningtree/svsjoin.cpp +++ b/src/modules/m_spanningtree/svsjoin.cpp @@ -19,19 +19,13 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" -#include "utils.h" -#include "treeserver.h" #include "commands.h" -CmdResult CommandSVSJoin::Handle(const std::vector<std::string>& parameters, User *user) +CmdResult CommandSVSJoin::Handle(User* user, std::vector<std::string>& parameters) { // Check for valid channel name - if (!ServerInstance->IsChannel(parameters[1].c_str(), ServerInstance->Config->Limits.ChanMax)) + if (!ServerInstance->IsChannel(parameters[1])) return CMD_FAILURE; // Check target exists @@ -40,8 +34,21 @@ CmdResult CommandSVSJoin::Handle(const std::vector<std::string>& parameters, Use return CMD_FAILURE; /* only join if it's local, otherwise just pass it on! */ - if (IS_LOCAL(u)) - Channel::JoinUser(u, parameters[1].c_str(), false, "", false, ServerInstance->Time()); + LocalUser* localuser = IS_LOCAL(u); + if (localuser) + { + bool override = false; + std::string key; + if (parameters.size() >= 3) + { + key = parameters[2]; + if (key.empty()) + override = true; + } + + Channel::JoinUser(localuser, parameters[1], override, key); + } + return CMD_SUCCESS; } diff --git a/src/modules/m_spanningtree/svsnick.cpp b/src/modules/m_spanningtree/svsnick.cpp index 59973202d..bb21fc54d 100644 --- a/src/modules/m_spanningtree/svsnick.cpp +++ b/src/modules/m_spanningtree/svsnick.cpp @@ -21,41 +21,50 @@ #include "inspircd.h" #include "main.h" -#include "utils.h" #include "commands.h" -CmdResult CommandSVSNick::Handle(const std::vector<std::string>& parameters, User *user) +CmdResult CommandSVSNick::Handle(User* user, std::vector<std::string>& parameters) { User* u = ServerInstance->FindNick(parameters[0]); if (u && IS_LOCAL(u)) { + // The 4th parameter is optional and it is the expected nick TS of the target user. If this parameter is + // present and it doesn't match the user's nick TS, the SVSNICK is not acted upon. + // This makes it possible to detect the case when services wants to change the nick of a user, but the + // user changes their nick before the SVSNICK arrives, making the SVSNICK nick change (usually to a guest nick) + // unnecessary. Consider the following for example: + // + // 1. test changes nick to Attila which is protected by services + // 2. Services SVSNICKs the user to Guest12345 + // 3. Attila changes nick to Attila_ which isn't protected by services + // 4. SVSNICK arrives + // 5. Attila_ gets his nick changed to Guest12345 unnecessarily + // + // In this case when the SVSNICK is processed the target has already changed his nick to something + // which isn't protected, so changing the nick again to a Guest nick is not desired. + // However, if the expected nick TS parameter is present in the SVSNICK then the nick change in step 5 + // won't happen because the timestamps won't match. + if (parameters.size() > 3) + { + time_t ExpectedTS = ConvToInt(parameters[3]); + if (u->age != ExpectedTS) + return CMD_FAILURE; // Ignore SVSNICK + } + std::string nick = parameters[1]; if (isdigit(nick[0])) nick = u->uuid; - // Don't update the TS if the nick is exactly the same - if (u->nick == nick) - return CMD_FAILURE; - time_t NickTS = ConvToInt(parameters[2]); if (NickTS <= 0) return CMD_FAILURE; - ModuleSpanningTree* st = (ModuleSpanningTree*)(Module*)creator; - st->KeepNickTS = true; - u->age = NickTS; - - if (!u->ForceNickChange(nick.c_str())) + if (!u->ChangeNick(nick, NickTS)) { /* buh. UID them */ - if (!u->ForceNickChange(u->uuid.c_str())) - { - ServerInstance->Users->QuitUser(u, "Nickname collision"); - } + u->ChangeNick(u->uuid); } - - st->KeepNickTS = false; } return CMD_SUCCESS; diff --git a/src/modules/m_spanningtree/svspart.cpp b/src/modules/m_spanningtree/svspart.cpp index 3bdf13b25..f86afa367 100644 --- a/src/modules/m_spanningtree/svspart.cpp +++ b/src/modules/m_spanningtree/svspart.cpp @@ -19,16 +19,10 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" -#include "main.h" -#include "utils.h" -#include "treeserver.h" #include "commands.h" -CmdResult CommandSVSPart::Handle(const std::vector<std::string>& parameters, User *user) +CmdResult CommandSVSPart::Handle(User* user, std::vector<std::string>& parameters) { User* u = ServerInstance->FindUUID(parameters[0]); if (!u) diff --git a/src/modules/m_spanningtree/operquit.cpp b/src/modules/m_spanningtree/translate.cpp index af2e04ebc..48c0632e5 100644 --- a/src/modules/m_spanningtree/operquit.cpp +++ b/src/modules/m_spanningtree/translate.cpp @@ -1,7 +1,7 @@ /* * InspIRCd -- Internet Relay Chat Daemon * - * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net> + * Copyright (C) 2014 Attila Molnar <attilamolnar@hush.com> * * This file is part of InspIRCd. InspIRCd is free software: you can * redistribute it and/or modify it under the terms of the GNU General Public @@ -18,28 +18,31 @@ #include "inspircd.h" -#include "xline.h" +#include "translate.h" -#include "treesocket.h" -#include "treeserver.h" -#include "utils.h" - -/* $ModDep: m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - - -bool TreeSocket::OperQuit(const std::string &prefix, parameterlist ¶ms) +std::string Translate::ModeChangeListToParams(const Modes::ChangeList::List& modes) { - if (params.size() < 1) - return true; - - User* u = ServerInstance->FindUUID(prefix); - - if ((u) && (!IS_SERVER(u))) + std::string ret; + for (Modes::ChangeList::List::const_iterator i = modes.begin(); i != modes.end(); ++i) { - ServerInstance->OperQuit.set(u, params[0]); - params[0] = ":" + params[0]; - Utils->DoOneToAllButSender(prefix,"OPERQUIT",params,prefix); + const Modes::Change& item = *i; + ModeHandler* mh = item.mh; + if (!mh->GetNumParams(item.adding)) + continue; + + ret.push_back(' '); + + if (mh->IsPrefixMode()) + { + User* target = ServerInstance->FindNick(item.param); + if (target) + { + ret.append(target->uuid); + continue; + } + } + + ret.append(item.param); } - return true; + return ret; } - diff --git a/src/modules/sasl.h b/src/modules/m_spanningtree/translate.h index f67351104..a2bc6df78 100644 --- a/src/modules/sasl.h +++ b/src/modules/m_spanningtree/translate.h @@ -1,7 +1,7 @@ /* * InspIRCd -- Internet Relay Chat Daemon * - * Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org> + * Copyright (C) 2014 Attila Molnar <attilamolnar@hush.com> * * This file is part of InspIRCd. InspIRCd is free software: you can * redistribute it and/or modify it under the terms of the GNU General Public @@ -17,18 +17,14 @@ */ -#ifndef SASL_H -#define SASL_H +#pragma once -class SASLFallback : public Event +namespace Translate { - public: - const parameterlist& params; - SASLFallback(Module* me, const parameterlist& p) - : Event(me, "sasl_fallback"), params(p) - { - Send(); - } -}; - -#endif + /** Generate a list of mode parameters suitable for FMODE/MODE from a Modes::ChangeList::List + * @param modes List of mode changes + * @return List of mode parameters built from the input. Does not include the modes themselves, + * only the parameters. + */ + std::string ModeChangeListToParams(const Modes::ChangeList::List& modes); +} diff --git a/src/modules/m_spanningtree/treeserver.cpp b/src/modules/m_spanningtree/treeserver.cpp index 493b05ebf..afd86c0ce 100644 --- a/src/modules/m_spanningtree/treeserver.cpp +++ b/src/modules/m_spanningtree/treeserver.cpp @@ -21,56 +21,46 @@ #include "inspircd.h" -#include "socket.h" #include "xline.h" #include "main.h" -#include "../spanningtree.h" +#include "modules/spanningtree.h" #include "utils.h" #include "treeserver.h" -/* $ModDep: m_spanningtree/utils.h m_spanningtree/treeserver.h */ - /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which * represents our own server. Therefore, it has no route, no parent, and * no socket associated with it. Its version string is our own local version. */ -TreeServer::TreeServer(SpanningTreeUtilities* Util, std::string Name, std::string Desc, const std::string &id) - : ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util), ServerUser(ServerInstance->FakeClient) +TreeServer::TreeServer() + : Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc) + , Parent(NULL), Route(NULL) + , VersionString(ServerInstance->GetVersionString()) + , fullversion(ServerInstance->GetVersionString(true)) + , Socket(NULL), sid(ServerInstance->Config->GetSID()), behind_bursting(0), isdead(false) + , pingtimer(this) + , ServerUser(ServerInstance->FakeClient) + , age(ServerInstance->Time()), UserCount(ServerInstance->Users.LocalUserCount()) + , OperCount(0), rtt(0), StartBurst(0), Hidden(false) { - age = ServerInstance->Time(); - bursting = false; - Parent = NULL; - VersionString.clear(); - ServerUserCount = ServerOperCount = 0; - VersionString = ServerInstance->GetVersionString(); - Route = NULL; - Socket = NULL; /* Fix by brain */ - StartBurst = rtt = 0; - Warned = Hidden = false; AddHashEntry(); - SetID(id); } /** When we create a new server, we call this constructor to initialize it. * This constructor initializes the server's Route and Parent, and sets up * its ping counters so that it will be pinged one minute from now. */ -TreeServer::TreeServer(SpanningTreeUtilities* Util, std::string Name, std::string Desc, const std::string &id, TreeServer* Above, TreeSocket* Sock, bool Hide) - : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util), ServerUser(new FakeUser(id, Name)), Hidden(Hide) +TreeServer::TreeServer(const std::string& Name, const std::string& Desc, const std::string& id, TreeServer* Above, TreeSocket* Sock, bool Hide) + : Server(Name, Desc) + , Parent(Above), Socket(Sock), sid(id), behind_bursting(Parent->behind_bursting), isdead(false) + , pingtimer(this) + , ServerUser(new FakeUser(id, this)) + , age(ServerInstance->Time()), UserCount(0), OperCount(0), rtt(0), StartBurst(0), Hidden(Hide) { - age = ServerInstance->Time(); - bursting = true; - VersionString.clear(); - ServerUserCount = ServerOperCount = 0; - SetNextPingTime(ServerInstance->Time() + Utils->PingFreq); - SetPingFlag(); - Warned = false; - rtt = 0; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "New server %s behind_bursting %u", GetName().c_str(), behind_bursting); + CheckULine(); - long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); - this->StartBurst = ts; - ServerInstance->Logs->Log("m_spanningtree",DEBUG, "Started bursting at time %lu", ts); + ServerInstance->Timers.AddTimer(&pingtimer); /* find the 'route' for this server (e.g. the one directly connected * to the local server, which we can use to reach it) @@ -124,246 +114,181 @@ TreeServer::TreeServer(SpanningTreeUtilities* Util, std::string Name, std::strin */ this->AddHashEntry(); - - SetID(id); + Parent->Children.push_back(this); } -const std::string& TreeServer::GetID() +void TreeServer::BeginBurst(unsigned long startms) { - return sid; + behind_bursting++; + + unsigned long now = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); + // If the start time is in the future (clocks are not synced) then use current time + if ((!startms) || (startms > now)) + startms = now; + this->StartBurst = startms; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s started bursting at time %lu behind_bursting %u", sid.c_str(), startms, behind_bursting); } void TreeServer::FinishBurstInternal() { - this->bursting = false; - SetNextPingTime(ServerInstance->Time() + Utils->PingFreq); - SetPingFlag(); - for(unsigned int q=0; q < ChildCount(); q++) + // Check is needed because 1202 protocol servers don't send the bursting state of a server, so servers + // introduced during a netburst may later send ENDBURST which would normally decrease this counter + if (behind_bursting > 0) + behind_bursting--; + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "FinishBurstInternal() %s behind_bursting %u", GetName().c_str(), behind_bursting); + + for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i) { - TreeServer* child = GetChild(q); + TreeServer* child = *i; child->FinishBurstInternal(); } } void TreeServer::FinishBurst() { - FinishBurstInternal(); ServerInstance->XLines->ApplyLines(); long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000); unsigned long bursttime = ts - this->StartBurst; ServerInstance->SNO->WriteToSnoMask(Parent == Utils->TreeRoot ? 'l' : 'L', "Received end of netburst from \2%s\2 (burst time: %lu %s)", - ServerName.c_str(), (bursttime > 10000 ? bursttime / 1000 : bursttime), (bursttime > 10000 ? "secs" : "msecs")); - AddServerEvent(Utils->Creator, ServerName.c_str()); -} + GetName().c_str(), (bursttime > 10000 ? bursttime / 1000 : bursttime), (bursttime > 10000 ? "secs" : "msecs")); + FOREACH_MOD_CUSTOM(Utils->Creator->GetEventProvider(), SpanningTreeEventListener, OnServerLink, (this)); -void TreeServer::SetID(const std::string &id) -{ - ServerInstance->Logs->Log("m_spanningtree",DEBUG, "Setting SID to " + id); - sid = id; - Utils->sidlist[sid] = this; + StartBurst = 0; + FinishBurstInternal(); } -int TreeServer::QuitUsers(const std::string &reason) +void TreeServer::SQuitChild(TreeServer* server, const std::string& reason) { - const char* reason_s = reason.c_str(); - std::vector<User*> time_to_die; - for (user_hash::iterator n = ServerInstance->Users->clientlist->begin(); n != ServerInstance->Users->clientlist->end(); n++) + FOREACH_MOD_CUSTOM(Utils->Creator->GetEventProvider(), SpanningTreeEventListener, OnServerSplit, (server)); + stdalgo::erase(Children, server); + + if (IsRoot()) { - if (n->second->server == ServerName) - { - time_to_die.push_back(n->second); - } + // Server split from us, generate a SQUIT message and broadcast it + ServerInstance->SNO->WriteGlobalSno('l', "Server \002" + server->GetName() + "\002 split: " + reason); + CmdBuilder("SQUIT").push(server->GetID()).push_last(reason).Broadcast(); } - for (std::vector<User*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++) + else { - User* a = (User*)*n; - if (!IS_LOCAL(a)) - { - if (this->Utils->quiet_bursts) - a->quietquit = true; - - if (ServerInstance->Config->HideSplits) - ServerInstance->Users->QuitUser(a, "*.net *.split", reason_s); - else - ServerInstance->Users->QuitUser(a, reason_s); - } + ServerInstance->SNO->WriteToSnoMask('L', "Server \002" + server->GetName() + "\002 split from server \002" + GetName() + "\002 with reason: " + reason); } - return time_to_die.size(); -} -/** This method is used to add the structure to the - * hash_map for linear searches. It is only called - * by the constructors. - */ -void TreeServer::AddHashEntry() -{ - server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str()); - if (iter == Utils->serverlist.end()) - Utils->serverlist[this->ServerName.c_str()] = this; -} - -/** This method removes the reference to this object - * from the hash_map which is used for linear searches. - * It is only called by the default destructor. - */ -void TreeServer::DelHashEntry() -{ - server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str()); - if (iter != Utils->serverlist.end()) - Utils->serverlist.erase(iter); -} - -/** These accessors etc should be pretty self- - * explanitory. - */ -TreeServer* TreeServer::GetRoute() -{ - return Route; -} - -std::string TreeServer::GetName() -{ - return ServerName.c_str(); -} + unsigned int num_lost_servers = 0; + server->SQuitInternal(num_lost_servers); -const std::string& TreeServer::GetDesc() -{ - return ServerDesc; -} + const std::string quitreason = GetName() + " " + server->GetName(); + unsigned int num_lost_users = QuitUsers(quitreason); -const std::string& TreeServer::GetVersion() -{ - return VersionString; -} + ServerInstance->SNO->WriteToSnoMask(IsRoot() ? 'l' : 'L', "Netsplit complete, lost \002%u\002 user%s on \002%u\002 server%s.", + num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : ""); -void TreeServer::SetNextPingTime(time_t t) -{ - this->NextPing = t; - LastPingWasGood = false; -} + // No-op if the socket is already closed (i.e. it called us) + if (server->IsLocal()) + server->GetSocket()->Close(); -time_t TreeServer::NextPingTime() -{ - return NextPing; + // Add the server to the cull list, the servers behind it are handled by cull() and the destructor + ServerInstance->GlobalCulls.AddItem(server); } -bool TreeServer::AnsweredLastPing() +void TreeServer::SQuitInternal(unsigned int& num_lost_servers) { - return LastPingWasGood; -} + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Server %s lost in split", GetName().c_str()); -void TreeServer::SetPingFlag() -{ - LastPingWasGood = true; -} - -unsigned int TreeServer::GetUserCount() -{ - return ServerUserCount; -} - -void TreeServer::SetUserCount(int diff) -{ - ServerUserCount += diff; -} - -void TreeServer::SetOperCount(int diff) -{ - ServerOperCount += diff; -} - -unsigned int TreeServer::GetOperCount() -{ - return ServerOperCount; -} - -TreeSocket* TreeServer::GetSocket() -{ - return Socket; -} - -TreeServer* TreeServer::GetParent() -{ - return Parent; -} + for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i) + { + TreeServer* server = *i; + server->SQuitInternal(num_lost_servers); + } -void TreeServer::SetVersion(const std::string &Version) -{ - VersionString = Version; + // Mark server as dead + isdead = true; + num_lost_servers++; + RemoveHash(); } -unsigned int TreeServer::ChildCount() +unsigned int TreeServer::QuitUsers(const std::string& reason) { - return Children.size(); -} + std::string publicreason = ServerInstance->Config->HideSplits ? "*.net *.split" : reason; -TreeServer* TreeServer::GetChild(unsigned int n) -{ - if (n < Children.size()) - { - /* Make sure they cant request - * an out-of-range object. After - * all we know what these programmer - * types are like *grin*. - */ - return Children[n]; - } - else + const user_hash& users = ServerInstance->Users->GetUsers(); + unsigned int original_size = users.size(); + for (user_hash::const_iterator i = users.begin(); i != users.end(); ) { - return NULL; + User* user = i->second; + // Increment the iterator now because QuitUser() removes the user from the container + ++i; + TreeServer* server = TreeServer::Get(user); + if (server->IsDead()) + ServerInstance->Users->QuitUser(user, publicreason, &reason); } + return original_size - users.size(); } -void TreeServer::AddChild(TreeServer* Child) +void TreeServer::CheckULine() { - Children.push_back(Child); -} + uline = silentuline = false; -bool TreeServer::DelChild(TreeServer* Child) -{ - std::vector<TreeServer*>::iterator it = std::find(Children.begin(), Children.end(), Child); - if (it != Children.end()) + ConfigTagList tags = ServerInstance->Config->ConfTags("uline"); + for (ConfigIter i = tags.first; i != tags.second; ++i) { - Children.erase(it); - return true; + ConfigTag* tag = i->second; + std::string server = tag->getString("server"); + if (!strcasecmp(server.c_str(), GetName().c_str())) + { + if (this->IsRoot()) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Servers should not uline themselves (at " + tag->getTagLocation() + ")"); + return; + } + + uline = true; + silentuline = tag->getBool("silent"); + break; + } } - return false; } -/** Removes child nodes of this node, and of that node, etc etc. - * This is used during netsplits to automatically tidy up the - * server tree. It is slow, we don't use it for much else. +/** This method is used to add the structure to the + * hash_map for linear searches. It is only called + * by the constructors. */ -bool TreeServer::Tidy() +void TreeServer::AddHashEntry() { - while (1) - { - std::vector<TreeServer*>::iterator a = Children.begin(); - if (a == Children.end()) - return true; - TreeServer* s = *a; - s->Tidy(); - s->cull(); - Children.erase(a); - delete s; - } + Utils->serverlist[GetName()] = this; + Utils->sidlist[sid] = this; } CullResult TreeServer::cull() { - if (ServerUser != ServerInstance->FakeClient) + // Recursively cull all servers that are under us in the tree + for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i) + { + TreeServer* server = *i; + server->cull(); + } + + if (!IsRoot()) ServerUser->cull(); return classbase::cull(); } TreeServer::~TreeServer() { - /* We'd better tidy up after ourselves, eh? */ - this->DelHashEntry(); - if (ServerUser != ServerInstance->FakeClient) + // Recursively delete all servers that are under us in the tree first + for (ChildServers::const_iterator i = Children.begin(); i != Children.end(); ++i) + delete *i; + + // Delete server user unless it's us + if (!IsRoot()) delete ServerUser; +} + +void TreeServer::RemoveHash() +{ + // XXX: Erase server from UserManager::uuidlist now, to allow sid reuse in the current main loop + // iteration, before the cull list is applied + ServerInstance->Users->uuidlist.erase(sid); - server_hash::iterator iter = Utils->sidlist.find(GetID()); - if (iter != Utils->sidlist.end()) - Utils->sidlist.erase(iter); + Utils->sidlist.erase(sid); + Utils->serverlist.erase(GetName()); } diff --git a/src/modules/m_spanningtree/treeserver.h b/src/modules/m_spanningtree/treeserver.h index 60b6d1def..1a0203ba0 100644 --- a/src/modules/m_spanningtree/treeserver.h +++ b/src/modules/m_spanningtree/treeserver.h @@ -19,10 +19,10 @@ */ -#ifndef M_SPANNINGTREE_TREESERVER_H -#define M_SPANNINGTREE_TREESERVER_H +#pragma once #include "treesocket.h" +#include "pingtimer.h" /** Each server in the tree is represented by one class of * type TreeServer. A locally connected TreeServer can @@ -38,90 +38,111 @@ * TreeServer items, deleting and inserting them as they * are created and destroyed. */ -class TreeServer : public classbase +class TreeServer : public Server { TreeServer* Parent; /* Parent entry */ TreeServer* Route; /* Route entry */ std::vector<TreeServer*> Children; /* List of child objects */ - irc::string ServerName; /* Server's name */ - std::string ServerDesc; /* Server's description */ std::string VersionString; /* Version string or empty string */ - unsigned int ServerUserCount; /* How many users are on this server? [note: doesn't care about +i] */ - unsigned int ServerOperCount; /* How many opers are on this server? */ - TreeSocket* Socket; /* For directly connected servers this points at the socket object */ - time_t NextPing; /* After this time, the server should be PINGed*/ - bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */ - SpanningTreeUtilities* Utils; /* Utility class */ + + /** Full version string including patch version and other info + */ + std::string fullversion; + + TreeSocket* Socket; /* Socket used to communicate with this server */ std::string sid; /* Server ID */ - /** Set server ID - * @param id Server ID - * @throws CoreException on duplicate ID + /** Counter counting how many servers are bursting in front of this server, including + * this server. Set to parents' value on construction then it is increased if the + * server itself starts bursting. Decreased when a server on the path to this server + * finishes burst. + */ + unsigned int behind_bursting; + + /** True if this server has been lost in a split and is awaiting destruction + */ + bool isdead; + + /** Timer handling PINGing the server and killing it on timeout */ - void SetID(const std::string &id); + PingTimer pingtimer; + + /** This method is used to add this TreeServer to the + * hash maps. It is only called by the constructors. + */ + void AddHashEntry(); + + /** Used by SQuit logic to recursively remove servers + */ + void SQuitInternal(unsigned int& num_lost_servers); + + /** Remove the reference to this server from the hash maps + */ + void RemoveHash(); public: + typedef std::vector<TreeServer*> ChildServers; FakeUser* const ServerUser; /* User representing this server */ - time_t age; + const time_t age; - bool Warned; /* True if we've warned opers about high latency on this server */ - bool bursting; /* whether or not this server is bursting */ + unsigned int UserCount; /* How many users are on this server? [note: doesn't care about +i] */ + unsigned int OperCount; /* How many opers are on this server? */ /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which * represents our own server. Therefore, it has no route, no parent, and * no socket associated with it. Its version string is our own local version. */ - TreeServer(SpanningTreeUtilities* Util, std::string Name, std::string Desc, const std::string &id); + TreeServer(); /** When we create a new server, we call this constructor to initialize it. * This constructor initializes the server's Route and Parent, and sets up * its ping counters so that it will be pinged one minute from now. */ - TreeServer(SpanningTreeUtilities* Util, std::string Name, std::string Desc, const std::string &id, TreeServer* Above, TreeSocket* Sock, bool Hide); - - int QuitUsers(const std::string &reason); + TreeServer(const std::string& Name, const std::string& Desc, const std::string& id, TreeServer* Above, TreeSocket* Sock, bool Hide); - /** This method is used to add the structure to the - * hash_map for linear searches. It is only called - * by the constructors. + /** SQuit a server connected to this server, removing the given server and all servers behind it + * @param server Server to squit, must be directly below this server + * @param reason Reason for quitting the server, sent to opers and other servers */ - void AddHashEntry(); + void SQuitChild(TreeServer* server, const std::string& reason); - /** This method removes the reference to this object - * from the hash_map which is used for linear searches. - * It is only called by the default destructor. + /** SQuit this server, removing this server and all servers behind it + * @param reason Reason for quitting the server, sent to opers and other servers */ - void DelHashEntry(); + void SQuit(const std::string& reason) + { + GetParent()->SQuitChild(this, reason); + } + + static unsigned int QuitUsers(const std::string& reason); /** Get route. * The 'route' is defined as the locally- * connected server which can be used to reach this server. */ - TreeServer* GetRoute(); - - /** Get server name - */ - std::string GetName(); + TreeServer* GetRoute() const { return Route; } - /** Get server description (GECOS) + /** Returns true if this server is the tree root (i.e.: us) */ - const std::string& GetDesc(); + bool IsRoot() const { return (this->Parent == NULL); } - /** Get server version string + /** Returns true if this server is locally connected */ - const std::string& GetVersion(); + bool IsLocal() const { return (this->Route == this); } - /** Set time we are next due to ping this server + /** Returns true if the server is awaiting destruction + * @return True if the server is waiting to be culled and deleted, false otherwise */ - void SetNextPingTime(time_t t); + bool IsDead() const { return isdead; } - /** Get the time we are next due to ping this server + /** Get server version string */ - time_t NextPingTime(); + const std::string& GetVersion() const { return VersionString; } - /** Last ping time in milliseconds, used to calculate round trip time + /** Get the full version string of this server + * @return The full version string of this server, including patch version and other info */ - unsigned long LastPingMsec; + const std::string& GetFullVersion() const { return fullversion; } /** Round trip time of last ping */ @@ -135,80 +156,81 @@ class TreeServer : public classbase */ bool Hidden; - /** True if the server answered their last ping - */ - bool AnsweredLastPing(); - - /** Set the server as responding to its last ping + /** Get the TreeSocket pointer for local servers. + * For remote servers, this returns NULL. */ - void SetPingFlag(); + TreeSocket* GetSocket() const { return Socket; } - /** Get the number of users on this server. + /** Get the parent server. + * For the root node, this returns NULL. */ - unsigned int GetUserCount(); + TreeServer* GetParent() const { return Parent; } - /** Increment or decrement the user count by diff. + /** Set the server version string */ - void SetUserCount(int diff); + void SetVersion(const std::string& verstr) { VersionString = verstr; } - /** Gets the numbers of opers on this server. + /** Set the full version string + * @param verstr The version string to set */ - unsigned int GetOperCount(); + void SetFullVersion(const std::string& verstr) { fullversion = verstr; } - /** Increment or decrement the oper count by diff. + /** Sets the description of this server. Called when the description of a remote server changes + * and we are notified about it. + * @param descstr The description to set */ - void SetOperCount(int diff); + void SetDesc(const std::string& descstr) { description = descstr; } - /** Get the TreeSocket pointer for local servers. - * For remote servers, this returns NULL. + /** Return all child servers */ - TreeSocket* GetSocket(); + const ChildServers& GetChildren() const { return Children; } - /** Get the parent server. - * For the root node, this returns NULL. + /** Get server ID */ - TreeServer* GetParent(); + const std::string& GetID() const { return sid; } - /** Set the server version string + /** Marks a server as having finished bursting and performs appropriate actions. */ - void SetVersion(const std::string &Version); + void FinishBurst(); + /** Recursive call for child servers */ + void FinishBurstInternal(); - /** Return number of child servers + /** (Re)check the uline state of this server */ - unsigned int ChildCount(); + void CheckULine(); - /** Return a child server indexed 0..n + /** Get the bursting state of this server + * @return True if this server is bursting, false if it isn't */ - TreeServer* GetChild(unsigned int n); + bool IsBursting() const { return (StartBurst != 0); } - /** Add a child server + /** Check whether this server is behind a bursting server or is itself bursting. + * This can tell whether a user is on a part of the network that is still bursting. + * @return True if this server is bursting or is behind a server that is bursting, false if it isn't */ - void AddChild(TreeServer* Child); + bool IsBehindBursting() const { return (behind_bursting != 0); } - /** Delete a child server, return false if it didn't exist. + /** Set the bursting state of the server + * @param startms Time the server started bursting, if 0 or omitted, use current time */ - bool DelChild(TreeServer* Child); + void BeginBurst(unsigned long startms = 0); - /** Removes child nodes of this node, and of that node, etc etc. - * This is used during netsplits to automatically tidy up the - * server tree. It is slow, we don't use it for much else. + /** Register a PONG from the server */ - bool Tidy(); + void OnPong() { pingtimer.OnPong(); } - /** Get server ID - */ - const std::string& GetID(); + CullResult cull(); - /** Marks a server as having finished bursting and performs appropriate actions. + /** Destructor, deletes ServerUser unless IsRoot() */ - void FinishBurst(); - /** Recursive call for child servers */ - void FinishBurstInternal(); + ~TreeServer(); - CullResult cull(); - /** Destructor + /** Returns the TreeServer the given user is connected to + * @param user The user whose server to return + * @return The TreeServer this user is connected to. */ - ~TreeServer(); + static TreeServer* Get(User* user) + { + return static_cast<TreeServer*>(user->server); + } }; - -#endif diff --git a/src/modules/m_spanningtree/treesocket.h b/src/modules/m_spanningtree/treesocket.h index abda28335..4887623c1 100644 --- a/src/modules/m_spanningtree/treesocket.h +++ b/src/modules/m_spanningtree/treesocket.h @@ -20,12 +20,9 @@ */ -#ifndef M_SPANNINGTREE_TREESOCKET_H -#define M_SPANNINGTREE_TREESOCKET_H +#pragma once -#include "socket.h" #include "inspircd.h" -#include "xline.h" #include "utils.h" @@ -76,7 +73,7 @@ struct CapabData std::string ourchallenge; /* Challenge sent for challenge/response */ std::string theirchallenge; /* Challenge recv for challenge/response */ int capab_phase; /* Have sent CAPAB already */ - bool auth_fingerprint; /* Did we auth using SSL fingerprint */ + bool auth_fingerprint; /* Did we auth using SSL certificate fingerprint */ bool auth_challenge; /* Did we auth using challenge/response */ // Data saved from incoming SERVER command, for later use when our credentials have been accepted by the other party @@ -92,37 +89,92 @@ struct CapabData */ class TreeSocket : public BufferedSocket { - SpanningTreeUtilities* Utils; /* Utility class */ + struct BurstState; + std::string linkID; /* Description for this link */ ServerState LinkState; /* Link state */ CapabData* capab; /* Link setup data (held until burst is sent) */ TreeServer* MyRoot; /* The server we are talking to */ int proto_version; /* Remote protocol version */ - bool ConnectionFailureShown; /* Set to true if a connection failure message was shown */ + + /** True if we've sent our burst. + * This only changes the behavior of message translation for 1202 protocol servers and it can be + * removed once 1202 support is dropped. + */ + bool burstsent; /** Checks if the given servername and sid are both free */ bool CheckDuplicate(const std::string& servername, const std::string& sid); + /** Send all ListModeBase modes set on the channel + */ + void SendListModes(Channel* chan); + + /** Send all known information about a channel */ + void SyncChannel(Channel* chan, BurstState& bs); + + /** Send all users and their oper state, away state and metadata */ + void SendUsers(BurstState& bs); + + /** Send all additional info about the given server to this server */ + void SendServerInfo(TreeServer* from); + + /** Find the User source of a command given a prefix and a command string. + * This connection must be fully up when calling this function. + * @param prefix Prefix string to find the source User object for. Can be a sid, a uuid or a server name. + * @param command The command whose source to find. This is required because certain commands (like mode + * changes and kills) must be processed even if their claimed source doesn't exist. If the given command is + * such a command and the source does not exist, the function returns a valid FakeUser that can be used to + * to process the command with. + * @return The command source to use when processing the command or NULL if the source wasn't found. + * Note that the direction of the returned source is not verified. + */ + User* FindSource(const std::string& prefix, const std::string& command); + + /** Finish the authentication phase of this connection. + * Change the state of the connection to CONNECTED, create a TreeServer object for the server on the + * other end of the connection using the details provided in the parameters, and finally send a burst. + * @param remotename Name of the remote server + * @param remotesid SID of the remote server + * @param remotedesc Description of the remote server + * @param hidden True if the remote server is hidden according to the configuration + */ + void FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden); + + /** Authenticate the remote server. + * Validate the parameters and find the link block that matches the remote server. In case of an error, + * an appropriate snotice is generated, an ERROR message is sent and the connection is closed. + * Failing to find a matching link block counts as an error. + * @param params Parameters they sent in the SERVER command + * @return Link block for the remote server, or NULL if an error occurred + */ + Link* AuthRemote(const parameterlist& params); + + /** Write a line on this socket with a new line character appended, skipping all translation for old protocols + * @param line Line to write without a new line character at the end + */ + void WriteLineNoCompat(const std::string& line); + public: - time_t age; + const time_t age; /** Because most of the I/O gubbins are encapsulated within * BufferedSocket, we just call the superclass constructor for * most of the action, and append a few of our own values * to it. */ - TreeSocket(SpanningTreeUtilities* Util, Link* link, Autoconnect* myac, const std::string& ipaddr); + TreeSocket(Link* link, Autoconnect* myac, const std::string& ipaddr); /** When a listening socket gives us a new file descriptor, * we must associate it with a socket without creating a new * connection. This constructor is used for this purpose. */ - TreeSocket(SpanningTreeUtilities* Util, int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server); + TreeSocket(int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server); /** Get link state */ - ServerState GetLinkState(); + ServerState GetLinkState() const { return LinkState; } /** Get challenge set in our CAPAB for challenge/response */ @@ -164,11 +216,11 @@ class TreeSocket : public BufferedSocket * to server docs on the inspircd.org site, the other side * will then send back its own server string. */ - virtual void OnConnected(); + void OnConnected(); /** Handle socket error event */ - virtual void OnError(BufferedSocketError e); + void OnError(BufferedSocketError e) CXX11_OVERRIDE; /** Sends an error to the remote server, and displays it locally to show * that it was sent. @@ -178,13 +230,8 @@ class TreeSocket : public BufferedSocket /** Recursively send the server tree with distances as hops. * This is used during network burst to inform the other server * (and any of ITS servers too) of what servers we know about. - * If at any point any of these servers already exist on the other - * end, our connection may be terminated. The hopcounts given - * by this function are relative, this doesn't matter so long as - * they are all >1, as all the remote servers re-calculate them - * to be relative too, with themselves as hop 0. */ - void SendServers(TreeServer* Current, TreeServer* s, int hops); + void SendServers(TreeServer* Current, TreeServer* s); /** Returns module list as a string, filtered by filter * @param filter a module version bitmask, such as VF_COMMON or VF_OPTCOMMON @@ -195,32 +242,12 @@ class TreeSocket : public BufferedSocket */ void SendCapabilities(int phase); - /** Add modules to VF_COMMON list for backwards compatability */ - void CompatAddModules(std::vector<std::string>& modlist); - /* Isolate and return the elements that are different between two lists */ void ListDifference(const std::string &one, const std::string &two, char sep, std::string& mleft, std::string& mright); bool Capab(const parameterlist ¶ms); - /** This function forces this server to quit, removing this server - * and any users on it (and servers and users below that, etc etc). - * It's very slow and pretty clunky, but luckily unless your network - * is having a REAL bad hair day, this function shouldnt be called - * too many times a month ;-) - */ - void SquitServer(std::string &from, TreeServer* Current, int& num_lost_servers, int& num_lost_users); - - /** This is a wrapper function for SquitServer above, which - * does some validation first and passes on the SQUIT to all - * other remaining servers. - */ - void Squit(TreeServer* Current, const std::string &reason); - - /* Used on nick collision ... XXX ugly function HACK */ - int DoCollision(User *u, time_t remotets, const std::string &remoteident, const std::string &remoteip, const std::string &remoteuid); - /** Send one or more FJOINs for a channel of users. * If the length of a single line is more than 480-NICKMAX * in length, it is split over multiple lines. @@ -230,11 +257,8 @@ class TreeSocket : public BufferedSocket /** Send G, Q, Z and E lines */ void SendXLines(); - /** Send channel modes and topics */ - void SendChannelModes(); - - /** send all users and their oper state/modes */ - void SendUsers(); + /** Send all known information about a channel */ + void SyncChannel(Channel* chan); /** This function is called when we want to send a netburst to a local * server. There is a set order we must do this, because for example @@ -250,57 +274,11 @@ class TreeSocket : public BufferedSocket /** Send one or more complete lines down the socket */ - void WriteLine(std::string line); + void WriteLine(const std::string& line); /** Handle ERROR command */ void Error(parameterlist ¶ms); - /** Remote AWAY */ - bool Away(const std::string &prefix, parameterlist ¶ms); - - /** SAVE to resolve nick collisions without killing */ - bool ForceNick(const std::string &prefix, parameterlist ¶ms); - - /** ENCAP command - */ - void Encap(User* who, parameterlist ¶ms); - - /** OPERQUIT command - */ - bool OperQuit(const std::string &prefix, parameterlist ¶ms); - - /** PONG - */ - bool LocalPong(const std::string &prefix, parameterlist ¶ms); - - /** VERSION - */ - bool ServerVersion(const std::string &prefix, parameterlist ¶ms); - - /** ADDLINE - */ - bool AddLine(const std::string &prefix, parameterlist ¶ms); - - /** DELLINE - */ - bool DelLine(const std::string &prefix, parameterlist ¶ms); - - /** WHOIS - */ - bool Whois(const std::string &prefix, parameterlist ¶ms); - - /** PUSH - */ - bool Push(const std::string &prefix, parameterlist ¶ms); - - /** PING - */ - bool LocalPing(const std::string &prefix, parameterlist ¶ms); - - /** <- (remote) <- SERVER - */ - bool RemoteServer(const std::string &prefix, parameterlist ¶ms); - /** (local) -> SERVER */ bool Outbound_Reply_Server(parameterlist ¶ms); @@ -321,15 +299,12 @@ class TreeSocket : public BufferedSocket /** Handle socket timeout from connect() */ - virtual void OnTimeout(); + void OnTimeout(); /** Handle server quit on close */ - virtual void Close(); + void Close(); - /** Returns true if this server was introduced to the rest of the network + /** Fixes messages coming from old servers so the new command handlers understand them */ - bool Introduced(); + bool PreProcessOldProtocolMessage(User*& who, std::string& cmd, std::vector<std::string>& params); }; - -#endif - diff --git a/src/modules/m_spanningtree/treesocket1.cpp b/src/modules/m_spanningtree/treesocket1.cpp index c9729cc0f..025bd1e61 100644 --- a/src/modules/m_spanningtree/treesocket1.cpp +++ b/src/modules/m_spanningtree/treesocket1.cpp @@ -21,46 +21,30 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" +#include "iohook.h" #include "main.h" -#include "../spanningtree.h" +#include "modules/spanningtree.h" #include "utils.h" #include "treeserver.h" #include "link.h" #include "treesocket.h" -#include "resolvers.h" +#include "commands.h" /** Because most of the I/O gubbins are encapsulated within * BufferedSocket, we just call the superclass constructor for * most of the action, and append a few of our own values * to it. */ -TreeSocket::TreeSocket(SpanningTreeUtilities* Util, Link* link, Autoconnect* myac, const std::string& ipaddr) - : Utils(Util) +TreeSocket::TreeSocket(Link* link, Autoconnect* myac, const std::string& ipaddr) + : linkID(assign(link->Name)), LinkState(CONNECTING), MyRoot(NULL), proto_version(0) + , burstsent(false), age(ServerInstance->Time()) { - age = ServerInstance->Time(); - linkID = assign(link->Name); capab = new CapabData; capab->link = link; capab->ac = myac; capab->capab_phase = 0; - MyRoot = NULL; - proto_version = 0; - ConnectionFailureShown = false; - LinkState = CONNECTING; - if (!link->Hook.empty()) - { - ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_IOHOOK, link->Hook); - if (!prov) - { - SetError("Could not find hook '" + link->Hook + "' for connection to " + linkID); - return; - } - AddIOHook(prov->creator); - } + DoConnect(ipaddr, link->Port, link->Timeout, link->Bind); Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, link->Timeout); SendCapabilities(1); @@ -70,31 +54,21 @@ TreeSocket::TreeSocket(SpanningTreeUtilities* Util, Link* link, Autoconnect* mya * we must associate it with a socket without creating a new * connection. This constructor is used for this purpose. */ -TreeSocket::TreeSocket(SpanningTreeUtilities* Util, int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) - : BufferedSocket(newfd), Utils(Util) +TreeSocket::TreeSocket(int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) + : BufferedSocket(newfd) + , linkID("inbound from " + client->addr()), LinkState(WAIT_AUTH_1), MyRoot(NULL), proto_version(0) + , burstsent(false), age(ServerInstance->Time()) { capab = new CapabData; capab->capab_phase = 0; - MyRoot = NULL; - age = ServerInstance->Time(); - LinkState = WAIT_AUTH_1; - proto_version = 0; - ConnectionFailureShown = false; - linkID = "inbound from " + client->addr(); - FOREACH_MOD(I_OnHookIO, OnHookIO(this, via)); - if (GetIOHook()) - GetIOHook()->OnStreamSocketAccept(this, client, server); + if (via->iohookprov) + via->iohookprov->OnAccept(this, client, server); SendCapabilities(1); Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, 30); } -ServerState TreeSocket::GetLinkState() -{ - return this->LinkState; -} - void TreeSocket::CleanNegotiationInfo() { // connect is good, reset the autoconnect block (if used) @@ -114,8 +88,7 @@ CullResult TreeSocket::cull() TreeSocket::~TreeSocket() { - if (capab) - delete capab; + delete capab; } /** When an outbound connection finishes connecting, we receive @@ -128,6 +101,17 @@ void TreeSocket::OnConnected() { if (this->LinkState == CONNECTING) { + if (!capab->link->Hook.empty()) + { + ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_IOHOOK, capab->link->Hook); + if (!prov) + { + SetError("Could not find hook '" + capab->link->Hook + "' for connection to " + linkID); + return; + } + static_cast<IOHookProvider*>(prov)->OnConnect(this); + } + ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2[%s] started.", linkID.c_str(), (capab->link->HiddenFromStats ? "<hidden>" : capab->link->IPAddr.c_str())); this->SendCapabilities(1); @@ -139,6 +123,7 @@ void TreeSocket::OnError(BufferedSocketError e) ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed with error: %s", linkID.c_str(), getError().c_str()); LinkState = DYING; + Close(); } void TreeSocket::SendError(const std::string &errormessage) @@ -149,79 +134,31 @@ void TreeSocket::SendError(const std::string &errormessage) SetError(errormessage); } -/** This function forces this server to quit, removing this server - * and any users on it (and servers and users below that, etc etc). - * It's very slow and pretty clunky, but luckily unless your network - * is having a REAL bad hair day, this function shouldnt be called - * too many times a month ;-) - */ -void TreeSocket::SquitServer(std::string &from, TreeServer* Current, int& num_lost_servers, int& num_lost_users) +CmdResult CommandSQuit::HandleServer(TreeServer* server, std::vector<std::string>& params) { - std::string servername = Current->GetName(); - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"SquitServer for %s from %s", - servername.c_str(), from.c_str()); - /* recursively squit the servers attached to 'Current'. - * We're going backwards so we don't remove users - * while we still need them ;) - */ - for (unsigned int q = 0; q < Current->ChildCount(); q++) + TreeServer* quitting = Utils->FindServer(params[0]); + if (!quitting) { - TreeServer* recursive_server = Current->GetChild(q); - this->SquitServer(from,recursive_server, num_lost_servers, num_lost_users); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Squit from unknown server"); + return CMD_FAILURE; } - /* Now we've whacked the kids, whack self */ - num_lost_servers++; - num_lost_users += Current->QuitUsers(from); -} -/** This is a wrapper function for SquitServer above, which - * does some validation first and passes on the SQUIT to all - * other remaining servers. - */ -void TreeSocket::Squit(TreeServer* Current, const std::string &reason) -{ - bool LocalSquit = false; - - if ((Current) && (Current != Utils->TreeRoot)) + CmdResult ret = CMD_SUCCESS; + if (quitting == server) { - DelServerEvent(Utils->Creator, Current->GetName()); + ret = CMD_FAILURE; + server = server->GetParent(); + } + else if (quitting->GetParent() != server) + throw ProtocolException("Attempted to SQUIT a non-directly connected server or the parent"); - if (!Current->GetSocket() || Current->GetSocket()->Introduced()) - { - parameterlist params; - params.push_back(Current->GetID()); - params.push_back(":"+reason); - Utils->DoOneToAllButSender(Current->GetParent()->GetID(),"SQUIT",params,Current->GetID()); - } + server->SQuitChild(quitting, params[1]); - if (Current->GetParent() == Utils->TreeRoot) - { - ServerInstance->SNO->WriteGlobalSno('l', "Server \002"+Current->GetName()+"\002 split: "+reason); - LocalSquit = true; - } - else - { - ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason); - } - int num_lost_servers = 0; - int num_lost_users = 0; - std::string from = Current->GetParent()->GetName()+" "+Current->GetName(); - SquitServer(from, Current, num_lost_servers, num_lost_users); - ServerInstance->SNO->WriteToSnoMask(LocalSquit ? 'l' : 'L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.", - num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : ""); - Current->Tidy(); - Current->GetParent()->DelChild(Current); - Current->cull(); - const bool ismyroot = (Current == MyRoot); - delete Current; - if (ismyroot) - { - MyRoot = NULL; - Close(); - } - } - else - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server"); + // XXX: Return CMD_FAILURE when servers SQUIT themselves (i.e. :00S SQUIT 00S :Shutting down) + // to stop this message from being forwarded. + // The squit logic generates a SQUIT message with our sid as the source and sends it to the + // remaining servers. + return ret; } /** This function is called when we receive data from a remote @@ -235,13 +172,24 @@ void TreeSocket::OnDataReady() { std::string::size_type rline = line.find('\r'); if (rline != std::string::npos) - line = line.substr(0,rline); + line.erase(rline); if (line.find('\0') != std::string::npos) { SendError("Read null character from socket"); break; } - ProcessLine(line); + + try + { + ProcessLine(line); + } + catch (CoreException& ex) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error while processing: " + line); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason()); + SendError(ex.GetReason() + " - check the log file for details"); + } + if (!getError().empty()) break; } @@ -249,8 +197,3 @@ void TreeSocket::OnDataReady() SendError("RecvQ overrun (line too long)"); Utils->Creator->loopCall = false; } - -bool TreeSocket::Introduced() -{ - return (capab == NULL); -} diff --git a/src/modules/m_spanningtree/treesocket2.cpp b/src/modules/m_spanningtree/treesocket2.cpp index acb822fbf..1f98f7819 100644 --- a/src/modules/m_spanningtree/treesocket2.cpp +++ b/src/modules/m_spanningtree/treesocket2.cpp @@ -23,16 +23,13 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" #include "main.h" #include "utils.h" #include "treeserver.h" -#include "link.h" #include "treesocket.h" #include "resolvers.h" +#include "commands.h" /* Handle ERROR command */ void TreeSocket::Error(parameterlist ¶ms) @@ -47,10 +44,10 @@ void TreeSocket::Split(const std::string& line, std::string& prefix, std::string if (!tokens.GetToken(prefix)) return; - + if (prefix[0] == ':') { - prefix = prefix.substr(1); + prefix.erase(prefix.begin()); if (prefix.empty()) { @@ -84,7 +81,7 @@ void TreeSocket::ProcessLine(std::string &line) std::string command; parameterlist params; - ServerInstance->Logs->Log("m_spanningtree", RAWIO, "S[%d] I %s", this->GetFd(), line.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str()); Split(line, prefix, command, params); @@ -151,7 +148,7 @@ void TreeSocket::ProcessLine(std::string &line) { if (params.size()) { - time_t them = atoi(params[0].c_str()); + time_t them = ConvToInt(params[0]); time_t delta = them - ServerInstance->Time(); if ((delta < -600) || (delta > 600)) { @@ -171,25 +168,7 @@ void TreeSocket::ProcessLine(std::string &line) if (!CheckDuplicate(capab->name, capab->sid)) return; - this->LinkState = CONNECTED; - Utils->timeoutlist.erase(this); - - linkID = capab->name; - - MyRoot = new TreeServer(Utils, capab->name, capab->description, capab->sid, Utils->TreeRoot, this, capab->hidden); - Utils->TreeRoot->AddChild(MyRoot); - - MyRoot->bursting = true; - this->DoBurst(MyRoot); - - parameterlist sparams; - sparams.push_back(MyRoot->GetName()); - sparams.push_back("*"); - sparams.push_back("0"); - sparams.push_back(MyRoot->GetID()); - sparams.push_back(":" + MyRoot->GetDesc()); - Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot->GetName()); - Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot->GetName()); + FinishAuth(capab->name, capab->sid, capab->description, capab->hidden); } else if (command == "ERROR") { @@ -235,52 +214,53 @@ void TreeSocket::ProcessLine(std::string &line) } } -void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params) +User* TreeSocket::FindSource(const std::string& prefix, const std::string& command) { + // Empty prefix means the source is the directly connected server that sent this command + if (prefix.empty()) + return MyRoot->ServerUser; + + // If the prefix string is a uuid or a sid FindUUID() returns the appropriate User object User* who = ServerInstance->FindUUID(prefix); - std::string direction; + if (who) + return who; - if (!who) - { - TreeServer* ServerSource = Utils->FindServer(prefix); - if (prefix.empty()) - ServerSource = MyRoot; + // Some implementations wrongly send a server name as prefix occasionally, handle that too for now + TreeServer* const server = Utils->FindServer(prefix); + if (server) + return server->ServerUser; - if (ServerSource) - { - who = ServerSource->ServerUser; - } - else - { - /* It is important that we don't close the link here, unknown prefix can occur - * due to various race conditions such as the KILL message for a user somehow - * crossing the users QUIT further upstream from the server. Thanks jilles! - */ + /* It is important that we don't close the link here, unknown prefix can occur + * due to various race conditions such as the KILL message for a user somehow + * crossing the users QUIT further upstream from the server. Thanks jilles! + */ - if ((prefix.length() == UUID_LENGTH-1) && (isdigit(prefix[0])) && - ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE"))) - { - /* Special case, we cannot drop these commands as they've been committed already on a - * part of the network by the time we receive them, so in this scenario pretend the - * command came from a server to avoid desync. - */ + if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) && + ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE"))) + { + /* Special case, we cannot drop these commands as they've been committed already on a + * part of the network by the time we receive them, so in this scenario pretend the + * command came from a server to avoid desync. + */ - who = ServerInstance->FindUUID(prefix.substr(0, 3)); - if (!who) - who = this->MyRoot->ServerUser; - } - else - { - ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.", - command.c_str(), prefix.c_str()); - return; - } - } + who = ServerInstance->FindUUID(prefix.substr(0, 3)); + if (who) + return who; + return this->MyRoot->ServerUser; } - // Make sure prefix is still good - direction = who->server; - prefix = who->uuid; + // Unknown prefix + return NULL; +} + +void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params) +{ + User* who = FindSource(prefix, command); + if (!who) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.", command.c_str(), prefix.c_str()); + return; + } /* * Check for fake direction here, and drop any instances that are found. @@ -298,214 +278,63 @@ void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, * a valid SID or a valid UUID, so that invalid UUID or SID never makes it * to the higher level functions. -- B */ - TreeServer* route_back_again = Utils->BestRouteTo(direction); - if ((!route_back_again) || (route_back_again->GetSocket() != this)) + TreeServer* const server = TreeServer::Get(who); + if (server->GetSocket() != this) { - if (route_back_again) - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'", - prefix.c_str(),linkID.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Protocol violation: Fake direction '%s' from connection '%s'", prefix.c_str(), linkID.c_str()); return; } - /* - * First up, check for any malformed commands (e.g. MODE without a timestamp) - * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w - */ - if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels. - command = "MODE"; - - // TODO move all this into Commands - if (command == "MAP") - { - Utils->Creator->HandleMap(params, who); - } - else if (command == "SERVER") - { - this->RemoteServer(prefix,params); - } - else if (command == "ERROR") - { - this->Error(params); - } - else if (command == "AWAY") - { - this->Away(prefix,params); - } - else if (command == "PING") - { - this->LocalPing(prefix,params); - } - else if (command == "PONG") - { - TreeServer *s = Utils->FindServer(prefix); - if (s && s->bursting) - { - ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str()); - s->FinishBurst(); - } - this->LocalPong(prefix,params); - } - else if (command == "VERSION") - { - this->ServerVersion(prefix,params); - } - else if (command == "ADDLINE") - { - this->AddLine(prefix,params); - } - else if (command == "DELLINE") - { - this->DelLine(prefix,params); - } - else if (command == "SAVE") - { - this->ForceNick(prefix,params); - } - else if (command == "OPERQUIT") - { - this->OperQuit(prefix,params); - } - else if (command == "IDLE") - { - this->Whois(prefix,params); - } - else if (command == "PUSH") - { - this->Push(prefix,params); - } - else if (command == "SQUIT") - { - if (params.size() == 2) - { - this->Squit(Utils->FindServer(params[0]),params[1]); - } - } - else if (command == "SNONOTICE") - { - if (params.size() >= 2) - { - ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + who->nick + ": "+ params[1]); - params[1] = ":" + params[1]; - Utils->DoOneToAllButSender(prefix, command, params, prefix); - } - } - else if (command == "BURST") + // Translate commands coming from servers using an older protocol + if (proto_version < ProtocolVersion) { - // Set prefix server as bursting - TreeServer* ServerSource = Utils->FindServer(prefix); - if (!ServerSource) - { - ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str()); + if (!PreProcessOldProtocolMessage(who, command, params)) return; - } - - ServerSource->bursting = true; - Utils->DoOneToAllButSender(prefix, command, params, prefix); } - else if (command == "ENDBURST") - { - TreeServer* ServerSource = Utils->FindServer(prefix); - if (!ServerSource) - { - ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str()); - return; - } - ServerSource->FinishBurst(); - Utils->DoOneToAllButSender(prefix, command, params, prefix); - } - else if (command == "ENCAP") + ServerCommand* scmd = Utils->Creator->CmdManager.GetHandler(command); + CommandBase* cmdbase = scmd; + Command* cmd = NULL; + if (!scmd) { - this->Encap(who, params); - } - else if (command == "NICK") - { - if (params.size() != 2) - { - SendError("Protocol violation: Wrong number of parameters for NICK message"); - return; - } - - if (IS_SERVER(who)) - { - SendError("Protocol violation: Server changing nick"); - return; - } - - if ((isdigit(params[0][0])) && (params[0] != who->uuid)) - { - SendError("Protocol violation: User changing nick to an invalid UID - " + params[0]); - return; - } - - /* Update timestamp on user when they change nicks */ - who->age = atoi(params[1].c_str()); - - /* - * On nick messages, check that the nick doesnt already exist here. - * If it does, perform collision logic. - */ - bool callfnc = true; - User* x = ServerInstance->FindNickOnly(params[0]); - if ((x) && (x != who) && (x->registered == REG_ALL)) + // Not a special server-to-server command + cmd = ServerInstance->Parser.GetHandler(command); + if (!cmd) { - int collideret = 0; - /* x is local, who is remote */ - collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid); - if (collideret != 1) + if (command == "ERROR") { - // Remote client lost, or both lost, rewrite this nick change as a change to uuid before - // forwarding and don't call ForceNickChange() because DoCollision() has done it already - params[0] = who->uuid; - callfnc = false; + this->Error(params); + return; } - } - if (callfnc) - who->ForceNickChange(params[0].c_str()); - Utils->RouteCommand(route_back_again, command, params, who); - } - else - { - Command* cmd = ServerInstance->Parser->GetHandler(command); - - if (!cmd) - { - irc::stringjoiner pmlist(" ", params, 0, params.size() - 1); - ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Unrecognised S2S command :%s %s %s", - who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str()); - SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules"); - return; - } - if (params.size() < cmd->min_params) - { - irc::stringjoiner pmlist(" ", params, 0, params.size() - 1); - ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Insufficient parameters for S2S command :%s %s %s", - who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str()); - SendError("Insufficient parameters for command '" + command + "'"); - return; + throw ProtocolException("Unknown command"); } + cmdbase = cmd; + } - if ((!params.empty()) && (params.back().empty()) && (!cmd->allow_empty_last_param)) - { - // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last - if (params.size()-1 < cmd->min_params) - return; - params.pop_back(); - } + if (params.size() < cmdbase->min_params) + throw ProtocolException("Insufficient parameters"); - CmdResult res = cmd->Handle(params, who); + if ((!params.empty()) && (params.back().empty()) && (!cmdbase->allow_empty_last_param)) + { + // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last + if (params.size()-1 < cmdbase->min_params) + return; + params.pop_back(); + } + CmdResult res; + if (scmd) + res = scmd->Handle(who, params); + else + { + res = cmd->Handle(params, who); if (res == CMD_INVALID) - { - irc::stringjoiner pmlist(" ", params, 0, params.size() - 1); - ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Error handling S2S command :%s %s %s", - who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str()); - SendError("Error handling '" + command + "' -- possibly loaded mismatched modules"); - } - else if (res == CMD_SUCCESS) - Utils->RouteCommand(route_back_again, command, params, who); + throw ProtocolException("Error in command handler"); } + + if (res == CMD_SUCCESS) + Utils->RouteCommand(server->GetRoute(), cmdbase, params, who); } void TreeSocket::OnTimeout() @@ -515,8 +344,10 @@ void TreeSocket::OnTimeout() void TreeSocket::Close() { - if (fd != -1) - ServerInstance->GlobalCulls.AddItem(this); + if (fd < 0) + return; + + ServerInstance->GlobalCulls.AddItem(this); this->BufferedSocket::Close(); SetError("Remote host closed connection"); @@ -524,18 +355,30 @@ void TreeSocket::Close() // If the connection is fully up (state CONNECTED) // then propogate a netsplit to all peers. if (MyRoot) - Squit(MyRoot,getError()); + MyRoot->SQuit(getError()); - if (!ConnectionFailureShown) - { - ConnectionFailureShown = true; - ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str()); + ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str()); - time_t server_uptime = ServerInstance->Time() - this->age; - if (server_uptime) - { - std::string timestr = Utils->Creator->TimeToStr(server_uptime); - ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str()); - } + time_t server_uptime = ServerInstance->Time() - this->age; + if (server_uptime) + { + std::string timestr = ModuleSpanningTree::TimeToStr(server_uptime); + ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str()); } } + +void TreeSocket::FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden) +{ + this->LinkState = CONNECTED; + Utils->timeoutlist.erase(this); + + linkID = remotename; + + MyRoot = new TreeServer(remotename, remotedesc, remotesid, Utils->TreeRoot, this, hidden); + + // Mark the server as bursting + MyRoot->BeginBurst(); + this->DoBurst(MyRoot); + + CommandServer::Builder(MyRoot).Forward(MyRoot); +} diff --git a/src/modules/m_spanningtree/uid.cpp b/src/modules/m_spanningtree/uid.cpp index 6620dd13a..398573616 100644 --- a/src/modules/m_spanningtree/uid.cpp +++ b/src/modules/m_spanningtree/uid.cpp @@ -23,173 +23,152 @@ #include "commands.h" #include "utils.h" -#include "link.h" -#include "treesocket.h" #include "treeserver.h" -#include "resolvers.h" -CmdResult CommandUID::Handle(const parameterlist ¶ms, User* serversrc) +CmdResult CommandUID::HandleServer(TreeServer* remoteserver, std::vector<std::string>& params) { - SpanningTreeUtilities* Utils = ((ModuleSpanningTree*)(Module*)creator)->Utils; /** Do we have enough parameters: * 0 1 2 3 4 5 6 7 8 9 (n-1) * UID uuid age nick host dhost ident ip.string signon +modes (modepara) :gecos */ - time_t age_t = ConvToInt(params[1]); - time_t signon = ConvToInt(params[7]); + time_t age_t = ServerCommand::ExtractTS(params[1]); + time_t signon = ServerCommand::ExtractTS(params[7]); std::string empty; - std::string modestr(params[8]); + const std::string& modestr = params[8]; - TreeServer* remoteserver = Utils->FindServer(serversrc->server); - - if (!remoteserver) - return CMD_INVALID; /* Is this a valid UID, and not misrouted? */ - if (params[0].length() != 9 || params[0].substr(0,3) != serversrc->uuid) - return CMD_INVALID; + if (params[0].length() != UIDGenerator::UUID_LENGTH || params[0].compare(0, 3, remoteserver->GetID())) + throw ProtocolException("Bogus UUID"); /* Check parameters for validity before introducing the client, discovered by dmb */ - if (!age_t) - return CMD_INVALID; - if (!signon) - return CMD_INVALID; if (modestr[0] != '+') - return CMD_INVALID; - TreeSocket* sock = remoteserver->GetRoute()->GetSocket(); - - /* check for collision */ - User* const collideswith = ServerInstance->FindNickOnly(params[2]); + throw ProtocolException("Invalid mode string"); + // See if there is a nick collision + User* collideswith = ServerInstance->FindNickOnly(params[2]); if ((collideswith) && (collideswith->registered != REG_ALL)) { // User that the incoming user is colliding with is not fully registered, we force nick change the // unregistered user to their uuid and tell them what happened collideswith->WriteFrom(collideswith, "NICK %s", collideswith->uuid.c_str()); - collideswith->WriteNumeric(433, "%s %s :Nickname overruled.", collideswith->nick.c_str(), collideswith->nick.c_str()); + collideswith->WriteNumeric(ERR_NICKNAMEINUSE, "%s :Nickname overruled.", collideswith->nick.c_str()); // Clear the bit before calling User::ChangeNick() to make it NOT run the OnUserPostNick() hook collideswith->registered &= ~REG_NICK; - collideswith->ChangeNick(collideswith->uuid, true); + collideswith->ChangeNick(collideswith->uuid); } else if (collideswith) { - /* - * Nick collision. - */ - int collide = sock->DoCollision(collideswith, age_t, params[5], params[6], params[0]); - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"*** Collision on %s, collide=%d", params[2].c_str(), collide); + // The user on this side is registered, handle the collision + bool they_change = Utils->DoCollision(collideswith, remoteserver, age_t, params[5], params[6], params[0]); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Collision on %s %d", params[2].c_str(), they_change); - if (collide != 1) + if (they_change) { - /* remote client lost, make sure we change their nick for the hash too - * - * This alters the line that will be sent to other servers, which - * commands normally shouldn't do; hence the required const_cast. - */ - const_cast<parameterlist&>(params)[2] = params[0]; + // The client being introduced needs to change nick to uuid, change the nick in the message before + // processing/forwarding it. Also change the nick TS to CommandSave::SavedTimestamp. + age_t = CommandSave::SavedTimestamp; + params[1] = ConvToStr(CommandSave::SavedTimestamp); + params[2] = params[0]; } } /* IMPORTANT NOTE: For remote users, we pass the UUID in the constructor. This automatically * sets it up in the UUID hash for us. + * + * If the UUID already exists User::User() throws an exception which causes this connection to be closed. */ - User* _new = NULL; - try - { - _new = new RemoteUser(params[0], remoteserver->GetName()); - } - catch (...) - { - ServerInstance->Logs->Log("m_spanningtree", DEFAULT, "Duplicate UUID %s in client introduction", params[0].c_str()); - return CMD_INVALID; - } - (*(ServerInstance->Users->clientlist))[params[2]] = _new; + RemoteUser* _new = new RemoteUser(params[0], remoteserver); + ServerInstance->Users->clientlist[params[2]] = _new; _new->nick = params[2]; _new->host = params[3]; _new->dhost = params[4]; _new->ident = params[5]; - _new->fullname = params[params.size() - 1]; + _new->fullname = params.back(); _new->registered = REG_ALL; _new->signon = signon; _new->age = age_t; - /* we need to remove the + from the modestring, so we can do our stuff */ - std::string::size_type pos_after_plus = modestr.find_first_not_of('+'); - if (pos_after_plus != std::string::npos) - modestr = modestr.substr(pos_after_plus); - unsigned int paramptr = 9; - for (std::string::iterator v = modestr.begin(); v != modestr.end(); v++) + + for (std::string::const_iterator v = modestr.begin(); v != modestr.end(); ++v) { - /* For each mode thats set, increase counter */ + // Accept more '+' chars, for now + if (*v == '+') + continue; + + /* For each mode thats set, find the mode handler and set it on the new user */ ModeHandler* mh = ServerInstance->Modes->FindMode(*v, MODETYPE_USER); + if (!mh) + throw ProtocolException("Unrecognised mode '" + std::string(1, *v) + "'"); - if (mh) + if (mh->GetNumParams(true)) { - if (mh->GetNumParams(true)) - { - if (paramptr >= params.size() - 1) - return CMD_INVALID; - std::string mp = params[paramptr++]; - /* IMPORTANT NOTE: - * All modes are assumed to succeed here as they are being set by a remote server. - * Modes CANNOT FAIL here. If they DO fail, then the failure is ignored. This is important - * to note as all but one modules currently cannot ever fail in this situation, except for - * m_servprotect which specifically works this way to prevent the mode being set ANYWHERE - * but here, at client introduction. You may safely assume this behaviour is standard and - * will not change in future versions if you want to make use of this protective behaviour - * yourself. - */ - mh->OnModeChange(_new, _new, NULL, mp, true); - } - else - mh->OnModeChange(_new, _new, NULL, empty, true); - _new->SetMode(*v, true); + if (paramptr >= params.size() - 1) + throw ProtocolException("Out of parameters while processing modes"); + std::string mp = params[paramptr++]; + /* IMPORTANT NOTE: + * All modes are assumed to succeed here as they are being set by a remote server. + * Modes CANNOT FAIL here. If they DO fail, then the failure is ignored. This is important + * to note as all but one modules currently cannot ever fail in this situation, except for + * m_servprotect which specifically works this way to prevent the mode being set ANYWHERE + * but here, at client introduction. You may safely assume this behaviour is standard and + * will not change in future versions if you want to make use of this protective behaviour + * yourself. + */ + mh->OnModeChange(_new, _new, NULL, mp, true); } + else + mh->OnModeChange(_new, _new, NULL, empty, true); + _new->SetMode(mh, true); } - /* now we've done with modes processing, put the + back for remote servers */ - if (modestr[0] != '+') - modestr = "+" + modestr; - _new->SetClientIP(params[6].c_str()); - ServerInstance->Users->AddGlobalClone(_new); - remoteserver->SetUserCount(1); // increment by 1 + ServerInstance->Users->AddClone(_new); + remoteserver->UserCount++; bool dosend = true; - if ((Utils->quiet_bursts && remoteserver->bursting) || ServerInstance->SilentULine(_new->server)) + if ((Utils->quiet_bursts && remoteserver->IsBehindBursting()) || _new->server->IsSilentULine()) dosend = false; if (dosend) - ServerInstance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s (%s) [%s]", _new->server.c_str(), _new->GetFullRealHost().c_str(), _new->GetIPString(), _new->fullname.c_str()); + ServerInstance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s (%s) [%s]", remoteserver->GetName().c_str(), _new->GetFullRealHost().c_str(), _new->GetIPString().c_str(), _new->fullname.c_str()); - FOREACH_MOD(I_OnPostConnect,OnPostConnect(_new)); + FOREACH_MOD(OnPostConnect, (_new)); return CMD_SUCCESS; } -CmdResult CommandFHost::Handle(const parameterlist ¶ms, User* src) +CmdResult CommandFHost::HandleRemote(RemoteUser* src, std::vector<std::string>& params) { - if (IS_SERVER(src)) - return CMD_FAILURE; - src->ChangeDisplayedHost(params[0].c_str()); + src->ChangeDisplayedHost(params[0]); return CMD_SUCCESS; } -CmdResult CommandFIdent::Handle(const parameterlist ¶ms, User* src) +CmdResult CommandFIdent::HandleRemote(RemoteUser* src, std::vector<std::string>& params) { - if (IS_SERVER(src)) - return CMD_FAILURE; - src->ChangeIdent(params[0].c_str()); + src->ChangeIdent(params[0]); return CMD_SUCCESS; } -CmdResult CommandFName::Handle(const parameterlist ¶ms, User* src) +CmdResult CommandFName::HandleRemote(RemoteUser* src, std::vector<std::string>& params) { - if (IS_SERVER(src)) - return CMD_FAILURE; - src->ChangeName(params[0].c_str()); + src->ChangeName(params[0]); return CMD_SUCCESS; } +CommandUID::Builder::Builder(User* user) + : CmdBuilder(TreeServer::Get(user)->GetID(), "UID") +{ + push(user->uuid); + push_int(user->age); + push(user->nick); + push(user->host); + push(user->dhost); + push(user->ident); + push(user->GetIPString()); + push_int(user->signon); + push('+').push_raw(user->FormatModes(true)); + push_last(user->fullname); +} diff --git a/src/modules/m_spanningtree/utils.cpp b/src/modules/m_spanningtree/utils.cpp index 367a3b921..d81bfa934 100644 --- a/src/modules/m_spanningtree/utils.cpp +++ b/src/modules/m_spanningtree/utils.cpp @@ -21,16 +21,15 @@ #include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" #include "main.h" #include "utils.h" #include "treeserver.h" -#include "link.h" #include "treesocket.h" #include "resolvers.h" +#include "commandbuilder.h" + +SpanningTreeUtilities* Utils = NULL; /* Create server sockets off a listener. */ ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) @@ -45,7 +44,7 @@ ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from if (*i == "*" || *i == incomingip || irc::sockets::cidr_mask(*i).match(*client)) { /* we don't need to do anything with the pointer, creating it stores it in the necessary places */ - new TreeSocket(Utils, newsock, from, client, server); + new TreeSocket(newsock, from, client, server); return MOD_RES_ALLOW; } } @@ -61,10 +60,10 @@ ModResult ModuleSpanningTree::OnAcceptConnection(int newsock, ListenSocket* from */ TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName) { - if (ServerInstance->IsSID(ServerName)) + if (InspIRCd::IsSID(ServerName)) return this->FindServerID(ServerName); - server_hash::iterator iter = serverlist.find(ServerName.c_str()); + server_hash::iterator iter = serverlist.find(ServerName); if (iter != serverlist.end()) { return iter->second; @@ -83,8 +82,6 @@ TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName) */ TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName) { - if (ServerName.c_str() == TreeRoot->GetName() || ServerName == ServerInstance->Config->GetSID()) - return NULL; TreeServer* Found = FindServer(ServerName); if (Found) { @@ -96,9 +93,7 @@ TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName) User *u = ServerInstance->FindNick(ServerName); if (u) { - Found = FindServer(u->server); - if (Found) - return Found->GetRoute(); + return TreeServer::Get(u)->GetRoute(); } return NULL; @@ -130,24 +125,19 @@ TreeServer* SpanningTreeUtilities::FindServerID(const std::string &id) return NULL; } -SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) : Creator(C) +SpanningTreeUtilities::SpanningTreeUtilities(ModuleSpanningTree* C) + : Creator(C), TreeRoot(NULL) { - ServerInstance->Logs->Log("m_spanningtree",DEBUG,"***** Using SID for hash: %s *****", ServerInstance->Config->GetSID().c_str()); - - this->TreeRoot = new TreeServer(this, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc, ServerInstance->Config->GetSID()); - this->ReadConfiguration(); + ServerInstance->Timers.AddTimer(&RefreshTimer); } CullResult SpanningTreeUtilities::cull() { - while (TreeRoot->ChildCount()) + const TreeServer::ChildServers& children = TreeRoot->GetChildren(); + while (!children.empty()) { - TreeServer* child_server = TreeRoot->GetChild(0); - if (child_server) - { - TreeSocket* sock = child_server->GetSocket(); - sock->Close(); - } + TreeSocket* sock = children.front()->GetSocket(); + sock->Close(); } for(std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = timeoutlist.begin(); i != timeoutlist.end(); ++i) @@ -165,26 +155,19 @@ SpanningTreeUtilities::~SpanningTreeUtilities() delete TreeRoot; } -void SpanningTreeUtilities::AddThisServer(TreeServer* server, TreeServerList &list) -{ - if (list.find(server) == list.end()) - list[server] = server; -} - /* returns a list of DIRECT servernames for a specific channel */ -void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list) +void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list) { unsigned int minrank = 0; if (status) { - ModeHandler* mh = ServerInstance->Modes->FindPrefix(status); + PrefixMode* mh = ServerInstance->Modes->FindPrefix(status); if (mh) minrank = mh->GetPrefixRank(); } - const UserMembList *ulist = c->GetUsers(); - - for (UserMembCIter i = ulist->begin(); i != ulist->end(); i++) + const Channel::MemberMap& ulist = c->GetUsers(); + for (Channel::MemberMap::const_iterator i = ulist.begin(); i != ulist.end(); ++i) { if (IS_LOCAL(i->first)) continue; @@ -194,86 +177,45 @@ void SpanningTreeUtilities::GetListOfServersForChannel(Channel* c, TreeServerLis if (exempt_list.find(i->first) == exempt_list.end()) { - TreeServer* best = this->BestRouteTo(i->first->server); - if (best) - AddThisServer(best,list); + TreeServer* best = TreeServer::Get(i->first); + list.insert(best->GetSocket()); } } return; } -bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, const parameterlist ¶ms, const std::string& omit) +void SpanningTreeUtilities::DoOneToAllButSender(const CmdBuilder& params, TreeServer* omitroute) { - TreeServer* omitroute = this->BestRouteTo(omit); - std::string FullLine = ":" + prefix + " " + command; - unsigned int words = params.size(); - for (unsigned int x = 0; x < words; x++) - { - FullLine = FullLine + " " + params[x]; - } - unsigned int items = this->TreeRoot->ChildCount(); - for (unsigned int x = 0; x < items; x++) + const std::string& FullLine = params.str(); + + const TreeServer::ChildServers& children = TreeRoot->GetChildren(); + for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i) { - TreeServer* Route = this->TreeRoot->GetChild(x); - // Send the line IF: - // The route has a socket (its a direct connection) - // The route isnt the one to be omitted - // The route isnt the path to the one to be omitted - if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route)) + TreeServer* Route = *i; + // Send the line if the route isn't the path to the one to be omitted + if (Route != omitroute) { - TreeSocket* Sock = Route->GetSocket(); - if (Sock) - Sock->WriteLine(FullLine); + Route->GetSocket()->WriteLine(FullLine); } } - return true; } -bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist ¶ms) +bool SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, const std::string& target) { - std::string FullLine = ":" + prefix + " " + command; - unsigned int words = params.size(); - for (unsigned int x = 0; x < words; x++) - { - FullLine = FullLine + " " + params[x]; - } - unsigned int items = this->TreeRoot->ChildCount(); - for (unsigned int x = 0; x < items; x++) - { - TreeServer* Route = this->TreeRoot->GetChild(x); - if (Route && Route->GetSocket()) - { - TreeSocket* Sock = Route->GetSocket(); - if (Sock) - Sock->WriteLine(FullLine); - } - } + TreeServer* Route = this->BestRouteTo(target); + if (!Route) + return false; + + DoOneToOne(params, Route); return true; } -bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, const parameterlist ¶ms, const std::string& target) +void SpanningTreeUtilities::DoOneToOne(const CmdBuilder& params, Server* server) { - TreeServer* Route = this->BestRouteTo(target); - if (Route) - { - std::string FullLine = ":" + prefix + " " + command; - unsigned int words = params.size(); - for (unsigned int x = 0; x < words; x++) - { - FullLine = FullLine + " " + params[x]; - } - if (Route && Route->GetSocket()) - { - TreeSocket* Sock = Route->GetSocket(); - if (Sock) - Sock->WriteLine(FullLine); - } - return true; - } - else - { - return false; - } + TreeServer* ts = static_cast<TreeServer*>(server); + TreeSocket* sock = ts->GetSocket(); + if (sock) + sock->WriteLine(params); } void SpanningTreeUtilities::RefreshIPCache() @@ -284,28 +226,27 @@ void SpanningTreeUtilities::RefreshIPCache() Link* L = *i; if (!L->Port) { - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"m_spanningtree: Ignoring a link block without a port."); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Ignoring a link block without a port."); /* Invalid link block */ continue; } - if (L->AllowMask.length()) - ValidIPs.push_back(L->AllowMask); + ValidIPs.insert(ValidIPs.end(), L->AllowMasks.begin(), L->AllowMasks.end()); irc::sockets::sockaddrs dummy; bool ipvalid = irc::sockets::aptosa(L->IPAddr, L->Port, dummy); if ((L->IPAddr == "*") || (ipvalid)) ValidIPs.push_back(L->IPAddr); - else + else if (this->Creator->DNS) { + SecurityIPResolver* sr = new SecurityIPResolver(Creator, *this->Creator->DNS, L->IPAddr, L, DNS::QUERY_AAAA); try { - bool cached = false; - SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA); - ServerInstance->AddResolver(sr, cached); + this->Creator->DNS->Process(sr); } - catch (...) + catch (DNS::Exception &) { + delete sr; } } } @@ -319,7 +260,6 @@ void SpanningTreeUtilities::ReadConfiguration() HideULines = security->getBool("hideulines"); AnnounceTSChange = options->getBool("announcets"); AllowOptCommon = options->getBool("allowmismatch"); - ChallengeResponse = !security->getBool("disablehmac"); quiet_bursts = ServerInstance->Config->ConfValue("performance")->getBool("quietbursts"); PingWarnTime = options->getInt("pingwarning"); PingFreq = options->getInt("serverpingfreq"); @@ -339,14 +279,18 @@ void SpanningTreeUtilities::ReadConfiguration() reference<Link> L = new Link(tag); std::string linkname = tag->getString("name"); L->Name = linkname.c_str(); - L->AllowMask = tag->getString("allowmask"); + + irc::spacesepstream sep = tag->getString("allowmask"); + for (std::string s; sep.GetToken(s);) + L->AllowMasks.push_back(s); + L->IPAddr = tag->getString("ipaddr"); L->Port = tag->getInt("port"); L->SendPass = tag->getString("sendpass", tag->getString("password")); L->RecvPass = tag->getString("recvpass", tag->getString("password")); L->Fingerprint = tag->getString("fingerprint"); L->HiddenFromStats = tag->getBool("statshidden"); - L->Timeout = tag->getInt("timeout", 30); + L->Timeout = tag->getDuration("timeout", 30); L->Hook = tag->getString("ssl"); L->Bind = tag->getString("bind"); L->Hidden = tag->getBool("hidden"); @@ -357,8 +301,8 @@ void SpanningTreeUtilities::ReadConfiguration() if (L->Name.find('.') == std::string::npos) throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it must contain at least one '.' character"); - if (L->Name.length() > 64) - throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than 64 characters"); + if (L->Name.length() > ServerInstance->Config->Limits.MaxHost) + throw ModuleException("The link name '"+assign(L->Name)+"' is invalid as it is longer than " + ConvToStr(ServerInstance->Config->Limits.MaxHost) + " characters"); if (L->RecvPass.empty()) throw ModuleException("Invalid configuration for server '"+assign(L->Name)+"', recvpass not defined"); @@ -375,11 +319,11 @@ void SpanningTreeUtilities::ReadConfiguration() if (L->IPAddr.empty()) { L->IPAddr = "*"; - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block '" + assign(L->Name) + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want."); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + assign(L->Name) + "' has no IP defined! This will allow any IP to connect as this server, and MAY not be what you want."); } if (!L->Port) - ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it."); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Configuration warning: Link block '" + assign(L->Name) + "' has no port defined, you will not be able to /connect it."); L->Fingerprint.erase(std::remove(L->Fingerprint.begin(), L->Fingerprint.end(), ':'), L->Fingerprint.end()); LinkBlocks.push_back(L); @@ -390,7 +334,7 @@ void SpanningTreeUtilities::ReadConfiguration() { ConfigTag* tag = i->second; reference<Autoconnect> A = new Autoconnect(tag); - A->Period = tag->getInt("period"); + A->Period = tag->getDuration("period", 60, 1); A->NextConnectTime = ServerInstance->Time() + A->Period; A->position = -1; irc::spacesepstream ss(tag->getString("server")); @@ -400,11 +344,6 @@ void SpanningTreeUtilities::ReadConfiguration() A->servers.push_back(server); } - if (A->Period <= 0) - { - throw ModuleException("Invalid configuration for autoconnect, period not a positive integer!"); - } - if (A->servers.empty()) { throw ModuleException("Invalid configuration for autoconnect, server cannot be empty!"); @@ -413,6 +352,9 @@ void SpanningTreeUtilities::ReadConfiguration() AutoconnectBlocks.push_back(A); } + for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i) + i->second->CheckULine(); + RefreshIPCache(); } @@ -429,15 +371,20 @@ Link* SpanningTreeUtilities::FindLink(const std::string& name) return NULL; } -void SpanningTreeUtilities::Rehash() +void SpanningTreeUtilities::SendChannelMessage(const std::string& prefix, Channel* target, const std::string& text, char status, const CUList& exempt_list, const char* message_type, TreeSocket* omit) { - server_hash temp; - for (server_hash::const_iterator i = serverlist.begin(); i != serverlist.end(); ++i) - temp.insert(std::make_pair(i->first, i->second)); - serverlist.swap(temp); - temp.clear(); - - for (server_hash::const_iterator i = sidlist.begin(); i != sidlist.end(); ++i) - temp.insert(std::make_pair(i->first, i->second)); - sidlist.swap(temp); + CmdBuilder msg(prefix, message_type); + msg.push_raw(' '); + if (status != 0) + msg.push_raw(status); + msg.push_raw(target->name).push_last(text); + + TreeSocketSet list; + this->GetListOfServersForChannel(target, list, status, exempt_list); + for (TreeSocketSet::iterator i = list.begin(); i != list.end(); ++i) + { + TreeSocket* Sock = *i; + if (Sock != omit) + Sock->WriteLine(msg); + } } diff --git a/src/modules/m_spanningtree/utils.h b/src/modules/m_spanningtree/utils.h index 5559b3459..3a419e2a4 100644 --- a/src/modules/m_spanningtree/utils.h +++ b/src/modules/m_spanningtree/utils.h @@ -20,10 +20,10 @@ */ -#ifndef M_SPANNINGTREE_UTILS_H -#define M_SPANNINGTREE_UTILS_H +#pragma once #include "inspircd.h" +#include "cachetimer.h" /* Foward declarations */ class TreeServer; @@ -32,24 +32,24 @@ class Link; class Autoconnect; class ModuleSpanningTree; class SpanningTreeUtilities; +class CmdBuilder; + +extern SpanningTreeUtilities* Utils; /* This hash_map holds the hash equivalent of the server * tree, used for rapid linear lookups. */ -#ifdef HASHMAP_DEPRECATED - typedef nspace::hash_map<std::string, TreeServer*, nspace::insensitive, irc::StrHashComp> server_hash; -#else - typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<std::string>, irc::StrHashComp> server_hash; -#endif - -typedef std::map<TreeServer*,TreeServer*> TreeServerList; +typedef TR1NS::unordered_map<std::string, TreeServer*, irc::insensitive, irc::StrHashComp> server_hash; /** Contains helper functions and variables for this module, * and keeps them out of the global namespace */ class SpanningTreeUtilities : public classbase { + CacheRefreshTimer RefreshTimer; + public: + typedef std::set<TreeSocket*> TreeSocketSet; typedef std::map<TreeSocket*, std::pair<std::string, int> > TimeoutList; /** Creator module @@ -100,14 +100,6 @@ class SpanningTreeUtilities : public classbase */ std::vector<reference<Autoconnect> > AutoconnectBlocks; - /** True (default) if we are to use challenge-response HMAC - * to authenticate passwords. - * - * NOTE: This defaults to on, but should be turned off if - * you are linking to an older version of inspircd. - */ - bool ChallengeResponse; - /** Ping frequency of server to server links */ int PingFreq; @@ -124,31 +116,32 @@ class SpanningTreeUtilities : public classbase */ ~SpanningTreeUtilities(); - void RouteCommand(TreeServer*, const std::string&, const parameterlist&, User*); + void RouteCommand(TreeServer* origin, CommandBase* cmd, const parameterlist& parameters, User* user); /** Send a message from this server to one other local or remote */ - bool DoOneToOne(const std::string &prefix, const std::string &command, const parameterlist ¶ms, const std::string& target); + bool DoOneToOne(const CmdBuilder& params, const std::string& target); + void DoOneToOne(const CmdBuilder& params, Server* target); /** Send a message from this server to all but one other, local or remote */ - bool DoOneToAllButSender(const std::string &prefix, const std::string &command, const parameterlist ¶ms, const std::string& omit); + void DoOneToAllButSender(const CmdBuilder& params, TreeServer* omit); /** Send a message from this server to all others */ - bool DoOneToMany(const std::string &prefix, const std::string &command, const parameterlist ¶ms); + void DoOneToMany(const CmdBuilder& params); /** Read the spanningtree module's tags from the config file */ void ReadConfiguration(); - /** Add a server to the server list for GetListOfServersForChannel + /** Handle nick collision */ - void AddThisServer(TreeServer* server, TreeServerList &list); + bool DoCollision(User* u, TreeServer* server, time_t remotets, const std::string& remoteident, const std::string& remoteip, const std::string& remoteuid); /** Compile a list of servers which contain members of channel c */ - void GetListOfServersForChannel(Channel* c, TreeServerList &list, char status, const CUList &exempt_list); + void GetListOfServersForChannel(Channel* c, TreeSocketSet& list, char status, const CUList& exempt_list); /** Find a server by name */ @@ -174,10 +167,12 @@ class SpanningTreeUtilities : public classbase */ void RefreshIPCache(); - /** Recreate serverlist and sidlist, this is needed because of m_nationalchars changing - * national_case_insensitive_map which is used by the hash function + /** Sends a PRIVMSG or a NOTICE to a channel obeying an exempt list and an optional prefix */ - void Rehash(); + void SendChannelMessage(const std::string& prefix, Channel* target, const std::string& text, char status, const CUList& exempt_list, const char* message_type, TreeSocket* omit = NULL); }; -#endif +inline void SpanningTreeUtilities::DoOneToMany(const CmdBuilder& params) +{ + DoOneToAllButSender(params, NULL); +} diff --git a/src/modules/m_spanningtree/version.cpp b/src/modules/m_spanningtree/version.cpp deleted file mode 100644 index e08d13e6e..000000000 --- a/src/modules/m_spanningtree/version.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#include "inspircd.h" -#include "socket.h" -#include "xline.h" -#include "socketengine.h" - -#include "main.h" -#include "utils.h" -#include "treeserver.h" -#include "treesocket.h" - -/* $ModDep: m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/treesocket.h */ - -bool TreeSocket::ServerVersion(const std::string &prefix, parameterlist ¶ms) -{ - if (params.size() < 1) - return true; - - TreeServer* ServerSource = Utils->FindServer(prefix); - - if (ServerSource) - { - ServerSource->SetVersion(params[0]); - } - params[0] = ":" + params[0]; - Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix); - return true; -} - diff --git a/src/modules/m_sqlauth.cpp b/src/modules/m_sqlauth.cpp index df97145be..1a5b68dd9 100644 --- a/src/modules/m_sqlauth.cpp +++ b/src/modules/m_sqlauth.cpp @@ -18,10 +18,9 @@ #include "inspircd.h" -#include "sql.h" -#include "hash.h" - -/* $ModDesc: Allow/Deny connections based upon an arbitrary SQL table */ +#include "modules/sql.h" +#include "modules/hash.h" +#include "modules/ssl.h" enum AuthState { AUTH_STATE_NONE = 0, @@ -39,8 +38,8 @@ class AuthQuery : public SQLQuery : SQLQuery(me), uid(u), pendingExt(e), verbose(v) { } - - void OnResult(SQLResult& res) + + void OnResult(SQLResult& res) CXX11_OVERRIDE { User* user = ServerInstance->FindNick(uid); if (!user) @@ -57,7 +56,7 @@ class AuthQuery : public SQLQuery } } - void OnError(SQLerror& error) + void OnError(SQLerror& error) CXX11_OVERRIDE { User* user = ServerInstance->FindNick(uid); if (!user) @@ -79,19 +78,13 @@ class ModuleSQLAuth : public Module bool verbose; public: - ModuleSQLAuth() : pendingExt("sqlauth-wait", this), SQL(this, "SQL") - { - } - - void init() + ModuleSQLAuth() + : pendingExt("sqlauth-wait", ExtensionItem::EXT_USER, this) + , SQL(this, "SQL") { - ServerInstance->Modules->AddService(pendingExt); - OnRehash(NULL); - Implementation eventlist[] = { I_OnCheckReady, I_OnRehash, I_OnUserRegister }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* conf = ServerInstance->Config->ConfValue("sqlauth"); std::string dbid = conf->getString("dbid"); @@ -105,7 +98,7 @@ class ModuleSQLAuth : public Module verbose = conf->getBool("verbose"); } - ModResult OnUserRegister(LocalUser* user) + ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE { // Note this is their initial (unresolved) connect block ConfigTag* tag = user->MyClass->config; @@ -133,18 +126,21 @@ class ModuleSQLAuth : public Module HashProvider* md5 = ServerInstance->Modules->FindDataService<HashProvider>("hash/md5"); if (md5) - userinfo["md5pass"] = md5->hexsum(user->password); + userinfo["md5pass"] = md5->Generate(user->password); HashProvider* sha256 = ServerInstance->Modules->FindDataService<HashProvider>("hash/sha256"); if (sha256) - userinfo["sha256pass"] = sha256->hexsum(user->password); + userinfo["sha256pass"] = sha256->Generate(user->password); + + const std::string certfp = SSLClientCert::GetFingerprint(&user->eh); + userinfo["certfp"] = certfp; SQL->submit(new AuthQuery(this, user->uuid, pendingExt, verbose), freeformquery, userinfo); return MOD_RES_PASSTHRU; } - ModResult OnCheckReady(LocalUser* user) + ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE { switch (pendingExt.get(user)) { @@ -159,7 +155,7 @@ class ModuleSQLAuth : public Module return MOD_RES_PASSTHRU; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allow/Deny connections based upon an arbitrary SQL table", VF_VENDOR); } diff --git a/src/modules/m_sqloper.cpp b/src/modules/m_sqloper.cpp index ae581cc4b..b5f0d6c47 100644 --- a/src/modules/m_sqloper.cpp +++ b/src/modules/m_sqloper.cpp @@ -18,24 +18,8 @@ #include "inspircd.h" -#include "sql.h" -#include "hash.h" - -/* $ModDesc: Allows storage of oper credentials in an SQL table */ - -static bool OneOfMatches(const char* host, const char* ip, const std::string& hostlist) -{ - std::stringstream hl(hostlist); - std::string xhost; - while (hl >> xhost) - { - if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map)) - { - return true; - } - } - return false; -} +#include "modules/sql.h" +#include "modules/hash.h" class OpMeQuery : public SQLQuery { @@ -46,9 +30,9 @@ class OpMeQuery : public SQLQuery { } - void OnResult(SQLResult& res) + void OnResult(SQLResult& res) CXX11_OVERRIDE { - ServerInstance->Logs->Log("m_sqloper",DEBUG, "SQLOPER: result for %s", uid.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "result for %s", uid.c_str()); User* user = ServerInstance->FindNick(uid); if (!user) return; @@ -57,30 +41,17 @@ class OpMeQuery : public SQLQuery SQLEntries row; while (res.GetRow(row)) { -#if 0 - parameterlist cols; - res.GetCols(cols); - - std::vector<KeyVal>* items; - reference<ConfigTag> tag = ConfigTag::create("oper", "<m_sqloper>", 0, items); - for(unsigned int i=0; i < cols.size(); i++) - { - if (!row[i].nul) - items->insert(std::make_pair(cols[i], row[i])); - } -#else if (OperUser(user, row[0], row[1])) return; -#endif } - ServerInstance->Logs->Log("m_sqloper",DEBUG, "SQLOPER: no matches for %s (checked %d rows)", uid.c_str(), res.Rows()); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "no matches for %s (checked %d rows)", uid.c_str(), res.Rows()); // nobody succeeded... fall back to OPER fallback(); } - void OnError(SQLerror& error) + void OnError(SQLerror& error) CXX11_OVERRIDE { - ServerInstance->Logs->Log("m_sqloper",DEFAULT, "SQLOPER: query failed (%s)", error.Str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "query failed (%s)", error.Str()); fallback(); } @@ -90,7 +61,7 @@ class OpMeQuery : public SQLQuery if (!user) return; - Command* oper_command = ServerInstance->Parser->GetHandler("OPER"); + Command* oper_command = ServerInstance->Parser.GetHandler("OPER"); if (oper_command) { @@ -101,16 +72,16 @@ class OpMeQuery : public SQLQuery } else { - ServerInstance->Logs->Log("m_sqloper",SPARSE, "BUG: WHAT?! Why do we have no OPER command?!"); + ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "BUG: WHAT?! Why do we have no OPER command?!"); } } bool OperUser(User* user, const std::string &pattern, const std::string &type) { - OperIndex::iterator iter = ServerInstance->Config->oper_blocks.find(" " + type); - if (iter == ServerInstance->Config->oper_blocks.end()) + ServerConfig::OperIndex::const_iterator iter = ServerInstance->Config->OperTypes.find(type); + if (iter == ServerInstance->Config->OperTypes.end()) { - ServerInstance->Logs->Log("m_sqloper",DEFAULT, "SQLOPER: bad type '%s' in returned row for oper %s", type.c_str(), username.c_str()); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "bad type '%s' in returned row for oper %s", type.c_str(), username.c_str()); return false; } OperInfo* ifo = iter->second; @@ -119,7 +90,7 @@ class OpMeQuery : public SQLQuery hostname.append("@").append(user->host); - if (OneOfMatches(hostname.c_str(), user->GetIPString(), pattern)) + if (InspIRCd::MatchMask(pattern, hostname, user->GetIPString())) { /* Opertype and host match, looks like this is it. */ @@ -140,15 +111,7 @@ class ModuleSQLOper : public Module public: ModuleSQLOper() : SQL(this, "SQL") {} - void init() - { - OnRehash(NULL); - - Implementation eventlist[] = { I_OnRehash, I_OnPreCommand }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("sqloper"); @@ -159,10 +122,10 @@ public: SQL.SetProvider("SQL/" + dbid); hashtype = tag->getString("hash"); - query = tag->getString("query", "SELECT hostname as host, type FROM ircd_opers WHERE username='$username' AND password='$password'"); + query = tag->getString("query", "SELECT hostname as host, type FROM ircd_opers WHERE username='$username' AND password='$password' AND active=1;"); } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { if (validated && command == "OPER" && parameters.size() >= 2) { @@ -172,7 +135,7 @@ public: /* Query is in progress, it will re-invoke OPER if needed */ return MOD_RES_DENY; } - ServerInstance->Logs->Log("m_sqloper",DEFAULT, "SQLOPER: database not present"); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "database not present"); } return MOD_RES_PASSTHRU; } @@ -184,16 +147,15 @@ public: ParamM userinfo; SQL->PopulateUserInfo(user, userinfo); userinfo["username"] = username; - userinfo["password"] = hash ? hash->hexsum(password) : password; + userinfo["password"] = hash ? hash->Generate(password) : password; SQL->submit(new OpMeQuery(this, user->uuid, username, password), query, userinfo); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Allows storage of oper credentials in an SQL table", VF_VENDOR); } - }; MODULE_INIT(ModuleSQLOper) diff --git a/src/modules/m_sslinfo.cpp b/src/modules/m_sslinfo.cpp index 2bfe0e1c4..523d52abb 100644 --- a/src/modules/m_sslinfo.cpp +++ b/src/modules/m_sslinfo.cpp @@ -18,13 +18,15 @@ #include "inspircd.h" -#include "ssl.h" - -/* $ModDesc: Provides SSL metadata, including /WHOIS information and /SSLINFO command */ +#include "modules/ssl.h" class SSLCertExt : public ExtensionItem { public: - SSLCertExt(Module* parent) : ExtensionItem("ssl_cert", parent) {} + SSLCertExt(Module* parent) + : ExtensionItem("ssl_cert", ExtensionItem::EXT_USER, parent) + { + } + ssl_cert* get(const Extensible* item) const { return static_cast<ssl_cert*>(get_raw(item)); @@ -93,90 +95,85 @@ class CommandSSLInfo : public Command if ((!target) || (target->registered != REG_ALL)) { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nickname", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nickname", parameters[0].c_str()); return CMD_FAILURE; } bool operonlyfp = ServerInstance->Config->ConfValue("sslinfo")->getBool("operonly"); - if (operonlyfp && !IS_OPER(user) && target != user) + if (operonlyfp && !user->IsOper() && target != user) { - user->WriteServ("NOTICE %s :*** You cannot view SSL certificate information for other users", user->nick.c_str()); + user->WriteNotice("*** You cannot view SSL certificate information for other users"); return CMD_FAILURE; } ssl_cert* cert = CertExt.get(target); if (!cert) { - user->WriteServ("NOTICE %s :*** No SSL certificate for this user", user->nick.c_str()); + user->WriteNotice("*** No SSL certificate for this user"); } else if (cert->GetError().length()) { - user->WriteServ("NOTICE %s :*** No SSL certificate information for this user (%s).", user->nick.c_str(), cert->GetError().c_str()); + user->WriteNotice("*** No SSL certificate information for this user (" + cert->GetError() + ")."); } else { - user->WriteServ("NOTICE %s :*** Distinguished Name: %s", user->nick.c_str(), cert->GetDN().c_str()); - user->WriteServ("NOTICE %s :*** Issuer: %s", user->nick.c_str(), cert->GetIssuer().c_str()); - user->WriteServ("NOTICE %s :*** Key Fingerprint: %s", user->nick.c_str(), cert->GetFingerprint().c_str()); + user->WriteNotice("*** Distinguished Name: " + cert->GetDN()); + user->WriteNotice("*** Issuer: " + cert->GetIssuer()); + user->WriteNotice("*** Key Fingerprint: " + cert->GetFingerprint()); } return CMD_SUCCESS; } }; -class ModuleSSLInfo : public Module +class UserCertificateAPIImpl : public UserCertificateAPIBase { - CommandSSLInfo cmd; + SSLCertExt& ext; public: - ModuleSSLInfo() : cmd(this) + UserCertificateAPIImpl(Module* mod, SSLCertExt& certext) + : UserCertificateAPIBase(mod), ext(certext) { } - void init() - { - ServerInstance->Modules->AddService(cmd); + ssl_cert* GetCertificate(User* user) CXX11_OVERRIDE + { + return ext.get(user); + } +}; - ServerInstance->Modules->AddService(cmd.CertExt); +class ModuleSSLInfo : public Module, public Whois::EventListener +{ + CommandSSLInfo cmd; + UserCertificateAPIImpl APIImpl; - Implementation eventlist[] = { I_OnWhois, I_OnPreCommand, I_OnSetConnectClass, I_OnUserConnect, I_OnPostConnect }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + public: + ModuleSSLInfo() + : Whois::EventListener(this) + , cmd(this) + , APIImpl(this, cmd.CertExt) + { } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("SSL Certificate Utilities", VF_VENDOR); } - void OnWhois(User* source, User* dest) + void OnWhois(Whois::Context& whois) CXX11_OVERRIDE { - ssl_cert* cert = cmd.CertExt.get(dest); + ssl_cert* cert = cmd.CertExt.get(whois.GetTarget()); if (cert) { - ServerInstance->SendWhoisLine(source, dest, 671, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str()); + whois.SendLine(671, ":is using a secure connection"); bool operonlyfp = ServerInstance->Config->ConfValue("sslinfo")->getBool("operonly"); - if ((!operonlyfp || source == dest || IS_OPER(source)) && !cert->fingerprint.empty()) - ServerInstance->SendWhoisLine(source, dest, 276, "%s %s :has client certificate fingerprint %s", - source->nick.c_str(), dest->nick.c_str(), cert->fingerprint.c_str()); - } - } - - bool OneOfMatches(const char* host, const char* ip, const char* hostlist) - { - std::stringstream hl(hostlist); - std::string xhost; - while (hl >> xhost) - { - if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map)) - { - return true; - } + if ((!operonlyfp || whois.IsSelfWhois() || whois.GetSource()->IsOper()) && !cert->fingerprint.empty()) + whois.SendLine(276, ":has client certificate fingerprint %s", cert->fingerprint.c_str()); } - return false; } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { if ((command == "OPER") && (validated)) { - OperIndex::iterator i = ServerInstance->Config->oper_blocks.find(parameters[0]); + ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->oper_blocks.find(parameters[0]); if (i != ServerInstance->Config->oper_blocks.end()) { OperInfo* ifo = i->second; @@ -184,7 +181,7 @@ class ModuleSSLInfo : public Module if (ifo->oper_block->getBool("sslonly") && !cert) { - user->WriteNumeric(491, "%s :This oper login requires an SSL connection.", user->nick.c_str()); + user->WriteNumeric(491, ":This oper login requires an SSL connection."); user->CommandFloodPenalty += 10000; return MOD_RES_DENY; } @@ -192,7 +189,7 @@ class ModuleSSLInfo : public Module std::string fingerprint; if (ifo->oper_block->readString("fingerprint", fingerprint) && (!cert || cert->GetFingerprint() != fingerprint)) { - user->WriteNumeric(491, "%s :This oper login requires a matching SSL fingerprint.",user->nick.c_str()); + user->WriteNumeric(491, ":This oper login requires a matching SSL certificate fingerprint."); user->CommandFloodPenalty += 10000; return MOD_RES_DENY; } @@ -203,21 +200,20 @@ class ModuleSSLInfo : public Module return MOD_RES_PASSTHRU; } - void OnUserConnect(LocalUser* user) + void OnUserConnect(LocalUser* user) CXX11_OVERRIDE { - SocketCertificateRequest req(&user->eh, this); - if (!req.cert) - return; - cmd.CertExt.set(user, req.cert); + ssl_cert* cert = SSLClientCert::GetCertificate(&user->eh); + if (cert) + cmd.CertExt.set(user, cert); } - void OnPostConnect(User* user) + void OnPostConnect(User* user) CXX11_OVERRIDE { ssl_cert *cert = cmd.CertExt.get(user); if (!cert || cert->fingerprint.empty()) return; // find an auto-oper block for this user - for(OperIndex::iterator i = ServerInstance->Config->oper_blocks.begin(); i != ServerInstance->Config->oper_blocks.end(); i++) + for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->oper_blocks.begin(); i != ServerInstance->Config->oper_blocks.end(); ++i) { OperInfo* ifo = i->second; std::string fp = ifo->oper_block->getString("fingerprint"); @@ -226,33 +222,23 @@ class ModuleSSLInfo : public Module } } - ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) + ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE { - SocketCertificateRequest req(&user->eh, this); + ssl_cert* cert = SSLClientCert::GetCertificate(&user->eh); bool ok = true; if (myclass->config->getString("requiressl") == "trusted") { - ok = (req.cert && req.cert->IsCAVerified()); + ok = (cert && cert->IsCAVerified()); } else if (myclass->config->getBool("requiressl")) { - ok = (req.cert != NULL); + ok = (cert != NULL); } if (!ok) return MOD_RES_DENY; return MOD_RES_PASSTHRU; } - - void OnRequest(Request& request) - { - if (strcmp("GET_USER_CERT", request.id) == 0) - { - UserCertificateRequest& req = static_cast<UserCertificateRequest&>(request); - req.cert = cmd.CertExt.get(req.user); - } - } }; MODULE_INIT(ModuleSSLInfo) - diff --git a/src/modules/m_sslmodes.cpp b/src/modules/m_sslmodes.cpp index c81c74207..1a596f5e0 100644 --- a/src/modules/m_sslmodes.cpp +++ b/src/modules/m_sslmodes.cpp @@ -22,38 +22,44 @@ #include "inspircd.h" -#include "ssl.h" - -/* $ModDesc: Provides channel mode +z to allow for Secure/SSL only channels */ +#include "modules/ssl.h" /** Handle channel mode +z */ class SSLMode : public ModeHandler { public: - SSLMode(Module* Creator) : ModeHandler(Creator, "sslonly", 'z', PARAM_NONE, MODETYPE_CHANNEL) { } + UserCertificateAPI API; + + SSLMode(Module* Creator) + : ModeHandler(Creator, "sslonly", 'z', PARAM_NONE, MODETYPE_CHANNEL) + , API(Creator) + { + } ModeAction OnModeChange(User* source, User* dest, Channel* channel, std::string ¶meter, bool adding) { if (adding) { - if (!channel->IsModeSet('z')) + if (!channel->IsModeSet(this)) { if (IS_LOCAL(source)) { - const UserMembList* userlist = channel->GetUsers(); - for(UserMembCIter i = userlist->begin(); i != userlist->end(); i++) + if (!API) + return MODEACTION_DENY; + + const Channel::MemberMap& userlist = channel->GetUsers(); + for (Channel::MemberMap::const_iterator i = userlist.begin(); i != userlist.end(); ++i) { - UserCertificateRequest req(i->first, creator); - req.Send(); - if(!req.cert && !ServerInstance->ULine(i->first->server)) + ssl_cert* cert = API->GetCertificate(i->first); + if (!cert && !i->first->server->IsULine()) { - source->WriteNumeric(ERR_ALLMUSTSSL, "%s %s :all members of the channel must be connected via SSL", source->nick.c_str(), channel->name.c_str()); + source->WriteNumeric(ERR_ALLMUSTSSL, "%s :all members of the channel must be connected via SSL", channel->name.c_str()); return MODEACTION_DENY; } } } - channel->SetMode('z',true); + channel->SetMode(this, true); return MODEACTION_ALLOW; } else @@ -63,9 +69,9 @@ class SSLMode : public ModeHandler } else { - if (channel->IsModeSet('z')) + if (channel->IsModeSet(this)) { - channel->SetMode('z',false); + channel->SetMode(this, false); return MODEACTION_ALLOW; } @@ -85,20 +91,15 @@ class ModuleSSLModes : public Module { } - void init() + ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(sslm); - Implementation eventlist[] = { I_OnUserPreJoin, I_OnCheckBan, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ModResult OnUserPreJoin(User* user, Channel* chan, const char* cname, std::string &privs, const std::string &keygiven) - { - if(chan && chan->IsModeSet('z')) + if(chan && chan->IsModeSet(sslm)) { - UserCertificateRequest req(user, this); - req.Send(); - if (req.cert) + if (!sslm.API) + return MOD_RES_DENY; + + ssl_cert* cert = sslm.API->GetCertificate(user); + if (cert) { // Let them in return MOD_RES_PASSTHRU; @@ -106,7 +107,7 @@ class ModuleSSLModes : public Module else { // Deny - user->WriteServ( "489 %s %s :Cannot join channel; SSL users only (+z)", user->nick.c_str(), cname); + user->WriteNumeric(489, "%s :Cannot join channel; SSL users only (+z)", cname.c_str()); return MOD_RES_DENY; } } @@ -114,33 +115,29 @@ class ModuleSSLModes : public Module return MOD_RES_PASSTHRU; } - ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) + ModResult OnCheckBan(User *user, Channel *c, const std::string& mask) CXX11_OVERRIDE { if ((mask.length() > 2) && (mask[0] == 'z') && (mask[1] == ':')) { - UserCertificateRequest req(user, this); - req.Send(); - if (req.cert && InspIRCd::Match(req.cert->GetFingerprint(), mask.substr(2))) + if (!sslm.API) + return MOD_RES_DENY; + + ssl_cert* cert = sslm.API->GetCertificate(user); + if (cert && InspIRCd::Match(cert->GetFingerprint(), mask.substr(2))) return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - ~ModuleSSLModes() - { - } - - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('z'); + tokens["EXTBAN"].push_back('z'); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel mode +z to allow for Secure/SSL only channels", VF_VENDOR); } }; - MODULE_INIT(ModuleSSLModes) - diff --git a/src/modules/m_starttls.cpp b/src/modules/m_starttls.cpp new file mode 100644 index 000000000..b05302fa9 --- /dev/null +++ b/src/modules/m_starttls.cpp @@ -0,0 +1,116 @@ +/* + * InspIRCd -- Internet Relay Chat Daemon + * + * Copyright (C) 2014 Adam <Adam@anope.org> + * + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "inspircd.h" +#include "modules/ssl.h" +#include "modules/cap.h" + +// From IRCv3 tls-3.1 +enum +{ + RPL_STARTTLS = 670, + ERR_STARTTLS = 691 +}; + +class CommandStartTLS : public SplitCommand +{ + dynamic_reference_nocheck<IOHookProvider>& ssl; + + public: + CommandStartTLS(Module* mod, dynamic_reference_nocheck<IOHookProvider>& s) + : SplitCommand(mod, "STARTTLS") + , ssl(s) + { + works_before_reg = true; + } + + CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) + { + if (!ssl) + { + user->WriteNumeric(ERR_STARTTLS, ":STARTTLS is not enabled"); + return CMD_FAILURE; + } + + if (user->registered == REG_ALL) + { + user->WriteNumeric(ERR_STARTTLS, ":STARTTLS is not permitted after client registration is complete"); + return CMD_FAILURE; + } + + if (user->eh.GetIOHook()) + { + user->WriteNumeric(ERR_STARTTLS, ":STARTTLS failure"); + return CMD_FAILURE; + } + + user->WriteNumeric(RPL_STARTTLS, ":STARTTLS successful, go ahead with TLS handshake"); + /* We need to flush the write buffer prior to adding the IOHook, + * otherwise we'll be sending this line inside the SSL session - which + * won't start its handshake until the client gets this line. Currently, + * we assume the write will not block here; this is usually safe, as + * STARTTLS is sent very early on in the registration phase, where the + * user hasn't built up much sendq. Handling a blocked write here would + * be very annoying. + */ + user->eh.DoWrite(); + + ssl->OnAccept(&user->eh, NULL, NULL); + + return CMD_SUCCESS; + } +}; + +class ModuleStartTLS : public Module +{ + CommandStartTLS starttls; + GenericCap tls; + dynamic_reference_nocheck<IOHookProvider> ssl; + + public: + ModuleStartTLS() + : starttls(this, ssl) + , tls(this, "tls") + , ssl(this, "ssl") + { + } + + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE + { + ConfigTag* conf = ServerInstance->Config->ConfValue("starttls"); + + std::string newprovider = conf->getString("provider"); + if (newprovider.empty()) + ssl.SetProvider("ssl"); + else + ssl.SetProvider("ssl/" + newprovider); + } + + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE + { + tokens["STARTTLS"]; + } + + Version GetVersion() CXX11_OVERRIDE + { + return Version("Provides support for the STARTTLS command", VF_VENDOR); + } +}; + +MODULE_INIT(ModuleStartTLS) diff --git a/src/modules/m_stripcolor.cpp b/src/modules/m_stripcolor.cpp index f1504edaf..0d4bdb877 100644 --- a/src/modules/m_stripcolor.cpp +++ b/src/modules/m_stripcolor.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides channel +S mode (strip ansi color) */ - /** Handles channel mode +S */ class ChannelStripColor : public SimpleChannelModeHandler @@ -50,24 +48,12 @@ class ModuleStripColor : public Module { } - void init() - { - ServerInstance->Modules->AddService(usc); - ServerInstance->Modules->AddService(csc); - Implementation eventlist[] = { I_OnUserPreMessage, I_OnUserPreNotice, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ~ModuleStripColor() - { - } - - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->AddExtBanChar('S'); + tokens["EXTBAN"].push_back('S'); } - virtual ModResult OnUserPreMessage(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + ModResult OnUserPreMessage(User* user, void* dest, int target_type, std::string& text, char status, CUList& exempt_list, MessageType msgtype) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return MOD_RES_PASSTHRU; @@ -76,7 +62,7 @@ class ModuleStripColor : public Module if (target_type == TYPE_USER) { User* t = (User*)dest; - active = t->IsModeSet('S'); + active = t->IsModeSet(usc); } else if (target_type == TYPE_CHANNEL) { @@ -86,7 +72,7 @@ class ModuleStripColor : public Module if (res == MOD_RES_ALLOW) return MOD_RES_PASSTHRU; - active = !t->GetExtBanStatus(user, 'S').check(!t->IsModeSet('S')); + active = !t->GetExtBanStatus(user, 'S').check(!t->IsModeSet(csc)); } if (active) @@ -97,12 +83,7 @@ class ModuleStripColor : public Module return MOD_RES_PASSTHRU; } - virtual ModResult OnUserPreNotice(User* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) - { - return OnUserPreMessage(user,dest,target_type,text,status,exempt_list); - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides channel +S mode (strip ansi color)", VF_VENDOR); } diff --git a/src/modules/m_svshold.cpp b/src/modules/m_svshold.cpp index e666b0fe2..a623e1553 100644 --- a/src/modules/m_svshold.cpp +++ b/src/modules/m_svshold.cpp @@ -23,8 +23,6 @@ #include "inspircd.h" #include "xline.h" -/* $ModDesc: Implements SVSHOLD. Like Q:Lines, but can only be added/removed by Services. */ - namespace { bool silent; @@ -35,16 +33,12 @@ namespace class SVSHold : public XLine { public: - irc::string nickname; + std::string nickname; SVSHold(time_t s_time, long d, const std::string& src, const std::string& re, const std::string& nick) : XLine(s_time, d, src, re, "SVSHOLD") { - this->nickname = nick.c_str(); - } - - ~SVSHold() - { + this->nickname = nick; } bool Matches(User *u) @@ -56,23 +50,21 @@ public: bool Matches(const std::string &s) { - if (nickname == s) - return true; - return false; + return InspIRCd::Match(s, nickname); } void DisplayExpiry() { if (!silent) { - ServerInstance->SNO->WriteToSnoMask('x',"Removing expired SVSHOLD %s (set by %s %ld seconds ago)", - this->nickname.c_str(), this->source.c_str(), (long int)(ServerInstance->Time() - this->set_time)); + ServerInstance->SNO->WriteToSnoMask('x', "Removing expired SVSHOLD %s (set by %s %ld seconds ago)", + nickname.c_str(), source.c_str(), (long)(ServerInstance->Time() - set_time)); } } - const char* Displayable() + const std::string& Displayable() { - return nickname.c_str(); + return nickname; } }; @@ -104,7 +96,6 @@ class CommandSvshold : public Command CommandSvshold(Module* Creator) : Command(Creator, "SVSHOLD", 1) { flags_needed = 'o'; this->syntax = "<nickname> [<duration> :<reason>]"; - TRANSLATE4(TR_TEXT, TR_TEXT, TR_TEXT, TR_END); } CmdResult Handle(const std::vector<std::string> ¶meters, User *user) @@ -112,7 +103,7 @@ class CommandSvshold : public Command /* syntax: svshold nickname time :reason goes here */ /* 'time' is a human-readable timestring, like 2d3h2s. */ - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) { /* don't allow SVSHOLD from non-ulined clients */ return CMD_FAILURE; @@ -127,7 +118,7 @@ class CommandSvshold : public Command } else { - user->WriteServ("NOTICE %s :*** SVSHOLD %s not found in list, try /stats S.",user->nick.c_str(),parameters[0].c_str()); + user->WriteNotice("*** SVSHOLD " + parameters[0] + " not found in list, try /stats S."); } } else @@ -135,8 +126,7 @@ class CommandSvshold : public Command if (parameters.size() < 3) return CMD_FAILURE; - // Adding - XXX todo make this respect <insane> tag perhaps.. - long duration = ServerInstance->Duration(parameters[1]); + unsigned long duration = InspIRCd::Duration(parameters[1]); SVSHold* r = new SVSHold(ServerInstance->Time(), duration, user->nick.c_str(), parameters[2].c_str(), parameters[0].c_str()); if (ServerInstance->XLines->AddLine(r, user)) @@ -151,7 +141,7 @@ class CommandSvshold : public Command else { time_t c_requires_crap = duration + ServerInstance->Time(); - std::string timestr = ServerInstance->TimeString(c_requires_crap); + std::string timestr = InspIRCd::TimeString(c_requires_crap); ServerInstance->SNO->WriteGlobalSno('x', "%s added timed SVSHOLD for %s, expires on %s: %s", user->nick.c_str(), parameters[0].c_str(), timestr.c_str(), parameters[2].c_str()); } } @@ -182,22 +172,18 @@ class ModuleSVSHold : public Module { } - void init() + void init() CXX11_OVERRIDE { ServerInstance->XLines->RegisterFactory(&s); - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnUserPreNick, I_OnStats, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - OnRehash(NULL); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { ConfigTag* tag = ServerInstance->Config->ConfValue("svshold"); - silent = tag->getBool("silent"); + silent = tag->getBool("silent", true); } - virtual ModResult OnStats(char symbol, User* user, string_list &out) + ModResult OnStats(char symbol, User* user, string_list &out) CXX11_OVERRIDE { if(symbol != 'S') return MOD_RES_PASSTHRU; @@ -206,26 +192,26 @@ class ModuleSVSHold : public Module return MOD_RES_DENY; } - virtual ModResult OnUserPreNick(User *user, const std::string &newnick) + ModResult OnUserPreNick(LocalUser* user, const std::string& newnick) CXX11_OVERRIDE { XLine *rl = ServerInstance->XLines->MatchesLine("SVSHOLD", newnick); if (rl) { - user->WriteServ( "432 %s %s :Services reserved nickname: %s", user->nick.c_str(), newnick.c_str(), rl->reason.c_str()); + user->WriteNumeric(ERR_ERRONEUSNICKNAME, "%s :Services reserved nickname: %s", newnick.c_str(), rl->reason.c_str()); return MOD_RES_DENY; } return MOD_RES_PASSTHRU; } - virtual ~ModuleSVSHold() + ~ModuleSVSHold() { ServerInstance->XLines->DelAll("SVSHOLD"); ServerInstance->XLines->UnregisterFactory(&s); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements SVSHOLD. Like Q:Lines, but can only be added/removed by Services.", VF_COMMON | VF_VENDOR); } diff --git a/src/modules/m_swhois.cpp b/src/modules/m_swhois.cpp index 742781747..e75921a80 100644 --- a/src/modules/m_swhois.cpp +++ b/src/modules/m_swhois.cpp @@ -25,18 +25,18 @@ #include "inspircd.h" -/* $ModDesc: Provides the SWHOIS command which allows setting of arbitrary WHOIS lines */ - /** Handle /SWHOIS */ class CommandSwhois : public Command { public: StringExtItem swhois; - CommandSwhois(Module* Creator) : Command(Creator,"SWHOIS", 2,2), swhois("swhois", Creator) + CommandSwhois(Module* Creator) + : Command(Creator, "SWHOIS", 2, 2) + , swhois("swhois", ExtensionItem::EXT_USER, Creator) { flags_needed = 'o'; syntax = "<nick> :<swhois>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle(const std::vector<std::string> ¶meters, User* user) @@ -45,7 +45,7 @@ class CommandSwhois : public Command if ((!dest) || (IS_SERVER(dest))) // allow setting swhois using SWHOIS before reg { - user->WriteNumeric(ERR_NOSUCHNICK, "%s %s :No such nick/channel", user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str()); return CMD_FAILURE; } @@ -53,11 +53,11 @@ class CommandSwhois : public Command if (text) { // We already had it set... - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) // Ulines set SWHOISes silently ServerInstance->SNO->WriteGlobalSno('a', "%s used SWHOIS to set %s's extra whois from '%s' to '%s'", user->nick.c_str(), dest->nick.c_str(), text->c_str(), parameters[1].c_str()); } - else if (!ServerInstance->ULine(user->server)) + else if (!user->server->IsULine()) { // Ulines set SWHOISes silently ServerInstance->SNO->WriteGlobalSno('a', "%s used SWHOIS to set %s's extra whois to '%s'", user->nick.c_str(), dest->nick.c_str(), parameters[1].c_str()); @@ -81,34 +81,28 @@ class CommandSwhois : public Command }; -class ModuleSWhois : public Module +class ModuleSWhois : public Module, public Whois::LineEventListener { CommandSwhois cmd; public: - ModuleSWhois() : cmd(this) - { - } - - void init() + ModuleSWhois() + : Whois::LineEventListener(this) + , cmd(this) { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(cmd.swhois); - Implementation eventlist[] = { I_OnWhoisLine, I_OnPostOper }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); } // :kenny.chatspike.net 320 Brain Azhrarn :is getting paid to play games. - ModResult OnWhoisLine(User* user, User* dest, int &numeric, std::string &text) + ModResult OnWhoisLine(Whois::Context& whois, unsigned int& numeric, std::string& text) CXX11_OVERRIDE { /* We use this and not OnWhois because this triggers for remote, too */ if (numeric == 312) { /* Insert our numeric before 312 */ - std::string* swhois = cmd.swhois.get(dest); + std::string* swhois = cmd.swhois.get(whois.GetTarget()); if (swhois) { - ServerInstance->SendWhoisLine(user, dest, 320, "%s %s :%s",user->nick.c_str(), dest->nick.c_str(), swhois->c_str()); + whois.SendLine(320, ":%s", swhois->c_str()); } } @@ -116,7 +110,7 @@ class ModuleSWhois : public Module return MOD_RES_PASSTHRU; } - void OnPostOper(User* user, const std::string &opertype, const std::string &opername) + void OnPostOper(User* user, const std::string &opertype, const std::string &opername) CXX11_OVERRIDE { if (!IS_LOCAL(user)) return; @@ -130,11 +124,7 @@ class ModuleSWhois : public Module ServerInstance->PI->SendMetaData(user, "swhois", swhois); } - ~ModuleSWhois() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the SWHOIS command which allows setting of arbitrary WHOIS lines", VF_OPTCOMMON | VF_VENDOR); } diff --git a/src/modules/m_testnet.cpp b/src/modules/m_testnet.cpp index 401766d8a..6e05ed681 100644 --- a/src/modules/m_testnet.cpp +++ b/src/modules/m_testnet.cpp @@ -17,167 +17,8 @@ */ -/* $ModDesc: Provides a module for testing the server while linked in a network */ - #include "inspircd.h" -struct vtbase -{ - virtual void isok(const char* name, int impl, Module* basemod, std::vector<std::string>& allmods) = 0; - virtual ~vtbase() {} -}; - -template<typename T> struct vtable : public vtbase -{ - union u { - T function; - struct v { - size_t delta; - size_t vtoff; - } v; - } u; - vtable(T t) { - u.function = t; - } - /** member function pointer dereference from vtable; depends on the GCC 4.4 ABI (x86_64) */ - template<typename E> void* read(E* obj) - { - if (u.v.delta & 1) - { - uint8_t* optr = reinterpret_cast<uint8_t*>(obj); - optr += u.v.vtoff; - uint8_t* vptr = *reinterpret_cast<uint8_t**>(optr); - vptr += u.v.delta - 1; - return *reinterpret_cast<void**>(vptr); - } - else - return reinterpret_cast<void*>(u.v.delta); - } - void isok(const char* name, int impl, Module* basemod, std::vector<std::string>& allmods) - { - void* base = read(basemod); - for(unsigned int i=0; i < allmods.size(); ++i) - { - Module* mod = ServerInstance->Modules->Find(allmods[i]); - void* fptr = read(mod); - for(EventHandlerIter j = ServerInstance->Modules->EventHandlers[impl].begin(); - j != ServerInstance->Modules->EventHandlers[impl].end(); j++) - { - if (mod == *j) - { - if (fptr == base) - { - ServerInstance->SNO->WriteToSnoMask('a', "Module %s implements %s but uses default function", - mod->ModuleSourceFile.c_str(), name); - } - goto done; - } - } - if (fptr != base) - { - ServerInstance->SNO->WriteToSnoMask('a', "Module %s does not implement %s but overrides function", - mod->ModuleSourceFile.c_str(), name); - } - done:; - } - } -}; - -template<typename T> vtbase* vtinit(T t) -{ - return new vtable<T>(t); -} - -static void checkall(Module* noimpl) -{ - std::vector<std::string> allmods = ServerInstance->Modules->GetAllModuleNames(0); -#define CHK(name) do { \ - vtbase* vt = vtinit(&Module::name); \ - vt->isok(#name, I_ ## name, noimpl, allmods); \ - delete vt; \ -} while (0) - CHK(OnUserConnect); - CHK(OnUserQuit); - CHK(OnUserDisconnect); - CHK(OnUserJoin); - CHK(OnUserPart); - CHK(OnRehash); - CHK(OnSendSnotice); - CHK(OnUserPreJoin); - CHK(OnUserPreKick); - CHK(OnUserKick); - CHK(OnOper); - CHK(OnInfo); - CHK(OnWhois); - CHK(OnUserPreInvite); - CHK(OnUserInvite); - CHK(OnUserPreMessage); - CHK(OnUserPreNotice); - CHK(OnUserPreNick); - CHK(OnUserMessage); - CHK(OnUserNotice); - CHK(OnMode); - CHK(OnGetServerDescription); - CHK(OnSyncUser); - CHK(OnSyncChannel); - CHK(OnDecodeMetaData); - CHK(OnWallops); - CHK(OnAcceptConnection); - CHK(OnChangeHost); - CHK(OnChangeName); - CHK(OnAddLine); - CHK(OnDelLine); - CHK(OnExpireLine); - CHK(OnUserPostNick); - CHK(OnPreMode); - CHK(On005Numeric); - CHK(OnKill); - CHK(OnRemoteKill); - CHK(OnLoadModule); - CHK(OnUnloadModule); - CHK(OnBackgroundTimer); - CHK(OnPreCommand); - CHK(OnCheckReady); - CHK(OnCheckInvite); - CHK(OnRawMode); - CHK(OnCheckKey); - CHK(OnCheckLimit); - CHK(OnCheckBan); - CHK(OnCheckChannelBan); - CHK(OnExtBanCheck); - CHK(OnStats); - CHK(OnChangeLocalUserHost); - CHK(OnPreTopicChange); - CHK(OnPostTopicChange); - CHK(OnEvent); - CHK(OnGlobalOper); - CHK(OnPostConnect); - CHK(OnAddBan); - CHK(OnDelBan); - CHK(OnChangeLocalUserGECOS); - CHK(OnUserRegister); - CHK(OnChannelPreDelete); - CHK(OnChannelDelete); - CHK(OnPostOper); - CHK(OnSyncNetwork); - CHK(OnSetAway); - CHK(OnPostCommand); - CHK(OnPostJoin); - CHK(OnWhoisLine); - CHK(OnBuildNeighborList); - CHK(OnGarbageCollect); - CHK(OnText); - CHK(OnPassCompare); - CHK(OnRunTestSuite); - CHK(OnNamesListItem); - CHK(OnNumeric); - CHK(OnHookIO); - CHK(OnPreRehash); - CHK(OnModuleRehash); - CHK(OnSendWhoLine); - CHK(OnChangeIdent); -} - class CommandTest : public Command { public: @@ -199,11 +40,6 @@ class CommandTest : public Command { IS_LOCAL(user)->CommandFloodPenalty += atoi(parameters[1].c_str()); } - else if (parameters[0] == "check") - { - checkall(creator); - ServerInstance->SNO->WriteToSnoMask('a', "Module check complete"); - } return CMD_SUCCESS; } }; @@ -216,18 +52,16 @@ class ModuleTest : public Module { } - void init() + void init() CXX11_OVERRIDE { if (!strstr(ServerInstance->Config->ServerName.c_str(), ".test")) throw ModuleException("Don't load modules without reading their descriptions!"); - ServerInstance->Modules->AddService(cmd); } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides a module for testing the server while linked in a network", VF_VENDOR|VF_OPTCOMMON); } }; MODULE_INIT(ModuleTest) - diff --git a/src/modules/m_timedbans.cpp b/src/modules/m_timedbans.cpp index b47327704..8196d37ba 100644 --- a/src/modules/m_timedbans.cpp +++ b/src/modules/m_timedbans.cpp @@ -20,9 +20,8 @@ */ -/* $ModDesc: Adds timed bans */ - #include "inspircd.h" +#include "listmode.h" /** Holds a timed ban */ @@ -42,21 +41,30 @@ timedbans TimedBanList; */ class CommandTban : public Command { - static bool IsBanSet(Channel* chan, const std::string& mask) + ChanModeReference banmode; + + bool IsBanSet(Channel* chan, const std::string& mask) { - for (BanList::const_iterator i = chan->bans.begin(); i != chan->bans.end(); ++i) + ListModeBase* banlm = static_cast<ListModeBase*>(*banmode); + const ListModeBase::ModeList* bans = banlm->GetList(chan); + if (bans) { - if (!strcasecmp(i->data.c_str(), mask.c_str())) - return true; + for (ListModeBase::ModeList::const_iterator i = bans->begin(); i != bans->end(); ++i) + { + const ListModeBase::ListItem& ban = *i; + if (!strcasecmp(ban.mask.c_str(), mask.c_str())) + return true; + } } + return false; } public: CommandTban(Module* Creator) : Command(Creator,"TBAN", 3) + , banmode(Creator, "ban") { syntax = "<channel> <duration> <banmask>"; - TRANSLATE4(TR_TEXT, TR_TEXT, TR_TEXT, TR_END); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -64,51 +72,47 @@ class CommandTban : public Command Channel* channel = ServerInstance->FindChan(parameters[0]); if (!channel) { - user->WriteNumeric(401, "%s %s :No such channel",user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such channel", parameters[0].c_str()); return CMD_FAILURE; } int cm = channel->GetPrefixValue(user); if (cm < HALFOP_VALUE) { - user->WriteNumeric(482, "%s %s :You do not have permission to set bans on this channel", - user->nick.c_str(), channel->name.c_str()); + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You do not have permission to set bans on this channel", + channel->name.c_str()); return CMD_FAILURE; - } + } TimedBan T; std::string channelname = parameters[0]; - long duration = ServerInstance->Duration(parameters[1]); + unsigned long duration = InspIRCd::Duration(parameters[1]); unsigned long expire = duration + ServerInstance->Time(); if (duration < 1) { - user->WriteServ("NOTICE "+user->nick+" :Invalid ban time"); + user->WriteNotice("Invalid ban time"); return CMD_FAILURE; } std::string mask = parameters[2]; - std::vector<std::string> setban; - setban.push_back(parameters[0]); - setban.push_back("+b"); bool isextban = ((mask.size() > 2) && (mask[1] == ':')); - if (!isextban && !ServerInstance->IsValidMask(mask)) + if (!isextban && !InspIRCd::IsValidMask(mask)) mask.append("!*@*"); - if ((mask.length() > 250) || (!ServerInstance->IsValidMask(mask) && !isextban)) - { - user->WriteServ("NOTICE "+user->nick+" :Invalid ban mask"); - return CMD_FAILURE; - } if (IsBanSet(channel, mask)) { - user->WriteServ("NOTICE %s :Ban already set", user->nick.c_str()); + user->WriteNotice("Ban already set"); return CMD_FAILURE; } - setban.push_back(mask); - // use CallHandler to make it so that the user sets the mode - // themselves - ServerInstance->Parser->CallHandler("MODE",setban,user); - if (!IsBanSet(channel, mask)) + Modes::ChangeList setban; + setban.push_add(ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL), mask); + // Pass the user (instead of ServerInstance->FakeClient) to ModeHandler::Process() to + // make it so that the user sets the mode themselves + ServerInstance->Modes->Process(user, channel, NULL, setban); + if (ServerInstance->Modes->GetLastParse().empty()) + { + user->WriteNotice("Invalid ban mask"); return CMD_FAILURE; + } CUList tmp; T.channel = channelname; @@ -131,6 +135,34 @@ class CommandTban : public Command } }; +class BanWatcher : public ModeWatcher +{ + public: + BanWatcher(Module* parent) + : ModeWatcher(parent, "ban", MODETYPE_CHANNEL) + { + } + + void AfterMode(User* source, User* dest, Channel* chan, const std::string& banmask, bool adding) + { + if (adding) + return; + + irc::string listitem = banmask.c_str(); + irc::string thischan = chan->name.c_str(); + for (timedbans::iterator i = TimedBanList.begin(); i != TimedBanList.end(); ++i) + { + irc::string target = i->mask.c_str(); + irc::string tchan = i->channel.c_str(); + if ((listitem == target) && (tchan == thischan)) + { + TimedBanList.erase(i); + break; + } + } + } +}; + class ChannelMatcher { Channel* const chan; @@ -150,37 +182,16 @@ class ChannelMatcher class ModuleTimedBans : public Module { CommandTban cmd; + BanWatcher banwatcher; + public: ModuleTimedBans() : cmd(this) + , banwatcher(this) { } - void init() - { - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_OnDelBan, I_OnBackgroundTimer, I_OnChannelDelete }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual ModResult OnDelBan(User* source, Channel* chan, const std::string &banmask) - { - irc::string listitem = banmask.c_str(); - irc::string thischan = chan->name.c_str(); - for (timedbans::iterator i = TimedBanList.begin(); i != TimedBanList.end(); i++) - { - irc::string target = i->mask.c_str(); - irc::string tchan = i->channel.c_str(); - if ((listitem == target) && (tchan == thischan)) - { - TimedBanList.erase(i); - break; - } - } - return MOD_RES_PASSTHRU; - } - - virtual void OnBackgroundTimer(time_t curtime) + void OnBackgroundTimer(time_t curtime) CXX11_OVERRIDE { timedbans expired; for (timedbans::iterator i = TimedBanList.begin(); i != TimedBanList.end();) @@ -201,17 +212,14 @@ class ModuleTimedBans : public Module Channel* cr = ServerInstance->FindChan(chan); if (cr) { - std::vector<std::string> setban; - setban.push_back(chan); - setban.push_back("-b"); - setban.push_back(mask); - CUList empty; std::string expiry = "*** Timed ban on " + chan + " expired."; cr->WriteAllExcept(ServerInstance->FakeClient, true, '@', empty, "NOTICE %s :%s", cr->name.c_str(), expiry.c_str()); ServerInstance->PI->SendChannelNotice(cr, '@', expiry); - ServerInstance->SendGlobalMode(setban, ServerInstance->FakeClient); + Modes::ChangeList setban; + setban.push_remove(ServerInstance->Modes->FindMode('b', MODETYPE_CHANNEL), mask); + ServerInstance->Modes->Process(ServerInstance->FakeClient, cr, NULL, setban); } } } @@ -222,11 +230,10 @@ class ModuleTimedBans : public Module TimedBanList.erase(std::remove_if(TimedBanList.begin(), TimedBanList.end(), ChannelMatcher(chan)), TimedBanList.end()); } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Adds timed bans", VF_COMMON | VF_VENDOR); } }; MODULE_INIT(ModuleTimedBans) - diff --git a/src/modules/m_tline.cpp b/src/modules/m_tline.cpp index b4e7e5a99..77ec0e26c 100644 --- a/src/modules/m_tline.cpp +++ b/src/modules/m_tline.cpp @@ -20,8 +20,6 @@ #include "inspircd.h" -/* $ModDesc: Provides /tline command used to test who a mask matches */ - /** Handle /TLINE */ class CommandTline : public Command @@ -34,14 +32,13 @@ class CommandTline : public Command CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { - float n_counted = 0; - float n_matched = 0; - float n_match_host = 0; - float n_match_ip = 0; + unsigned int n_matched = 0; + unsigned int n_match_host = 0; + unsigned int n_match_ip = 0; - for (user_hash::const_iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++) + const user_hash& users = ServerInstance->Users->GetUsers(); + for (user_hash::const_iterator u = users.begin(); u != users.end(); ++u) { - n_counted++; if (InspIRCd::Match(u->second->GetFullRealHost(),parameters[0])) { n_matched++; @@ -57,10 +54,15 @@ class CommandTline : public Command } } } + + unsigned long n_counted = users.size(); if (n_matched) - user->WriteServ( "NOTICE %s :*** TLINE: Counted %0.0f user(s). Matched '%s' against %0.0f user(s) (%0.2f%% of the userbase). %0.0f by hostname and %0.0f by IP address.",user->nick.c_str(), n_counted, parameters[0].c_str(), n_matched, (n_matched/n_counted)*100, n_match_host, n_match_ip); + { + float p = (n_matched / (float)n_counted) * 100; + user->WriteNotice(InspIRCd::Format("*** TLINE: Counted %lu user(s). Matched '%s' against %u user(s) (%0.2f%% of the userbase). %u by hostname and %u by IP address.", n_counted, parameters[0].c_str(), n_matched, p, n_match_host, n_match_ip)); + } else - user->WriteServ( "NOTICE %s :*** TLINE: Counted %0.0f user(s). Matched '%s' against no user(s).", user->nick.c_str(), n_counted, parameters[0].c_str()); + user->WriteNotice(InspIRCd::Format("*** TLINE: Counted %lu user(s). Matched '%s' against no user(s).", n_counted, parameters[0].c_str())); return CMD_SUCCESS; } @@ -75,20 +77,10 @@ class ModuleTLine : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleTLine() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides /tline command used to test who a mask matches", VF_VENDOR); } }; MODULE_INIT(ModuleTLine) - diff --git a/src/modules/m_topiclock.cpp b/src/modules/m_topiclock.cpp index 3e8a846e7..6053bc849 100644 --- a/src/modules/m_topiclock.cpp +++ b/src/modules/m_topiclock.cpp @@ -16,8 +16,6 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -/* $ModDesc: Implements server-side topic locks and the server-to-server command SVSTOPIC */ - #include "inspircd.h" class CommandSVSTOPIC : public Command @@ -31,7 +29,7 @@ class CommandSVSTOPIC : public Command CmdResult Handle(const std::vector<std::string> ¶meters, User *user) { - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) { // Ulines only return CMD_FAILURE; @@ -47,7 +45,7 @@ class CommandSVSTOPIC : public Command time_t topicts = ConvToInt(parameters[1]); if (!topicts) { - ServerInstance->Logs->Log("m_topiclock", DEFAULT, "Received SVSTOPIC with a 0 topicts, dropped."); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Received SVSTOPIC with a 0 topicts, dropped."); return CMD_INVALID; } @@ -92,11 +90,7 @@ class FlagExtItem : public ExtensionItem { public: FlagExtItem(const std::string& key, Module* owner) - : ExtensionItem(key, owner) - { - } - - virtual ~FlagExtItem() + : ExtensionItem(key, ExtensionItem::EXT_CHANNEL, owner) { } @@ -151,14 +145,7 @@ class ModuleTopicLock : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - ServerInstance->Modules->AddService(topiclock); - ServerInstance->Modules->Attach(I_OnPreTopicChange, this); - } - - ModResult OnPreTopicChange(User* user, Channel* chan, const std::string &topic) + ModResult OnPreTopicChange(User* user, Channel* chan, const std::string &topic) CXX11_OVERRIDE { // Only fired for local users currently, but added a check anyway if ((IS_LOCAL(user)) && (topiclock.get(chan))) @@ -170,7 +157,7 @@ class ModuleTopicLock : public Module return MOD_RES_PASSTHRU; } - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Implements server-side topic locks and the server-to-server command SVSTOPIC", VF_COMMON | VF_VENDOR); } diff --git a/src/modules/m_uhnames.cpp b/src/modules/m_uhnames.cpp index 2cd090f97..90bac54f5 100644 --- a/src/modules/m_uhnames.cpp +++ b/src/modules/m_uhnames.cpp @@ -20,9 +20,7 @@ #include "inspircd.h" -#include "m_cap.h" - -/* $ModDesc: Provides the UHNAMES facility. */ +#include "modules/cap.h" class ModuleUHNames : public Module { @@ -33,27 +31,17 @@ class ModuleUHNames : public Module { } - void init() - { - Implementation eventlist[] = { I_OnEvent, I_OnPreCommand, I_OnNamesListItem, I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - ~ModuleUHNames() - { - } - - Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the UHNAMES facility.",VF_VENDOR); } - void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - output.append(" UHNAMES"); + tokens["UHNAMES"]; } - ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ModResult OnPreCommand(std::string &command, std::vector<std::string> ¶meters, LocalUser *user, bool validated, const std::string &original_line) CXX11_OVERRIDE { /* We don't actually create a proper command handler class for PROTOCTL, * because other modules might want to have PROTOCTL hooks too. @@ -71,20 +59,12 @@ class ModuleUHNames : public Module return MOD_RES_PASSTHRU; } - void OnNamesListItem(User* issuer, Membership* memb, std::string &prefixes, std::string &nick) + ModResult OnNamesListItem(User* issuer, Membership* memb, std::string& prefixes, std::string& nick) CXX11_OVERRIDE { - if (!cap.ext.get(issuer)) - return; - - if (nick.empty()) - return; - - nick = memb->user->GetFullHost(); - } + if (cap.ext.get(issuer)) + nick = memb->user->GetFullHost(); - void OnEvent(Event& ev) - { - cap.HandleEvent(ev); + return MOD_RES_PASSTHRU; } }; diff --git a/src/modules/m_uninvite.cpp b/src/modules/m_uninvite.cpp index ff392edc3..97ad841f1 100644 --- a/src/modules/m_uninvite.cpp +++ b/src/modules/m_uninvite.cpp @@ -20,8 +20,6 @@ */ -/* $ModDesc: Provides the UNINVITE command which lets users un-invite other users from channels (!) */ - #include "inspircd.h" /** Handle /UNINVITE @@ -32,7 +30,7 @@ class CommandUninvite : public Command CommandUninvite(Module* Creator) : Command(Creator,"UNINVITE", 2) { syntax = "<nick> <channel>"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); + TRANSLATE2(TR_NICK, TR_TEXT); } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -49,11 +47,11 @@ class CommandUninvite : public Command { if (!c) { - user->WriteNumeric(401, "%s %s :No such nick/channel",user->nick.c_str(), parameters[1].c_str()); + user->WriteNumeric(401, "%s :No such nick/channel", parameters[1].c_str()); } else { - user->WriteNumeric(401, "%s %s :No such nick/channel",user->nick.c_str(), parameters[0].c_str()); + user->WriteNumeric(401, "%s :No such nick/channel", parameters[0].c_str()); } return CMD_FAILURE; @@ -63,7 +61,7 @@ class CommandUninvite : public Command { if (c->GetPrefixValue(user) < HALFOP_VALUE) { - user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s %s :You must be a channel %soperator", user->nick.c_str(), c->name.c_str(), c->GetPrefixValue(u) == HALFOP_VALUE ? "" : "half-"); + user->WriteNumeric(ERR_CHANOPRIVSNEEDED, "%s :You must be a channel %soperator", c->name.c_str(), c->GetPrefixValue(u) == HALFOP_VALUE ? "" : "half-"); return CMD_FAILURE; } } @@ -75,16 +73,14 @@ class CommandUninvite : public Command LocalUser* lu = IS_LOCAL(u); if (lu) { - irc::string xname(c->name.c_str()); - if (!lu->IsInvited(xname)) + if (!lu->RemoveInvite(c)) { - user->SendText(":%s 505 %s %s %s :Is not invited to channel %s", user->server.c_str(), user->nick.c_str(), u->nick.c_str(), c->name.c_str(), c->name.c_str()); + user->SendText(":%s 505 %s %s %s :Is not invited to channel %s", user->server->GetName().c_str(), user->nick.c_str(), u->nick.c_str(), c->name.c_str(), c->name.c_str()); return CMD_FAILURE; } - user->SendText(":%s 494 %s %s %s :Uninvited", user->server.c_str(), user->nick.c_str(), c->name.c_str(), u->nick.c_str()); - lu->RemoveInvite(xname); - lu->WriteNumeric(493, "%s :You were uninvited from %s by %s", u->nick.c_str(), c->name.c_str(), user->nick.c_str()); + user->SendText(":%s 494 %s %s %s :Uninvited", user->server->GetName().c_str(), user->nick.c_str(), c->name.c_str(), u->nick.c_str()); + lu->WriteNumeric(493, ":You were uninvited from %s by %s", c->name.c_str(), user->nick.c_str()); std::string msg = "*** " + user->nick + " uninvited " + u->nick + "."; c->WriteChannelWithServ(ServerInstance->Config->ServerName, "NOTICE " + c->name + " :" + msg); @@ -111,20 +107,10 @@ class ModuleUninvite : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleUninvite() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides the UNINVITE command which lets users un-invite other users from channels", VF_VENDOR | VF_OPTCOMMON); } }; MODULE_INIT(ModuleUninvite) - diff --git a/src/modules/m_userip.cpp b/src/modules/m_userip.cpp index 9502c91b1..043967393 100644 --- a/src/modules/m_userip.cpp +++ b/src/modules/m_userip.cpp @@ -21,8 +21,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for USERIP command */ - /** Handle /USERIP */ class CommandUserip : public Command @@ -54,15 +52,15 @@ class CommandUserip : public Command checked_privs = true; has_privs = user->HasPrivPermission("users/auspex"); if (!has_privs) - user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str()); + user->WriteNumeric(ERR_NOPRIVILEGES, ":Permission Denied - You do not have the required operator privileges"); } if (!has_privs) continue; } - retbuf = retbuf + u->nick + (IS_OPER(u) ? "*" : "") + "="; - if (IS_AWAY(u)) + retbuf = retbuf + u->nick + (u->IsOper() ? "*" : "") + "="; + if (u->IsAway()) retbuf += "-"; else retbuf += "+"; @@ -87,28 +85,15 @@ class ModuleUserIP : public Module { } - void init() + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - ServerInstance->Modules->AddService(cmd); - Implementation eventlist[] = { I_On005Numeric }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); + tokens["USERIP"]; } - virtual void On005Numeric(std::string &output) - { - output = output + " USERIP"; - } - - virtual ~ModuleUserIP() - { - } - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for USERIP command",VF_VENDOR); } - }; MODULE_INIT(ModuleUserIP) - diff --git a/src/modules/m_vhost.cpp b/src/modules/m_vhost.cpp index 31c504af8..53910fdbe 100644 --- a/src/modules/m_vhost.cpp +++ b/src/modules/m_vhost.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides masking of user hostnames via traditional /VHOST command */ - /** Handle /VHOST */ class CommandVhost : public Command @@ -45,25 +43,24 @@ class CommandVhost : public Command std::string pass = tag->getString("pass"); std::string hash = tag->getString("hash"); - if (parameters[0] == username && !ServerInstance->PassCompare(user, pass, parameters[1], hash)) + if (parameters[0] == username && ServerInstance->PassCompare(user, pass, parameters[1], hash)) { if (!mask.empty()) { - user->WriteServ("NOTICE "+user->nick+" :Setting your VHost: " + mask); - user->ChangeDisplayedHost(mask.c_str()); + user->WriteNotice("Setting your VHost: " + mask); + user->ChangeDisplayedHost(mask); return CMD_SUCCESS; } } } - user->WriteServ("NOTICE "+user->nick+" :Invalid username or password."); + user->WriteNotice("Invalid username or password."); return CMD_FAILURE; } }; class ModuleVHost : public Module { - private: CommandVhost cmd; public: @@ -71,22 +68,10 @@ class ModuleVHost : public Module { } - void init() - { - ServerInstance->Modules->AddService(cmd); - } - - virtual ~ModuleVHost() - { - } - - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides masking of user hostnames via traditional /VHOST command",VF_VENDOR); } - }; MODULE_INIT(ModuleVHost) - diff --git a/src/modules/m_watch.cpp b/src/modules/m_watch.cpp index a86483291..d0e42af6f 100644 --- a/src/modules/m_watch.cpp +++ b/src/modules/m_watch.cpp @@ -22,8 +22,6 @@ #include "inspircd.h" -/* $ModDesc: Provides support for the /WATCH command */ - /* * Okay, it's nice that this was documented and all, but I at least understood very little @@ -92,12 +90,7 @@ * of users using WATCH. */ -/* - * Before you start screaming, this definition is only used here, so moving it to a header is pointless. - * Yes, it's horrid. Blame cl for being different. -- w00t - */ - -typedef nspace::hash_map<irc::string, std::deque<User*>, irc::hash> watchentries; +typedef TR1NS::unordered_map<irc::string, std::deque<User*>, irc::hash> watchentries; typedef std::map<irc::string, std::string> watchlist; /* Who's watching each nickname. @@ -112,12 +105,12 @@ class CommandSVSWatch : public Command CommandSVSWatch(Module* Creator) : Command(Creator,"SVSWATCH", 2) { syntax = "<target> [C|L|S]|[+|-<nick>]"; - TRANSLATE3(TR_NICK, TR_TEXT, TR_END); /* we watch for a nick. not a UID. */ + TRANSLATE2(TR_NICK, TR_TEXT); /* we watch for a nick. not a UID. */ } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) { - if (!ServerInstance->ULine(user->server)) + if (!user->server->IsULine()) return CMD_FAILURE; User *u = ServerInstance->FindNick(parameters[0]); @@ -126,7 +119,7 @@ class CommandSVSWatch : public Command if (IS_LOCAL(u)) { - ServerInstance->Parser->CallHandler("WATCH", parameters, u); + ServerInstance->Parser.CallHandler("WATCH", parameters, u); } return CMD_SUCCESS; @@ -151,9 +144,9 @@ class CommandWatch : public Command CmdResult remove_watch(User* user, const char* nick) { // removing an item from the list - if (!ServerInstance->IsNick(nick, ServerInstance->Config->Limits.NickMax)) + if (!ServerInstance->IsNick(nick)) { - user->WriteNumeric(942, "%s %s :Invalid nickname", user->nick.c_str(), nick); + user->WriteNumeric(942, "%s :Invalid nickname", nick); return CMD_FAILURE; } @@ -166,9 +159,9 @@ class CommandWatch : public Command if (n != wl->end()) { if (!n->second.empty()) - user->WriteNumeric(602, "%s %s %s :stopped watching", user->nick.c_str(), n->first.c_str(), n->second.c_str()); + user->WriteNumeric(602, "%s %s :stopped watching", n->first.c_str(), n->second.c_str()); else - user->WriteNumeric(602, "%s %s * * 0 :stopped watching", user->nick.c_str(), nick); + user->WriteNumeric(602, "%s * * 0 :stopped watching", nick); wl->erase(n); } @@ -198,9 +191,9 @@ class CommandWatch : public Command CmdResult add_watch(User* user, const char* nick) { - if (!ServerInstance->IsNick(nick, ServerInstance->Config->Limits.NickMax)) + if (!ServerInstance->IsNick(nick)) { - user->WriteNumeric(942, "%s %s :Invalid nickname",user->nick.c_str(),nick); + user->WriteNumeric(942, "%s :Invalid nickname", nick); return CMD_FAILURE; } @@ -213,7 +206,7 @@ class CommandWatch : public Command if (wl->size() >= MAX_WATCH) { - user->WriteNumeric(512, "%s %s :Too many WATCH entries", user->nick.c_str(), nick); + user->WriteNumeric(512, "%s :Too many WATCH entries", nick); return CMD_FAILURE; } @@ -238,26 +231,25 @@ class CommandWatch : public Command if ((target) && (target->registered == REG_ALL)) { (*wl)[nick] = std::string(target->ident).append(" ").append(target->dhost).append(" ").append(ConvToStr(target->age)); - user->WriteNumeric(604, "%s %s %s :is online",user->nick.c_str(), nick, (*wl)[nick].c_str()); - if (IS_AWAY(target)) + user->WriteNumeric(604, "%s %s :is online", nick, (*wl)[nick].c_str()); + if (target->IsAway()) { - user->WriteNumeric(609, "%s %s %s %s %lu :is away", user->nick.c_str(), target->nick.c_str(), target->ident.c_str(), target->dhost.c_str(), (unsigned long) target->awaytime); + user->WriteNumeric(609, "%s %s %s %lu :is away", target->nick.c_str(), target->ident.c_str(), target->dhost.c_str(), (unsigned long) target->awaytime); } } else { (*wl)[nick].clear(); - user->WriteNumeric(605, "%s %s * * 0 :is offline",user->nick.c_str(), nick); + user->WriteNumeric(605, "%s * * 0 :is offline", nick); } } return CMD_SUCCESS; } - CommandWatch(Module* parent, unsigned int &maxwatch) : Command(parent,"WATCH", 0), MAX_WATCH(maxwatch), ext("watchlist", parent) + CommandWatch(Module* parent, unsigned int &maxwatch) : Command(parent,"WATCH", 0), MAX_WATCH(maxwatch), ext("watchlist", ExtensionItem::EXT_USER, parent) { syntax = "[C|L|S]|[+|-<nick>]"; - TRANSLATE2(TR_TEXT, TR_END); /* we watch for a nick. not a UID. */ } CmdResult Handle (const std::vector<std::string> ¶meters, User *user) @@ -270,10 +262,10 @@ class CommandWatch : public Command for (watchlist::iterator q = wl->begin(); q != wl->end(); q++) { if (!q->second.empty()) - user->WriteNumeric(604, "%s %s %s :is online", user->nick.c_str(), q->first.c_str(), q->second.c_str()); + user->WriteNumeric(604, "%s %s :is online", q->first.c_str(), q->second.c_str()); } } - user->WriteNumeric(607, "%s :End of WATCH list",user->nick.c_str()); + user->WriteNumeric(607, ":End of WATCH list"); } else if (parameters.size() > 0) { @@ -316,17 +308,17 @@ class CommandWatch : public Command User* targ = ServerInstance->FindNick(q->first.c_str()); if (targ && !q->second.empty()) { - user->WriteNumeric(604, "%s %s %s :is online", user->nick.c_str(), q->first.c_str(), q->second.c_str()); - if (IS_AWAY(targ)) + user->WriteNumeric(604, "%s %s :is online", q->first.c_str(), q->second.c_str()); + if (targ->IsAway()) { - user->WriteNumeric(609, "%s %s %s %s %lu :is away", user->nick.c_str(), targ->nick.c_str(), targ->ident.c_str(), targ->dhost.c_str(), (unsigned long) targ->awaytime); + user->WriteNumeric(609, "%s %s %s %lu :is away", targ->nick.c_str(), targ->ident.c_str(), targ->dhost.c_str(), (unsigned long) targ->awaytime); } } else - user->WriteNumeric(605, "%s %s * * 0 :is offline", user->nick.c_str(), q->first.c_str()); + user->WriteNumeric(605, "%s * * 0 :is offline", q->first.c_str()); } } - user->WriteNumeric(607, "%s :End of WATCH list",user->nick.c_str()); + user->WriteNumeric(607, ":End of WATCH list"); } else if (!strcasecmp(nick,"S")) { @@ -346,9 +338,9 @@ class CommandWatch : public Command if (i2 != whos_watching_me->end()) youre_on = i2->second.size(); - user->WriteNumeric(603, "%s :You have %d and are on %d WATCH entries", user->nick.c_str(), you_have, youre_on); - user->WriteNumeric(606, "%s :%s",user->nick.c_str(), list.c_str()); - user->WriteNumeric(607, "%s :End of WATCH S",user->nick.c_str()); + user->WriteNumeric(603, ":You have %d and are on %d WATCH entries", you_have, youre_on); + user->WriteNumeric(606, ":%s", list.c_str()); + user->WriteNumeric(607, ":End of WATCH S"); } else if (nick[0] == '-') { @@ -379,24 +371,14 @@ class Modulewatch : public Module whos_watching_me = new watchentries(); } - void init() - { - OnRehash(NULL); - ServerInstance->Modules->AddService(cmdw); - ServerInstance->Modules->AddService(sw); - ServerInstance->Modules->AddService(cmdw.ext); - Implementation eventlist[] = { I_OnRehash, I_OnGarbageCollect, I_OnUserQuit, I_OnPostConnect, I_OnUserPostNick, I_On005Numeric, I_OnSetAway }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); - } - - virtual void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { maxwatch = ServerInstance->Config->ConfValue("watch")->getInt("maxentries", 32); if (!maxwatch) maxwatch = 32; } - virtual ModResult OnSetAway(User *user, const std::string &awaymsg) + ModResult OnSetAway(User *user, const std::string &awaymsg) CXX11_OVERRIDE { std::string numeric; int inum; @@ -417,21 +399,21 @@ class Modulewatch : public Module { for (std::deque<User*>::iterator n = x->second.begin(); n != x->second.end(); n++) { - (*n)->WriteNumeric(inum, (*n)->nick + " " + numeric); + (*n)->WriteNumeric(inum, numeric); } } return MOD_RES_PASSTHRU; } - virtual void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) + void OnUserQuit(User* user, const std::string &reason, const std::string &oper_message) CXX11_OVERRIDE { watchentries::iterator x = whos_watching_me->find(user->nick.c_str()); if (x != whos_watching_me->end()) { for (std::deque<User*>::iterator n = x->second.begin(); n != x->second.end(); n++) { - (*n)->WriteNumeric(601, "%s %s %s %s %lu :went offline", (*n)->nick.c_str() ,user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) ServerInstance->Time()); + (*n)->WriteNumeric(601, "%s %s %s %lu :went offline", user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) ServerInstance->Time()); watchlist* wl = cmdw.ext.get(*n); if (wl) @@ -464,7 +446,7 @@ class Modulewatch : public Module } } - virtual void OnGarbageCollect() + void OnGarbageCollect() { watchentries* old_watch = whos_watching_me; whos_watching_me = new watchentries(); @@ -475,14 +457,14 @@ class Modulewatch : public Module delete old_watch; } - virtual void OnPostConnect(User* user) + void OnPostConnect(User* user) CXX11_OVERRIDE { watchentries::iterator x = whos_watching_me->find(user->nick.c_str()); if (x != whos_watching_me->end()) { for (std::deque<User*>::iterator n = x->second.begin(); n != x->second.end(); n++) { - (*n)->WriteNumeric(600, "%s %s %s %s %lu :arrived online", (*n)->nick.c_str(), user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) user->age); + (*n)->WriteNumeric(600, "%s %s %s %lu :arrived online", user->nick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) user->age); watchlist* wl = cmdw.ext.get(*n); if (wl) @@ -492,7 +474,7 @@ class Modulewatch : public Module } } - virtual void OnUserPostNick(User* user, const std::string &oldnick) + void OnUserPostNick(User* user, const std::string &oldnick) CXX11_OVERRIDE { watchentries::iterator new_offline = whos_watching_me->find(oldnick.c_str()); watchentries::iterator new_online = whos_watching_me->find(user->nick.c_str()); @@ -504,7 +486,7 @@ class Modulewatch : public Module watchlist* wl = cmdw.ext.get(*n); if (wl) { - (*n)->WriteNumeric(601, "%s %s %s %s %lu :went offline", (*n)->nick.c_str(), oldnick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) user->age); + (*n)->WriteNumeric(601, "%s %s %s %lu :went offline", oldnick.c_str(), user->ident.c_str(), user->dhost.c_str(), (unsigned long) user->age); (*wl)[oldnick.c_str()].clear(); } } @@ -518,28 +500,26 @@ class Modulewatch : public Module if (wl) { (*wl)[user->nick.c_str()] = std::string(user->ident).append(" ").append(user->dhost).append(" ").append(ConvToStr(user->age)); - (*n)->WriteNumeric(600, "%s %s %s :arrived online", (*n)->nick.c_str(), user->nick.c_str(), (*wl)[user->nick.c_str()].c_str()); + (*n)->WriteNumeric(600, "%s %s :arrived online", user->nick.c_str(), (*wl)[user->nick.c_str()].c_str()); } } } } - virtual void On005Numeric(std::string &output) + void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE { - // we don't really have a limit... - output = output + " WATCH=" + ConvToStr(maxwatch); + tokens["WATCH"] = ConvToStr(maxwatch); } - virtual ~Modulewatch() + ~Modulewatch() { delete whos_watching_me; } - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Provides support for the /WATCH command", VF_OPTCOMMON | VF_VENDOR); } }; MODULE_INIT(Modulewatch) - diff --git a/src/modules/m_xline_db.cpp b/src/modules/m_xline_db.cpp index 2237b0d08..c514ffb76 100644 --- a/src/modules/m_xline_db.cpp +++ b/src/modules/m_xline_db.cpp @@ -20,45 +20,36 @@ #include "inspircd.h" #include "xline.h" - -/* $ModConfig: <xlinedb filename="data/xline.db"> - * Specify the filename for the xline database here*/ -/* $ModDesc: Keeps a dynamic log of all XLines created, and stores them in a seperate conf file (xline.db). */ +#include <fstream> class ModuleXLineDB : public Module { bool dirty; std::string xlinedbpath; public: - void init() + void init() CXX11_OVERRIDE { /* Load the configuration * Note: - * this is on purpose not in the OnRehash() method. It would be non-trivial to change the database on-the-fly. + * This is on purpose not changed on a rehash. It would be non-trivial to change the database on-the-fly. * Imagine a scenario where the new file already exists. Merging the current XLines with the existing database is likely a bad idea * ...and so is discarding all current in-memory XLines for the ones in the database. */ ConfigTag* Conf = ServerInstance->Config->ConfValue("xlinedb"); - xlinedbpath = Conf->getString("filename", DATA_PATH "/xline.db"); + xlinedbpath = ServerInstance->Config->Paths.PrependData(Conf->getString("filename", "xline.db")); // Read xlines before attaching to events ReadDatabase(); - Implementation eventlist[] = { I_OnAddLine, I_OnDelLine, I_OnExpireLine, I_OnBackgroundTimer }; - ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation)); dirty = false; } - virtual ~ModuleXLineDB() - { - } - /** Called whenever an xline is added by a local user. * This method is triggered after the line is added. * @param source The sender of the line or NULL for local server * @param line The xline being added */ - void OnAddLine(User* source, XLine* line) + void OnAddLine(User* source, XLine* line) CXX11_OVERRIDE { dirty = true; } @@ -68,17 +59,17 @@ class ModuleXLineDB : public Module * @param source The user removing the line or NULL for local server * @param line the line being deleted */ - void OnDelLine(User* source, XLine* line) + void OnDelLine(User* source, XLine* line) CXX11_OVERRIDE { dirty = true; } - void OnExpireLine(XLine *line) + void OnExpireLine(XLine *line) CXX11_OVERRIDE { dirty = true; } - void OnBackgroundTimer(time_t now) + void OnBackgroundTimer(time_t now) CXX11_OVERRIDE { if (dirty) { @@ -89,25 +80,23 @@ class ModuleXLineDB : public Module bool WriteDatabase() { - FILE *f; - /* * We need to perform an atomic write so as not to fuck things up. - * So, let's write to a temporary file, flush and sync the FD, then rename the file.. + * So, let's write to a temporary file, flush it, then rename the file.. * Technically, that means that this can block, but I have *never* seen that. - * -- w00t + * -- w00t */ - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Opening temporary database"); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opening temporary database"); std::string xlinenewdbpath = xlinedbpath + ".new"; - f = fopen(xlinenewdbpath.c_str(), "w"); - if (!f) + std::ofstream stream(xlinenewdbpath.c_str()); + if (!stream.is_open()) { - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot create database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot create database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno); return false; } - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Opened. Writing.."); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Opened. Writing.."); /* * Now, much as I hate writing semi-unportable formats, additional @@ -116,7 +105,7 @@ class ModuleXLineDB : public Module * semblance of backwards compatibility for reading on startup.. * -- w00t */ - fprintf(f, "VERSION 1\n"); + stream << "VERSION 1" << std::endl; // Now, let's write. std::vector<std::string> types = ServerInstance->XLines->GetAllTypes(); @@ -129,22 +118,21 @@ class ModuleXLineDB : public Module for (LookupIter i = lookup->begin(); i != lookup->end(); ++i) { XLine* line = i->second; - fprintf(f, "LINE %s %s %s %lu %lu :%s\n", line->type.c_str(), line->Displayable(), - ServerInstance->Config->ServerName.c_str(), (unsigned long)line->set_time, (unsigned long)line->duration, line->reason.c_str()); + stream << "LINE " << line->type << " " << line->Displayable() << " " + << ServerInstance->Config->ServerName << " " << line->set_time << " " + << line->duration << " :" << line->reason << std::endl; } } - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Finished writing XLines. Checking for error.."); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Finished writing XLines. Checking for error.."); - int write_error = 0; - write_error = ferror(f); - write_error |= fclose(f); - if (write_error) + if (stream.fail()) { - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot write to new database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot write to new database \"%s\"! %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new xline db \"%s\": %s (%d)", xlinenewdbpath.c_str(), strerror(errno), errno); return false; } + stream.close(); #ifdef _WIN32 remove(xlinedbpath.c_str()); @@ -152,8 +140,8 @@ class ModuleXLineDB : public Module // Use rename to move temporary to new db - this is guarenteed not to fuck up, even in case of a crash. if (rename(xlinenewdbpath.c_str(), xlinedbpath.c_str()) < 0) { - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot move new to old database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot replace old database \"%s\" with new database \"%s\"! %s (%d)", xlinedbpath.c_str(), xlinenewdbpath.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old xline db \"%s\" with new db \"%s\": %s (%d)", xlinedbpath.c_str(), xlinenewdbpath.c_str(), strerror(errno), errno); return false; } @@ -162,42 +150,23 @@ class ModuleXLineDB : public Module bool ReadDatabase() { - FILE *f; - char linebuf[MAXBUF]; + // If the xline database doesn't exist then we don't need to load it. + if (!FileSystem::FileExists(xlinedbpath)) + return true; - f = fopen(xlinedbpath.c_str(), "r"); - if (!f) + std::ifstream stream(xlinedbpath.c_str()); + if (!stream.is_open()) { - if (errno == ENOENT) - { - /* xline.db doesn't exist, fake good return value (we don't care about this) */ - return true; - } - else - { - /* this might be slightly more problematic. */ - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Cannot read database! %s (%d)", strerror(errno), errno); - ServerInstance->SNO->WriteToSnoMask('a', "database: cannot read db: %s (%d)", strerror(errno), errno); - return false; - } + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cannot read database \"%s\"! %s (%d)", xlinedbpath.c_str(), strerror(errno), errno); + ServerInstance->SNO->WriteToSnoMask('a', "database: cannot read xline db \"%s\": %s (%d)", xlinedbpath.c_str(), strerror(errno), errno); + return false; } - while (fgets(linebuf, MAXBUF, f)) + std::string line; + while (std::getline(stream, line)) { - char *c = linebuf; - - while (c && *c) - { - if (*c == '\n') - { - *c = '\0'; - } - - c++; - } - // Inspired by the command parser. :) - irc::tokenstream tokens(linebuf); + irc::tokenstream tokens(line); int items = 0; std::string command_p[7]; std::string tmp; @@ -208,18 +177,14 @@ class ModuleXLineDB : public Module items++; } - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Processing %s", linebuf); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing %s", line.c_str()); if (command_p[0] == "VERSION") { - if (command_p[1] == "1") - { - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: Reading db version %s", command_p[1].c_str()); - } - else + if (command_p[1] != "1") { - fclose(f); - ServerInstance->Logs->Log("m_xline_db",DEBUG, "xlinedb: I got database version %s - I don't understand it", command_p[1].c_str()); + stream.close(); + ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "I got database version %s - I don't understand it", command_p[1].c_str()); ServerInstance->SNO->WriteToSnoMask('a', "database: I got a database version (%s) I don't understand", command_p[1].c_str()); return false; } @@ -246,18 +211,14 @@ class ModuleXLineDB : public Module delete xl; } } - - fclose(f); + stream.close(); return true; } - - - virtual Version GetVersion() + Version GetVersion() CXX11_OVERRIDE { return Version("Keeps a dynamic log of all XLines created, and stores them in a separate conf file (xline.db).", VF_VENDOR); } }; MODULE_INIT(ModuleXLineDB) - diff --git a/src/modules/spanningtree.h b/src/modules/spanningtree.h deleted file mode 100644 index 212f35ff3..000000000 --- a/src/modules/spanningtree.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef SPANNINGTREE_H -#define SPANNINGTREE_H - -struct AddServerEvent : public Event -{ - const std::string servername; - AddServerEvent(Module* me, const std::string& name) - : Event(me, "new_server"), servername(name) - { - Send(); - } -}; - -struct DelServerEvent : public Event -{ - const std::string servername; - DelServerEvent(Module* me, const std::string& name) - : Event(me, "lost_server"), servername(name) - { - Send(); - } -}; - -#endif diff --git a/src/modules/sql.h b/src/modules/sql.h deleted file mode 100644 index 436cd1da8..000000000 --- a/src/modules/sql.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2010 Daniel De Graaf <danieldg@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef INSPIRCD_SQLAPI_3 -#define INSPIRCD_SQLAPI_3 - -/** Defines the error types which SQLerror may be set to - */ -enum SQLerrorNum { SQL_NO_ERROR, SQL_BAD_DBID, SQL_BAD_CONN, SQL_QSEND_FAIL, SQL_QREPLY_FAIL }; - -/** A list of format parameters for an SQLquery object. - */ -typedef std::vector<std::string> ParamL; - -typedef std::map<std::string, std::string> ParamM; - -class SQLEntry -{ - public: - std::string value; - bool nul; - SQLEntry() : nul(true) {} - SQLEntry(const std::string& v) : value(v), nul(false) {} - inline operator std::string&() { return value; } -}; - -typedef std::vector<SQLEntry> SQLEntries; - -/** - * Result of an SQL query. Only valid inside OnResult - */ -class SQLResult : public classbase -{ - public: - /** - * Return the number of rows in the result. - * - * Note that if you have perfomed an INSERT or UPDATE query or other - * query which will not return rows, this will return the number of - * affected rows. In this case you SHOULD NEVER access any of the result - * set rows, as there aren't any! - * @returns Number of rows in the result set. - */ - virtual int Rows() = 0; - - /** - * Return a single row (result of the query). The internal row counter - * is incremented by one. - * - * @param result Storage for the result data. - * @returns true if there was a row, false if no row exists (end of - * iteration) - */ - virtual bool GetRow(SQLEntries& result) = 0; - - /** Returns column names for the items in this row - */ - virtual void GetCols(std::vector<std::string>& result) = 0; -}; - -/** SQLerror holds the error state of a request. - * The error string varies from database software to database software - * and should be used to display informational error messages to users. - */ -class SQLerror -{ - public: - /** The error id - */ - SQLerrorNum id; - - /** The error string - */ - std::string str; - - /** Initialize an SQLerror - * @param i The error ID to set - * @param s The (optional) error string to set - */ - SQLerror(SQLerrorNum i, const std::string &s = "") - : id(i), str(s) - { - } - - /** Return the error string for an error - */ - const char* Str() - { - if(str.length()) - return str.c_str(); - - switch(id) - { - case SQL_BAD_DBID: - return "Invalid database ID"; - case SQL_BAD_CONN: - return "Invalid connection"; - case SQL_QSEND_FAIL: - return "Sending query failed"; - case SQL_QREPLY_FAIL: - return "Getting query result failed"; - default: - return "Unknown error"; - } - } -}; - -/** - * Object representing an SQL query. This should be allocated on the heap and - * passed to an SQLProvider, which will free it when the query is complete or - * when the querying module is unloaded. - * - * You should store whatever information is needed to have the callbacks work in - * this object (UID of user, channel name, etc). - */ -class SQLQuery : public classbase -{ - public: - ModuleRef creator; - - SQLQuery(Module* Creator) : creator(Creator) {} - virtual ~SQLQuery() {} - - virtual void OnResult(SQLResult& result) = 0; - /** - * Called when the query fails - */ - virtual void OnError(SQLerror& error) { } -}; - -/** - * Provider object for SQL servers - */ -class SQLProvider : public DataProvider -{ - public: - SQLProvider(Module* Creator, const std::string& Name) : DataProvider(Creator, Name) {} - /** Submit an asynchronous SQL request - * @param callback The result reporting point - * @param query The hardcoded query string. If you have parameters to substitute, see below. - */ - virtual void submit(SQLQuery* callback, const std::string& query) = 0; - - /** Submit an asynchronous SQL request - * @param callback The result reporting point - * @param format The simple parameterized query string ('?' parameters) - * @param p Parameters to fill in for the '?' entries - */ - virtual void submit(SQLQuery* callback, const std::string& format, const ParamL& p) = 0; - - /** Submit an asynchronous SQL request. - * @param callback The result reporting point - * @param format The parameterized query string ('$name' parameters) - * @param p Parameters to fill in for the '$name' entries - */ - virtual void submit(SQLQuery* callback, const std::string& format, const ParamM& p) = 0; - - /** Convenience function to prepare a map from a User* */ - void PopulateUserInfo(User* user, ParamM& userinfo) - { - userinfo["nick"] = user->nick; - userinfo["host"] = user->host; - userinfo["ip"] = user->GetIPString(); - userinfo["gecos"] = user->fullname; - userinfo["ident"] = user->ident; - userinfo["server"] = user->server; - userinfo["uuid"] = user->uuid; - } -}; - -#endif diff --git a/src/modules/ssl.h b/src/modules/ssl.h deleted file mode 100644 index 4c877551d..000000000 --- a/src/modules/ssl.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * Copyright (C) 2006 Craig Edwards <craigedwards@brainbox.cc> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef SSL_H -#define SSL_H - -#include <map> -#include <string> - -/** ssl_cert is a class which abstracts SSL certificate - * and key information. - * - * Because gnutls and openssl represent key information in - * wildly different ways, this class allows it to be accessed - * in a unified manner. These classes are attached to ssl- - * connected local users using SSLCertExt - */ -class ssl_cert : public refcountbase -{ - public: - std::string dn; - std::string issuer; - std::string error; - std::string fingerprint; - bool trusted, invalid, unknownsigner, revoked; - - ssl_cert() : trusted(false), invalid(true), unknownsigner(true), revoked(false) {} - - /** Get certificate distinguished name - * @return Certificate DN - */ - const std::string& GetDN() - { - return dn; - } - - /** Get Certificate issuer - * @return Certificate issuer - */ - const std::string& GetIssuer() - { - return issuer; - } - - /** Get error string if an error has occured - * @return The error associated with this users certificate, - * or an empty string if there is no error. - */ - const std::string& GetError() - { - return error; - } - - /** Get key fingerprint. - * @return The key fingerprint as a hex string. - */ - const std::string& GetFingerprint() - { - return fingerprint; - } - - /** Get trust status - * @return True if this is a trusted certificate - * (the certificate chain validates) - */ - bool IsTrusted() - { - return trusted; - } - - /** Get validity status - * @return True if the certificate itself is - * correctly formed. - */ - bool IsInvalid() - { - return invalid; - } - - /** Get signer status - * @return True if the certificate appears to be - * self-signed. - */ - bool IsUnknownSigner() - { - return unknownsigner; - } - - /** Get revokation status. - * @return True if the certificate is revoked. - * Note that this only works properly for GnuTLS - * right now. - */ - bool IsRevoked() - { - return revoked; - } - - bool IsCAVerified() - { - return trusted && !invalid && !revoked && !unknownsigner && error.empty(); - } - - std::string GetMetaLine() - { - std::stringstream value; - bool hasError = !error.empty(); - value << (IsInvalid() ? "v" : "V") << (IsTrusted() ? "T" : "t") << (IsRevoked() ? "R" : "r") - << (IsUnknownSigner() ? "s" : "S") << (hasError ? "E" : "e") << " "; - if (hasError) - value << GetError(); - else - value << GetFingerprint() << " " << GetDN() << " " << GetIssuer(); - return value.str(); - } -}; - -/** Get certificate from a socket (only useful with an SSL module) */ -struct SocketCertificateRequest : public Request -{ - StreamSocket* const sock; - ssl_cert* cert; - - SocketCertificateRequest(StreamSocket* ss, Module* Me) - : Request(Me, ss->GetIOHook(), "GET_SSL_CERT"), sock(ss), cert(NULL) - { - Send(); - } - - std::string GetFingerprint() - { - if (cert) - return cert->GetFingerprint(); - return ""; - } -}; - -/** Get certificate from a user (requires m_sslinfo) */ -struct UserCertificateRequest : public Request -{ - User* const user; - ssl_cert* cert; - - UserCertificateRequest(User* u, Module* Me, Module* info = ServerInstance->Modules->Find("m_sslinfo.so")) - : Request(Me, info, "GET_USER_CERT"), user(u), cert(NULL) - { - Send(); - } - - std::string GetFingerprint() - { - if (cert) - return cert->GetFingerprint(); - return ""; - } -}; - -class SSLRawSessionRequest : public Request -{ - public: - const int fd; - void* data; - - SSLRawSessionRequest(int FD, Module* srcmod, Module* destmod) - : Request(srcmod, destmod, "GET_RAW_SSL_SESSION") - , fd(FD) - , data(NULL) - { - Send(); - } -}; - -#endif diff --git a/src/modules/u_listmode.h b/src/modules/u_listmode.h deleted file mode 100644 index a728eb839..000000000 --- a/src/modules/u_listmode.h +++ /dev/null @@ -1,425 +0,0 @@ -/* - * InspIRCd -- Internet Relay Chat Daemon - * - * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org> - * - * This file is part of InspIRCd. InspIRCd is free software: you can - * redistribute it and/or modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation, version 2. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - - -#ifndef INSPIRCD_LISTMODE_PROVIDER -#define INSPIRCD_LISTMODE_PROVIDER - -/** Get the time as a string - */ -inline std::string stringtime() -{ - std::ostringstream TIME; - TIME << ServerInstance->Time(); - return TIME.str(); -} - -/** An item in a listmode's list - */ -class ListItem -{ -public: - std::string nick; - std::string mask; - std::string time; -}; - -/** The number of items a listmode's list may contain - */ -class ListLimit -{ -public: - std::string mask; - unsigned int limit; -}; - -/** Items stored in the channel's list - */ -typedef std::list<ListItem> modelist; -/** Max items per channel by name - */ -typedef std::list<ListLimit> limitlist; - -/** The base class for list modes, should be inherited. - */ -class ListModeBase : public ModeHandler -{ - protected: - /** Numeric to use when outputting the list - */ - unsigned int listnumeric; - /** Numeric to indicate end of list - */ - unsigned int endoflistnumeric; - /** String to send for end of list - */ - std::string endofliststring; - /** Automatically tidy up entries - */ - bool tidy; - /** Config tag to check for max items per channel - */ - std::string configtag; - /** Limits on a per-channel basis read from the tag - * specified in ListModeBase::configtag - */ - limitlist chanlimits; - - public: - /** Storage key - */ - SimpleExtItem<modelist> extItem; - - /** Constructor. - * @param Instance The creator of this class - * @param modechar Mode character - * @param eolstr End of list string - * @pram lnum List numeric - * @param eolnum End of list numeric - * @param autotidy Automatically tidy list entries on add - * @param ctag Configuration tag to get limits from - */ - ListModeBase(Module* Creator, const std::string& Name, char modechar, const std::string &eolstr, unsigned int lnum, unsigned int eolnum, bool autotidy, const std::string &ctag = "banlist") - : ModeHandler(Creator, Name, modechar, PARAM_ALWAYS, MODETYPE_CHANNEL), - listnumeric(lnum), endoflistnumeric(eolnum), endofliststring(eolstr), tidy(autotidy), - configtag(ctag), extItem("listbase_mode_" + name + "_list", Creator) - { - list = true; - } - - /** See mode.h - */ - std::pair<bool,std::string> ModeSet(User*, User*, Channel* channel, const std::string ¶meter) - { - modelist* el = extItem.get(channel); - if (el) - { - for (modelist::iterator it = el->begin(); it != el->end(); it++) - { - if(parameter == it->mask) - { - return std::make_pair(true, parameter); - } - } - } - return std::make_pair(false, parameter); - } - - /** Display the list for this mode - * @param user The user to send the list to - * @param channel The channel the user is requesting the list for - */ - virtual void DisplayList(User* user, Channel* channel) - { - modelist* el = extItem.get(channel); - if (el) - { - for (modelist::reverse_iterator it = el->rbegin(); it != el->rend(); ++it) - { - user->WriteNumeric(listnumeric, "%s %s %s %s %s", user->nick.c_str(), channel->name.c_str(), it->mask.c_str(), (it->nick.length() ? it->nick.c_str() : ServerInstance->Config->ServerName.c_str()), it->time.c_str()); - } - } - user->WriteNumeric(endoflistnumeric, "%s %s :%s", user->nick.c_str(), channel->name.c_str(), endofliststring.c_str()); - } - - virtual void DisplayEmptyList(User* user, Channel* channel) - { - user->WriteNumeric(endoflistnumeric, "%s %s :%s", user->nick.c_str(), channel->name.c_str(), endofliststring.c_str()); - } - - /** Remove all instances of the mode from a channel. - * See mode.h - * @param channel The channel to remove all instances of the mode from - */ - virtual void RemoveMode(Channel* channel, irc::modestacker* stack) - { - modelist* el = extItem.get(channel); - if (el) - { - irc::modestacker modestack(false); - - for (modelist::iterator it = el->begin(); it != el->end(); it++) - { - if (stack) - stack->Push(this->GetModeChar(), it->mask); - else - modestack.Push(this->GetModeChar(), it->mask); - } - - if (stack) - return; - - std::vector<std::string> stackresult; - stackresult.push_back(channel->name); - while (modestack.GetStackedLine(stackresult)) - { - ServerInstance->SendMode(stackresult, ServerInstance->FakeClient); - stackresult.clear(); - stackresult.push_back(channel->name); - } - } - } - - /** See mode.h - */ - virtual void RemoveMode(User*, irc::modestacker* stack) - { - /* Listmodes dont get set on users */ - } - - /** Perform a rehash of this mode's configuration data - */ - virtual void DoRehash() - { - ConfigTagList tags = ServerInstance->Config->ConfTags(configtag); - - chanlimits.clear(); - - for (ConfigIter i = tags.first; i != tags.second; i++) - { - // For each <banlist> tag - ConfigTag* c = i->second; - ListLimit limit; - limit.mask = c->getString("chan"); - limit.limit = c->getInt("limit"); - - if (limit.mask.size() && limit.limit > 0) - chanlimits.push_back(limit); - } - - // Add the default entry. This is inserted last so if the user specifies a - // wildcard record in the config it will take precedence over this entry. - ListLimit limit; - limit.mask = "*"; - limit.limit = 64; - chanlimits.push_back(limit); - } - - /** Populate the Implements list with the correct events for a List Mode - */ - virtual void DoImplements(Module* m) - { - ServerInstance->Modules->AddService(extItem); - this->DoRehash(); - Implementation eventlist[] = { I_OnSyncChannel, I_OnRehash }; - ServerInstance->Modules->Attach(eventlist, m, sizeof(eventlist)/sizeof(Implementation)); - } - - /** Handle the list mode. - * See mode.h - */ - virtual ModeAction OnModeChange(User* source, User*, Channel* channel, std::string ¶meter, bool adding) - { - // Try and grab the list - modelist* el = extItem.get(channel); - - if (adding) - { - if (tidy) - ModeParser::CleanMask(parameter); - - if (parameter.length() > 250) - return MODEACTION_DENY; - - // If there was no list - if (!el) - { - // Make one - el = new modelist; - extItem.set(channel, el); - } - - // Check if the item already exists in the list - for (modelist::iterator it = el->begin(); it != el->end(); it++) - { - if (parameter == it->mask) - { - /* Give a subclass a chance to error about this */ - TellAlreadyOnList(source, channel, parameter); - - // it does, deny the change - return MODEACTION_DENY; - } - } - - unsigned int maxsize = 0; - - for (limitlist::iterator it = chanlimits.begin(); it != chanlimits.end(); it++) - { - if (InspIRCd::Match(channel->name, it->mask)) - { - // We have a pattern matching the channel... - maxsize = el->size(); - if (!IS_LOCAL(source) || (maxsize < it->limit)) - { - /* Ok, it *could* be allowed, now give someone subclassing us - * a chance to validate the parameter. - * The param is passed by reference, so they can both modify it - * and tell us if we allow it or not. - * - * eg, the subclass could: - * 1) allow - * 2) 'fix' parameter and then allow - * 3) deny - */ - if (ValidateParam(source, channel, parameter)) - { - // And now add the mask onto the list... - ListItem e; - e.mask = parameter; - e.nick = source->nick; - e.time = stringtime(); - - el->push_back(e); - return MODEACTION_ALLOW; - } - else - { - /* If they deny it they have the job of giving an error message */ - return MODEACTION_DENY; - } - } - else - break; - } - } - - /* List is full, give subclass a chance to send a custom message */ - if (!TellListTooLong(source, channel, parameter)) - { - source->WriteNumeric(478, "%s %s %s :Channel ban/ignore list is full", source->nick.c_str(), channel->name.c_str(), parameter.c_str()); - } - - parameter.clear(); - return MODEACTION_DENY; - } - else - { - // We're taking the mode off - if (el) - { - for (modelist::iterator it = el->begin(); it != el->end(); it++) - { - if (parameter == it->mask) - { - el->erase(it); - if (el->empty()) - { - extItem.unset(channel); - } - return MODEACTION_ALLOW; - } - } - /* Tried to remove something that wasn't set */ - TellNotSet(source, channel, parameter); - parameter.clear(); - return MODEACTION_DENY; - } - else - { - /* Hmm, taking an exception off a non-existant list, DIE */ - TellNotSet(source, channel, parameter); - parameter.clear(); - return MODEACTION_DENY; - } - } - return MODEACTION_DENY; - } - - /** Syncronize channel item list with another server. - * See modules.h - * @param chan Channel to syncronize - * @param proto Protocol module pointer - * @param opaque Opaque connection handle - */ - virtual void DoSyncChannel(Channel* chan, Module* proto, void* opaque) - { - modelist* mlist = extItem.get(chan); - irc::modestacker modestack(true); - std::vector<std::string> stackresult; - std::vector<TranslateType> types; - types.push_back(TR_TEXT); - if (mlist) - { - for (modelist::iterator it = mlist->begin(); it != mlist->end(); it++) - { - modestack.Push(std::string(1, mode)[0], it->mask); - } - } - while (modestack.GetStackedLine(stackresult)) - { - types.assign(stackresult.size(), this->GetTranslateType()); - proto->ProtoSendMode(opaque, TYPE_CHANNEL, chan, stackresult, types); - stackresult.clear(); - } - } - - /** Clean up module on unload - * @param target_type Type of target to clean - * @param item Item to clean - */ - virtual void DoCleanup(int, void*) - { - } - - /** Validate parameters. - * Overridden by implementing module. - * @param source Source user adding the parameter - * @param channel Channel the parameter is being added to - * @param parameter The actual parameter being added - * @return true if the parameter is valid - */ - virtual bool ValidateParam(User*, Channel*, std::string&) - { - return true; - } - - /** Tell the user the list is too long. - * Overridden by implementing module. - * @param source Source user adding the parameter - * @param channel Channel the parameter is being added to - * @param parameter The actual parameter being added - * @return Ignored - */ - virtual bool TellListTooLong(User*, Channel*, std::string&) - { - return false; - } - - /** Tell the user an item is already on the list. - * Overridden by implementing module. - * @param source Source user adding the parameter - * @param channel Channel the parameter is being added to - * @param parameter The actual parameter being added - */ - virtual void TellAlreadyOnList(User*, Channel*, std::string&) - { - } - - /** Tell the user that the parameter is not in the list. - * Overridden by implementing module. - * @param source Source user removing the parameter - * @param channel Channel the parameter is being removed from - * @param parameter The actual parameter being removed - */ - virtual void TellNotSet(User*, Channel*, std::string&) - { - } -}; - -#endif |