From f2acdbc3820f0f4f5ef76a0a64e73d2a320df91f Mon Sep 17 00:00:00 2001 From: peavey Date: Mon, 16 Jul 2007 17:30:04 +0000 Subject: OOPS! We try again, since I'm smoking craq. LF is 0x0a NOT CR. git-svn-id: http://svn.inspircd.org/repository/trunk/inspircd@7456 e03df62e-2008-0410-955e-edbf42e46eb7 --- src/modules/extra/README | 8 +- src/modules/extra/m_filter_pcre.cpp | 183 ++- src/modules/extra/m_httpclienttest.cpp | 82 +- src/modules/extra/m_mysql.cpp | 890 +++++++++++++- src/modules/extra/m_pgsql.cpp | 985 +++++++++++++++- src/modules/extra/m_sqlauth.cpp | 195 +++- src/modules/extra/m_sqlite3.cpp | 661 ++++++++++- src/modules/extra/m_sqllog.cpp | 311 ++++- src/modules/extra/m_sqloper.cpp | 284 ++++- src/modules/extra/m_sqlutils.cpp | 239 +++- src/modules/extra/m_sqlutils.h | 144 ++- src/modules/extra/m_sqlv2.h | 606 +++++++++- src/modules/extra/m_ssl_gnutls.cpp | 844 +++++++++++++- src/modules/extra/m_ssl_openssl.cpp | 902 +++++++++++++- src/modules/extra/m_ssl_oper_cert.cpp | 181 ++- src/modules/extra/m_sslinfo.cpp | 95 +- src/modules/extra/m_testclient.cpp | 111 +- src/modules/extra/m_ziplink.cpp | 453 ++++++- src/modules/httpclient.h | 128 +- src/modules/httpd.h | 167 ++- src/modules/m_alias.cpp | 273 ++++- src/modules/m_alltime.cpp | 84 +- src/modules/m_antibear.cpp | 79 +- src/modules/m_antibottler.cpp | 100 +- src/modules/m_auditorium.cpp | 192 ++- src/modules/m_banexception.cpp | 154 ++- src/modules/m_banredirect.cpp | 344 +++++- src/modules/m_blockamsg.cpp | 192 ++- src/modules/m_blockcaps.cpp | 144 ++- src/modules/m_blockcolor.cpp | 119 +- src/modules/m_botmode.cpp | 96 +- src/modules/m_cban.cpp | 252 +++- src/modules/m_censor.cpp | 197 +++- src/modules/m_cgiirc.cpp | 512 +++++++- src/modules/m_chancreate.cpp | 56 +- src/modules/m_chanfilter.cpp | 156 ++- src/modules/m_chanprotect.cpp | 532 ++++++++- src/modules/m_check.cpp | 189 ++- src/modules/m_chghost.cpp | 121 +- src/modules/m_chgident.cpp | 93 +- src/modules/m_chgname.cpp | 90 +- src/modules/m_cloaking.cpp | 316 ++++- src/modules/m_clones.cpp | 101 +- src/modules/m_conn_join.cpp | 97 +- src/modules/m_conn_umodes.cpp | 105 +- src/modules/m_conn_waitpong.cpp | 149 ++- src/modules/m_connflood.cpp | 121 +- src/modules/m_cycle.cpp | 100 +- src/modules/m_dccallow.cpp | 490 +++++++- src/modules/m_deaf.cpp | 136 ++- src/modules/m_denychans.cpp | 81 +- src/modules/m_devoice.cpp | 82 +- src/modules/m_dnsbl.cpp | 354 +++++- src/modules/m_filter.cpp | 136 ++- src/modules/m_filter.h | 454 +++++++- src/modules/m_foobar.cpp | 99 +- src/modules/m_globalload.cpp | 142 ++- src/modules/m_globops.cpp | 77 +- src/modules/m_hash.h | 197 +++- src/modules/m_helpop.cpp | 192 ++- src/modules/m_hidechans.cpp | 96 +- src/modules/m_hideoper.cpp | 95 +- src/modules/m_hostchange.cpp | 149 ++- src/modules/m_http_client.cpp | 347 +++++- src/modules/m_httpd.cpp | 420 ++++++- src/modules/m_httpd_stats.cpp | 242 +++- src/modules/m_ident.cpp | 327 +++++- src/modules/m_invisible.cpp | 278 ++++- src/modules/m_inviteexception.cpp | 151 ++- src/modules/m_joinflood.cpp | 286 ++++- src/modules/m_jumpserver.cpp | 165 ++- src/modules/m_kicknorejoin.cpp | 225 +++- src/modules/m_knock.cpp | 130 ++- src/modules/m_lockserv.cpp | 132 ++- src/modules/m_md5.cpp | 323 ++++- src/modules/m_messageflood.cpp | 305 ++++- src/modules/m_namesx.cpp | 128 +- src/modules/m_nicklock.cpp | 160 ++- src/modules/m_noctcp.cpp | 108 +- src/modules/m_noinvite.cpp | 89 +- src/modules/m_nokicks.cpp | 106 +- src/modules/m_nonicks.cpp | 103 +- src/modules/m_nonotice.cpp | 104 +- src/modules/m_oper_hash.cpp | 164 ++- src/modules/m_operchans.cpp | 98 +- src/modules/m_operjoin.cpp | 91 +- src/modules/m_operlevels.cpp | 123 +- src/modules/m_operlog.cpp | 76 +- src/modules/m_opermodes.cpp | 110 +- src/modules/m_opermotd.cpp | 117 +- src/modules/m_override.cpp | 295 ++++- src/modules/m_randquote.cpp | 139 ++- src/modules/m_redirect.cpp | 161 ++- src/modules/m_regonlycreate.cpp | 62 +- src/modules/m_remove.cpp | 289 ++++- src/modules/m_restrictbanned.cpp | 99 +- src/modules/m_restrictchans.cpp | 86 +- src/modules/m_restrictmsg.cpp | 76 +- src/modules/m_safelist.cpp | 269 ++++- src/modules/m_sajoin.cpp | 115 +- src/modules/m_samode.cpp | 99 +- src/modules/m_sanick.cpp | 98 +- src/modules/m_sapart.cpp | 114 +- src/modules/m_saquit.cpp | 83 +- src/modules/m_securelist.cpp | 98 +- src/modules/m_seenicks.cpp | 56 +- src/modules/m_services.cpp | 311 ++++- src/modules/m_services_account.cpp | 333 +++++- src/modules/m_sethost.cpp | 109 +- src/modules/m_setident.cpp | 84 +- src/modules/m_setidle.cpp | 75 +- src/modules/m_setname.cpp | 81 +- src/modules/m_sha256.cpp | 297 ++++- src/modules/m_showwhois.cpp | 110 +- src/modules/m_silence.cpp | 216 +++- src/modules/m_silence_ext.cpp | 373 +++++- src/modules/m_spanningtree/README | 25 +- src/modules/m_spanningtree/handshaketimer.cpp | 63 +- src/modules/m_spanningtree/handshaketimer.h | 38 +- src/modules/m_spanningtree/link.h | 43 +- src/modules/m_spanningtree/main.cpp | 1393 +++++++++++++++++++++- src/modules/m_spanningtree/main.h | 199 +++- src/modules/m_spanningtree/rconnect.cpp | 68 +- src/modules/m_spanningtree/rconnect.h | 29 +- src/modules/m_spanningtree/resolvers.cpp | 89 +- src/modules/m_spanningtree/resolvers.h | 91 +- src/modules/m_spanningtree/rsquit.cpp | 124 +- src/modules/m_spanningtree/rsquit.h | 30 +- src/modules/m_spanningtree/timesynctimer.cpp | 53 +- src/modules/m_spanningtree/timesynctimer.h | 48 +- src/modules/m_spanningtree/treeserver.cpp | 326 +++++- src/modules/m_spanningtree/treeserver.h | 187 ++- src/modules/m_spanningtree/treesocket.h | 414 ++++++- src/modules/m_spanningtree/treesocket1.cpp | 1274 +++++++++++++++++++- src/modules/m_spanningtree/treesocket2.cpp | 1555 ++++++++++++++++++++++++- src/modules/m_spanningtree/utils.cpp | 650 ++++++++++- src/modules/m_spanningtree/utils.h | 195 +++- src/modules/m_spy.cpp | 164 ++- src/modules/m_ssl_dummy.cpp | 85 +- src/modules/m_sslmodes.cpp | 146 ++- src/modules/m_stripcolor.cpp | 186 ++- src/modules/m_svshold.cpp | 283 ++++- src/modules/m_swhois.cpp | 268 ++++- src/modules/m_taxonomy.cpp | 100 +- src/modules/m_testcommand.cpp | 68 +- src/modules/m_timedbans.cpp | 205 +++- src/modules/m_tline.cpp | 96 +- src/modules/m_uhnames.cpp | 99 +- src/modules/m_uninvite.cpp | 108 +- src/modules/m_userip.cpp | 87 +- src/modules/m_vhost.cpp | 96 +- src/modules/m_watch.cpp | 473 +++++++- src/modules/m_xmlsocket.cpp | 171 ++- src/modules/transport.h | 232 +++- 154 files changed, 33856 insertions(+), 154 deletions(-) (limited to 'src/modules') diff --git a/src/modules/extra/README b/src/modules/extra/README index 4c4beef9d..7e3096b34 100644 --- a/src/modules/extra/README +++ b/src/modules/extra/README @@ -1 +1,7 @@ -This directory stores modules which require external libraries to compile. For example, m_filter_pcre requires the PCRE libraries. To compile any of these modules first ensure you have the required dependencies (read the online documentation at http://www.inspircd.org/wiki/) and then cp the .cpp file from this directory into the parent directory (src/modules/) and re-configure your inspircd with ./configure -update to detect the new module. \ No newline at end of file +This directory stores modules which require external libraries to compile. +For example, m_filter_pcre requires the PCRE libraries. + +To compile any of these modules first ensure you have the required dependencies +(read the online documentation at http://www.inspircd.org/wiki/) and then cp +the .cpp file from this directory into the parent directory (src/modules/) and +re-configure your inspircd with ./configure -update to detect the new module. diff --git a/src/modules/extra/m_filter_pcre.cpp b/src/modules/extra/m_filter_pcre.cpp index 0c6c05c8c..6fe79a981 100644 --- a/src/modules/extra/m_filter_pcre.cpp +++ b/src/modules/extra/m_filter_pcre.cpp @@ -1 +1,182 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include "users.h" #include "channels.h" #include "modules.h" #include "m_filter.h" /* $ModDesc: m_filter with regexps */ /* $CompileFlags: exec("pcre-config --cflags") */ /* $LinkerFlags: exec("pcre-config --libs") rpath("pcre-config --libs") -lpcre */ /* $ModDep: m_filter.h */ #ifdef WINDOWS #pragma comment(lib, "pcre.lib") #endif class PCREFilter : public FilterResult { public: pcre* regexp; PCREFilter(pcre* r, const std::string &rea, const std::string &act, long gline_time, const std::string &pat, const std::string &flags) : FilterResult(pat, rea, act, gline_time, flags), regexp(r) { } PCREFilter() { } }; class ModuleFilterPCRE : public FilterBase { std::vector filters; pcre *re; const char *error; int erroffset; PCREFilter fr; public: ModuleFilterPCRE(InspIRCd* Me) : FilterBase(Me, "m_filter_pcre.so") { OnRehash(NULL,""); } virtual ~ModuleFilterPCRE() { } virtual FilterResult* FilterMatch(userrec* user, const std::string &text, int flags) { for (std::vector::iterator index = filters.begin(); index != filters.end(); index++) { /* Skip ones that dont apply to us */ if (!FilterBase::AppliesToMe(user, dynamic_cast(&(*index)), flags)) continue; if (pcre_exec(index->regexp, NULL, text.c_str(), text.length(), 0, 0, NULL, 0) > -1) { fr = *index; if (index != filters.begin()) { filters.erase(index); filters.insert(filters.begin(), fr); } return &fr; } } return NULL; } virtual bool DeleteFilter(const std::string &freeform) { for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) { if (i->freeform == freeform) { pcre_free((*i).regexp); filters.erase(i); return true; } } return false; } virtual void SyncFilters(Module* proto, void* opaque) { for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) { this->SendFilter(proto, opaque, &(*i)); } } virtual std::pair AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flags) { for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) { if (i->freeform == freeform) { return std::make_pair(false, "Filter already exists"); } } re = pcre_compile(freeform.c_str(),0,&error,&erroffset,NULL); if (!re) { ServerInstance->Log(DEFAULT,"Error in regular expression: %s at offset %d: %s\n", freeform.c_str(), erroffset, error); ServerInstance->Log(DEFAULT,"Regular expression %s not loaded.", freeform.c_str()); return std::make_pair(false, "Error in regular expression at offset " + ConvToStr(erroffset) + ": "+error); } else { filters.push_back(PCREFilter(re, reason, type, duration, freeform, flags)); return std::make_pair(true, ""); } } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader MyConf(ServerInstance); for (int index = 0; index < MyConf.Enumerate("keyword"); index++) { this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index)); std::string pattern = MyConf.ReadValue("keyword", "pattern", index); std::string reason = MyConf.ReadValue("keyword", "reason", index); std::string action = MyConf.ReadValue("keyword", "action", index); std::string flags = MyConf.ReadValue("keyword", "flags", index); long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index)); if (action.empty()) action = "none"; if (flags.empty()) flags = "*"; re = pcre_compile(pattern.c_str(),0,&error,&erroffset,NULL); if (!re) { ServerInstance->Log(DEFAULT,"Error in regular expression: %s at offset %d: %s\n", pattern.c_str(), erroffset, error); ServerInstance->Log(DEFAULT,"Regular expression %s not loaded.", pattern.c_str()); } else { filters.push_back(PCREFilter(re, reason, action, gline_time, pattern, flags)); ServerInstance->Log(DEFAULT,"Regular expression %s loaded.", pattern.c_str()); } } } virtual int OnStats(char symbol, userrec* user, string_list &results) { if (symbol == 's') { std::string sn = ServerInstance->Config->ServerName; for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) { results.push_back(sn+" 223 "+user->nick+" :REGEXP:"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason); } } return 0; } }; MODULE_INIT(ModuleFilterPCRE); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "m_filter.h" + +/* $ModDesc: m_filter with regexps */ +/* $CompileFlags: exec("pcre-config --cflags") */ +/* $LinkerFlags: exec("pcre-config --libs") rpath("pcre-config --libs") -lpcre */ +/* $ModDep: m_filter.h */ + +#ifdef WINDOWS +#pragma comment(lib, "pcre.lib") +#endif + +class PCREFilter : public FilterResult +{ + public: + pcre* regexp; + + PCREFilter(pcre* r, const std::string &rea, const std::string &act, long gline_time, const std::string &pat, const std::string &flags) + : FilterResult(pat, rea, act, gline_time, flags), regexp(r) + { + } + + PCREFilter() + { + } +}; + +class ModuleFilterPCRE : public FilterBase +{ + std::vector filters; + pcre *re; + const char *error; + int erroffset; + PCREFilter fr; + + public: + ModuleFilterPCRE(InspIRCd* Me) + : FilterBase(Me, "m_filter_pcre.so") + { + OnRehash(NULL,""); + } + + virtual ~ModuleFilterPCRE() + { + } + + virtual FilterResult* FilterMatch(userrec* user, const std::string &text, int flags) + { + for (std::vector::iterator index = filters.begin(); index != filters.end(); index++) + { + /* Skip ones that dont apply to us */ + + if (!FilterBase::AppliesToMe(user, dynamic_cast(&(*index)), flags)) + continue; + + if (pcre_exec(index->regexp, NULL, text.c_str(), text.length(), 0, 0, NULL, 0) > -1) + { + fr = *index; + if (index != filters.begin()) + { + filters.erase(index); + filters.insert(filters.begin(), fr); + } + return &fr; + } + } + return NULL; + } + + virtual bool DeleteFilter(const std::string &freeform) + { + for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) + { + if (i->freeform == freeform) + { + pcre_free((*i).regexp); + filters.erase(i); + return true; + } + } + return false; + } + + virtual void SyncFilters(Module* proto, void* opaque) + { + for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) + { + this->SendFilter(proto, opaque, &(*i)); + } + } + + virtual std::pair AddFilter(const std::string &freeform, const std::string &type, const std::string &reason, long duration, const std::string &flags) + { + for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) + { + if (i->freeform == freeform) + { + return std::make_pair(false, "Filter already exists"); + } + } + + re = pcre_compile(freeform.c_str(),0,&error,&erroffset,NULL); + + if (!re) + { + ServerInstance->Log(DEFAULT,"Error in regular expression: %s at offset %d: %s\n", freeform.c_str(), erroffset, error); + ServerInstance->Log(DEFAULT,"Regular expression %s not loaded.", freeform.c_str()); + return std::make_pair(false, "Error in regular expression at offset " + ConvToStr(erroffset) + ": "+error); + } + else + { + filters.push_back(PCREFilter(re, reason, type, duration, freeform, flags)); + return std::make_pair(true, ""); + } + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader MyConf(ServerInstance); + + for (int index = 0; index < MyConf.Enumerate("keyword"); index++) + { + this->DeleteFilter(MyConf.ReadValue("keyword", "pattern", index)); + + std::string pattern = MyConf.ReadValue("keyword", "pattern", index); + std::string reason = MyConf.ReadValue("keyword", "reason", index); + std::string action = MyConf.ReadValue("keyword", "action", index); + std::string flags = MyConf.ReadValue("keyword", "flags", index); + long gline_time = ServerInstance->Duration(MyConf.ReadValue("keyword", "duration", index)); + if (action.empty()) + action = "none"; + if (flags.empty()) + flags = "*"; + + re = pcre_compile(pattern.c_str(),0,&error,&erroffset,NULL); + + if (!re) + { + ServerInstance->Log(DEFAULT,"Error in regular expression: %s at offset %d: %s\n", pattern.c_str(), erroffset, error); + ServerInstance->Log(DEFAULT,"Regular expression %s not loaded.", pattern.c_str()); + } + else + { + filters.push_back(PCREFilter(re, reason, action, gline_time, pattern, flags)); + ServerInstance->Log(DEFAULT,"Regular expression %s loaded.", pattern.c_str()); + } + } + } + + virtual int OnStats(char symbol, userrec* user, string_list &results) + { + if (symbol == 's') + { + std::string sn = ServerInstance->Config->ServerName; + for (std::vector::iterator i = filters.begin(); i != filters.end(); i++) + { + results.push_back(sn+" 223 "+user->nick+" :REGEXP:"+i->freeform+" "+i->flags+" "+i->action+" "+ConvToStr(i->gline_time)+" :"+i->reason); + } + } + return 0; + } +}; + +MODULE_INIT(ModuleFilterPCRE); + diff --git a/src/modules/extra/m_httpclienttest.cpp b/src/modules/extra/m_httpclienttest.cpp index 3f74b549b..90e7a5159 100644 --- a/src/modules/extra/m_httpclienttest.cpp +++ b/src/modules/extra/m_httpclienttest.cpp @@ -1 +1,81 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "httpclient.h" /* $ModDep: httpclient.h */ class MyModule : public Module { public: MyModule(InspIRCd* Me) : Module::Module(Me) { } virtual ~MyModule() { } virtual void Implements(char* List) { List[I_OnRequest] = List[I_OnUserJoin] = List[I_OnUserPart] = 1; } virtual Version GetVersion() { return Version(1,0,0,1,VF_VENDOR,API_VERSION); } virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) { // method called when a user joins a channel std::string chan = channel->name; std::string nick = user->nick; ServerInstance->Log(DEBUG,"User " + nick + " joined " + chan); Module* target = ServerInstance->FindModule("m_http_client.so"); if(target) { HTTPClientRequest req(ServerInstance, this, target, "http://znc.in/~psychon"); req.Send(); } else ServerInstance->Log(DEBUG,"module not found, load it!!"); } char* OnRequest(Request* req) { HTTPClientResponse* resp = (HTTPClientResponse*)req; if(!strcmp(resp->GetId(), HTTP_CLIENT_RESPONSE)) { ServerInstance->Log(DEBUG, resp->GetData()); } return NULL; } virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent) { } }; MODULE_INIT(MyModule); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "httpclient.h" + +/* $ModDep: httpclient.h */ + +class MyModule : public Module +{ + +public: + + MyModule(InspIRCd* Me) + : Module::Module(Me) + { + } + + virtual ~MyModule() + { + } + + virtual void Implements(char* List) + { + List[I_OnRequest] = List[I_OnUserJoin] = List[I_OnUserPart] = 1; + } + + virtual Version GetVersion() + { + return Version(1,0,0,1,VF_VENDOR,API_VERSION); + } + + virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) + { + // method called when a user joins a channel + + std::string chan = channel->name; + std::string nick = user->nick; + ServerInstance->Log(DEBUG,"User " + nick + " joined " + chan); + + Module* target = ServerInstance->FindModule("m_http_client.so"); + if(target) + { + HTTPClientRequest req(ServerInstance, this, target, "http://znc.in/~psychon"); + req.Send(); + } + else + ServerInstance->Log(DEBUG,"module not found, load it!!"); + } + + char* OnRequest(Request* req) + { + HTTPClientResponse* resp = (HTTPClientResponse*)req; + if(!strcmp(resp->GetId(), HTTP_CLIENT_RESPONSE)) + { + ServerInstance->Log(DEBUG, resp->GetData()); + } + return NULL; + } + + virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent) + { + } + +}; + +MODULE_INIT(MyModule); + diff --git a/src/modules/extra/m_mysql.cpp b/src/modules/extra/m_mysql.cpp index eeabe5d48..6605bed3c 100644 --- a/src/modules/extra/m_mysql.cpp +++ b/src/modules/extra/m_mysql.cpp @@ -1 +1,889 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #include "users.h" #include "channels.h" #include "modules.h" #include "m_sqlv2.h" /* VERSION 2 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") */ /* $ModDep: m_sqlv2.h */ /* THE NONBLOCKING MYSQL API! * * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend * that instead, you should thread your program. This is what i've done here to allow for * asyncronous SQL requests via mysql. The way this works is as follows: * * The module spawns a thread via pthreads, and performs its mysql queries in this thread, * using a queue with priorities. There is a mutex on either end which prevents two threads * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the * worker thread wakes up, and checks if there is a request at the head of its queue. * If there is, it processes this request, blocking the worker thread but leaving the ircd * thread to go about its business as usual. During this period, the ircd thread is able * to insert futher pending requests into the queue. * * Once the processing of a request is complete, it is removed from the incoming queue to * an outgoing queue, and initialized as a 'response'. The worker thread then signals the * ircd thread (via a loopback socket) of the fact a result is available, by sending the * connection ID through the connection. * * The ircd thread then mutexes the queue once more, reads the outbound response off the head * of the queue, and sends it on its way to the original calling module. * * XXX: You might be asking "why doesnt he just send the response from within the worker thread?" * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not * threadsafe. This module is designed to be threadsafe and is careful with its use of threads, * however, if we were to call a module's OnRequest even from within a thread which was not the * one the module was originally instantiated upon, there is a chance of all hell breaking loose * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100% * gauranteed threadsafe!) * * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2 */ class SQLConnection; class Notifier; typedef std::map ConnMap; bool giveup = false; static Module* SQLModule = NULL; static Notifier* MessagePipe = NULL; int QueueFD = -1; #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224 #define mysql_field_count mysql_num_fields #endif typedef std::deque ResultQueue; /* A mutex to wrap around queue accesses */ pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER; /** Represents a mysql result set */ class MySQLresult : public SQLresult { int currentrow; std::vector colnames; std::vector fieldlists; SQLfieldMap* fieldmap; SQLfieldMap fieldmap2; SQLfieldList emptyfieldlist; int rows; public: MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL) { /* A number of affected rows from from mysql_affected_rows. */ fieldlists.clear(); rows = 0; if (affected_rows >= 1) { rows = affected_rows; fieldlists.resize(rows); } unsigned int field_count = 0; if (res) { MYSQL_ROW row; int n = 0; while ((row = mysql_fetch_row(res))) { if (fieldlists.size() < (unsigned int)rows+1) { fieldlists.resize(fieldlists.size()+1); } field_count = 0; MYSQL_FIELD *fields = mysql_fetch_fields(res); if(mysql_num_fields(res) == 0) break; if (fields && mysql_num_fields(res)) { colnames.clear(); while (field_count < mysql_num_fields(res)) { std::string a = (fields[field_count].name ? fields[field_count].name : ""); std::string b = (row[field_count] ? row[field_count] : ""); SQLfield sqlf(b, !row[field_count]); colnames.push_back(a); fieldlists[n].push_back(sqlf); field_count++; } n++; } rows++; } mysql_free_result(res); } } MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0) { rows = 0; error = e; } ~MySQLresult() { } virtual int Rows() { return rows; } virtual int Cols() { return colnames.size(); } virtual std::string ColName(int column) { if (column < (int)colnames.size()) { return colnames[column]; } else { throw SQLbadColName(); } return ""; } virtual int ColNum(const std::string &column) { for (unsigned int i = 0; i < colnames.size(); i++) { if (column == colnames[i]) return i; } throw SQLbadColName(); return 0; } virtual SQLfield GetValue(int row, int column) { if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) { return fieldlists[row][column]; } throw SQLbadColName(); /* XXX: We never actually get here because of the throw */ return SQLfield("",true); } virtual SQLfieldList& GetRow() { if (currentrow < rows) return fieldlists[currentrow]; else return emptyfieldlist; } virtual SQLfieldMap& GetRowMap() { fieldmap2.clear(); if (currentrow < rows) { for (int i = 0; i < Cols(); i++) { fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i))); } currentrow++; } return fieldmap2; } virtual SQLfieldList* GetRowPtr() { SQLfieldList* fieldlist = new SQLfieldList(); if (currentrow < rows) { for (int i = 0; i < Rows(); i++) { fieldlist->push_back(fieldlists[currentrow][i]); } currentrow++; } return fieldlist; } virtual SQLfieldMap* GetRowMapPtr() { fieldmap = new SQLfieldMap(); if (currentrow < rows) { for (int i = 0; i < Cols(); i++) { fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i))); } currentrow++; } return fieldmap; } virtual void Free(SQLfieldMap* fm) { delete fm; } virtual void Free(SQLfieldList* fl) { delete fl; } }; class SQLConnection; void NotifyMainThread(SQLConnection* connection_with_new_result); /** Represents a connection to a mysql database */ class SQLConnection : public classbase { protected: MYSQL connection; MYSQL_RES *res; MYSQL_ROW row; SQLhost host; std::map thisrow; bool Enabled; public: QueryQueue queue; ResultQueue rq; // This constructor creates an SQLConnection object with the given credentials, but does not connect yet. SQLConnection(const SQLhost &hi) : host(hi), Enabled(false) { } ~SQLConnection() { Close(); } // This method connects to the database using the credentials supplied to the constructor, and returns // true upon success. bool Connect() { unsigned int timeout = 1; mysql_init(&connection); mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout); return mysql_real_connect(&connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0); } void DoLeadingQuery() { if (!CheckConnection()) return; /* Parse the command string and dispatch it to mysql */ SQLrequest& req = queue.front(); /* Pointer to the buffer we screw around with substitution in */ char* query; /* Pointer to the current end of query, where we append new stuff */ char* queryend; /* Total length of the unescaped parameters */ unsigned long paramlen; /* Total length of query, used for binary-safety in mysql_real_query */ unsigned long querylength = 0; paramlen = 0; for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) { paramlen += i->size(); } /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. * sizeofquery + (totalparamlength*2) + 1 * * The +1 is for null-terminating the string for mysql_real_escape_string */ query = new char[req.query.q.length() + (paramlen*2) + 1]; queryend = query; /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting * the parameters into it... */ for(unsigned long i = 0; i < req.query.q.length(); i++) { if(req.query.q[i] == '?') { /* We found a place to substitute..what fun. * use mysql calls to escape and write the * escaped string onto the end of our query buffer, * then we "just" need to make sure queryend is * pointing at the right place. */ if(req.query.p.size()) { unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length()); queryend += len; req.query.p.pop_front(); } else break; } else { *queryend = req.query.q[i]; queryend++; } querylength++; } *queryend = 0; pthread_mutex_lock(&queue_mutex); req.query.q = query; pthread_mutex_unlock(&queue_mutex); if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length())) { /* Successfull query */ res = mysql_use_result(&connection); unsigned long rows = mysql_affected_rows(&connection); MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id); r->dbid = this->GetID(); r->query = req.query.q; /* Put this new result onto the results queue. * XXX: Remember to mutex the queue! */ pthread_mutex_lock(&results_mutex); rq.push_back(r); pthread_mutex_unlock(&results_mutex); } else { /* XXX: See /usr/include/mysql/mysqld_error.h for a list of * possible error numbers and error messages */ SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection)); MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id); r->dbid = this->GetID(); r->query = req.query.q; pthread_mutex_lock(&results_mutex); rq.push_back(r); pthread_mutex_unlock(&results_mutex); } /* Now signal the main thread that we've got a result to process. * Pass them this connection id as what to examine */ delete[] query; NotifyMainThread(this); } bool ConnectionLost() { if (&connection) { return (mysql_ping(&connection) != 0); } else return false; } bool CheckConnection() { if (ConnectionLost()) { return Connect(); } else return true; } std::string GetError() { return mysql_error(&connection); } const std::string& GetID() { return host.id; } std::string GetHost() { return host.host; } void SetEnable(bool Enable) { Enabled = Enable; } bool IsEnabled() { return Enabled; } void Close() { mysql_close(&connection); } const SQLhost& GetConfHost() { return host; } }; ConnMap Connections; bool HasHost(const SQLhost &host) { for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++) { if (host == iter->second->GetConfHost()) return true; } return false; } bool HostInConf(ConfigReader* conf, const SQLhost &h) { for(int i = 0; i < conf->Enumerate("database"); i++) { SQLhost host; host.id = conf->ReadValue("database", "id", i); host.host = conf->ReadValue("database", "hostname", i); host.port = conf->ReadInteger("database", "port", i, true); host.name = conf->ReadValue("database", "name", i); host.user = conf->ReadValue("database", "username", i); host.pass = conf->ReadValue("database", "password", i); host.ssl = conf->ReadFlag("database", "ssl", i); if (h == host) return true; } return false; } void ClearOldConnections(ConfigReader* conf) { ConnMap::iterator i,safei; for (i = Connections.begin(); i != Connections.end(); i++) { if (!HostInConf(conf, i->second->GetConfHost())) { DELETE(i->second); safei = i; --i; Connections.erase(safei); } } } void ClearAllConnections() { ConnMap::iterator i; while ((i = Connections.begin()) != Connections.end()) { Connections.erase(i); DELETE(i->second); } } void ConnectDatabases(InspIRCd* ServerInstance) { for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++) { if (i->second->IsEnabled()) continue; i->second->SetEnable(true); if (!i->second->Connect()) { /* XXX: MUTEX */ pthread_mutex_lock(&logging_mutex); ServerInstance->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError()); i->second->SetEnable(false); pthread_mutex_unlock(&logging_mutex); } } } void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance) { ClearOldConnections(conf); for (int j =0; j < conf->Enumerate("database"); j++) { SQLhost host; host.id = conf->ReadValue("database", "id", j); host.host = conf->ReadValue("database", "hostname", j); host.port = conf->ReadInteger("database", "port", j, true); host.name = conf->ReadValue("database", "name", j); host.user = conf->ReadValue("database", "username", j); host.pass = conf->ReadValue("database", "password", j); host.ssl = conf->ReadFlag("database", "ssl", j); if (HasHost(host)) continue; if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty()) { SQLConnection* ThisSQL = new SQLConnection(host); Connections[host.id] = ThisSQL; } } ConnectDatabases(ServerInstance); } char FindCharId(const std::string &id) { char i = 1; for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i) { if (iter->first == id) { return i; } } return 0; } ConnMap::iterator GetCharId(char id) { char i = 1; for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i) { if (i == id) return iter; } return Connections.end(); } void NotifyMainThread(SQLConnection* connection_with_new_result) { /* Here we write() to the socket the main thread has open * and we connect()ed back to before our thread became active. * The main thread is using a nonblocking socket tied into * the socket engine, so they wont block and they'll receive * nearly instant notification. Because we're in a seperate * thread, we can just use standard connect(), and we can * block if we like. We just send the connection id of the * connection back. * * NOTE: We only send a single char down the connection, this * way we know it wont get a partial read at the other end if * the system is especially congested (see bug #263). * The function FindCharId translates a connection name into a * one character id, and GetCharId translates a character id * back into an iterator. */ char id = FindCharId(connection_with_new_result->GetID()); send(QueueFD, &id, 1, 0); } void* DispatcherThread(void* arg); /** Used by m_mysql to notify one thread when the other has a result */ class Notifier : public InspSocket { insp_sockaddr sock_us; socklen_t uslen; public: /* Create a socket on a random port. Let the tcp stack allocate us an available port */ #ifdef IPV6 Notifier(InspIRCd* SI) : InspSocket(SI, "::1", 0, true, 3000) #else Notifier(InspIRCd* SI) : InspSocket(SI, "127.0.0.1", 0, true, 3000) #endif { uslen = sizeof(sock_us); if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen)) { throw ModuleException("Could not create random listening port on localhost"); } } Notifier(InspIRCd* SI, int newfd, char* ip) : InspSocket(SI, newfd, ip) { } /* Using getsockname and ntohs, we can determine which port number we were allocated */ int GetPort() { #ifdef IPV6 return ntohs(sock_us.sin6_port); #else return ntohs(sock_us.sin_port); #endif } virtual int OnIncomingConnection(int newsock, char* ip) { Notifier* n = new Notifier(this->Instance, newsock, ip); n = n; /* Stop bitching at me, GCC */ return true; } virtual bool OnDataReady() { char data = 0; /* NOTE: Only a single character is read so we know we * cant get a partial read. (We've been told that theres * data waiting, so we wont ever get EAGAIN) * The function GetCharId translates a single character * back into an iterator. */ if (read(this->GetFd(), &data, 1) > 0) { ConnMap::iterator iter = GetCharId(data); if (iter != Connections.end()) { /* Lock the mutex, send back the data */ pthread_mutex_lock(&results_mutex); ResultQueue::iterator n = iter->second->rq.begin(); (*n)->Send(); iter->second->rq.pop_front(); pthread_mutex_unlock(&results_mutex); return true; } /* No error, but unknown id */ return true; } /* Erk, error on descriptor! */ return false; } }; /** MySQL module */ class ModuleSQL : public Module { public: ConfigReader *Conf; InspIRCd* PublicServerInstance; pthread_t Dispatcher; int currid; bool rehashing; ModuleSQL(InspIRCd* Me) : Module::Module(Me), rehashing(false) { ServerInstance->UseInterface("SQLutils"); Conf = new ConfigReader(ServerInstance); PublicServerInstance = ServerInstance; currid = 0; SQLModule = this; MessagePipe = new Notifier(ServerInstance); pthread_attr_t attribs; pthread_attr_init(&attribs); pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED); if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0) { throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno))); } if (!ServerInstance->PublishFeature("SQL", this)) { /* Tell worker thread to exit NOW */ giveup = true; throw ModuleException("m_mysql: Unable to publish feature 'SQL'"); } ServerInstance->PublishInterface("SQL", this); } virtual ~ModuleSQL() { giveup = true; ClearAllConnections(); DELETE(Conf); ServerInstance->UnpublishInterface("SQL", this); ServerInstance->UnpublishFeature("SQL"); ServerInstance->DoneWithInterface("SQLutils"); } void Implements(char* List) { List[I_OnRehash] = List[I_OnRequest] = 1; } unsigned long NewID() { if (currid+1 == 0) currid++; return ++currid; } char* OnRequest(Request* request) { if(strcmp(SQLREQID, request->GetId()) == 0) { SQLrequest* req = (SQLrequest*)request; /* XXX: Lock */ pthread_mutex_lock(&queue_mutex); ConnMap::iterator iter; char* returnval = NULL; if((iter = Connections.find(req->dbid)) != Connections.end()) { req->id = NewID(); iter->second->queue.push(*req); returnval = SQLSUCCESS; } else { req->error.Id(BAD_DBID); } pthread_mutex_unlock(&queue_mutex); /* XXX: Unlock */ return returnval; } return NULL; } virtual void OnRehash(userrec* user, const std::string ¶meter) { rehashing = true; } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION); } }; void* DispatcherThread(void* arg) { ModuleSQL* thismodule = (ModuleSQL*)arg; LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance); /* Connect back to the Notifier */ if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1) { /* crap, we're out of sockets... */ return NULL; } insp_sockaddr addr; #ifdef IPV6 insp_aton("::1", &addr.sin6_addr); addr.sin6_family = AF_FAMILY; addr.sin6_port = htons(MessagePipe->GetPort()); #else insp_inaddr ia; insp_aton("127.0.0.1", &ia); addr.sin_family = AF_FAMILY; addr.sin_addr = ia; addr.sin_port = htons(MessagePipe->GetPort()); #endif if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1) { /* wtf, we cant connect to it, but we just created it! */ return NULL; } while (!giveup) { if (thismodule->rehashing) { /* XXX: Lock */ pthread_mutex_lock(&queue_mutex); thismodule->rehashing = false; LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance); pthread_mutex_unlock(&queue_mutex); /* XXX: Unlock */ } SQLConnection* conn = NULL; /* XXX: Lock here for safety */ pthread_mutex_lock(&queue_mutex); for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++) { if (i->second->queue.totalsize()) { conn = i->second; break; } } pthread_mutex_unlock(&queue_mutex); /* XXX: Unlock */ /* Theres an item! */ if (conn) { conn->DoLeadingQuery(); /* XXX: Lock */ pthread_mutex_lock(&queue_mutex); conn->queue.pop(); pthread_mutex_unlock(&queue_mutex); /* XXX: Unlock */ } usleep(50); } return NULL; } MODULE_INIT(ModuleSQL); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "m_sqlv2.h" + +/* VERSION 2 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") */ +/* $ModDep: m_sqlv2.h */ + +/* THE NONBLOCKING MYSQL API! + * + * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend + * that instead, you should thread your program. This is what i've done here to allow for + * asyncronous SQL requests via mysql. The way this works is as follows: + * + * The module spawns a thread via pthreads, and performs its mysql queries in this thread, + * using a queue with priorities. There is a mutex on either end which prevents two threads + * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the + * worker thread wakes up, and checks if there is a request at the head of its queue. + * If there is, it processes this request, blocking the worker thread but leaving the ircd + * thread to go about its business as usual. During this period, the ircd thread is able + * to insert futher pending requests into the queue. + * + * Once the processing of a request is complete, it is removed from the incoming queue to + * an outgoing queue, and initialized as a 'response'. The worker thread then signals the + * ircd thread (via a loopback socket) of the fact a result is available, by sending the + * connection ID through the connection. + * + * The ircd thread then mutexes the queue once more, reads the outbound response off the head + * of the queue, and sends it on its way to the original calling module. + * + * XXX: You might be asking "why doesnt he just send the response from within the worker thread?" + * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not + * threadsafe. This module is designed to be threadsafe and is careful with its use of threads, + * however, if we were to call a module's OnRequest even from within a thread which was not the + * one the module was originally instantiated upon, there is a chance of all hell breaking loose + * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data + * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100% + * gauranteed threadsafe!) + * + * For a diagram of this system please see http://www.inspircd.org/wiki/Mysql2 + */ + + +class SQLConnection; +class Notifier; + + +typedef std::map ConnMap; +bool giveup = false; +static Module* SQLModule = NULL; +static Notifier* MessagePipe = NULL; +int QueueFD = -1; + + +#if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224 +#define mysql_field_count mysql_num_fields +#endif + +typedef std::deque ResultQueue; + +/* A mutex to wrap around queue accesses */ +pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER; + +pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER; + +pthread_mutex_t logging_mutex = PTHREAD_MUTEX_INITIALIZER; + +/** Represents a mysql result set + */ +class MySQLresult : public SQLresult +{ + int currentrow; + std::vector colnames; + std::vector fieldlists; + SQLfieldMap* fieldmap; + SQLfieldMap fieldmap2; + SQLfieldList emptyfieldlist; + int rows; + public: + + MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int id) : SQLresult(self, to, id), currentrow(0), fieldmap(NULL) + { + /* A number of affected rows from from mysql_affected_rows. + */ + fieldlists.clear(); + rows = 0; + if (affected_rows >= 1) + { + rows = affected_rows; + fieldlists.resize(rows); + } + unsigned int field_count = 0; + if (res) + { + MYSQL_ROW row; + int n = 0; + while ((row = mysql_fetch_row(res))) + { + if (fieldlists.size() < (unsigned int)rows+1) + { + fieldlists.resize(fieldlists.size()+1); + } + field_count = 0; + MYSQL_FIELD *fields = mysql_fetch_fields(res); + if(mysql_num_fields(res) == 0) + break; + if (fields && mysql_num_fields(res)) + { + colnames.clear(); + while (field_count < mysql_num_fields(res)) + { + std::string a = (fields[field_count].name ? fields[field_count].name : ""); + std::string b = (row[field_count] ? row[field_count] : ""); + SQLfield sqlf(b, !row[field_count]); + colnames.push_back(a); + fieldlists[n].push_back(sqlf); + field_count++; + } + n++; + } + rows++; + } + mysql_free_result(res); + } + } + + MySQLresult(Module* self, Module* to, SQLerror e, unsigned int id) : SQLresult(self, to, id), currentrow(0) + { + rows = 0; + error = e; + } + + ~MySQLresult() + { + } + + virtual int Rows() + { + return rows; + } + + virtual int Cols() + { + return colnames.size(); + } + + virtual std::string ColName(int column) + { + if (column < (int)colnames.size()) + { + return colnames[column]; + } + else + { + throw SQLbadColName(); + } + return ""; + } + + virtual int ColNum(const std::string &column) + { + for (unsigned int i = 0; i < colnames.size(); i++) + { + if (column == colnames[i]) + return i; + } + throw SQLbadColName(); + return 0; + } + + virtual SQLfield GetValue(int row, int column) + { + if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) + { + return fieldlists[row][column]; + } + + throw SQLbadColName(); + + /* XXX: We never actually get here because of the throw */ + return SQLfield("",true); + } + + virtual SQLfieldList& GetRow() + { + if (currentrow < rows) + return fieldlists[currentrow]; + else + return emptyfieldlist; + } + + virtual SQLfieldMap& GetRowMap() + { + fieldmap2.clear(); + + if (currentrow < rows) + { + for (int i = 0; i < Cols(); i++) + { + fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i))); + } + currentrow++; + } + + return fieldmap2; + } + + virtual SQLfieldList* GetRowPtr() + { + SQLfieldList* fieldlist = new SQLfieldList(); + + if (currentrow < rows) + { + for (int i = 0; i < Rows(); i++) + { + fieldlist->push_back(fieldlists[currentrow][i]); + } + currentrow++; + } + return fieldlist; + } + + virtual SQLfieldMap* GetRowMapPtr() + { + fieldmap = new SQLfieldMap(); + + if (currentrow < rows) + { + for (int i = 0; i < Cols(); i++) + { + fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i))); + } + currentrow++; + } + + return fieldmap; + } + + virtual void Free(SQLfieldMap* fm) + { + delete fm; + } + + virtual void Free(SQLfieldList* fl) + { + delete fl; + } +}; + +class SQLConnection; + +void NotifyMainThread(SQLConnection* connection_with_new_result); + +/** Represents a connection to a mysql database + */ +class SQLConnection : public classbase +{ + protected: + + MYSQL connection; + MYSQL_RES *res; + MYSQL_ROW row; + SQLhost host; + std::map thisrow; + bool Enabled; + + public: + + QueryQueue queue; + ResultQueue rq; + + // This constructor creates an SQLConnection object with the given credentials, but does not connect yet. + SQLConnection(const SQLhost &hi) : host(hi), Enabled(false) + { + } + + ~SQLConnection() + { + Close(); + } + + // This method connects to the database using the credentials supplied to the constructor, and returns + // true upon success. + bool Connect() + { + unsigned int timeout = 1; + mysql_init(&connection); + mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout); + return mysql_real_connect(&connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0); + } + + void DoLeadingQuery() + { + if (!CheckConnection()) + return; + + /* Parse the command string and dispatch it to mysql */ + SQLrequest& req = queue.front(); + + /* Pointer to the buffer we screw around with substitution in */ + char* query; + + /* Pointer to the current end of query, where we append new stuff */ + char* queryend; + + /* Total length of the unescaped parameters */ + unsigned long paramlen; + + /* Total length of query, used for binary-safety in mysql_real_query */ + unsigned long querylength = 0; + + paramlen = 0; + + for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) + { + paramlen += i->size(); + } + + /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. + * sizeofquery + (totalparamlength*2) + 1 + * + * The +1 is for null-terminating the string for mysql_real_escape_string + */ + + query = new char[req.query.q.length() + (paramlen*2) + 1]; + queryend = query; + + /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting + * the parameters into it... + */ + + for(unsigned long i = 0; i < req.query.q.length(); i++) + { + if(req.query.q[i] == '?') + { + /* We found a place to substitute..what fun. + * use mysql calls to escape and write the + * escaped string onto the end of our query buffer, + * then we "just" need to make sure queryend is + * pointing at the right place. + */ + if(req.query.p.size()) + { + unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length()); + + queryend += len; + req.query.p.pop_front(); + } + else + break; + } + else + { + *queryend = req.query.q[i]; + queryend++; + } + querylength++; + } + + *queryend = 0; + + pthread_mutex_lock(&queue_mutex); + req.query.q = query; + pthread_mutex_unlock(&queue_mutex); + + if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length())) + { + /* Successfull query */ + res = mysql_use_result(&connection); + unsigned long rows = mysql_affected_rows(&connection); + MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows, req.id); + r->dbid = this->GetID(); + r->query = req.query.q; + /* Put this new result onto the results queue. + * XXX: Remember to mutex the queue! + */ + pthread_mutex_lock(&results_mutex); + rq.push_back(r); + pthread_mutex_unlock(&results_mutex); + } + else + { + /* XXX: See /usr/include/mysql/mysqld_error.h for a list of + * possible error numbers and error messages */ + SQLerror e(QREPLY_FAIL, ConvToStr(mysql_errno(&connection)) + std::string(": ") + mysql_error(&connection)); + MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e, req.id); + r->dbid = this->GetID(); + r->query = req.query.q; + + pthread_mutex_lock(&results_mutex); + rq.push_back(r); + pthread_mutex_unlock(&results_mutex); + } + + /* Now signal the main thread that we've got a result to process. + * Pass them this connection id as what to examine + */ + + delete[] query; + + NotifyMainThread(this); + } + + bool ConnectionLost() + { + if (&connection) { + return (mysql_ping(&connection) != 0); + } + else return false; + } + + bool CheckConnection() + { + if (ConnectionLost()) { + return Connect(); + } + else return true; + } + + std::string GetError() + { + return mysql_error(&connection); + } + + const std::string& GetID() + { + return host.id; + } + + std::string GetHost() + { + return host.host; + } + + void SetEnable(bool Enable) + { + Enabled = Enable; + } + + bool IsEnabled() + { + return Enabled; + } + + void Close() + { + mysql_close(&connection); + } + + const SQLhost& GetConfHost() + { + return host; + } + +}; + +ConnMap Connections; + +bool HasHost(const SQLhost &host) +{ + for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++) + { + if (host == iter->second->GetConfHost()) + return true; + } + return false; +} + +bool HostInConf(ConfigReader* conf, const SQLhost &h) +{ + for(int i = 0; i < conf->Enumerate("database"); i++) + { + SQLhost host; + host.id = conf->ReadValue("database", "id", i); + host.host = conf->ReadValue("database", "hostname", i); + host.port = conf->ReadInteger("database", "port", i, true); + host.name = conf->ReadValue("database", "name", i); + host.user = conf->ReadValue("database", "username", i); + host.pass = conf->ReadValue("database", "password", i); + host.ssl = conf->ReadFlag("database", "ssl", i); + if (h == host) + return true; + } + return false; +} + +void ClearOldConnections(ConfigReader* conf) +{ + ConnMap::iterator i,safei; + for (i = Connections.begin(); i != Connections.end(); i++) + { + if (!HostInConf(conf, i->second->GetConfHost())) + { + DELETE(i->second); + safei = i; + --i; + Connections.erase(safei); + } + } +} + +void ClearAllConnections() +{ + ConnMap::iterator i; + while ((i = Connections.begin()) != Connections.end()) + { + Connections.erase(i); + DELETE(i->second); + } +} + +void ConnectDatabases(InspIRCd* ServerInstance) +{ + for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++) + { + if (i->second->IsEnabled()) + continue; + + i->second->SetEnable(true); + if (!i->second->Connect()) + { + /* XXX: MUTEX */ + pthread_mutex_lock(&logging_mutex); + ServerInstance->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError()); + i->second->SetEnable(false); + pthread_mutex_unlock(&logging_mutex); + } + } +} + +void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance) +{ + ClearOldConnections(conf); + for (int j =0; j < conf->Enumerate("database"); j++) + { + SQLhost host; + host.id = conf->ReadValue("database", "id", j); + host.host = conf->ReadValue("database", "hostname", j); + host.port = conf->ReadInteger("database", "port", j, true); + host.name = conf->ReadValue("database", "name", j); + host.user = conf->ReadValue("database", "username", j); + host.pass = conf->ReadValue("database", "password", j); + host.ssl = conf->ReadFlag("database", "ssl", j); + + if (HasHost(host)) + continue; + + if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty()) + { + SQLConnection* ThisSQL = new SQLConnection(host); + Connections[host.id] = ThisSQL; + } + } + ConnectDatabases(ServerInstance); +} + +char FindCharId(const std::string &id) +{ + char i = 1; + for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i) + { + if (iter->first == id) + { + return i; + } + } + return 0; +} + +ConnMap::iterator GetCharId(char id) +{ + char i = 1; + for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i) + { + if (i == id) + return iter; + } + return Connections.end(); +} + +void NotifyMainThread(SQLConnection* connection_with_new_result) +{ + /* Here we write() to the socket the main thread has open + * and we connect()ed back to before our thread became active. + * The main thread is using a nonblocking socket tied into + * the socket engine, so they wont block and they'll receive + * nearly instant notification. Because we're in a seperate + * thread, we can just use standard connect(), and we can + * block if we like. We just send the connection id of the + * connection back. + * + * NOTE: We only send a single char down the connection, this + * way we know it wont get a partial read at the other end if + * the system is especially congested (see bug #263). + * The function FindCharId translates a connection name into a + * one character id, and GetCharId translates a character id + * back into an iterator. + */ + char id = FindCharId(connection_with_new_result->GetID()); + send(QueueFD, &id, 1, 0); +} + +void* DispatcherThread(void* arg); + +/** Used by m_mysql to notify one thread when the other has a result + */ +class Notifier : public InspSocket +{ + insp_sockaddr sock_us; + socklen_t uslen; + + + public: + + /* Create a socket on a random port. Let the tcp stack allocate us an available port */ +#ifdef IPV6 + Notifier(InspIRCd* SI) : InspSocket(SI, "::1", 0, true, 3000) +#else + Notifier(InspIRCd* SI) : InspSocket(SI, "127.0.0.1", 0, true, 3000) +#endif + { + uslen = sizeof(sock_us); + if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen)) + { + throw ModuleException("Could not create random listening port on localhost"); + } + } + + Notifier(InspIRCd* SI, int newfd, char* ip) : InspSocket(SI, newfd, ip) + { + } + + /* Using getsockname and ntohs, we can determine which port number we were allocated */ + int GetPort() + { +#ifdef IPV6 + return ntohs(sock_us.sin6_port); +#else + return ntohs(sock_us.sin_port); +#endif + } + + virtual int OnIncomingConnection(int newsock, char* ip) + { + Notifier* n = new Notifier(this->Instance, newsock, ip); + n = n; /* Stop bitching at me, GCC */ + return true; + } + + virtual bool OnDataReady() + { + char data = 0; + /* NOTE: Only a single character is read so we know we + * cant get a partial read. (We've been told that theres + * data waiting, so we wont ever get EAGAIN) + * The function GetCharId translates a single character + * back into an iterator. + */ + if (read(this->GetFd(), &data, 1) > 0) + { + ConnMap::iterator iter = GetCharId(data); + if (iter != Connections.end()) + { + /* Lock the mutex, send back the data */ + pthread_mutex_lock(&results_mutex); + ResultQueue::iterator n = iter->second->rq.begin(); + (*n)->Send(); + iter->second->rq.pop_front(); + pthread_mutex_unlock(&results_mutex); + return true; + } + /* No error, but unknown id */ + return true; + } + + /* Erk, error on descriptor! */ + return false; + } +}; + +/** MySQL module + */ +class ModuleSQL : public Module +{ + public: + + ConfigReader *Conf; + InspIRCd* PublicServerInstance; + pthread_t Dispatcher; + int currid; + bool rehashing; + + ModuleSQL(InspIRCd* Me) + : Module::Module(Me), rehashing(false) + { + ServerInstance->UseInterface("SQLutils"); + + Conf = new ConfigReader(ServerInstance); + PublicServerInstance = ServerInstance; + currid = 0; + SQLModule = this; + + MessagePipe = new Notifier(ServerInstance); + + pthread_attr_t attribs; + pthread_attr_init(&attribs); + pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED); + if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0) + { + throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno))); + } + + if (!ServerInstance->PublishFeature("SQL", this)) + { + /* Tell worker thread to exit NOW */ + giveup = true; + throw ModuleException("m_mysql: Unable to publish feature 'SQL'"); + } + + ServerInstance->PublishInterface("SQL", this); + } + + virtual ~ModuleSQL() + { + giveup = true; + ClearAllConnections(); + DELETE(Conf); + ServerInstance->UnpublishInterface("SQL", this); + ServerInstance->UnpublishFeature("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + } + + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnRequest] = 1; + } + + unsigned long NewID() + { + if (currid+1 == 0) + currid++; + return ++currid; + } + + char* OnRequest(Request* request) + { + if(strcmp(SQLREQID, request->GetId()) == 0) + { + SQLrequest* req = (SQLrequest*)request; + + /* XXX: Lock */ + pthread_mutex_lock(&queue_mutex); + + ConnMap::iterator iter; + + char* returnval = NULL; + + if((iter = Connections.find(req->dbid)) != Connections.end()) + { + req->id = NewID(); + iter->second->queue.push(*req); + returnval = SQLSUCCESS; + } + else + { + req->error.Id(BAD_DBID); + } + + pthread_mutex_unlock(&queue_mutex); + /* XXX: Unlock */ + + return returnval; + } + + return NULL; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + rehashing = true; + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION); + } + +}; + +void* DispatcherThread(void* arg) +{ + ModuleSQL* thismodule = (ModuleSQL*)arg; + LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance); + + /* Connect back to the Notifier */ + + if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1) + { + /* crap, we're out of sockets... */ + return NULL; + } + + insp_sockaddr addr; + +#ifdef IPV6 + insp_aton("::1", &addr.sin6_addr); + addr.sin6_family = AF_FAMILY; + addr.sin6_port = htons(MessagePipe->GetPort()); +#else + insp_inaddr ia; + insp_aton("127.0.0.1", &ia); + addr.sin_family = AF_FAMILY; + addr.sin_addr = ia; + addr.sin_port = htons(MessagePipe->GetPort()); +#endif + + if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1) + { + /* wtf, we cant connect to it, but we just created it! */ + return NULL; + } + + while (!giveup) + { + if (thismodule->rehashing) + { + /* XXX: Lock */ + pthread_mutex_lock(&queue_mutex); + thismodule->rehashing = false; + LoadDatabases(thismodule->Conf, thismodule->PublicServerInstance); + pthread_mutex_unlock(&queue_mutex); + /* XXX: Unlock */ + } + + SQLConnection* conn = NULL; + /* XXX: Lock here for safety */ + pthread_mutex_lock(&queue_mutex); + for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++) + { + if (i->second->queue.totalsize()) + { + conn = i->second; + break; + } + } + pthread_mutex_unlock(&queue_mutex); + /* XXX: Unlock */ + + /* Theres an item! */ + if (conn) + { + conn->DoLeadingQuery(); + + /* XXX: Lock */ + pthread_mutex_lock(&queue_mutex); + conn->queue.pop(); + pthread_mutex_unlock(&queue_mutex); + /* XXX: Unlock */ + } + + usleep(50); + } + + return NULL; +} + +MODULE_INIT(ModuleSQL); + diff --git a/src/modules/extra/m_pgsql.cpp b/src/modules/extra/m_pgsql.cpp index 9e85a40de..5d267fc1a 100644 --- a/src/modules/extra/m_pgsql.cpp +++ b/src/modules/extra/m_pgsql.cpp @@ -1 +1,984 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #include #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" #include "m_sqlv2.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 */ /* $ModDep: m_sqlv2.h */ /* SQLConn rewritten by peavey to * use EventHandler instead of * InspSocket. This is much neater * and gives total control of destroy * and delete of resources. */ /* Forward declare, so we can have the typedef neatly at the top */ class SQLConn; typedef std::map ConnMap; /* CREAD, Connecting and wants read event * CWRITE, Connecting and wants write event * WREAD, Connected/Working and wants read event * WWRITE, Connected/Working and wants write event * RREAD, Resetting and wants read event * RWRITE, Resetting and wants write event */ enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE }; /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL */ std::string SQLhost::GetDSN() { std::ostringstream conninfo("connect_timeout = '2'"); if (ip.length()) conninfo << " hostaddr = '" << ip << "'"; if (port) conninfo << " port = '" << port << "'"; if (name.length()) conninfo << " dbname = '" << name << "'"; if (user.length()) conninfo << " user = '" << user << "'"; if (pass.length()) conninfo << " password = '" << pass << "'"; if (ssl) { conninfo << " sslmode = 'require'"; } else { conninfo << " sslmode = 'disable'"; } return conninfo.str(); } class ReconnectTimer : public InspTimer { private: Module* mod; public: ReconnectTimer(InspIRCd* SI, Module* m) : InspTimer(5, SI->Time(), false), mod(m) { } virtual void Tick(time_t TIME); }; /** Used to resolve sql server hostnames */ class SQLresolver : public Resolver { private: SQLhost host; Module* mod; public: SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached) : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m) { } virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached); virtual void OnError(ResolverError e, const std::string &errormessage) { ServerInstance->Log(DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str()); } }; /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult. * All SQL providers must create their own subclass and define it's methods using that * database library's data retriveal functions. The aim is to avoid a slow and inefficient process * of converting all data to a common format before it reaches the result structure. This way * data is passes to the module nearly as directly as if it was using the API directly itself. */ class PgSQLresult : public SQLresult { PGresult* res; int currentrow; int rows; int cols; SQLfieldList* fieldlist; SQLfieldMap* fieldmap; public: PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result) : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL) { rows = PQntuples(res); cols = PQnfields(res); } ~PgSQLresult() { /* If we allocated these, free them... */ if(fieldlist) DELETE(fieldlist); if(fieldmap) DELETE(fieldmap); PQclear(res); } virtual int Rows() { if(!cols && !rows) { return atoi(PQcmdTuples(res)); } else { return rows; } } virtual int Cols() { return PQnfields(res); } virtual std::string ColName(int column) { char* name = PQfname(res, column); return (name) ? name : ""; } virtual int ColNum(const std::string &column) { int n = PQfnumber(res, column.c_str()); if(n == -1) { throw SQLbadColName(); } else { return n; } } virtual SQLfield GetValue(int row, int column) { char* v = PQgetvalue(res, row, column); if(v) { return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column)); } else { throw SQLbadColName(); } } virtual SQLfieldList& GetRow() { /* In an effort to reduce overhead we don't actually allocate the list * until the first time it's needed...so... */ if(fieldlist) { fieldlist->clear(); } else { fieldlist = new SQLfieldList; } if(currentrow < PQntuples(res)) { int cols = PQnfields(res); for(int i = 0; i < cols; i++) { fieldlist->push_back(GetValue(currentrow, i)); } currentrow++; } return *fieldlist; } virtual SQLfieldMap& GetRowMap() { /* In an effort to reduce overhead we don't actually allocate the map * until the first time it's needed...so... */ if(fieldmap) { fieldmap->clear(); } else { fieldmap = new SQLfieldMap; } if(currentrow < PQntuples(res)) { int cols = PQnfields(res); for(int i = 0; i < cols; i++) { fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); } currentrow++; } return *fieldmap; } virtual SQLfieldList* GetRowPtr() { SQLfieldList* fl = new SQLfieldList; if(currentrow < PQntuples(res)) { int cols = PQnfields(res); for(int i = 0; i < cols; i++) { fl->push_back(GetValue(currentrow, i)); } currentrow++; } return fl; } virtual SQLfieldMap* GetRowMapPtr() { SQLfieldMap* fm = new SQLfieldMap; if(currentrow < PQntuples(res)) { int cols = PQnfields(res); for(int i = 0; i < cols; i++) { fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); } currentrow++; } return fm; } virtual void Free(SQLfieldMap* fm) { DELETE(fm); } virtual void Free(SQLfieldList* fl) { DELETE(fl); } }; /** SQLConn represents one SQL session. */ class SQLConn : public EventHandler { private: InspIRCd* Instance; SQLhost confhost; /* The entry */ Module* us; /* Pointer to the SQL provider itself */ PGconn* sql; /* PgSQL database connection handle */ SQLstatus status; /* PgSQL database connection status */ bool qinprog; /* If there is currently a query in progress */ QueryQueue queue; /* Queue of queries waiting to be executed on this connection */ time_t idle; /* Time we last heard from the database */ public: SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi) : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false) { idle = this->Instance->Time(); if(!DoConnect()) { Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id)); DelayReconnect(); } } ~SQLConn() { Close(); } virtual void HandleEvent(EventType et, int errornum) { switch (et) { case EVENT_READ: OnDataReady(); break; case EVENT_WRITE: OnWriteReady(); break; case EVENT_ERROR: DelayReconnect(); break; default: break; } } bool DoConnect() { if(!(sql = PQconnectStart(confhost.GetDSN().c_str()))) return false; if(PQstatus(sql) == CONNECTION_BAD) return false; if(PQsetnonblocking(sql, 1) == -1) return false; /* OK, we've initalised the connection, now to get it hooked into the socket engine * and then start polling it. */ this->fd = PQsocket(sql); if(this->fd <= -1) return false; if (!this->Instance->SE->AddFd(this)) { Instance->Log(DEBUG, "BUG: Couldn't add pgsql socket to socket engine"); return false; } /* Socket all hooked into the engine, now to tell PgSQL to start connecting */ return DoPoll(); } bool DoPoll() { switch(PQconnectPoll(sql)) { case PGRES_POLLING_WRITING: Instance->SE->WantWrite(this); status = CWRITE; return true; case PGRES_POLLING_READING: status = CREAD; return true; case PGRES_POLLING_FAILED: return false; case PGRES_POLLING_OK: status = WWRITE; return DoConnectedPoll(); default: return true; } } bool DoConnectedPoll() { if(!qinprog && queue.totalsize()) { /* There's no query currently in progress, and there's queries in the queue. */ SQLrequest& query = queue.front(); DoQuery(query); } if(PQconsumeInput(sql)) { /* We just read stuff from the server, that counts as it being alive * so update the idle-since time :p */ idle = this->Instance->Time(); if (PQisBusy(sql)) { /* Nothing happens here */ } else if (qinprog) { /* Grab the request we're processing */ SQLrequest& query = queue.front(); /* Get a pointer to the module we're about to return the result to */ Module* to = query.GetSource(); /* Fetch the result.. */ PGresult* result = PQgetResult(sql); /* PgSQL would allow a query string to be sent which has multiple * queries in it, this isn't portable across database backends and * we don't want modules doing it. But just in case we make sure we * drain any results there are and just use the last one. * If the module devs are behaving there will only be one result. */ while (PGresult* temp = PQgetResult(sql)) { PQclear(result); result = temp; } if(to) { /* ..and the result */ PgSQLresult reply(us, to, query.id, result); /* Fix by brain, make sure the original query gets sent back in the reply */ reply.query = query.query.q; switch(PQresultStatus(result)) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: reply.error.Id(QREPLY_FAIL); reply.error.Str(PQresultErrorMessage(result)); default:; /* No action, other values are not errors */ } reply.Send(); /* PgSQLresult's destructor will free the PGresult */ } else { /* If the client module is unloaded partway through a query then the provider will set * the pointer to NULL. We cannot just cancel the query as the result will still come * through at some point...and it could get messy if we play with invalid pointers... */ PQclear(result); } qinprog = false; queue.pop(); DoConnectedPoll(); } return true; } else { /* I think we'll assume this means the server died...it might not, * but I think that any error serious enough we actually get here * deserves to reconnect [/excuse] * Returning true so the core doesn't try and close the connection. */ DelayReconnect(); return true; } } bool DoResetPoll() { switch(PQresetPoll(sql)) { case PGRES_POLLING_WRITING: Instance->SE->WantWrite(this); status = CWRITE; return DoPoll(); case PGRES_POLLING_READING: status = CREAD; return true; case PGRES_POLLING_FAILED: return false; case PGRES_POLLING_OK: status = WWRITE; return DoConnectedPoll(); default: return true; } } bool OnDataReady() { /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */ return DoEvent(); } bool OnWriteReady() { /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */ return DoEvent(); } bool OnConnected() { return DoEvent(); } void DelayReconnect(); bool DoEvent() { bool ret; if((status == CREAD) || (status == CWRITE)) { ret = DoPoll(); } else if((status == RREAD) || (status == RWRITE)) { ret = DoResetPoll(); } else { ret = DoConnectedPoll(); } return ret; } SQLerror DoQuery(SQLrequest &req) { if((status == WREAD) || (status == WWRITE)) { if(!qinprog) { /* Parse the command string and dispatch it */ /* Pointer to the buffer we screw around with substitution in */ char* query; /* Pointer to the current end of query, where we append new stuff */ char* queryend; /* Total length of the unescaped parameters */ unsigned int paramlen; paramlen = 0; for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) { paramlen += i->size(); } /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. * sizeofquery + (totalparamlength*2) + 1 * * The +1 is for null-terminating the string for PQsendQuery() */ query = new char[req.query.q.length() + (paramlen*2) + 1]; queryend = query; /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting * the parameters into it... */ for(unsigned int i = 0; i < req.query.q.length(); i++) { if(req.query.q[i] == '?') { /* We found a place to substitute..what fun. * Use the PgSQL calls to escape and write the * escaped string onto the end of our query buffer, * then we "just" need to make sure queryend is * pointing at the right place. */ if(req.query.p.size()) { int error = 0; size_t len = 0; #ifdef PGSQL_HAS_ESCAPECONN len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error); #else len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length()); #endif if(error) { Instance->Log(DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do..."); } /* Incremenet queryend to the end of the newly escaped parameter */ queryend += len; /* Remove the parameter we just substituted in */ req.query.p.pop_front(); } else { Instance->Log(DEBUG, "BUG: Found a substitution location but no parameter to substitute :|"); break; } } else { *queryend = req.query.q[i]; queryend++; } } /* Null-terminate the query */ *queryend = 0; req.query.q = query; if(PQsendQuery(sql, query)) { qinprog = true; delete[] query; return SQLerror(); } else { delete[] query; return SQLerror(QSEND_FAIL, PQerrorMessage(sql)); } } } return SQLerror(BAD_CONN, "Can't query until connection is complete"); } SQLerror Query(const SQLrequest &req) { queue.push(req); if(!qinprog && queue.totalsize()) { /* There's no query currently in progress, and there's queries in the queue. */ SQLrequest& query = queue.front(); return DoQuery(query); } else { return SQLerror(); } } void OnUnloadModule(Module* mod) { queue.PurgeModule(mod); } const SQLhost GetConfHost() { return confhost; } void Close() { if (!this->Instance->SE->DelFd(this)) { if (sql && PQstatus(sql) == CONNECTION_BAD) { this->Instance->SE->DelFd(this, true); } else { Instance->Log(DEBUG, "BUG: PQsocket cant be removed from socket engine!"); } } if(sql) { PQfinish(sql); sql = NULL; } } }; class ModulePgSQL : public Module { private: ConnMap connections; unsigned long currid; char* sqlsuccess; ReconnectTimer* retimer; public: ModulePgSQL(InspIRCd* Me) : Module::Module(Me), currid(0) { ServerInstance->UseInterface("SQLutils"); sqlsuccess = new char[strlen(SQLSUCCESS)+1]; strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS)); if (!ServerInstance->PublishFeature("SQL", this)) { throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'"); } ReadConf(); ServerInstance->PublishInterface("SQL", this); } virtual ~ModulePgSQL() { if (retimer) ServerInstance->Timers->DelTimer(retimer); ClearAllConnections(); delete[] sqlsuccess; ServerInstance->UnpublishInterface("SQL", this); ServerInstance->UnpublishFeature("SQL"); ServerInstance->DoneWithInterface("SQLutils"); } void Implements(char* List) { List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { ReadConf(); } bool HasHost(const SQLhost &host) { for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { if (host == iter->second->GetConfHost()) return true; } return false; } bool HostInConf(const SQLhost &h) { ConfigReader conf(ServerInstance); for(int i = 0; i < conf.Enumerate("database"); i++) { SQLhost host; host.id = conf.ReadValue("database", "id", i); host.host = conf.ReadValue("database", "hostname", i); host.port = conf.ReadInteger("database", "port", i, true); host.name = conf.ReadValue("database", "name", i); host.user = conf.ReadValue("database", "username", i); host.pass = conf.ReadValue("database", "password", i); host.ssl = conf.ReadFlag("database", "ssl", "0", i); if (h == host) return true; } return false; } void ReadConf() { ClearOldConnections(); ConfigReader conf(ServerInstance); for(int i = 0; i < conf.Enumerate("database"); i++) { SQLhost host; int ipvalid; host.id = conf.ReadValue("database", "id", i); host.host = conf.ReadValue("database", "hostname", i); host.port = conf.ReadInteger("database", "port", i, true); host.name = conf.ReadValue("database", "name", i); host.user = conf.ReadValue("database", "username", i); host.pass = conf.ReadValue("database", "password", i); host.ssl = conf.ReadFlag("database", "ssl", "0", i); if (HasHost(host)) continue; #ifdef IPV6 if (strchr(host.host.c_str(),':')) { in6_addr blargle; ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle); } else #endif { in_addr blargle; ipvalid = inet_aton(host.host.c_str(), &blargle); } if(ipvalid > 0) { /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */ host.ip = host.host; this->AddConn(host); } else if(ipvalid == 0) { /* Conversion failed, assume it's a host */ SQLresolver* resolver; try { bool cached; resolver = new SQLresolver(this, ServerInstance, host, cached); ServerInstance->AddResolver(resolver, cached); } catch(...) { /* THE WORLD IS COMING TO AN END! */ } } else { /* Invalid address family, die horribly. */ ServerInstance->Log(DEBUG, "BUG: insp_aton failed returning -1, oh noes."); } } } void ClearOldConnections() { ConnMap::iterator iter,safei; for (iter = connections.begin(); iter != connections.end(); iter++) { if (!HostInConf(iter->second->GetConfHost())) { DELETE(iter->second); safei = iter; --iter; connections.erase(safei); } } } void ClearAllConnections() { ConnMap::iterator i; while ((i = connections.begin()) != connections.end()) { connections.erase(i); DELETE(i->second); } } void AddConn(const SQLhost& hi) { if (HasHost(hi)) { ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str()); return; } SQLConn* newconn; /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */ newconn = new SQLConn(ServerInstance, this, hi); connections.insert(std::make_pair(hi.id, newconn)); } void ReconnectConn(SQLConn* conn) { for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { if (conn == iter->second) { DELETE(iter->second); connections.erase(iter); break; } } retimer = new ReconnectTimer(ServerInstance, this); ServerInstance->Timers->AddTimer(retimer); } virtual char* OnRequest(Request* request) { if(strcmp(SQLREQID, request->GetId()) == 0) { SQLrequest* req = (SQLrequest*)request; ConnMap::iterator iter; if((iter = connections.find(req->dbid)) != connections.end()) { /* Execute query */ req->id = NewID(); req->error = iter->second->Query(*req); return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL; } else { req->error.Id(BAD_DBID); return NULL; } } return NULL; } virtual void OnUnloadModule(Module* mod, const std::string& name) { /* When a module unloads we have to check all the pending queries for all our connections * and set the Module* specifying where the query came from to NULL. If the query has already * been dispatched then when it is processed it will be dropped if the pointer is NULL. * * If the queries we find are not already being executed then we can simply remove them immediately. */ for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { iter->second->OnUnloadModule(mod); } } unsigned long NewID() { if (currid+1 == 0) currid++; return ++currid; } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION); } }; /* move this here to use AddConn, rather that than having the whole * module above SQLConn, since this is buggin me right now :/ */ void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) { host.ip = result; ((ModulePgSQL*)mod)->AddConn(host); ((ModulePgSQL*)mod)->ClearOldConnections(); } void ReconnectTimer::Tick(time_t time) { ((ModulePgSQL*)mod)->ReadConf(); } void SQLConn::DelayReconnect() { ((ModulePgSQL*)us)->ReconnectConn(this); } MODULE_INIT(ModulePgSQL); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" +#include "m_sqlv2.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 */ +/* $ModDep: m_sqlv2.h */ + + +/* SQLConn rewritten by peavey to + * use EventHandler instead of + * InspSocket. This is much neater + * and gives total control of destroy + * and delete of resources. + */ + +/* Forward declare, so we can have the typedef neatly at the top */ +class SQLConn; + +typedef std::map ConnMap; + +/* CREAD, Connecting and wants read event + * CWRITE, Connecting and wants write event + * WREAD, Connected/Working and wants read event + * WWRITE, Connected/Working and wants write event + * RREAD, Resetting and wants read event + * RWRITE, Resetting and wants write event + */ +enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE }; + +/** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL + */ +std::string SQLhost::GetDSN() +{ + std::ostringstream conninfo("connect_timeout = '2'"); + + if (ip.length()) + conninfo << " hostaddr = '" << ip << "'"; + + if (port) + conninfo << " port = '" << port << "'"; + + if (name.length()) + conninfo << " dbname = '" << name << "'"; + + if (user.length()) + conninfo << " user = '" << user << "'"; + + if (pass.length()) + conninfo << " password = '" << pass << "'"; + + if (ssl) + { + conninfo << " sslmode = 'require'"; + } + else + { + conninfo << " sslmode = 'disable'"; + } + + return conninfo.str(); +} + +class ReconnectTimer : public InspTimer +{ + private: + Module* mod; + public: + ReconnectTimer(InspIRCd* SI, Module* m) + : InspTimer(5, SI->Time(), false), mod(m) + { + } + virtual void Tick(time_t TIME); +}; + + +/** Used to resolve sql server hostnames + */ +class SQLresolver : public Resolver +{ + private: + SQLhost host; + Module* mod; + public: + SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached) + : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m) + { + } + + virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached); + + virtual void OnError(ResolverError e, const std::string &errormessage) + { + ServerInstance->Log(DEBUG, "PgSQL: DNS lookup failed (%s), dying horribly", errormessage.c_str()); + } +}; + +/** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult. + * All SQL providers must create their own subclass and define it's methods using that + * database library's data retriveal functions. The aim is to avoid a slow and inefficient process + * of converting all data to a common format before it reaches the result structure. This way + * data is passes to the module nearly as directly as if it was using the API directly itself. + */ + +class PgSQLresult : public SQLresult +{ + PGresult* res; + int currentrow; + int rows; + int cols; + + SQLfieldList* fieldlist; + SQLfieldMap* fieldmap; +public: + PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result) + : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL) + { + rows = PQntuples(res); + cols = PQnfields(res); + } + + ~PgSQLresult() + { + /* If we allocated these, free them... */ + if(fieldlist) + DELETE(fieldlist); + + if(fieldmap) + DELETE(fieldmap); + + PQclear(res); + } + + virtual int Rows() + { + if(!cols && !rows) + { + return atoi(PQcmdTuples(res)); + } + else + { + return rows; + } + } + + virtual int Cols() + { + return PQnfields(res); + } + + virtual std::string ColName(int column) + { + char* name = PQfname(res, column); + + return (name) ? name : ""; + } + + virtual int ColNum(const std::string &column) + { + int n = PQfnumber(res, column.c_str()); + + if(n == -1) + { + throw SQLbadColName(); + } + else + { + return n; + } + } + + virtual SQLfield GetValue(int row, int column) + { + char* v = PQgetvalue(res, row, column); + + if(v) + { + return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column)); + } + else + { + throw SQLbadColName(); + } + } + + virtual SQLfieldList& GetRow() + { + /* In an effort to reduce overhead we don't actually allocate the list + * until the first time it's needed...so... + */ + if(fieldlist) + { + fieldlist->clear(); + } + else + { + fieldlist = new SQLfieldList; + } + + if(currentrow < PQntuples(res)) + { + int cols = PQnfields(res); + + for(int i = 0; i < cols; i++) + { + fieldlist->push_back(GetValue(currentrow, i)); + } + + currentrow++; + } + + return *fieldlist; + } + + virtual SQLfieldMap& GetRowMap() + { + /* In an effort to reduce overhead we don't actually allocate the map + * until the first time it's needed...so... + */ + if(fieldmap) + { + fieldmap->clear(); + } + else + { + fieldmap = new SQLfieldMap; + } + + if(currentrow < PQntuples(res)) + { + int cols = PQnfields(res); + + for(int i = 0; i < cols; i++) + { + fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); + } + + currentrow++; + } + + return *fieldmap; + } + + virtual SQLfieldList* GetRowPtr() + { + SQLfieldList* fl = new SQLfieldList; + + if(currentrow < PQntuples(res)) + { + int cols = PQnfields(res); + + for(int i = 0; i < cols; i++) + { + fl->push_back(GetValue(currentrow, i)); + } + + currentrow++; + } + + return fl; + } + + virtual SQLfieldMap* GetRowMapPtr() + { + SQLfieldMap* fm = new SQLfieldMap; + + if(currentrow < PQntuples(res)) + { + int cols = PQnfields(res); + + for(int i = 0; i < cols; i++) + { + fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); + } + + currentrow++; + } + + return fm; + } + + virtual void Free(SQLfieldMap* fm) + { + DELETE(fm); + } + + virtual void Free(SQLfieldList* fl) + { + DELETE(fl); + } +}; + +/** SQLConn represents one SQL session. + */ +class SQLConn : public EventHandler +{ + private: + InspIRCd* Instance; + SQLhost confhost; /* The entry */ + Module* us; /* Pointer to the SQL provider itself */ + PGconn* sql; /* PgSQL database connection handle */ + SQLstatus status; /* PgSQL database connection status */ + bool qinprog; /* If there is currently a query in progress */ + QueryQueue queue; /* Queue of queries waiting to be executed on this connection */ + time_t idle; /* Time we last heard from the database */ + + public: + SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi) + : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false) + { + idle = this->Instance->Time(); + if(!DoConnect()) + { + Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id)); + DelayReconnect(); + } + } + + ~SQLConn() + { + Close(); + } + + virtual void HandleEvent(EventType et, int errornum) + { + switch (et) + { + case EVENT_READ: + OnDataReady(); + break; + + case EVENT_WRITE: + OnWriteReady(); + break; + + case EVENT_ERROR: + DelayReconnect(); + break; + + default: + break; + } + } + + bool DoConnect() + { + if(!(sql = PQconnectStart(confhost.GetDSN().c_str()))) + return false; + + if(PQstatus(sql) == CONNECTION_BAD) + return false; + + if(PQsetnonblocking(sql, 1) == -1) + return false; + + /* OK, we've initalised the connection, now to get it hooked into the socket engine + * and then start polling it. + */ + this->fd = PQsocket(sql); + + if(this->fd <= -1) + return false; + + if (!this->Instance->SE->AddFd(this)) + { + Instance->Log(DEBUG, "BUG: Couldn't add pgsql socket to socket engine"); + return false; + } + + /* Socket all hooked into the engine, now to tell PgSQL to start connecting */ + return DoPoll(); + } + + bool DoPoll() + { + switch(PQconnectPoll(sql)) + { + case PGRES_POLLING_WRITING: + Instance->SE->WantWrite(this); + status = CWRITE; + return true; + case PGRES_POLLING_READING: + status = CREAD; + return true; + case PGRES_POLLING_FAILED: + return false; + case PGRES_POLLING_OK: + status = WWRITE; + return DoConnectedPoll(); + default: + return true; + } + } + + bool DoConnectedPoll() + { + if(!qinprog && queue.totalsize()) + { + /* There's no query currently in progress, and there's queries in the queue. */ + SQLrequest& query = queue.front(); + DoQuery(query); + } + + if(PQconsumeInput(sql)) + { + /* We just read stuff from the server, that counts as it being alive + * so update the idle-since time :p + */ + idle = this->Instance->Time(); + + if (PQisBusy(sql)) + { + /* Nothing happens here */ + } + else if (qinprog) + { + /* Grab the request we're processing */ + SQLrequest& query = queue.front(); + + /* Get a pointer to the module we're about to return the result to */ + Module* to = query.GetSource(); + + /* Fetch the result.. */ + PGresult* result = PQgetResult(sql); + + /* PgSQL would allow a query string to be sent which has multiple + * queries in it, this isn't portable across database backends and + * we don't want modules doing it. But just in case we make sure we + * drain any results there are and just use the last one. + * If the module devs are behaving there will only be one result. + */ + while (PGresult* temp = PQgetResult(sql)) + { + PQclear(result); + result = temp; + } + + if(to) + { + /* ..and the result */ + PgSQLresult reply(us, to, query.id, result); + + /* Fix by brain, make sure the original query gets sent back in the reply */ + reply.query = query.query.q; + + switch(PQresultStatus(result)) + { + case PGRES_EMPTY_QUERY: + case PGRES_BAD_RESPONSE: + case PGRES_FATAL_ERROR: + reply.error.Id(QREPLY_FAIL); + reply.error.Str(PQresultErrorMessage(result)); + default:; + /* No action, other values are not errors */ + } + + reply.Send(); + + /* PgSQLresult's destructor will free the PGresult */ + } + else + { + /* If the client module is unloaded partway through a query then the provider will set + * the pointer to NULL. We cannot just cancel the query as the result will still come + * through at some point...and it could get messy if we play with invalid pointers... + */ + PQclear(result); + } + qinprog = false; + queue.pop(); + DoConnectedPoll(); + } + return true; + } + else + { + /* I think we'll assume this means the server died...it might not, + * but I think that any error serious enough we actually get here + * deserves to reconnect [/excuse] + * Returning true so the core doesn't try and close the connection. + */ + DelayReconnect(); + return true; + } + } + + bool DoResetPoll() + { + switch(PQresetPoll(sql)) + { + case PGRES_POLLING_WRITING: + Instance->SE->WantWrite(this); + status = CWRITE; + return DoPoll(); + case PGRES_POLLING_READING: + status = CREAD; + return true; + case PGRES_POLLING_FAILED: + return false; + case PGRES_POLLING_OK: + status = WWRITE; + return DoConnectedPoll(); + default: + return true; + } + } + + bool OnDataReady() + { + /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */ + return DoEvent(); + } + + bool OnWriteReady() + { + /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */ + return DoEvent(); + } + + bool OnConnected() + { + return DoEvent(); + } + + void DelayReconnect(); + + bool DoEvent() + { + bool ret; + + if((status == CREAD) || (status == CWRITE)) + { + ret = DoPoll(); + } + else if((status == RREAD) || (status == RWRITE)) + { + ret = DoResetPoll(); + } + else + { + ret = DoConnectedPoll(); + } + return ret; + } + + SQLerror DoQuery(SQLrequest &req) + { + if((status == WREAD) || (status == WWRITE)) + { + if(!qinprog) + { + /* Parse the command string and dispatch it */ + + /* Pointer to the buffer we screw around with substitution in */ + char* query; + /* Pointer to the current end of query, where we append new stuff */ + char* queryend; + /* Total length of the unescaped parameters */ + unsigned int paramlen; + + paramlen = 0; + + for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) + { + paramlen += i->size(); + } + + /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. + * sizeofquery + (totalparamlength*2) + 1 + * + * The +1 is for null-terminating the string for PQsendQuery() + */ + + query = new char[req.query.q.length() + (paramlen*2) + 1]; + queryend = query; + + /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting + * the parameters into it... + */ + + for(unsigned int i = 0; i < req.query.q.length(); i++) + { + if(req.query.q[i] == '?') + { + /* We found a place to substitute..what fun. + * Use the PgSQL calls to escape and write the + * escaped string onto the end of our query buffer, + * then we "just" need to make sure queryend is + * pointing at the right place. + */ + + if(req.query.p.size()) + { + int error = 0; + size_t len = 0; + +#ifdef PGSQL_HAS_ESCAPECONN + len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error); +#else + len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length()); +#endif + if(error) + { + Instance->Log(DEBUG, "BUG: Apparently PQescapeStringConn() failed somehow...don't know how or what to do..."); + } + + /* Incremenet queryend to the end of the newly escaped parameter */ + queryend += len; + + /* Remove the parameter we just substituted in */ + req.query.p.pop_front(); + } + else + { + Instance->Log(DEBUG, "BUG: Found a substitution location but no parameter to substitute :|"); + break; + } + } + else + { + *queryend = req.query.q[i]; + queryend++; + } + } + + /* Null-terminate the query */ + *queryend = 0; + req.query.q = query; + + if(PQsendQuery(sql, query)) + { + qinprog = true; + delete[] query; + return SQLerror(); + } + else + { + delete[] query; + return SQLerror(QSEND_FAIL, PQerrorMessage(sql)); + } + } + } + return SQLerror(BAD_CONN, "Can't query until connection is complete"); + } + + SQLerror Query(const SQLrequest &req) + { + queue.push(req); + + if(!qinprog && queue.totalsize()) + { + /* There's no query currently in progress, and there's queries in the queue. */ + SQLrequest& query = queue.front(); + return DoQuery(query); + } + else + { + return SQLerror(); + } + } + + void OnUnloadModule(Module* mod) + { + queue.PurgeModule(mod); + } + + const SQLhost GetConfHost() + { + return confhost; + } + + void Close() { + if (!this->Instance->SE->DelFd(this)) + { + if (sql && PQstatus(sql) == CONNECTION_BAD) + { + this->Instance->SE->DelFd(this, true); + } + else + { + Instance->Log(DEBUG, "BUG: PQsocket cant be removed from socket engine!"); + } + } + + if(sql) + { + PQfinish(sql); + sql = NULL; + } + } + +}; + +class ModulePgSQL : public Module +{ + private: + ConnMap connections; + unsigned long currid; + char* sqlsuccess; + ReconnectTimer* retimer; + + public: + ModulePgSQL(InspIRCd* Me) + : Module::Module(Me), currid(0) + { + ServerInstance->UseInterface("SQLutils"); + + sqlsuccess = new char[strlen(SQLSUCCESS)+1]; + + strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS)); + + if (!ServerInstance->PublishFeature("SQL", this)) + { + throw ModuleException("BUG: PgSQL Unable to publish feature 'SQL'"); + } + + ReadConf(); + + ServerInstance->PublishInterface("SQL", this); + } + + virtual ~ModulePgSQL() + { + if (retimer) + ServerInstance->Timers->DelTimer(retimer); + ClearAllConnections(); + delete[] sqlsuccess; + ServerInstance->UnpublishInterface("SQL", this); + ServerInstance->UnpublishFeature("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + } + + void Implements(char* List) + { + List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ReadConf(); + } + + bool HasHost(const SQLhost &host) + { + for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + if (host == iter->second->GetConfHost()) + return true; + } + return false; + } + + bool HostInConf(const SQLhost &h) + { + ConfigReader conf(ServerInstance); + for(int i = 0; i < conf.Enumerate("database"); i++) + { + SQLhost host; + host.id = conf.ReadValue("database", "id", i); + host.host = conf.ReadValue("database", "hostname", i); + host.port = conf.ReadInteger("database", "port", i, true); + host.name = conf.ReadValue("database", "name", i); + host.user = conf.ReadValue("database", "username", i); + host.pass = conf.ReadValue("database", "password", i); + host.ssl = conf.ReadFlag("database", "ssl", "0", i); + if (h == host) + return true; + } + return false; + } + + void ReadConf() + { + ClearOldConnections(); + + ConfigReader conf(ServerInstance); + for(int i = 0; i < conf.Enumerate("database"); i++) + { + SQLhost host; + int ipvalid; + + host.id = conf.ReadValue("database", "id", i); + host.host = conf.ReadValue("database", "hostname", i); + host.port = conf.ReadInteger("database", "port", i, true); + host.name = conf.ReadValue("database", "name", i); + host.user = conf.ReadValue("database", "username", i); + host.pass = conf.ReadValue("database", "password", i); + host.ssl = conf.ReadFlag("database", "ssl", "0", i); + + if (HasHost(host)) + continue; + +#ifdef IPV6 + if (strchr(host.host.c_str(),':')) + { + in6_addr blargle; + ipvalid = inet_pton(AF_INET6, host.host.c_str(), &blargle); + } + else +#endif + { + in_addr blargle; + ipvalid = inet_aton(host.host.c_str(), &blargle); + } + + if(ipvalid > 0) + { + /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */ + host.ip = host.host; + this->AddConn(host); + } + else if(ipvalid == 0) + { + /* Conversion failed, assume it's a host */ + SQLresolver* resolver; + + try + { + bool cached; + resolver = new SQLresolver(this, ServerInstance, host, cached); + ServerInstance->AddResolver(resolver, cached); + } + catch(...) + { + /* THE WORLD IS COMING TO AN END! */ + } + } + else + { + /* Invalid address family, die horribly. */ + ServerInstance->Log(DEBUG, "BUG: insp_aton failed returning -1, oh noes."); + } + } + } + + void ClearOldConnections() + { + ConnMap::iterator iter,safei; + for (iter = connections.begin(); iter != connections.end(); iter++) + { + if (!HostInConf(iter->second->GetConfHost())) + { + DELETE(iter->second); + safei = iter; + --iter; + connections.erase(safei); + } + } + } + + void ClearAllConnections() + { + ConnMap::iterator i; + while ((i = connections.begin()) != connections.end()) + { + connections.erase(i); + DELETE(i->second); + } + } + + void AddConn(const SQLhost& hi) + { + if (HasHost(hi)) + { + ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str()); + return; + } + + SQLConn* newconn; + + /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */ + newconn = new SQLConn(ServerInstance, this, hi); + + connections.insert(std::make_pair(hi.id, newconn)); + } + + void ReconnectConn(SQLConn* conn) + { + for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + if (conn == iter->second) + { + DELETE(iter->second); + connections.erase(iter); + break; + } + } + retimer = new ReconnectTimer(ServerInstance, this); + ServerInstance->Timers->AddTimer(retimer); + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLREQID, request->GetId()) == 0) + { + SQLrequest* req = (SQLrequest*)request; + ConnMap::iterator iter; + if((iter = connections.find(req->dbid)) != connections.end()) + { + /* Execute query */ + req->id = NewID(); + req->error = iter->second->Query(*req); + + return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL; + } + else + { + req->error.Id(BAD_DBID); + return NULL; + } + } + return NULL; + } + + virtual void OnUnloadModule(Module* mod, const std::string& name) + { + /* When a module unloads we have to check all the pending queries for all our connections + * and set the Module* specifying where the query came from to NULL. If the query has already + * been dispatched then when it is processed it will be dropped if the pointer is NULL. + * + * If the queries we find are not already being executed then we can simply remove them immediately. + */ + for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + iter->second->OnUnloadModule(mod); + } + } + + unsigned long NewID() + { + if (currid+1 == 0) + currid++; + + return ++currid; + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION); + } +}; + +/* move this here to use AddConn, rather that than having the whole + * module above SQLConn, since this is buggin me right now :/ + */ +void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) +{ + host.ip = result; + ((ModulePgSQL*)mod)->AddConn(host); + ((ModulePgSQL*)mod)->ClearOldConnections(); +} + +void ReconnectTimer::Tick(time_t time) +{ + ((ModulePgSQL*)mod)->ReadConf(); +} + +void SQLConn::DelayReconnect() +{ + ((ModulePgSQL*)us)->ReconnectConn(this); +} + +MODULE_INIT(ModulePgSQL); + diff --git a/src/modules/extra/m_sqlauth.cpp b/src/modules/extra/m_sqlauth.cpp index 862929919..6b05ee521 100644 --- a/src/modules/extra/m_sqlauth.cpp +++ b/src/modules/extra/m_sqlauth.cpp @@ -1 +1,194 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "m_sqlv2.h" #include "m_sqlutils.h" /* $ModDesc: Allow/Deny connections based upon an arbitary SQL table */ /* $ModDep: m_sqlv2.h m_sqlutils.h */ class ModuleSQLAuth : public Module { Module* SQLutils; Module* SQLprovider; std::string usertable; std::string userfield; std::string passfield; std::string encryption; std::string killreason; std::string allowpattern; std::string databaseid; bool verbose; public: ModuleSQLAuth(InspIRCd* Me) : Module::Module(Me) { ServerInstance->UseInterface("SQLutils"); ServerInstance->UseInterface("SQL"); SQLutils = ServerInstance->FindModule("m_sqlutils.so"); if (!SQLutils) throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqlauth.so."); SQLprovider = ServerInstance->FindFeature("SQL"); if (!SQLprovider) throw ModuleException("Can't find an SQL provider module. Please load one before attempting to load m_sqlauth."); OnRehash(NULL,""); } virtual ~ModuleSQLAuth() { ServerInstance->DoneWithInterface("SQL"); ServerInstance->DoneWithInterface("SQLutils"); } void Implements(char* List) { List[I_OnUserDisconnect] = List[I_OnCheckReady] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader Conf(ServerInstance); usertable = Conf.ReadValue("sqlauth", "usertable", 0); /* User table name */ databaseid = Conf.ReadValue("sqlauth", "dbid", 0); /* Database ID, given to the SQL service provider */ userfield = Conf.ReadValue("sqlauth", "userfield", 0); /* Field name where username can be found */ passfield = Conf.ReadValue("sqlauth", "passfield", 0); /* Field name where password can be found */ killreason = Conf.ReadValue("sqlauth", "killreason", 0); /* Reason to give when access is denied to a user (put your reg details here) */ allowpattern= Conf.ReadValue("sqlauth", "allowpattern",0 ); /* Allow nicks matching this pattern without requiring auth */ encryption = Conf.ReadValue("sqlauth", "encryption", 0); /* Name of sql function used to encrypt password, e.g. "md5" or "passwd". * define, but leave blank if no encryption is to be used. */ verbose = Conf.ReadFlag("sqlauth", "verbose", 0); /* Set to true if failed connects should be reported to operators */ if (encryption.find("(") == std::string::npos) { encryption.append("("); } } virtual int OnUserRegister(userrec* user) { if ((!allowpattern.empty()) && (ServerInstance->MatchText(user->nick,allowpattern))) { user->Extend("sqlauthed"); return 0; } if (!CheckCredentials(user)) { userrec::QuitUser(ServerInstance,user,killreason); return 1; } return 0; } bool CheckCredentials(userrec* user) { SQLrequest req = SQLreq(this, SQLprovider, databaseid, "SELECT ? FROM ? WHERE ? = '?' AND ? = ?'?')", userfield, usertable, userfield, user->nick, passfield, encryption, user->password); if(req.Send()) { /* When we get the query response from the service provider we will be given an ID to play with, * just an ID number which is unique to this query. We need a way of associating that ID with a userrec * so we insert it into a map mapping the IDs to users. * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling * us to discard the query. */ AssociateUser(this, SQLutils, req.id, user).Send(); return true; } else { if (verbose) ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, req.error.Str()); return false; } } virtual char* OnRequest(Request* request) { if(strcmp(SQLRESID, request->GetId()) == 0) { SQLresult* res = static_cast(request); userrec* user = GetAssocUser(this, SQLutils, res->id).S().user; UnAssociate(this, SQLutils, res->id).S(); if(user) { if(res->error.Id() == NO_ERROR) { if(res->Rows()) { /* We got a row in the result, this is enough really */ user->Extend("sqlauthed"); } else if (verbose) { /* No rows in result, this means there was no record matching the user */ ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query returned no matches)", user->nick, user->ident, user->host); user->Extend("sqlauth_failed"); } } else if (verbose) { ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, res->error.Str()); user->Extend("sqlauth_failed"); } } else { return NULL; } if (!user->GetExt("sqlauthed")) { userrec::QuitUser(ServerInstance,user,killreason); } return SQLSUCCESS; } return NULL; } virtual void OnUserDisconnect(userrec* user) { user->Shrink("sqlauthed"); user->Shrink("sqlauth_failed"); } virtual bool OnCheckReady(userrec* user) { return user->GetExt("sqlauthed"); } virtual Version GetVersion() { return Version(1,1,1,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleSQLAuth); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "m_sqlv2.h" +#include "m_sqlutils.h" + +/* $ModDesc: Allow/Deny connections based upon an arbitary SQL table */ +/* $ModDep: m_sqlv2.h m_sqlutils.h */ + +class ModuleSQLAuth : public Module +{ + Module* SQLutils; + Module* SQLprovider; + + std::string usertable; + std::string userfield; + std::string passfield; + std::string encryption; + std::string killreason; + std::string allowpattern; + std::string databaseid; + + bool verbose; + +public: + ModuleSQLAuth(InspIRCd* Me) + : Module::Module(Me) + { + ServerInstance->UseInterface("SQLutils"); + ServerInstance->UseInterface("SQL"); + + SQLutils = ServerInstance->FindModule("m_sqlutils.so"); + if (!SQLutils) + throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqlauth.so."); + + SQLprovider = ServerInstance->FindFeature("SQL"); + if (!SQLprovider) + throw ModuleException("Can't find an SQL provider module. Please load one before attempting to load m_sqlauth."); + + OnRehash(NULL,""); + } + + virtual ~ModuleSQLAuth() + { + ServerInstance->DoneWithInterface("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + } + + void Implements(char* List) + { + List[I_OnUserDisconnect] = List[I_OnCheckReady] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader Conf(ServerInstance); + + usertable = Conf.ReadValue("sqlauth", "usertable", 0); /* User table name */ + databaseid = Conf.ReadValue("sqlauth", "dbid", 0); /* Database ID, given to the SQL service provider */ + userfield = Conf.ReadValue("sqlauth", "userfield", 0); /* Field name where username can be found */ + passfield = Conf.ReadValue("sqlauth", "passfield", 0); /* Field name where password can be found */ + killreason = Conf.ReadValue("sqlauth", "killreason", 0); /* Reason to give when access is denied to a user (put your reg details here) */ + allowpattern= Conf.ReadValue("sqlauth", "allowpattern",0 ); /* Allow nicks matching this pattern without requiring auth */ + encryption = Conf.ReadValue("sqlauth", "encryption", 0); /* Name of sql function used to encrypt password, e.g. "md5" or "passwd". + * define, but leave blank if no encryption is to be used. + */ + verbose = Conf.ReadFlag("sqlauth", "verbose", 0); /* Set to true if failed connects should be reported to operators */ + + if (encryption.find("(") == std::string::npos) + { + encryption.append("("); + } + } + + virtual int OnUserRegister(userrec* user) + { + if ((!allowpattern.empty()) && (ServerInstance->MatchText(user->nick,allowpattern))) + { + user->Extend("sqlauthed"); + return 0; + } + + if (!CheckCredentials(user)) + { + userrec::QuitUser(ServerInstance,user,killreason); + return 1; + } + return 0; + } + + bool CheckCredentials(userrec* user) + { + SQLrequest req = SQLreq(this, SQLprovider, databaseid, "SELECT ? FROM ? WHERE ? = '?' AND ? = ?'?')", userfield, usertable, userfield, user->nick, passfield, encryption, user->password); + + if(req.Send()) + { + /* When we get the query response from the service provider we will be given an ID to play with, + * just an ID number which is unique to this query. We need a way of associating that ID with a userrec + * so we insert it into a map mapping the IDs to users. + * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the + * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling + * us to discard the query. + */ + AssociateUser(this, SQLutils, req.id, user).Send(); + + return true; + } + else + { + if (verbose) + ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, req.error.Str()); + return false; + } + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLRESID, request->GetId()) == 0) + { + SQLresult* res = static_cast(request); + + userrec* user = GetAssocUser(this, SQLutils, res->id).S().user; + UnAssociate(this, SQLutils, res->id).S(); + + if(user) + { + if(res->error.Id() == NO_ERROR) + { + if(res->Rows()) + { + /* We got a row in the result, this is enough really */ + user->Extend("sqlauthed"); + } + else if (verbose) + { + /* No rows in result, this means there was no record matching the user */ + ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query returned no matches)", user->nick, user->ident, user->host); + user->Extend("sqlauth_failed"); + } + } + else if (verbose) + { + ServerInstance->WriteOpers("Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick, user->ident, user->host, res->error.Str()); + user->Extend("sqlauth_failed"); + } + } + else + { + return NULL; + } + + if (!user->GetExt("sqlauthed")) + { + userrec::QuitUser(ServerInstance,user,killreason); + } + return SQLSUCCESS; + } + return NULL; + } + + virtual void OnUserDisconnect(userrec* user) + { + user->Shrink("sqlauthed"); + user->Shrink("sqlauth_failed"); + } + + virtual bool OnCheckReady(userrec* user) + { + return user->GetExt("sqlauthed"); + } + + virtual Version GetVersion() + { + return Version(1,1,1,0,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleSQLAuth); + diff --git a/src/modules/extra/m_sqlite3.cpp b/src/modules/extra/m_sqlite3.cpp index 6741d7745..66955de07 100644 --- a/src/modules/extra/m_sqlite3.cpp +++ b/src/modules/extra/m_sqlite3.cpp @@ -1 +1,660 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include "users.h" #include "channels.h" #include "modules.h" #include "m_sqlv2.h" /* $ModDesc: sqlite3 provider */ /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */ /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */ /* $ModDep: m_sqlv2.h */ class SQLConn; class SQLite3Result; class ResultNotifier; typedef std::map ConnMap; typedef std::deque paramlist; typedef std::deque ResultQueue; ResultNotifier* resultnotify = NULL; class ResultNotifier : public InspSocket { Module* mod; insp_sockaddr sock_us; socklen_t uslen; public: /* Create a socket on a random port. Let the tcp stack allocate us an available port */ #ifdef IPV6 ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "::1", 0, true, 3000), mod(m) #else ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "127.0.0.1", 0, true, 3000), mod(m) #endif { uslen = sizeof(sock_us); if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen)) { throw ModuleException("Could not create random listening port on localhost"); } } ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : InspSocket(SI, newfd, ip), mod(m) { } /* Using getsockname and ntohs, we can determine which port number we were allocated */ int GetPort() { #ifdef IPV6 return ntohs(sock_us.sin6_port); #else return ntohs(sock_us.sin_port); #endif } virtual int OnIncomingConnection(int newsock, char* ip) { Dispatch(); return false; } void Dispatch(); }; class SQLite3Result : public SQLresult { private: int currentrow; int rows; int cols; std::vector colnames; std::vector fieldlists; SQLfieldList emptyfieldlist; SQLfieldList* fieldlist; SQLfieldMap* fieldmap; public: SQLite3Result(Module* self, Module* to, unsigned int id) : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL) { } ~SQLite3Result() { } void AddRow(int colsnum, char **data, char **colname) { colnames.clear(); cols = colsnum; for (int i = 0; i < colsnum; i++) { fieldlists.resize(fieldlists.size()+1); colnames.push_back(colname[i]); SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true); fieldlists[rows].push_back(sf); } rows++; } void UpdateAffectedCount() { rows++; } virtual int Rows() { return rows; } virtual int Cols() { return cols; } virtual std::string ColName(int column) { if (column < (int)colnames.size()) { return colnames[column]; } else { throw SQLbadColName(); } return ""; } virtual int ColNum(const std::string &column) { for (unsigned int i = 0; i < colnames.size(); i++) { if (column == colnames[i]) return i; } throw SQLbadColName(); return 0; } virtual SQLfield GetValue(int row, int column) { if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) { return fieldlists[row][column]; } throw SQLbadColName(); /* XXX: We never actually get here because of the throw */ return SQLfield("",true); } virtual SQLfieldList& GetRow() { if (currentrow < rows) return fieldlists[currentrow]; else return emptyfieldlist; } virtual SQLfieldMap& GetRowMap() { /* In an effort to reduce overhead we don't actually allocate the map * until the first time it's needed...so... */ if(fieldmap) { fieldmap->clear(); } else { fieldmap = new SQLfieldMap; } if (currentrow < rows) { for (int i = 0; i < Cols(); i++) { fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); } currentrow++; } return *fieldmap; } virtual SQLfieldList* GetRowPtr() { fieldlist = new SQLfieldList(); if (currentrow < rows) { for (int i = 0; i < Rows(); i++) { fieldlist->push_back(fieldlists[currentrow][i]); } currentrow++; } return fieldlist; } virtual SQLfieldMap* GetRowMapPtr() { fieldmap = new SQLfieldMap(); if (currentrow < rows) { for (int i = 0; i < Cols(); i++) { fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i))); } currentrow++; } return fieldmap; } virtual void Free(SQLfieldMap* fm) { delete fm; } virtual void Free(SQLfieldList* fl) { delete fl; } }; class SQLConn : public classbase { private: ResultQueue results; InspIRCd* Instance; Module* mod; SQLhost host; sqlite3* conn; public: SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi) : Instance(SI), mod(m), host(hi) { if (OpenDB() != SQLITE_OK) { Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id); CloseDB(); } } ~SQLConn() { CloseDB(); } SQLerror Query(SQLrequest &req) { /* Pointer to the buffer we screw around with substitution in */ char* query; /* Pointer to the current end of query, where we append new stuff */ char* queryend; /* Total length of the unescaped parameters */ unsigned long paramlen; /* Total length of query, used for binary-safety in mysql_real_query */ unsigned long querylength = 0; paramlen = 0; for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) { paramlen += i->size(); } /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. * sizeofquery + (totalparamlength*2) + 1 * * The +1 is for null-terminating the string for mysql_real_escape_string */ query = new char[req.query.q.length() + (paramlen*2) + 1]; queryend = query; for(unsigned long i = 0; i < req.query.q.length(); i++) { if(req.query.q[i] == '?') { if(req.query.p.size()) { char* escaped; escaped = sqlite3_mprintf("%q", req.query.p.front().c_str()); for (char* n = escaped; *n; n++) { *queryend = *n; queryend++; } sqlite3_free(escaped); req.query.p.pop_front(); } else break; } else { *queryend = req.query.q[i]; queryend++; } querylength++; } *queryend = 0; req.query.q = query; SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id); res->dbid = host.id; res->query = req.query.q; paramlist params; params.push_back(this); params.push_back(res); char *errmsg = 0; sqlite3_update_hook(conn, QueryUpdateHook, ¶ms); if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK) { std::string error(errmsg); sqlite3_free(errmsg); delete[] query; delete res; return SQLerror(QSEND_FAIL, error); } delete[] query; results.push_back(res); SendNotify(); return SQLerror(); } static int QueryResult(void *params, int argc, char **argv, char **azColName) { paramlist* p = (paramlist*)params; ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName); return 0; } static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid) { paramlist* p = (paramlist*)params; ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1])); } void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames) { res->AddRow(cols, data, colnames); } void AffectedReady(SQLite3Result *res) { res->UpdateAffectedCount(); } int OpenDB() { return sqlite3_open(host.host.c_str(), &conn); } void CloseDB() { sqlite3_interrupt(conn); sqlite3_close(conn); } SQLhost GetConfHost() { return host; } void SendResults() { while (results.size()) { SQLite3Result* res = results[0]; if (res->GetDest()) { res->Send(); } else { /* If the client module is unloaded partway through a query then the provider will set * the pointer to NULL. We cannot just cancel the query as the result will still come * through at some point...and it could get messy if we play with invalid pointers... */ delete res; } results.pop_front(); } } void ClearResults() { while (results.size()) { SQLite3Result* res = results[0]; delete res; results.pop_front(); } } void SendNotify() { int QueueFD; if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1) { /* crap, we're out of sockets... */ return; } insp_sockaddr addr; #ifdef IPV6 insp_aton("::1", &addr.sin6_addr); addr.sin6_family = AF_FAMILY; addr.sin6_port = htons(resultnotify->GetPort()); #else insp_inaddr ia; insp_aton("127.0.0.1", &ia); addr.sin_family = AF_FAMILY; addr.sin_addr = ia; addr.sin_port = htons(resultnotify->GetPort()); #endif if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1) { /* wtf, we cant connect to it, but we just created it! */ return; } } }; class ModuleSQLite3 : public Module { private: ConnMap connections; unsigned long currid; public: ModuleSQLite3(InspIRCd* Me) : Module::Module(Me), currid(0) { ServerInstance->UseInterface("SQLutils"); if (!ServerInstance->PublishFeature("SQL", this)) { throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'"); } resultnotify = new ResultNotifier(ServerInstance, this); ReadConf(); ServerInstance->PublishInterface("SQL", this); } virtual ~ModuleSQLite3() { ClearQueue(); ClearAllConnections(); resultnotify->SetFd(-1); resultnotify->state = I_ERROR; resultnotify->OnError(I_ERR_SOCKET); resultnotify->ClosePending = true; delete resultnotify; ServerInstance->UnpublishInterface("SQL", this); ServerInstance->UnpublishFeature("SQL"); ServerInstance->DoneWithInterface("SQLutils"); } void Implements(char* List) { List[I_OnRequest] = List[I_OnRehash] = 1; } void SendQueue() { for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { iter->second->SendResults(); } } void ClearQueue() { for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { iter->second->ClearResults(); } } bool HasHost(const SQLhost &host) { for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) { if (host == iter->second->GetConfHost()) return true; } return false; } bool HostInConf(const SQLhost &h) { ConfigReader conf(ServerInstance); for(int i = 0; i < conf.Enumerate("database"); i++) { SQLhost host; host.id = conf.ReadValue("database", "id", i); host.host = conf.ReadValue("database", "hostname", i); host.port = conf.ReadInteger("database", "port", i, true); host.name = conf.ReadValue("database", "name", i); host.user = conf.ReadValue("database", "username", i); host.pass = conf.ReadValue("database", "password", i); host.ssl = conf.ReadFlag("database", "ssl", "0", i); if (h == host) return true; } return false; } void ReadConf() { ClearOldConnections(); ConfigReader conf(ServerInstance); for(int i = 0; i < conf.Enumerate("database"); i++) { SQLhost host; host.id = conf.ReadValue("database", "id", i); host.host = conf.ReadValue("database", "hostname", i); host.port = conf.ReadInteger("database", "port", i, true); host.name = conf.ReadValue("database", "name", i); host.user = conf.ReadValue("database", "username", i); host.pass = conf.ReadValue("database", "password", i); host.ssl = conf.ReadFlag("database", "ssl", "0", i); if (HasHost(host)) continue; this->AddConn(host); } } void AddConn(const SQLhost& hi) { if (HasHost(hi)) { ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str()); return; } SQLConn* newconn; newconn = new SQLConn(ServerInstance, this, hi); connections.insert(std::make_pair(hi.id, newconn)); } void ClearOldConnections() { ConnMap::iterator iter,safei; for (iter = connections.begin(); iter != connections.end(); iter++) { if (!HostInConf(iter->second->GetConfHost())) { DELETE(iter->second); safei = iter; --iter; connections.erase(safei); } } } void ClearAllConnections() { ConnMap::iterator i; while ((i = connections.begin()) != connections.end()) { connections.erase(i); DELETE(i->second); } } virtual void OnRehash(userrec* user, const std::string ¶meter) { ReadConf(); } virtual char* OnRequest(Request* request) { if(strcmp(SQLREQID, request->GetId()) == 0) { SQLrequest* req = (SQLrequest*)request; ConnMap::iterator iter; if((iter = connections.find(req->dbid)) != connections.end()) { req->id = NewID(); req->error = iter->second->Query(*req); return SQLSUCCESS; } else { req->error.Id(BAD_DBID); return NULL; } } return NULL; } unsigned long NewID() { if (currid+1 == 0) currid++; return ++currid; } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION); } }; void ResultNotifier::Dispatch() { ((ModuleSQLite3*)mod)->SendQueue(); } MODULE_INIT(ModuleSQLite3); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include "users.h" +#include "channels.h" +#include "modules.h" + +#include "m_sqlv2.h" + +/* $ModDesc: sqlite3 provider */ +/* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */ +/* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */ +/* $ModDep: m_sqlv2.h */ + + +class SQLConn; +class SQLite3Result; +class ResultNotifier; + +typedef std::map ConnMap; +typedef std::deque paramlist; +typedef std::deque ResultQueue; + +ResultNotifier* resultnotify = NULL; + + +class ResultNotifier : public InspSocket +{ + Module* mod; + insp_sockaddr sock_us; + socklen_t uslen; + + public: + /* Create a socket on a random port. Let the tcp stack allocate us an available port */ +#ifdef IPV6 + ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "::1", 0, true, 3000), mod(m) +#else + ResultNotifier(InspIRCd* SI, Module* m) : InspSocket(SI, "127.0.0.1", 0, true, 3000), mod(m) +#endif + { + uslen = sizeof(sock_us); + if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen)) + { + throw ModuleException("Could not create random listening port on localhost"); + } + } + + ResultNotifier(InspIRCd* SI, Module* m, int newfd, char* ip) : InspSocket(SI, newfd, ip), mod(m) + { + } + + /* Using getsockname and ntohs, we can determine which port number we were allocated */ + int GetPort() + { +#ifdef IPV6 + return ntohs(sock_us.sin6_port); +#else + return ntohs(sock_us.sin_port); +#endif + } + + virtual int OnIncomingConnection(int newsock, char* ip) + { + Dispatch(); + return false; + } + + void Dispatch(); +}; + + +class SQLite3Result : public SQLresult +{ + private: + int currentrow; + int rows; + int cols; + + std::vector colnames; + std::vector fieldlists; + SQLfieldList emptyfieldlist; + + SQLfieldList* fieldlist; + SQLfieldMap* fieldmap; + + public: + SQLite3Result(Module* self, Module* to, unsigned int id) + : SQLresult(self, to, id), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL) + { + } + + ~SQLite3Result() + { + } + + void AddRow(int colsnum, char **data, char **colname) + { + colnames.clear(); + cols = colsnum; + for (int i = 0; i < colsnum; i++) + { + fieldlists.resize(fieldlists.size()+1); + colnames.push_back(colname[i]); + SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true); + fieldlists[rows].push_back(sf); + } + rows++; + } + + void UpdateAffectedCount() + { + rows++; + } + + virtual int Rows() + { + return rows; + } + + virtual int Cols() + { + return cols; + } + + virtual std::string ColName(int column) + { + if (column < (int)colnames.size()) + { + return colnames[column]; + } + else + { + throw SQLbadColName(); + } + return ""; + } + + virtual int ColNum(const std::string &column) + { + for (unsigned int i = 0; i < colnames.size(); i++) + { + if (column == colnames[i]) + return i; + } + throw SQLbadColName(); + return 0; + } + + virtual SQLfield GetValue(int row, int column) + { + if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols())) + { + return fieldlists[row][column]; + } + + throw SQLbadColName(); + + /* XXX: We never actually get here because of the throw */ + return SQLfield("",true); + } + + virtual SQLfieldList& GetRow() + { + if (currentrow < rows) + return fieldlists[currentrow]; + else + return emptyfieldlist; + } + + virtual SQLfieldMap& GetRowMap() + { + /* In an effort to reduce overhead we don't actually allocate the map + * until the first time it's needed...so... + */ + if(fieldmap) + { + fieldmap->clear(); + } + else + { + fieldmap = new SQLfieldMap; + } + + if (currentrow < rows) + { + for (int i = 0; i < Cols(); i++) + { + fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i))); + } + currentrow++; + } + + return *fieldmap; + } + + virtual SQLfieldList* GetRowPtr() + { + fieldlist = new SQLfieldList(); + + if (currentrow < rows) + { + for (int i = 0; i < Rows(); i++) + { + fieldlist->push_back(fieldlists[currentrow][i]); + } + currentrow++; + } + return fieldlist; + } + + virtual SQLfieldMap* GetRowMapPtr() + { + fieldmap = new SQLfieldMap(); + + if (currentrow < rows) + { + for (int i = 0; i < Cols(); i++) + { + fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i))); + } + currentrow++; + } + + return fieldmap; + } + + virtual void Free(SQLfieldMap* fm) + { + delete fm; + } + + virtual void Free(SQLfieldList* fl) + { + delete fl; + } + + +}; + +class SQLConn : public classbase +{ + private: + ResultQueue results; + InspIRCd* Instance; + Module* mod; + SQLhost host; + sqlite3* conn; + + public: + SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi) + : Instance(SI), mod(m), host(hi) + { + if (OpenDB() != SQLITE_OK) + { + Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id); + CloseDB(); + } + } + + ~SQLConn() + { + CloseDB(); + } + + SQLerror Query(SQLrequest &req) + { + /* Pointer to the buffer we screw around with substitution in */ + char* query; + + /* Pointer to the current end of query, where we append new stuff */ + char* queryend; + + /* Total length of the unescaped parameters */ + unsigned long paramlen; + + /* Total length of query, used for binary-safety in mysql_real_query */ + unsigned long querylength = 0; + + paramlen = 0; + for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++) + { + paramlen += i->size(); + } + + /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be. + * sizeofquery + (totalparamlength*2) + 1 + * + * The +1 is for null-terminating the string for mysql_real_escape_string + */ + query = new char[req.query.q.length() + (paramlen*2) + 1]; + queryend = query; + + for(unsigned long i = 0; i < req.query.q.length(); i++) + { + if(req.query.q[i] == '?') + { + if(req.query.p.size()) + { + char* escaped; + escaped = sqlite3_mprintf("%q", req.query.p.front().c_str()); + for (char* n = escaped; *n; n++) + { + *queryend = *n; + queryend++; + } + sqlite3_free(escaped); + req.query.p.pop_front(); + } + else + break; + } + else + { + *queryend = req.query.q[i]; + queryend++; + } + querylength++; + } + *queryend = 0; + req.query.q = query; + + SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id); + res->dbid = host.id; + res->query = req.query.q; + paramlist params; + params.push_back(this); + params.push_back(res); + + char *errmsg = 0; + sqlite3_update_hook(conn, QueryUpdateHook, ¶ms); + if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK) + { + std::string error(errmsg); + sqlite3_free(errmsg); + delete[] query; + delete res; + return SQLerror(QSEND_FAIL, error); + } + delete[] query; + + results.push_back(res); + SendNotify(); + return SQLerror(); + } + + static int QueryResult(void *params, int argc, char **argv, char **azColName) + { + paramlist* p = (paramlist*)params; + ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName); + return 0; + } + + static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid) + { + paramlist* p = (paramlist*)params; + ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1])); + } + + void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames) + { + res->AddRow(cols, data, colnames); + } + + void AffectedReady(SQLite3Result *res) + { + res->UpdateAffectedCount(); + } + + int OpenDB() + { + return sqlite3_open(host.host.c_str(), &conn); + } + + void CloseDB() + { + sqlite3_interrupt(conn); + sqlite3_close(conn); + } + + SQLhost GetConfHost() + { + return host; + } + + void SendResults() + { + while (results.size()) + { + SQLite3Result* res = results[0]; + if (res->GetDest()) + { + res->Send(); + } + else + { + /* If the client module is unloaded partway through a query then the provider will set + * the pointer to NULL. We cannot just cancel the query as the result will still come + * through at some point...and it could get messy if we play with invalid pointers... + */ + delete res; + } + results.pop_front(); + } + } + + void ClearResults() + { + while (results.size()) + { + SQLite3Result* res = results[0]; + delete res; + results.pop_front(); + } + } + + void SendNotify() + { + int QueueFD; + if ((QueueFD = socket(AF_FAMILY, SOCK_STREAM, 0)) == -1) + { + /* crap, we're out of sockets... */ + return; + } + + insp_sockaddr addr; + +#ifdef IPV6 + insp_aton("::1", &addr.sin6_addr); + addr.sin6_family = AF_FAMILY; + addr.sin6_port = htons(resultnotify->GetPort()); +#else + insp_inaddr ia; + insp_aton("127.0.0.1", &ia); + addr.sin_family = AF_FAMILY; + addr.sin_addr = ia; + addr.sin_port = htons(resultnotify->GetPort()); +#endif + + if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1) + { + /* wtf, we cant connect to it, but we just created it! */ + return; + } + } + +}; + + +class ModuleSQLite3 : public Module +{ + private: + ConnMap connections; + unsigned long currid; + + public: + ModuleSQLite3(InspIRCd* Me) + : Module::Module(Me), currid(0) + { + ServerInstance->UseInterface("SQLutils"); + + if (!ServerInstance->PublishFeature("SQL", this)) + { + throw ModuleException("m_sqlite3: Unable to publish feature 'SQL'"); + } + + resultnotify = new ResultNotifier(ServerInstance, this); + + ReadConf(); + + ServerInstance->PublishInterface("SQL", this); + } + + virtual ~ModuleSQLite3() + { + ClearQueue(); + ClearAllConnections(); + resultnotify->SetFd(-1); + resultnotify->state = I_ERROR; + resultnotify->OnError(I_ERR_SOCKET); + resultnotify->ClosePending = true; + delete resultnotify; + ServerInstance->UnpublishInterface("SQL", this); + ServerInstance->UnpublishFeature("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + } + + void Implements(char* List) + { + List[I_OnRequest] = List[I_OnRehash] = 1; + } + + void SendQueue() + { + for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + iter->second->SendResults(); + } + } + + void ClearQueue() + { + for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + iter->second->ClearResults(); + } + } + + bool HasHost(const SQLhost &host) + { + for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++) + { + if (host == iter->second->GetConfHost()) + return true; + } + return false; + } + + bool HostInConf(const SQLhost &h) + { + ConfigReader conf(ServerInstance); + for(int i = 0; i < conf.Enumerate("database"); i++) + { + SQLhost host; + host.id = conf.ReadValue("database", "id", i); + host.host = conf.ReadValue("database", "hostname", i); + host.port = conf.ReadInteger("database", "port", i, true); + host.name = conf.ReadValue("database", "name", i); + host.user = conf.ReadValue("database", "username", i); + host.pass = conf.ReadValue("database", "password", i); + host.ssl = conf.ReadFlag("database", "ssl", "0", i); + if (h == host) + return true; + } + return false; + } + + void ReadConf() + { + ClearOldConnections(); + + ConfigReader conf(ServerInstance); + for(int i = 0; i < conf.Enumerate("database"); i++) + { + SQLhost host; + + host.id = conf.ReadValue("database", "id", i); + host.host = conf.ReadValue("database", "hostname", i); + host.port = conf.ReadInteger("database", "port", i, true); + host.name = conf.ReadValue("database", "name", i); + host.user = conf.ReadValue("database", "username", i); + host.pass = conf.ReadValue("database", "password", i); + host.ssl = conf.ReadFlag("database", "ssl", "0", i); + + if (HasHost(host)) + continue; + + this->AddConn(host); + } + } + + void AddConn(const SQLhost& hi) + { + if (HasHost(hi)) + { + ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str()); + return; + } + + SQLConn* newconn; + + newconn = new SQLConn(ServerInstance, this, hi); + + connections.insert(std::make_pair(hi.id, newconn)); + } + + void ClearOldConnections() + { + ConnMap::iterator iter,safei; + for (iter = connections.begin(); iter != connections.end(); iter++) + { + if (!HostInConf(iter->second->GetConfHost())) + { + DELETE(iter->second); + safei = iter; + --iter; + connections.erase(safei); + } + } + } + + void ClearAllConnections() + { + ConnMap::iterator i; + while ((i = connections.begin()) != connections.end()) + { + connections.erase(i); + DELETE(i->second); + } + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ReadConf(); + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLREQID, request->GetId()) == 0) + { + SQLrequest* req = (SQLrequest*)request; + ConnMap::iterator iter; + if((iter = connections.find(req->dbid)) != connections.end()) + { + req->id = NewID(); + req->error = iter->second->Query(*req); + return SQLSUCCESS; + } + else + { + req->error.Id(BAD_DBID); + return NULL; + } + } + return NULL; + } + + unsigned long NewID() + { + if (currid+1 == 0) + currid++; + + return ++currid; + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION); + } + +}; + +void ResultNotifier::Dispatch() +{ + ((ModuleSQLite3*)mod)->SendQueue(); +} + +MODULE_INIT(ModuleSQLite3); + diff --git a/src/modules/extra/m_sqllog.cpp b/src/modules/extra/m_sqllog.cpp index 04eb1fef1..391e4bbba 100644 --- a/src/modules/extra/m_sqllog.cpp +++ b/src/modules/extra/m_sqllog.cpp @@ -1 +1,310 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" #include "m_sqlv2.h" static Module* SQLModule; static Module* MyMod; static std::string dbid; enum LogTypes { LT_OPER = 1, LT_KILL, LT_SERVLINK, LT_XLINE, LT_CONNECT, LT_DISCONNECT, LT_FLOOD, LT_LOADMODULE }; enum QueryState { FIND_SOURCE, FIND_NICK, FIND_HOST, DONE}; class QueryInfo; std::map active_queries; class QueryInfo { public: QueryState qs; unsigned long id; std::string nick; std::string source; std::string hostname; int sourceid; int nickid; int hostid; int category; time_t date; bool insert; QueryInfo(const std::string &n, const std::string &s, const std::string &h, unsigned long i, int cat) { qs = FIND_SOURCE; nick = n; source = s; hostname = h; id = i; category = cat; sourceid = nickid = hostid = -1; date = time(NULL); insert = false; } void Go(SQLresult* res) { SQLrequest req = SQLreq(MyMod, SQLModule, dbid, "", ""); switch (qs) { case FIND_SOURCE: if (res->Rows() && sourceid == -1 && !insert) { sourceid = atoi(res->GetValue(0,0).d.c_str()); req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", nick); if(req.Send()) { insert = false; qs = FIND_NICK; active_queries[req.id] = this; } } else if (res->Rows() && sourceid == -1 && insert) { req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", source); if(req.Send()) { insert = false; qs = FIND_SOURCE; active_queries[req.id] = this; } } else { req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors (actor) VALUES('?')", source); if(req.Send()) { insert = true; qs = FIND_SOURCE; active_queries[req.id] = this; } } break; case FIND_NICK: if (res->Rows() && nickid == -1 && !insert) { nickid = atoi(res->GetValue(0,0).d.c_str()); req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,hostname FROM ircd_log_hosts WHERE hostname='?'", hostname); if(req.Send()) { insert = false; qs = FIND_HOST; active_queries[req.id] = this; } } else if (res->Rows() && nickid == -1 && insert) { req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", nick); if(req.Send()) { insert = false; qs = FIND_NICK; active_queries[req.id] = this; } } else { req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors (actor) VALUES('?')",nick); if(req.Send()) { insert = true; qs = FIND_NICK; active_queries[req.id] = this; } } break; case FIND_HOST: if (res->Rows() && hostid == -1 && !insert) { hostid = atoi(res->GetValue(0,0).d.c_str()); req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log (category_id,nick,host,source,dtime) VALUES("+ConvToStr(category)+","+ConvToStr(nickid)+","+ConvToStr(hostid)+","+ConvToStr(sourceid)+","+ConvToStr(date)+")"); if(req.Send()) { insert = true; qs = DONE; active_queries[req.id] = this; } } else if (res->Rows() && hostid == -1 && insert) { req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,hostname FROM ircd_log_hosts WHERE hostname='?'", hostname); if(req.Send()) { insert = false; qs = FIND_HOST; active_queries[req.id] = this; } } else { req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_hosts (hostname) VALUES('?')", hostname); if(req.Send()) { insert = true; qs = FIND_HOST; active_queries[req.id] = this; } } break; case DONE: delete active_queries[req.id]; active_queries[req.id] = NULL; break; } } }; /* $ModDesc: Logs network-wide data to an SQL database */ class ModuleSQLLog : public Module { ConfigReader* Conf; public: ModuleSQLLog(InspIRCd* Me) : Module::Module(Me) { ServerInstance->UseInterface("SQLutils"); ServerInstance->UseInterface("SQL"); Module* SQLutils = ServerInstance->FindModule("m_sqlutils.so"); if (!SQLutils) throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqlauth.so."); SQLModule = ServerInstance->FindFeature("SQL"); OnRehash(NULL,""); MyMod = this; active_queries.clear(); } virtual ~ModuleSQLLog() { ServerInstance->DoneWithInterface("SQL"); ServerInstance->DoneWithInterface("SQLutils"); } void Implements(char* List) { List[I_OnRehash] = List[I_OnOper] = List[I_OnGlobalOper] = List[I_OnKill] = 1; List[I_OnPreCommand] = List[I_OnUserConnect] = 1; List[I_OnUserQuit] = List[I_OnLoadModule] = List[I_OnRequest] = 1; } void ReadConfig() { ConfigReader Conf(ServerInstance); dbid = Conf.ReadValue("sqllog","dbid",0); // database id of a database configured in sql module } virtual void OnRehash(userrec* user, const std::string ¶meter) { ReadConfig(); } virtual char* OnRequest(Request* request) { if(strcmp(SQLRESID, request->GetId()) == 0) { SQLresult* res; std::map::iterator n; res = static_cast(request); n = active_queries.find(res->id); if (n != active_queries.end()) { n->second->Go(res); std::map::iterator n = active_queries.find(res->id); active_queries.erase(n); } return SQLSUCCESS; } return NULL; } void AddLogEntry(int category, const std::string &nick, const std::string &host, const std::string &source) { // is the sql module loaded? If not, we don't attempt to do anything. if (!SQLModule) return; SQLrequest req = SQLreq(this, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", source); if(req.Send()) { QueryInfo* i = new QueryInfo(nick, source, host, req.id, category); i->qs = FIND_SOURCE; active_queries[req.id] = i; } } virtual void OnOper(userrec* user, const std::string &opertype) { AddLogEntry(LT_OPER,user->nick,user->host,user->server); } virtual void OnGlobalOper(userrec* user) { AddLogEntry(LT_OPER,user->nick,user->host,user->server); } virtual int OnKill(userrec* source, userrec* dest, const std::string &reason) { AddLogEntry(LT_KILL,dest->nick,dest->host,source->nick); return 0; } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { if ((command == "GLINE" || command == "KLINE" || command == "ELINE" || command == "ZLINE") && validated) { AddLogEntry(LT_XLINE,user->nick,command[0]+std::string(":")+std::string(parameters[0]),user->server); } return 0; } virtual void OnUserConnect(userrec* user) { AddLogEntry(LT_CONNECT,user->nick,user->host,user->server); } virtual void OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message) { AddLogEntry(LT_DISCONNECT,user->nick,user->host,user->server); } virtual void OnLoadModule(Module* mod, const std::string &name) { AddLogEntry(LT_LOADMODULE,name,ServerInstance->Config->ServerName, ServerInstance->Config->ServerName); } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleSQLLog); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" +#include "m_sqlv2.h" + +static Module* SQLModule; +static Module* MyMod; +static std::string dbid; + +enum LogTypes { LT_OPER = 1, LT_KILL, LT_SERVLINK, LT_XLINE, LT_CONNECT, LT_DISCONNECT, LT_FLOOD, LT_LOADMODULE }; + +enum QueryState { FIND_SOURCE, FIND_NICK, FIND_HOST, DONE}; + +class QueryInfo; + +std::map active_queries; + +class QueryInfo +{ +public: + QueryState qs; + unsigned long id; + std::string nick; + std::string source; + std::string hostname; + int sourceid; + int nickid; + int hostid; + int category; + time_t date; + bool insert; + + QueryInfo(const std::string &n, const std::string &s, const std::string &h, unsigned long i, int cat) + { + qs = FIND_SOURCE; + nick = n; + source = s; + hostname = h; + id = i; + category = cat; + sourceid = nickid = hostid = -1; + date = time(NULL); + insert = false; + } + + void Go(SQLresult* res) + { + SQLrequest req = SQLreq(MyMod, SQLModule, dbid, "", ""); + switch (qs) + { + case FIND_SOURCE: + if (res->Rows() && sourceid == -1 && !insert) + { + sourceid = atoi(res->GetValue(0,0).d.c_str()); + req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", nick); + if(req.Send()) + { + insert = false; + qs = FIND_NICK; + active_queries[req.id] = this; + } + } + else if (res->Rows() && sourceid == -1 && insert) + { + req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", source); + if(req.Send()) + { + insert = false; + qs = FIND_SOURCE; + active_queries[req.id] = this; + } + } + else + { + req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors (actor) VALUES('?')", source); + if(req.Send()) + { + insert = true; + qs = FIND_SOURCE; + active_queries[req.id] = this; + } + } + break; + + case FIND_NICK: + if (res->Rows() && nickid == -1 && !insert) + { + nickid = atoi(res->GetValue(0,0).d.c_str()); + req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,hostname FROM ircd_log_hosts WHERE hostname='?'", hostname); + if(req.Send()) + { + insert = false; + qs = FIND_HOST; + active_queries[req.id] = this; + } + } + else if (res->Rows() && nickid == -1 && insert) + { + req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", nick); + if(req.Send()) + { + insert = false; + qs = FIND_NICK; + active_queries[req.id] = this; + } + } + else + { + req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors (actor) VALUES('?')",nick); + if(req.Send()) + { + insert = true; + qs = FIND_NICK; + active_queries[req.id] = this; + } + } + break; + + case FIND_HOST: + if (res->Rows() && hostid == -1 && !insert) + { + hostid = atoi(res->GetValue(0,0).d.c_str()); + req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log (category_id,nick,host,source,dtime) VALUES("+ConvToStr(category)+","+ConvToStr(nickid)+","+ConvToStr(hostid)+","+ConvToStr(sourceid)+","+ConvToStr(date)+")"); + if(req.Send()) + { + insert = true; + qs = DONE; + active_queries[req.id] = this; + } + } + else if (res->Rows() && hostid == -1 && insert) + { + req = SQLreq(MyMod, SQLModule, dbid, "SELECT id,hostname FROM ircd_log_hosts WHERE hostname='?'", hostname); + if(req.Send()) + { + insert = false; + qs = FIND_HOST; + active_queries[req.id] = this; + } + } + else + { + req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_hosts (hostname) VALUES('?')", hostname); + if(req.Send()) + { + insert = true; + qs = FIND_HOST; + active_queries[req.id] = this; + } + } + break; + + case DONE: + delete active_queries[req.id]; + active_queries[req.id] = NULL; + break; + } + } +}; + +/* $ModDesc: Logs network-wide data to an SQL database */ + +class ModuleSQLLog : public Module +{ + ConfigReader* Conf; + + public: + ModuleSQLLog(InspIRCd* Me) + : Module::Module(Me) + { + ServerInstance->UseInterface("SQLutils"); + ServerInstance->UseInterface("SQL"); + + Module* SQLutils = ServerInstance->FindModule("m_sqlutils.so"); + if (!SQLutils) + throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqlauth.so."); + + SQLModule = ServerInstance->FindFeature("SQL"); + + OnRehash(NULL,""); + MyMod = this; + active_queries.clear(); + } + + virtual ~ModuleSQLLog() + { + ServerInstance->DoneWithInterface("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnOper] = List[I_OnGlobalOper] = List[I_OnKill] = 1; + List[I_OnPreCommand] = List[I_OnUserConnect] = 1; + List[I_OnUserQuit] = List[I_OnLoadModule] = List[I_OnRequest] = 1; + } + + void ReadConfig() + { + ConfigReader Conf(ServerInstance); + dbid = Conf.ReadValue("sqllog","dbid",0); // database id of a database configured in sql module + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ReadConfig(); + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLRESID, request->GetId()) == 0) + { + SQLresult* res; + std::map::iterator n; + + res = static_cast(request); + n = active_queries.find(res->id); + + if (n != active_queries.end()) + { + n->second->Go(res); + std::map::iterator n = active_queries.find(res->id); + active_queries.erase(n); + } + + return SQLSUCCESS; + } + + return NULL; + } + + void AddLogEntry(int category, const std::string &nick, const std::string &host, const std::string &source) + { + // is the sql module loaded? If not, we don't attempt to do anything. + if (!SQLModule) + return; + + SQLrequest req = SQLreq(this, SQLModule, dbid, "SELECT id,actor FROM ircd_log_actors WHERE actor='?'", source); + if(req.Send()) + { + QueryInfo* i = new QueryInfo(nick, source, host, req.id, category); + i->qs = FIND_SOURCE; + active_queries[req.id] = i; + } + } + + virtual void OnOper(userrec* user, const std::string &opertype) + { + AddLogEntry(LT_OPER,user->nick,user->host,user->server); + } + + virtual void OnGlobalOper(userrec* user) + { + AddLogEntry(LT_OPER,user->nick,user->host,user->server); + } + + virtual int OnKill(userrec* source, userrec* dest, const std::string &reason) + { + AddLogEntry(LT_KILL,dest->nick,dest->host,source->nick); + return 0; + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + if ((command == "GLINE" || command == "KLINE" || command == "ELINE" || command == "ZLINE") && validated) + { + AddLogEntry(LT_XLINE,user->nick,command[0]+std::string(":")+std::string(parameters[0]),user->server); + } + return 0; + } + + virtual void OnUserConnect(userrec* user) + { + AddLogEntry(LT_CONNECT,user->nick,user->host,user->server); + } + + virtual void OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message) + { + AddLogEntry(LT_DISCONNECT,user->nick,user->host,user->server); + } + + virtual void OnLoadModule(Module* mod, const std::string &name) + { + AddLogEntry(LT_LOADMODULE,name,ServerInstance->Config->ServerName, ServerInstance->Config->ServerName); + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleSQLLog); + diff --git a/src/modules/extra/m_sqloper.cpp b/src/modules/extra/m_sqloper.cpp index 4b09ac26e..520869e21 100644 --- a/src/modules/extra/m_sqloper.cpp +++ b/src/modules/extra/m_sqloper.cpp @@ -1 +1,283 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" #include "m_sqlv2.h" #include "m_sqlutils.h" #include "m_hash.h" #include "commands/cmd_oper.h" /* $ModDesc: Allows storage of oper credentials in an SQL table */ /* $ModDep: m_sqlv2.h m_sqlutils.h */ class ModuleSQLOper : public Module { Module* SQLutils; Module* HashModule; std::string databaseid; public: ModuleSQLOper(InspIRCd* Me) : Module::Module(Me) { ServerInstance->UseInterface("SQLutils"); ServerInstance->UseInterface("SQL"); ServerInstance->UseInterface("HashRequest"); /* Attempt to locate the md5 service provider, bail if we can't find it */ HashModule = ServerInstance->FindModule("m_md5.so"); if (!HashModule) throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_sqloper.so."); SQLutils = ServerInstance->FindModule("m_sqlutils.so"); if (!SQLutils) throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqloper.so."); OnRehash(NULL,""); } virtual ~ModuleSQLOper() { ServerInstance->DoneWithInterface("SQL"); ServerInstance->DoneWithInterface("SQLutils"); ServerInstance->DoneWithInterface("HashRequest"); } void Implements(char* List) { List[I_OnRequest] = List[I_OnRehash] = List[I_OnPreCommand] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader Conf(ServerInstance); databaseid = Conf.ReadValue("sqloper", "dbid", 0); /* Database ID of a database configured for the service provider module */ } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { if ((validated) && (command == "OPER")) { if (LookupOper(user, parameters[0], parameters[1])) { /* Returning true here just means the query is in progress, or on it's way to being * in progress. Nothing about the /oper actually being successful.. * If the oper lookup fails later, we pass the command to the original handler * for /oper by calling its Handle method directly. */ return 1; } } return 0; } bool LookupOper(userrec* user, const std::string &username, const std::string &password) { Module* target; target = ServerInstance->FindFeature("SQL"); if (target) { /* Reset hash module first back to MD5 standard state */ HashResetRequest(this, HashModule).Send(); /* Make an MD5 hash of the password for using in the query */ std::string md5_pass_hash = HashSumRequest(this, HashModule, password.c_str()).Send(); /* We generate our own MD5 sum here because some database providers (e.g. SQLite) dont have a builtin md5 function, * also hashing it in the module and only passing a remote query containing a hash is more secure. */ SQLrequest req = SQLreq(this, target, databaseid, "SELECT username, password, hostname, type FROM ircd_opers WHERE username = '?' AND password='?'", username, md5_pass_hash); if (req.Send()) { /* When we get the query response from the service provider we will be given an ID to play with, * just an ID number which is unique to this query. We need a way of associating that ID with a userrec * so we insert it into a map mapping the IDs to users. * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling * us to discard the query. */ AssociateUser(this, SQLutils, req.id, user).Send(); user->Extend("oper_user", strdup(username.c_str())); user->Extend("oper_pass", strdup(password.c_str())); return true; } else { return false; } } else { ServerInstance->Log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be able to oper up unless their o:line is statically configured"); return false; } } virtual char* OnRequest(Request* request) { if (strcmp(SQLRESID, request->GetId()) == 0) { SQLresult* res = static_cast(request); userrec* user = GetAssocUser(this, SQLutils, res->id).S().user; UnAssociate(this, SQLutils, res->id).S(); char* tried_user = NULL; char* tried_pass = NULL; user->GetExt("oper_user", tried_user); user->GetExt("oper_pass", tried_pass); if (user) { if (res->error.Id() == NO_ERROR) { if (res->Rows()) { /* We got a row in the result, this means there was a record for the oper.. * now we just need to check if their host matches, and if it does then * oper them up. * * We now (previous versions of the module didn't) support multiple SQL * rows per-oper in the same way the config file does, all rows will be tried * until one is found which matches. This is useful to define several different * hosts for a single oper. * * The for() loop works as SQLresult::GetRowMap() returns an empty map when there * are no more rows to return. */ for (SQLfieldMap& row = res->GetRowMap(); row.size(); row = res->GetRowMap()) { if (OperUser(user, row["username"].d, row["password"].d, row["hostname"].d, row["type"].d)) { /* If/when one of the rows matches, stop checking and return */ return SQLSUCCESS; } if (tried_user && tried_pass) { LoginFail(user, tried_user, tried_pass); free(tried_user); free(tried_pass); user->Shrink("oper_user"); user->Shrink("oper_pass"); } } } else { /* No rows in result, this means there was no oper line for the user, * we should have already checked the o:lines so now we need an * "insufficient awesomeness" (invalid credentials) error */ if (tried_user && tried_pass) { LoginFail(user, tried_user, tried_pass); free(tried_user); free(tried_pass); user->Shrink("oper_user"); user->Shrink("oper_pass"); } } } else { /* This one shouldn't happen, the query failed for some reason. * We have to fail the /oper request and give them the same error * as above. */ if (tried_user && tried_pass) { LoginFail(user, tried_user, tried_pass); free(tried_user); free(tried_pass); user->Shrink("oper_user"); user->Shrink("oper_pass"); } } } return SQLSUCCESS; } return NULL; } void LoginFail(userrec* user, const std::string &username, const std::string &pass) { command_t* oper_command = ServerInstance->Parser->GetHandler("OPER"); if (oper_command) { const char* params[] = { username.c_str(), pass.c_str() }; oper_command->Handle(params, 2, user); } else { ServerInstance->Log(DEBUG, "BUG: WHAT?! Why do we have no OPER command?!"); } } bool OperUser(userrec* user, const std::string &username, const std::string &password, const std::string &pattern, const std::string &type) { ConfigReader Conf(ServerInstance); for (int j = 0; j < Conf.Enumerate("type"); j++) { std::string tname = Conf.ReadValue("type","name",j); std::string hostname(user->ident); hostname.append("@").append(user->host); if ((tname == type) && OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str())) { /* Opertype and host match, looks like this is it. */ std::string operhost = Conf.ReadValue("type", "host", j); if (operhost.size()) user->ChangeDisplayedHost(operhost.c_str()); ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s", user->nick, user->ident, user->host, type.c_str()); user->WriteServ("381 %s :You are now an IRC operator of type %s", user->nick, type.c_str()); if (!user->modes[UM_OPERATOR]) user->Oper(type); return true; } } return false; } virtual Version GetVersion() { return Version(1,1,1,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleSQLOper); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" + +#include "m_sqlv2.h" +#include "m_sqlutils.h" +#include "m_hash.h" +#include "commands/cmd_oper.h" + +/* $ModDesc: Allows storage of oper credentials in an SQL table */ +/* $ModDep: m_sqlv2.h m_sqlutils.h */ + +class ModuleSQLOper : public Module +{ + Module* SQLutils; + Module* HashModule; + std::string databaseid; + +public: + ModuleSQLOper(InspIRCd* Me) + : Module::Module(Me) + { + ServerInstance->UseInterface("SQLutils"); + ServerInstance->UseInterface("SQL"); + ServerInstance->UseInterface("HashRequest"); + + /* Attempt to locate the md5 service provider, bail if we can't find it */ + HashModule = ServerInstance->FindModule("m_md5.so"); + if (!HashModule) + throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_sqloper.so."); + + SQLutils = ServerInstance->FindModule("m_sqlutils.so"); + if (!SQLutils) + throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqloper.so."); + + OnRehash(NULL,""); + } + + virtual ~ModuleSQLOper() + { + ServerInstance->DoneWithInterface("SQL"); + ServerInstance->DoneWithInterface("SQLutils"); + ServerInstance->DoneWithInterface("HashRequest"); + } + + void Implements(char* List) + { + List[I_OnRequest] = List[I_OnRehash] = List[I_OnPreCommand] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader Conf(ServerInstance); + + databaseid = Conf.ReadValue("sqloper", "dbid", 0); /* Database ID of a database configured for the service provider module */ + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + if ((validated) && (command == "OPER")) + { + if (LookupOper(user, parameters[0], parameters[1])) + { + /* Returning true here just means the query is in progress, or on it's way to being + * in progress. Nothing about the /oper actually being successful.. + * If the oper lookup fails later, we pass the command to the original handler + * for /oper by calling its Handle method directly. + */ + return 1; + } + } + return 0; + } + + bool LookupOper(userrec* user, const std::string &username, const std::string &password) + { + Module* target; + + target = ServerInstance->FindFeature("SQL"); + + if (target) + { + /* Reset hash module first back to MD5 standard state */ + HashResetRequest(this, HashModule).Send(); + /* Make an MD5 hash of the password for using in the query */ + std::string md5_pass_hash = HashSumRequest(this, HashModule, password.c_str()).Send(); + + /* We generate our own MD5 sum here because some database providers (e.g. SQLite) dont have a builtin md5 function, + * also hashing it in the module and only passing a remote query containing a hash is more secure. + */ + + SQLrequest req = SQLreq(this, target, databaseid, "SELECT username, password, hostname, type FROM ircd_opers WHERE username = '?' AND password='?'", username, md5_pass_hash); + + if (req.Send()) + { + /* When we get the query response from the service provider we will be given an ID to play with, + * just an ID number which is unique to this query. We need a way of associating that ID with a userrec + * so we insert it into a map mapping the IDs to users. + * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the + * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling + * us to discard the query. + */ + AssociateUser(this, SQLutils, req.id, user).Send(); + + user->Extend("oper_user", strdup(username.c_str())); + user->Extend("oper_pass", strdup(password.c_str())); + + return true; + } + else + { + return false; + } + } + else + { + ServerInstance->Log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be able to oper up unless their o:line is statically configured"); + return false; + } + } + + virtual char* OnRequest(Request* request) + { + if (strcmp(SQLRESID, request->GetId()) == 0) + { + SQLresult* res = static_cast(request); + + userrec* user = GetAssocUser(this, SQLutils, res->id).S().user; + UnAssociate(this, SQLutils, res->id).S(); + + char* tried_user = NULL; + char* tried_pass = NULL; + + user->GetExt("oper_user", tried_user); + user->GetExt("oper_pass", tried_pass); + + if (user) + { + if (res->error.Id() == NO_ERROR) + { + if (res->Rows()) + { + /* We got a row in the result, this means there was a record for the oper.. + * now we just need to check if their host matches, and if it does then + * oper them up. + * + * We now (previous versions of the module didn't) support multiple SQL + * rows per-oper in the same way the config file does, all rows will be tried + * until one is found which matches. This is useful to define several different + * hosts for a single oper. + * + * The for() loop works as SQLresult::GetRowMap() returns an empty map when there + * are no more rows to return. + */ + + for (SQLfieldMap& row = res->GetRowMap(); row.size(); row = res->GetRowMap()) + { + if (OperUser(user, row["username"].d, row["password"].d, row["hostname"].d, row["type"].d)) + { + /* If/when one of the rows matches, stop checking and return */ + return SQLSUCCESS; + } + if (tried_user && tried_pass) + { + LoginFail(user, tried_user, tried_pass); + free(tried_user); + free(tried_pass); + user->Shrink("oper_user"); + user->Shrink("oper_pass"); + } + } + } + else + { + /* No rows in result, this means there was no oper line for the user, + * we should have already checked the o:lines so now we need an + * "insufficient awesomeness" (invalid credentials) error + */ + if (tried_user && tried_pass) + { + LoginFail(user, tried_user, tried_pass); + free(tried_user); + free(tried_pass); + user->Shrink("oper_user"); + user->Shrink("oper_pass"); + } + } + } + else + { + /* This one shouldn't happen, the query failed for some reason. + * We have to fail the /oper request and give them the same error + * as above. + */ + if (tried_user && tried_pass) + { + LoginFail(user, tried_user, tried_pass); + free(tried_user); + free(tried_pass); + user->Shrink("oper_user"); + user->Shrink("oper_pass"); + } + + } + } + + return SQLSUCCESS; + } + + return NULL; + } + + void LoginFail(userrec* user, const std::string &username, const std::string &pass) + { + command_t* oper_command = ServerInstance->Parser->GetHandler("OPER"); + + if (oper_command) + { + const char* params[] = { username.c_str(), pass.c_str() }; + oper_command->Handle(params, 2, user); + } + else + { + ServerInstance->Log(DEBUG, "BUG: WHAT?! Why do we have no OPER command?!"); + } + } + + bool OperUser(userrec* user, const std::string &username, const std::string &password, const std::string &pattern, const std::string &type) + { + ConfigReader Conf(ServerInstance); + + for (int j = 0; j < Conf.Enumerate("type"); j++) + { + std::string tname = Conf.ReadValue("type","name",j); + std::string hostname(user->ident); + + hostname.append("@").append(user->host); + + if ((tname == type) && OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str())) + { + /* Opertype and host match, looks like this is it. */ + std::string operhost = Conf.ReadValue("type", "host", j); + + if (operhost.size()) + user->ChangeDisplayedHost(operhost.c_str()); + + ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s", user->nick, user->ident, user->host, type.c_str()); + user->WriteServ("381 %s :You are now an IRC operator of type %s", user->nick, type.c_str()); + + if (!user->modes[UM_OPERATOR]) + user->Oper(type); + + return true; + } + } + + return false; + } + + virtual Version GetVersion() + { + return Version(1,1,1,0,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleSQLOper); + diff --git a/src/modules/extra/m_sqlutils.cpp b/src/modules/extra/m_sqlutils.cpp index 6cd09252b..b470f99af 100644 --- a/src/modules/extra/m_sqlutils.cpp +++ b/src/modules/extra/m_sqlutils.cpp @@ -1 +1,238 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" #include "m_sqlutils.h" /* $ModDesc: Provides some utilities to SQL client modules, such as mapping queries to users and channels */ /* $ModDep: m_sqlutils.h */ typedef std::map IdUserMap; typedef std::map IdChanMap; typedef std::list AssocIdList; class ModuleSQLutils : public Module { private: IdUserMap iduser; IdChanMap idchan; public: ModuleSQLutils(InspIRCd* Me) : Module::Module(Me) { ServerInstance->PublishInterface("SQLutils", this); } virtual ~ModuleSQLutils() { ServerInstance->UnpublishInterface("SQLutils", this); } void Implements(char* List) { List[I_OnChannelDelete] = List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnUserDisconnect] = 1; } virtual char* OnRequest(Request* request) { if(strcmp(SQLUTILAU, request->GetId()) == 0) { AssociateUser* req = (AssociateUser*)request; iduser.insert(std::make_pair(req->id, req->user)); AttachList(req->user, req->id); } else if(strcmp(SQLUTILAC, request->GetId()) == 0) { AssociateChan* req = (AssociateChan*)request; idchan.insert(std::make_pair(req->id, req->chan)); AttachList(req->chan, req->id); } else if(strcmp(SQLUTILUA, request->GetId()) == 0) { UnAssociate* req = (UnAssociate*)request; /* Unassociate a given query ID with all users and channels * it is associated with. */ DoUnAssociate(iduser, req->id); DoUnAssociate(idchan, req->id); } else if(strcmp(SQLUTILGU, request->GetId()) == 0) { GetAssocUser* req = (GetAssocUser*)request; IdUserMap::iterator iter = iduser.find(req->id); if(iter != iduser.end()) { req->user = iter->second; } } else if(strcmp(SQLUTILGC, request->GetId()) == 0) { GetAssocChan* req = (GetAssocChan*)request; IdChanMap::iterator iter = idchan.find(req->id); if(iter != idchan.end()) { req->chan = iter->second; } } return SQLUTILSUCCESS; } virtual void OnUserDisconnect(userrec* user) { /* A user is disconnecting, first we need to check if they have a list of queries associated with them. * Then, if they do, we need to erase each of them from our IdUserMap (iduser) so when the module that * associated them asks to look them up then it gets a NULL result and knows to discard the query. */ AssocIdList* il; if(user->GetExt("sqlutils_queryids", il)) { for(AssocIdList::iterator listiter = il->begin(); listiter != il->end(); listiter++) { IdUserMap::iterator iter; iter = iduser.find(*listiter); if(iter != iduser.end()) { if(iter->second != user) { ServerInstance->Log(DEBUG, "BUG: ID associated with user %s doesn't have the same userrec* associated with it in the map (erasing anyway)", user->nick); } iduser.erase(iter); } else { ServerInstance->Log(DEBUG, "BUG: user %s was extended with sqlutils_queryids but there was nothing matching in the map", user->nick); } } user->Shrink("sqlutils_queryids"); delete il; } } void AttachList(Extensible* obj, unsigned long id) { AssocIdList* il; if(!obj->GetExt("sqlutils_queryids", il)) { /* Doesn't already exist, create a new list and attach it. */ il = new AssocIdList; obj->Extend("sqlutils_queryids", il); } /* Now either way we have a valid list in il, attached. */ il->push_back(id); } void RemoveFromList(Extensible* obj, unsigned long id) { AssocIdList* il; if(obj->GetExt("sqlutils_queryids", il)) { /* Only do anything if the list exists... (which it ought to) */ il->remove(id); if(il->empty()) { /* If we just emptied it.. */ delete il; obj->Shrink("sqlutils_queryids"); } } } template void DoUnAssociate(T &map, unsigned long id) { /* For each occurence of 'id' (well, only one..it's not a multimap) in 'map' * remove it from the map, take an Extensible* value from the map and remove * 'id' from the list of query IDs attached to it. */ typename T::iterator iter = map.find(id); if(iter != map.end()) { /* Found a value indexed by 'id', call RemoveFromList() * on it with 'id' to remove 'id' from the list attached * to the value. */ RemoveFromList(iter->second, id); } } virtual void OnChannelDelete(chanrec* chan) { /* A channel is being destroyed, first we need to check if it has a list of queries associated with it. * Then, if it does, we need to erase each of them from our IdChanMap (idchan) so when the module that * associated them asks to look them up then it gets a NULL result and knows to discard the query. */ AssocIdList* il; if(chan->GetExt("sqlutils_queryids", il)) { for(AssocIdList::iterator listiter = il->begin(); listiter != il->end(); listiter++) { IdChanMap::iterator iter; iter = idchan.find(*listiter); if(iter != idchan.end()) { if(iter->second != chan) { ServerInstance->Log(DEBUG, "BUG: ID associated with channel %s doesn't have the same chanrec* associated with it in the map (erasing anyway)", chan->name); } idchan.erase(iter); } else { ServerInstance->Log(DEBUG, "BUG: channel %s was extended with sqlutils_queryids but there was nothing matching in the map", chan->name); } } chan->Shrink("sqlutils_queryids"); delete il; } } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION); } }; MODULE_INIT(ModuleSQLutils); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" +#include "m_sqlutils.h" + +/* $ModDesc: Provides some utilities to SQL client modules, such as mapping queries to users and channels */ +/* $ModDep: m_sqlutils.h */ + +typedef std::map IdUserMap; +typedef std::map IdChanMap; +typedef std::list AssocIdList; + +class ModuleSQLutils : public Module +{ +private: + IdUserMap iduser; + IdChanMap idchan; + +public: + ModuleSQLutils(InspIRCd* Me) + : Module::Module(Me) + { + ServerInstance->PublishInterface("SQLutils", this); + } + + virtual ~ModuleSQLutils() + { + ServerInstance->UnpublishInterface("SQLutils", this); + } + + void Implements(char* List) + { + List[I_OnChannelDelete] = List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnUserDisconnect] = 1; + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLUTILAU, request->GetId()) == 0) + { + AssociateUser* req = (AssociateUser*)request; + + iduser.insert(std::make_pair(req->id, req->user)); + + AttachList(req->user, req->id); + } + else if(strcmp(SQLUTILAC, request->GetId()) == 0) + { + AssociateChan* req = (AssociateChan*)request; + + idchan.insert(std::make_pair(req->id, req->chan)); + + AttachList(req->chan, req->id); + } + else if(strcmp(SQLUTILUA, request->GetId()) == 0) + { + UnAssociate* req = (UnAssociate*)request; + + /* Unassociate a given query ID with all users and channels + * it is associated with. + */ + + DoUnAssociate(iduser, req->id); + DoUnAssociate(idchan, req->id); + } + else if(strcmp(SQLUTILGU, request->GetId()) == 0) + { + GetAssocUser* req = (GetAssocUser*)request; + + IdUserMap::iterator iter = iduser.find(req->id); + + if(iter != iduser.end()) + { + req->user = iter->second; + } + } + else if(strcmp(SQLUTILGC, request->GetId()) == 0) + { + GetAssocChan* req = (GetAssocChan*)request; + + IdChanMap::iterator iter = idchan.find(req->id); + + if(iter != idchan.end()) + { + req->chan = iter->second; + } + } + + return SQLUTILSUCCESS; + } + + virtual void OnUserDisconnect(userrec* user) + { + /* A user is disconnecting, first we need to check if they have a list of queries associated with them. + * Then, if they do, we need to erase each of them from our IdUserMap (iduser) so when the module that + * associated them asks to look them up then it gets a NULL result and knows to discard the query. + */ + AssocIdList* il; + + if(user->GetExt("sqlutils_queryids", il)) + { + for(AssocIdList::iterator listiter = il->begin(); listiter != il->end(); listiter++) + { + IdUserMap::iterator iter; + + iter = iduser.find(*listiter); + + if(iter != iduser.end()) + { + if(iter->second != user) + { + ServerInstance->Log(DEBUG, "BUG: ID associated with user %s doesn't have the same userrec* associated with it in the map (erasing anyway)", user->nick); + } + + iduser.erase(iter); + } + else + { + ServerInstance->Log(DEBUG, "BUG: user %s was extended with sqlutils_queryids but there was nothing matching in the map", user->nick); + } + } + + user->Shrink("sqlutils_queryids"); + delete il; + } + } + + void AttachList(Extensible* obj, unsigned long id) + { + AssocIdList* il; + + if(!obj->GetExt("sqlutils_queryids", il)) + { + /* Doesn't already exist, create a new list and attach it. */ + il = new AssocIdList; + obj->Extend("sqlutils_queryids", il); + } + + /* Now either way we have a valid list in il, attached. */ + il->push_back(id); + } + + void RemoveFromList(Extensible* obj, unsigned long id) + { + AssocIdList* il; + + if(obj->GetExt("sqlutils_queryids", il)) + { + /* Only do anything if the list exists... (which it ought to) */ + il->remove(id); + + if(il->empty()) + { + /* If we just emptied it.. */ + delete il; + obj->Shrink("sqlutils_queryids"); + } + } + } + + template void DoUnAssociate(T &map, unsigned long id) + { + /* For each occurence of 'id' (well, only one..it's not a multimap) in 'map' + * remove it from the map, take an Extensible* value from the map and remove + * 'id' from the list of query IDs attached to it. + */ + typename T::iterator iter = map.find(id); + + if(iter != map.end()) + { + /* Found a value indexed by 'id', call RemoveFromList() + * on it with 'id' to remove 'id' from the list attached + * to the value. + */ + RemoveFromList(iter->second, id); + } + } + + virtual void OnChannelDelete(chanrec* chan) + { + /* A channel is being destroyed, first we need to check if it has a list of queries associated with it. + * Then, if it does, we need to erase each of them from our IdChanMap (idchan) so when the module that + * associated them asks to look them up then it gets a NULL result and knows to discard the query. + */ + AssocIdList* il; + + if(chan->GetExt("sqlutils_queryids", il)) + { + for(AssocIdList::iterator listiter = il->begin(); listiter != il->end(); listiter++) + { + IdChanMap::iterator iter; + + iter = idchan.find(*listiter); + + if(iter != idchan.end()) + { + if(iter->second != chan) + { + ServerInstance->Log(DEBUG, "BUG: ID associated with channel %s doesn't have the same chanrec* associated with it in the map (erasing anyway)", chan->name); + } + idchan.erase(iter); + } + else + { + ServerInstance->Log(DEBUG, "BUG: channel %s was extended with sqlutils_queryids but there was nothing matching in the map", chan->name); + } + } + + chan->Shrink("sqlutils_queryids"); + delete il; + } + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION); + } + +}; + +MODULE_INIT(ModuleSQLutils); + diff --git a/src/modules/extra/m_sqlutils.h b/src/modules/extra/m_sqlutils.h index cdde51f67..92fbdf5c7 100644 --- a/src/modules/extra/m_sqlutils.h +++ b/src/modules/extra/m_sqlutils.h @@ -1 +1,143 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #ifndef INSPIRCD_SQLUTILS #define INSPIRCD_SQLUTILS #include "modules.h" #define SQLUTILAU "SQLutil AssociateUser" #define SQLUTILAC "SQLutil AssociateChan" #define SQLUTILUA "SQLutil UnAssociate" #define SQLUTILGU "SQLutil GetAssocUser" #define SQLUTILGC "SQLutil GetAssocChan" #define SQLUTILSUCCESS "You shouldn't be reading this (success)" /** Used to associate an SQL query with a user */ class AssociateUser : public Request { public: /** Query ID */ unsigned long id; /** User */ userrec* user; AssociateUser(Module* s, Module* d, unsigned long i, userrec* u) : Request(s, d, SQLUTILAU), id(i), user(u) { } AssociateUser& S() { Send(); return *this; } }; /** Used to associate an SQL query with a channel */ class AssociateChan : public Request { public: /** Query ID */ unsigned long id; /** Channel */ chanrec* chan; AssociateChan(Module* s, Module* d, unsigned long i, chanrec* u) : Request(s, d, SQLUTILAC), id(i), chan(u) { } AssociateChan& S() { Send(); return *this; } }; /** Unassociate a user or class from an SQL query */ class UnAssociate : public Request { public: /** The query ID */ unsigned long id; UnAssociate(Module* s, Module* d, unsigned long i) : Request(s, d, SQLUTILUA), id(i) { } UnAssociate& S() { Send(); return *this; } }; /** Get the user associated with an SQL query ID */ class GetAssocUser : public Request { public: /** The query id */ unsigned long id; /** The user */ userrec* user; GetAssocUser(Module* s, Module* d, unsigned long i) : Request(s, d, SQLUTILGU), id(i), user(NULL) { } GetAssocUser& S() { Send(); return *this; } }; /** Get the channel associated with an SQL query ID */ class GetAssocChan : public Request { public: /** The query id */ unsigned long id; /** The channel */ chanrec* chan; GetAssocChan(Module* s, Module* d, unsigned long i) : Request(s, d, SQLUTILGC), id(i), chan(NULL) { } GetAssocChan& S() { Send(); return *this; } }; #endif \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#ifndef INSPIRCD_SQLUTILS +#define INSPIRCD_SQLUTILS + +#include "modules.h" + +#define SQLUTILAU "SQLutil AssociateUser" +#define SQLUTILAC "SQLutil AssociateChan" +#define SQLUTILUA "SQLutil UnAssociate" +#define SQLUTILGU "SQLutil GetAssocUser" +#define SQLUTILGC "SQLutil GetAssocChan" +#define SQLUTILSUCCESS "You shouldn't be reading this (success)" + +/** Used to associate an SQL query with a user + */ +class AssociateUser : public Request +{ +public: + /** Query ID + */ + unsigned long id; + /** User + */ + userrec* user; + + AssociateUser(Module* s, Module* d, unsigned long i, userrec* u) + : Request(s, d, SQLUTILAU), id(i), user(u) + { + } + + AssociateUser& S() + { + Send(); + return *this; + } +}; + +/** Used to associate an SQL query with a channel + */ +class AssociateChan : public Request +{ +public: + /** Query ID + */ + unsigned long id; + /** Channel + */ + chanrec* chan; + + AssociateChan(Module* s, Module* d, unsigned long i, chanrec* u) + : Request(s, d, SQLUTILAC), id(i), chan(u) + { + } + + AssociateChan& S() + { + Send(); + return *this; + } +}; + +/** Unassociate a user or class from an SQL query + */ +class UnAssociate : public Request +{ +public: + /** The query ID + */ + unsigned long id; + + UnAssociate(Module* s, Module* d, unsigned long i) + : Request(s, d, SQLUTILUA), id(i) + { + } + + UnAssociate& S() + { + Send(); + return *this; + } +}; + +/** Get the user associated with an SQL query ID + */ +class GetAssocUser : public Request +{ +public: + /** The query id + */ + unsigned long id; + /** The user + */ + userrec* user; + + GetAssocUser(Module* s, Module* d, unsigned long i) + : Request(s, d, SQLUTILGU), id(i), user(NULL) + { + } + + GetAssocUser& S() + { + Send(); + return *this; + } +}; + +/** Get the channel associated with an SQL query ID + */ +class GetAssocChan : public Request +{ +public: + /** The query id + */ + unsigned long id; + /** The channel + */ + chanrec* chan; + + GetAssocChan(Module* s, Module* d, unsigned long i) + : Request(s, d, SQLUTILGC), id(i), chan(NULL) + { + } + + GetAssocChan& S() + { + Send(); + return *this; + } +}; + +#endif diff --git a/src/modules/extra/m_sqlv2.h b/src/modules/extra/m_sqlv2.h index decac4b57..c7f6edbb9 100644 --- a/src/modules/extra/m_sqlv2.h +++ b/src/modules/extra/m_sqlv2.h @@ -1 +1,605 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #ifndef INSPIRCD_SQLAPI_2 #define INSPIRCD_SQLAPI_2 #include #include #include #include "modules.h" /** SQLreq define. * This is the voodoo magic which lets us pass multiple * parameters to the SQLrequest constructor... voodoo... */ #define SQLreq(a, b, c, d, e...) SQLrequest(a, b, c, (SQLquery(d), ##e)) /** Identifiers used to identify Request types */ #define SQLREQID "SQLv2 Request" #define SQLRESID "SQLv2 Result" #define SQLSUCCESS "You shouldn't be reading this (success)" /** Defines the error types which SQLerror may be set to */ enum SQLerrorNum { NO_ERROR, BAD_DBID, BAD_CONN, QSEND_FAIL, QREPLY_FAIL }; /** A list of format parameters for an SQLquery object. */ typedef std::deque ParamL; /** The base class of SQL exceptions */ class SQLexception : public ModuleException { public: SQLexception(const std::string &reason) : ModuleException(reason) { } SQLexception() : ModuleException("SQLv2: Undefined exception") { } }; /** An exception thrown when a bad column or row name or id is requested */ class SQLbadColName : public SQLexception { public: SQLbadColName() : SQLexception("SQLv2: Bad column name") { } }; /** SQLerror holds the error state of any SQLrequest or SQLresult. * The error string varies from database software to database software * and should be used to display informational error messages to users. */ class SQLerror : public classbase { /** The error id */ SQLerrorNum id; /** The error string */ std::string str; public: /** Initialize an SQLerror * @param i The error ID to set * @param s The (optional) error string to set */ SQLerror(SQLerrorNum i = NO_ERROR, const std::string &s = "") : id(i), str(s) { } /** Return the ID of the error */ SQLerrorNum Id() { return id; } /** Set the ID of an error * @param i The new error ID to set * @return the ID which was set */ SQLerrorNum Id(SQLerrorNum i) { id = i; return id; } /** Set the error string for an error * @param s The new error string to set */ void Str(const std::string &s) { str = s; } /** Return the error string for an error */ const char* Str() { if(str.length()) return str.c_str(); switch(id) { case NO_ERROR: return "No error"; case BAD_DBID: return "Invalid database ID"; case BAD_CONN: return "Invalid connection"; case QSEND_FAIL: return "Sending query failed"; case QREPLY_FAIL: return "Getting query result failed"; default: return "Unknown error"; } } }; /** SQLquery provides a way to represent a query string, and its parameters in a type-safe way. * C++ has no native type-safe way of having a variable number of arguments to a function, * the workaround for this isn't easy to describe simply, but in a nutshell what's really * happening when - from the above example - you do this: * * SQLrequest foo = SQLreq(this, target, "databaseid", "SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?", "Hello", "42"); * * what's actually happening is functionally this: * * SQLrequest foo = SQLreq(this, target, "databaseid", query("SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?").addparam("Hello").addparam("42")); * * with 'query()' returning a reference to an object with a 'addparam()' member function which * in turn returns a reference to that object. There are actually four ways you can create a * SQLrequest..all have their disadvantages and advantages. In the real implementations the * 'query()' function is replaced by the constructor of another class 'SQLquery' which holds * the query string and a ParamL (std::deque) of query parameters. * This is essentially the same as the above example except 'addparam()' is replaced by operator,(). The full syntax for this method is: * * SQLrequest foo = SQLrequest(this, target, "databaseid", (SQLquery("SELECT.. ?"), parameter, parameter)); */ class SQLquery : public classbase { public: /** The query 'format string' */ std::string q; /** The query parameter list * There should be one parameter for every ? character * within the format string shown above. */ ParamL p; /** Initialize an SQLquery with a given format string only */ SQLquery(const std::string &query) : q(query) { } /** Initialize an SQLquery with a format string and parameters. * If you provide parameters, you must initialize the list yourself * if you choose to do it via this method, using std::deque::push_back(). */ SQLquery(const std::string &query, const ParamL ¶ms) : q(query), p(params) { } /** An overloaded operator for pushing parameters onto the parameter list */ template SQLquery& operator,(const T &foo) { p.push_back(ConvToStr(foo)); return *this; } /** An overloaded operator for pushing parameters onto the parameter list. * This has higher precedence than 'operator,' and can save on parenthesis. */ template SQLquery& operator%(const T &foo) { p.push_back(ConvToStr(foo)); return *this; } }; /** SQLrequest is sent to the SQL API to command it to run a query and return the result. * You must instantiate this object with a valid SQLquery object and its parameters, then * send it using its Send() method to the module providing the 'SQL' feature. To find this * module, use Server::FindFeature(). */ class SQLrequest : public Request { public: /** The fully parsed and expanded query string * This is initialized from the SQLquery parameter given in the constructor. */ SQLquery query; /** The database ID to apply the request to */ std::string dbid; /** True if this is a priority query. * Priority queries may 'queue jump' in the request queue. */ bool pri; /** The query ID, assigned by the SQL api. * After your request is processed, this will * be initialized for you by the API to a valid request ID, * except in the case of an error. */ unsigned long id; /** If an error occured, error.id will be any other value than NO_ERROR. */ SQLerror error; /** Initialize an SQLrequest. * For example: * * SQLrequest req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors VALUES('','?')", nick); * * @param s A pointer to the sending module, where the result should be routed * @param d A pointer to the receiving module, identified as implementing the 'SQL' feature * @param databaseid The database ID to perform the query on. This must match a valid * database ID from the configuration of the SQL module. * @param q A properly initialized SQLquery object. */ SQLrequest(Module* s, Module* d, const std::string &databaseid, const SQLquery &q) : Request(s, d, SQLREQID), query(q), dbid(databaseid), pri(false), id(0) { } /** Set the priority of a request. */ void Priority(bool p = true) { pri = p; } /** Set the source of a request. You should not need to use this method. */ void SetSource(Module* mod) { source = mod; } }; /** * This class contains a field's data plus a way to determine if the field * is NULL or not without having to mess around with NULL pointers. */ class SQLfield { public: /** * The data itself */ std::string d; /** * If the field was null */ bool null; /** Initialize an SQLfield */ SQLfield(const std::string &data = "", bool n = false) : d(data), null(n) { } }; /** A list of items which make up a row of a result or table (tuple) * This does not include field names. */ typedef std::vector SQLfieldList; /** A list of items which make up a row of a result or table (tuple) * This also includes the field names. */ typedef std::map SQLfieldMap; /** SQLresult is a reply to a previous query. * If you send a query to the SQL api, the response will arrive at your * OnRequest method of your module at some later time, depending on the * congestion of the SQL server and complexity of the query. The ID of * this result will match the ID assigned to your original request. * SQLresult contains its own internal cursor (row counter) which is * incremented with each method call which retrieves a single row. */ class SQLresult : public Request { public: /** The original query string passed initially to the SQL API */ std::string query; /** The database ID the query was executed on */ std::string dbid; /** * The error (if any) which occured. * If an error occured the value of error.id will be any * other value than NO_ERROR. */ SQLerror error; /** * This will match query ID you were given when sending * the request at an earlier time. */ unsigned long id; /** Used by the SQL API to instantiate an SQLrequest */ SQLresult(Module* s, Module* d, unsigned long i) : Request(s, d, SQLRESID), id(i) { } /** * 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, and SQLresult::Cols() * will contain 0. In this case you SHOULD NEVER * access any of the result set rows, as there arent any! * @returns Number of rows in the result set. */ virtual int Rows() = 0; /** * Return the number of columns in the result. * If you performed an UPDATE or INSERT which * does not return a dataset, this value will * be 0. * @returns Number of columns in the result set. */ virtual int Cols() = 0; /** * Get a string name of the column by an index number * @param column The id number of a column * @returns The column name associated with the given ID */ virtual std::string ColName(int column) = 0; /** * Get an index number for a column from a string name. * An exception of type SQLbadColName will be thrown if * the name given is invalid. * @param column The column name to get the ID of * @returns The ID number of the column provided */ virtual int ColNum(const std::string &column) = 0; /** * Get a string value in a given row and column * This does not effect the internal cursor. * @returns The value stored at [row,column] in the table */ virtual SQLfield GetValue(int row, int column) = 0; /** * Return a list of values in a row, this should * increment an internal counter so you can repeatedly * call it until it returns an empty vector. * This returns a reference to an internal object, * the same object is used for all calls to this function * and therefore the return value is only valid until * you call this function again. It is also invalid if * the SQLresult object is destroyed. * The internal cursor (row counter) is incremented by one. * @returns A reference to the current row's SQLfieldList */ virtual SQLfieldList& GetRow() = 0; /** * As above, but return a map indexed by key name. * The internal cursor (row counter) is incremented by one. * @returns A reference to the current row's SQLfieldMap */ virtual SQLfieldMap& GetRowMap() = 0; /** * Like GetRow(), but returns a pointer to a dynamically * allocated object which must be explicitly freed. For * portability reasons this must be freed with SQLresult::Free() * The internal cursor (row counter) is incremented by one. * @returns A newly-allocated SQLfieldList */ virtual SQLfieldList* GetRowPtr() = 0; /** * As above, but return a map indexed by key name * The internal cursor (row counter) is incremented by one. * @returns A newly-allocated SQLfieldMap */ virtual SQLfieldMap* GetRowMapPtr() = 0; /** * Overloaded function for freeing the lists and maps * returned by GetRowPtr or GetRowMapPtr. * @param fm The SQLfieldMap to free */ virtual void Free(SQLfieldMap* fm) = 0; /** * Overloaded function for freeing the lists and maps * returned by GetRowPtr or GetRowMapPtr. * @param fl The SQLfieldList to free */ virtual void Free(SQLfieldList* fl) = 0; }; /** SQLHost represents a config line and is useful * for storing in a map and iterating on rehash to see which * tags was added/removed/unchanged. */ class SQLhost { public: std::string id; /* Database handle id */ std::string host; /* Database server hostname */ std::string ip; /* resolved IP, needed for at least pgsql.so */ unsigned int port; /* Database server port */ std::string name; /* Database name */ std::string user; /* Database username */ std::string pass; /* Database password */ bool ssl; /* If we should require SSL */ SQLhost() { } SQLhost(const std::string& i, const std::string& h, unsigned int p, const std::string& n, const std::string& u, const std::string& pa, bool s) : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s) { } /** Overload this to return a correct Data source Name (DSN) for * the current SQL module. */ std::string GetDSN(); }; /** Overload operator== for two SQLhost objects for easy comparison. */ bool operator== (const SQLhost& l, const SQLhost& r) { return (l.id == r.id && l.host == r.host && l.port == r.port && l.name == r.name && l.user == l.user && l.pass == r.pass && l.ssl == r.ssl); } /** QueryQueue, a queue of queries waiting to be executed. * This maintains two queues internally, one for 'priority' * queries and one for less important ones. Each queue has * new queries appended to it and ones to execute are popped * off the front. This keeps them flowing round nicely and no * query should ever get 'stuck' for too long. If there are * queries in the priority queue they will be executed first, * 'unimportant' queries will only be executed when the * priority queue is empty. * * We store lists of SQLrequest's here, by value as we want to avoid storing * any data allocated inside the client module (in case that module is unloaded * while the query is in progress). * * Because we want to work on the current SQLrequest in-situ, we need a way * of accessing the request we are currently processing, QueryQueue::front(), * but that call needs to always return the same request until that request * is removed from the queue, this is what the 'which' variable is. New queries are * always added to the back of one of the two queues, but if when front() * is first called then the priority queue is empty then front() will return * a query from the normal queue, but if a query is then added to the priority * queue then front() must continue to return the front of the *normal* queue * until pop() is called. */ class QueryQueue : public classbase { private: typedef std::deque ReqDeque; ReqDeque priority; /* The priority queue */ ReqDeque normal; /* The 'normal' queue */ enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */ public: QueryQueue() : which(NON) { } void push(const SQLrequest &q) { if(q.pri) priority.push_back(q); else normal.push_back(q); } void pop() { if((which == PRI) && priority.size()) { priority.pop_front(); } else if((which == NOR) && normal.size()) { normal.pop_front(); } /* Reset this */ which = NON; /* Silently do nothing if there was no element to pop() */ } SQLrequest& front() { switch(which) { case PRI: return priority.front(); case NOR: return normal.front(); default: if(priority.size()) { which = PRI; return priority.front(); } if(normal.size()) { which = NOR; return normal.front(); } /* This will probably result in a segfault, * but the caller should have checked totalsize() * first so..meh - moron :p */ return priority.front(); } } std::pair size() { return std::make_pair(priority.size(), normal.size()); } int totalsize() { return priority.size() + normal.size(); } void PurgeModule(Module* mod) { DoPurgeModule(mod, priority); DoPurgeModule(mod, normal); } private: void DoPurgeModule(Module* mod, ReqDeque& q) { for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++) { if(iter->GetSource() == mod) { if(iter->id == front().id) { /* It's the currently active query.. :x */ iter->SetSource(NULL); } else { /* It hasn't been executed yet..just remove it */ iter = q.erase(iter); } } } } }; #endif \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#ifndef INSPIRCD_SQLAPI_2 +#define INSPIRCD_SQLAPI_2 + +#include +#include +#include +#include "modules.h" + +/** SQLreq define. + * This is the voodoo magic which lets us pass multiple + * parameters to the SQLrequest constructor... voodoo... + */ +#define SQLreq(a, b, c, d, e...) SQLrequest(a, b, c, (SQLquery(d), ##e)) + +/** Identifiers used to identify Request types + */ +#define SQLREQID "SQLv2 Request" +#define SQLRESID "SQLv2 Result" +#define SQLSUCCESS "You shouldn't be reading this (success)" + +/** Defines the error types which SQLerror may be set to + */ +enum SQLerrorNum { NO_ERROR, BAD_DBID, BAD_CONN, QSEND_FAIL, QREPLY_FAIL }; + +/** A list of format parameters for an SQLquery object. + */ +typedef std::deque ParamL; + +/** The base class of SQL exceptions + */ +class SQLexception : public ModuleException +{ + public: + SQLexception(const std::string &reason) : ModuleException(reason) + { + } + + SQLexception() : ModuleException("SQLv2: Undefined exception") + { + } +}; + +/** An exception thrown when a bad column or row name or id is requested + */ +class SQLbadColName : public SQLexception +{ +public: + SQLbadColName() : SQLexception("SQLv2: Bad column name") + { + } +}; + +/** SQLerror holds the error state of any SQLrequest or SQLresult. + * The error string varies from database software to database software + * and should be used to display informational error messages to users. + */ +class SQLerror : public classbase +{ + /** The error id + */ + SQLerrorNum id; + /** The error string + */ + std::string str; +public: + /** Initialize an SQLerror + * @param i The error ID to set + * @param s The (optional) error string to set + */ + SQLerror(SQLerrorNum i = NO_ERROR, const std::string &s = "") + : id(i), str(s) + { + } + + /** Return the ID of the error + */ + SQLerrorNum Id() + { + return id; + } + + /** Set the ID of an error + * @param i The new error ID to set + * @return the ID which was set + */ + SQLerrorNum Id(SQLerrorNum i) + { + id = i; + return id; + } + + /** Set the error string for an error + * @param s The new error string to set + */ + void Str(const std::string &s) + { + str = s; + } + + /** Return the error string for an error + */ + const char* Str() + { + if(str.length()) + return str.c_str(); + + switch(id) + { + case NO_ERROR: + return "No error"; + case BAD_DBID: + return "Invalid database ID"; + case BAD_CONN: + return "Invalid connection"; + case QSEND_FAIL: + return "Sending query failed"; + case QREPLY_FAIL: + return "Getting query result failed"; + default: + return "Unknown error"; + } + } +}; + +/** SQLquery provides a way to represent a query string, and its parameters in a type-safe way. + * C++ has no native type-safe way of having a variable number of arguments to a function, + * the workaround for this isn't easy to describe simply, but in a nutshell what's really + * happening when - from the above example - you do this: + * + * SQLrequest foo = SQLreq(this, target, "databaseid", "SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?", "Hello", "42"); + * + * what's actually happening is functionally this: + * + * SQLrequest foo = SQLreq(this, target, "databaseid", query("SELECT (foo, bar) FROM rawr WHERE foo = '?' AND bar = ?").addparam("Hello").addparam("42")); + * + * with 'query()' returning a reference to an object with a 'addparam()' member function which + * in turn returns a reference to that object. There are actually four ways you can create a + * SQLrequest..all have their disadvantages and advantages. In the real implementations the + * 'query()' function is replaced by the constructor of another class 'SQLquery' which holds + * the query string and a ParamL (std::deque) of query parameters. + * This is essentially the same as the above example except 'addparam()' is replaced by operator,(). The full syntax for this method is: + * + * SQLrequest foo = SQLrequest(this, target, "databaseid", (SQLquery("SELECT.. ?"), parameter, parameter)); + */ +class SQLquery : public classbase +{ +public: + /** The query 'format string' + */ + std::string q; + /** The query parameter list + * There should be one parameter for every ? character + * within the format string shown above. + */ + ParamL p; + + /** Initialize an SQLquery with a given format string only + */ + SQLquery(const std::string &query) + : q(query) + { + } + + /** Initialize an SQLquery with a format string and parameters. + * If you provide parameters, you must initialize the list yourself + * if you choose to do it via this method, using std::deque::push_back(). + */ + SQLquery(const std::string &query, const ParamL ¶ms) + : q(query), p(params) + { + } + + /** An overloaded operator for pushing parameters onto the parameter list + */ + template SQLquery& operator,(const T &foo) + { + p.push_back(ConvToStr(foo)); + return *this; + } + + /** An overloaded operator for pushing parameters onto the parameter list. + * This has higher precedence than 'operator,' and can save on parenthesis. + */ + template SQLquery& operator%(const T &foo) + { + p.push_back(ConvToStr(foo)); + return *this; + } +}; + +/** SQLrequest is sent to the SQL API to command it to run a query and return the result. + * You must instantiate this object with a valid SQLquery object and its parameters, then + * send it using its Send() method to the module providing the 'SQL' feature. To find this + * module, use Server::FindFeature(). + */ +class SQLrequest : public Request +{ +public: + /** The fully parsed and expanded query string + * This is initialized from the SQLquery parameter given in the constructor. + */ + SQLquery query; + /** The database ID to apply the request to + */ + std::string dbid; + /** True if this is a priority query. + * Priority queries may 'queue jump' in the request queue. + */ + bool pri; + /** The query ID, assigned by the SQL api. + * After your request is processed, this will + * be initialized for you by the API to a valid request ID, + * except in the case of an error. + */ + unsigned long id; + /** If an error occured, error.id will be any other value than NO_ERROR. + */ + SQLerror error; + + /** Initialize an SQLrequest. + * For example: + * + * SQLrequest req = SQLreq(MyMod, SQLModule, dbid, "INSERT INTO ircd_log_actors VALUES('','?')", nick); + * + * @param s A pointer to the sending module, where the result should be routed + * @param d A pointer to the receiving module, identified as implementing the 'SQL' feature + * @param databaseid The database ID to perform the query on. This must match a valid + * database ID from the configuration of the SQL module. + * @param q A properly initialized SQLquery object. + */ + SQLrequest(Module* s, Module* d, const std::string &databaseid, const SQLquery &q) + : Request(s, d, SQLREQID), query(q), dbid(databaseid), pri(false), id(0) + { + } + + /** Set the priority of a request. + */ + void Priority(bool p = true) + { + pri = p; + } + + /** Set the source of a request. You should not need to use this method. + */ + void SetSource(Module* mod) + { + source = mod; + } +}; + +/** + * This class contains a field's data plus a way to determine if the field + * is NULL or not without having to mess around with NULL pointers. + */ +class SQLfield +{ +public: + /** + * The data itself + */ + std::string d; + + /** + * If the field was null + */ + bool null; + + /** Initialize an SQLfield + */ + SQLfield(const std::string &data = "", bool n = false) + : d(data), null(n) + { + + } +}; + +/** A list of items which make up a row of a result or table (tuple) + * This does not include field names. + */ +typedef std::vector SQLfieldList; +/** A list of items which make up a row of a result or table (tuple) + * This also includes the field names. + */ +typedef std::map SQLfieldMap; + +/** SQLresult is a reply to a previous query. + * If you send a query to the SQL api, the response will arrive at your + * OnRequest method of your module at some later time, depending on the + * congestion of the SQL server and complexity of the query. The ID of + * this result will match the ID assigned to your original request. + * SQLresult contains its own internal cursor (row counter) which is + * incremented with each method call which retrieves a single row. + */ +class SQLresult : public Request +{ +public: + /** The original query string passed initially to the SQL API + */ + std::string query; + /** The database ID the query was executed on + */ + std::string dbid; + /** + * The error (if any) which occured. + * If an error occured the value of error.id will be any + * other value than NO_ERROR. + */ + SQLerror error; + /** + * This will match query ID you were given when sending + * the request at an earlier time. + */ + unsigned long id; + + /** Used by the SQL API to instantiate an SQLrequest + */ + SQLresult(Module* s, Module* d, unsigned long i) + : Request(s, d, SQLRESID), id(i) + { + } + + /** + * 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, and SQLresult::Cols() + * will contain 0. In this case you SHOULD NEVER + * access any of the result set rows, as there arent any! + * @returns Number of rows in the result set. + */ + virtual int Rows() = 0; + + /** + * Return the number of columns in the result. + * If you performed an UPDATE or INSERT which + * does not return a dataset, this value will + * be 0. + * @returns Number of columns in the result set. + */ + virtual int Cols() = 0; + + /** + * Get a string name of the column by an index number + * @param column The id number of a column + * @returns The column name associated with the given ID + */ + virtual std::string ColName(int column) = 0; + + /** + * Get an index number for a column from a string name. + * An exception of type SQLbadColName will be thrown if + * the name given is invalid. + * @param column The column name to get the ID of + * @returns The ID number of the column provided + */ + virtual int ColNum(const std::string &column) = 0; + + /** + * Get a string value in a given row and column + * This does not effect the internal cursor. + * @returns The value stored at [row,column] in the table + */ + virtual SQLfield GetValue(int row, int column) = 0; + + /** + * Return a list of values in a row, this should + * increment an internal counter so you can repeatedly + * call it until it returns an empty vector. + * This returns a reference to an internal object, + * the same object is used for all calls to this function + * and therefore the return value is only valid until + * you call this function again. It is also invalid if + * the SQLresult object is destroyed. + * The internal cursor (row counter) is incremented by one. + * @returns A reference to the current row's SQLfieldList + */ + virtual SQLfieldList& GetRow() = 0; + + /** + * As above, but return a map indexed by key name. + * The internal cursor (row counter) is incremented by one. + * @returns A reference to the current row's SQLfieldMap + */ + virtual SQLfieldMap& GetRowMap() = 0; + + /** + * Like GetRow(), but returns a pointer to a dynamically + * allocated object which must be explicitly freed. For + * portability reasons this must be freed with SQLresult::Free() + * The internal cursor (row counter) is incremented by one. + * @returns A newly-allocated SQLfieldList + */ + virtual SQLfieldList* GetRowPtr() = 0; + + /** + * As above, but return a map indexed by key name + * The internal cursor (row counter) is incremented by one. + * @returns A newly-allocated SQLfieldMap + */ + virtual SQLfieldMap* GetRowMapPtr() = 0; + + /** + * Overloaded function for freeing the lists and maps + * returned by GetRowPtr or GetRowMapPtr. + * @param fm The SQLfieldMap to free + */ + virtual void Free(SQLfieldMap* fm) = 0; + + /** + * Overloaded function for freeing the lists and maps + * returned by GetRowPtr or GetRowMapPtr. + * @param fl The SQLfieldList to free + */ + virtual void Free(SQLfieldList* fl) = 0; +}; + + +/** SQLHost represents a config line and is useful + * for storing in a map and iterating on rehash to see which + * tags was added/removed/unchanged. + */ +class SQLhost +{ + public: + std::string id; /* Database handle id */ + std::string host; /* Database server hostname */ + std::string ip; /* resolved IP, needed for at least pgsql.so */ + unsigned int port; /* Database server port */ + std::string name; /* Database name */ + std::string user; /* Database username */ + std::string pass; /* Database password */ + bool ssl; /* If we should require SSL */ + + SQLhost() + { + } + + SQLhost(const std::string& i, const std::string& h, unsigned int p, const std::string& n, const std::string& u, const std::string& pa, bool s) + : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s) + { + } + + /** Overload this to return a correct Data source Name (DSN) for + * the current SQL module. + */ + std::string GetDSN(); +}; + +/** Overload operator== for two SQLhost objects for easy comparison. + */ +bool operator== (const SQLhost& l, const SQLhost& r) +{ + return (l.id == r.id && l.host == r.host && l.port == r.port && l.name == r.name && l.user == l.user && l.pass == r.pass && l.ssl == r.ssl); +} + + +/** QueryQueue, a queue of queries waiting to be executed. + * This maintains two queues internally, one for 'priority' + * queries and one for less important ones. Each queue has + * new queries appended to it and ones to execute are popped + * off the front. This keeps them flowing round nicely and no + * query should ever get 'stuck' for too long. If there are + * queries in the priority queue they will be executed first, + * 'unimportant' queries will only be executed when the + * priority queue is empty. + * + * We store lists of SQLrequest's here, by value as we want to avoid storing + * any data allocated inside the client module (in case that module is unloaded + * while the query is in progress). + * + * Because we want to work on the current SQLrequest in-situ, we need a way + * of accessing the request we are currently processing, QueryQueue::front(), + * but that call needs to always return the same request until that request + * is removed from the queue, this is what the 'which' variable is. New queries are + * always added to the back of one of the two queues, but if when front() + * is first called then the priority queue is empty then front() will return + * a query from the normal queue, but if a query is then added to the priority + * queue then front() must continue to return the front of the *normal* queue + * until pop() is called. + */ + +class QueryQueue : public classbase +{ +private: + typedef std::deque ReqDeque; + + ReqDeque priority; /* The priority queue */ + ReqDeque normal; /* The 'normal' queue */ + enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */ + +public: + QueryQueue() + : which(NON) + { + } + + void push(const SQLrequest &q) + { + if(q.pri) + priority.push_back(q); + else + normal.push_back(q); + } + + void pop() + { + if((which == PRI) && priority.size()) + { + priority.pop_front(); + } + else if((which == NOR) && normal.size()) + { + normal.pop_front(); + } + + /* Reset this */ + which = NON; + + /* Silently do nothing if there was no element to pop() */ + } + + SQLrequest& front() + { + switch(which) + { + case PRI: + return priority.front(); + case NOR: + return normal.front(); + default: + if(priority.size()) + { + which = PRI; + return priority.front(); + } + + if(normal.size()) + { + which = NOR; + return normal.front(); + } + + /* This will probably result in a segfault, + * but the caller should have checked totalsize() + * first so..meh - moron :p + */ + + return priority.front(); + } + } + + std::pair size() + { + return std::make_pair(priority.size(), normal.size()); + } + + int totalsize() + { + return priority.size() + normal.size(); + } + + void PurgeModule(Module* mod) + { + DoPurgeModule(mod, priority); + DoPurgeModule(mod, normal); + } + +private: + void DoPurgeModule(Module* mod, ReqDeque& q) + { + for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++) + { + if(iter->GetSource() == mod) + { + if(iter->id == front().id) + { + /* It's the currently active query.. :x */ + iter->SetSource(NULL); + } + else + { + /* It hasn't been executed yet..just remove it */ + iter = q.erase(iter); + } + } + } + } +}; + + +#endif diff --git a/src/modules/extra/m_ssl_gnutls.cpp b/src/modules/extra/m_ssl_gnutls.cpp index 037d2cf72..fd8b12d32 100644 --- a/src/modules/extra/m_ssl_gnutls.cpp +++ b/src/modules/extra/m_ssl_gnutls.cpp @@ -1 +1,843 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #include "inspircd_config.h" #include "configreader.h" #include "users.h" #include "channels.h" #include "modules.h" #include "socket.h" #include "hashcomp.h" #include "transport.h" #ifdef WINDOWS #pragma comment(lib, "libgnutls-13.lib") #undef MAX_DESCRIPTORS #define MAX_DESCRIPTORS 10000 #endif /* $ModDesc: Provides SSL support for clients */ /* $CompileFlags: exec("libgnutls-config --cflags") */ /* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */ /* $ModDep: transport.h */ enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED }; bool isin(int port, const std::vector &portlist) { for(unsigned int i = 0; i < portlist.size(); i++) if(portlist[i] == port) return true; return false; } /** Represents an SSL user's extra data */ class issl_session : public classbase { public: gnutls_session_t sess; issl_status status; std::string outbuf; int inbufoffset; char* inbuf; int fd; }; class ModuleSSLGnuTLS : public Module { ConfigReader* Conf; char* dummy; std::vector listenports; int inbufsize; issl_session sessions[MAX_DESCRIPTORS]; gnutls_certificate_credentials x509_cred; gnutls_dh_params dh_params; std::string keyfile; std::string certfile; std::string cafile; std::string crlfile; std::string sslports; int dh_bits; int clientactive; public: ModuleSSLGnuTLS(InspIRCd* Me) : Module(Me) { ServerInstance->PublishInterface("InspSocketHook", this); // Not rehashable...because I cba to reduce all the sizes of existing buffers. inbufsize = ServerInstance->Config->NetBufferSize; gnutls_global_init(); // This must be called once in the program if(gnutls_certificate_allocate_credentials(&x509_cred) != 0) ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials"); // Guessing return meaning if(gnutls_dh_params_init(&dh_params) < 0) ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters"); // Needs the flag as it ignores a plain /rehash OnRehash(NULL,"ssl"); // Void return, guess we assume success gnutls_certificate_set_dh_params(x509_cred, dh_params); } virtual void OnRehash(userrec* user, const std::string ¶m) { if(param != "ssl") return; Conf = new ConfigReader(ServerInstance); for(unsigned int i = 0; i < listenports.size(); i++) { ServerInstance->Config->DelIOHook(listenports[i]); } listenports.clear(); clientactive = 0; sslports.clear(); for(int i = 0; i < Conf->Enumerate("bind"); i++) { // For each tag std::string x = Conf->ReadValue("bind", "type", i); if(((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls")) { // Get the port we're meant to be listening on with SSL std::string port = Conf->ReadValue("bind", "port", i); irc::portparser portrange(port, false); long portno = -1; while ((portno = portrange.GetToken())) { clientactive++; try { if (ServerInstance->Config->AddIOHook(portno, this)) { listenports.push_back(portno); for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++) if (ServerInstance->Config->ports[i]->GetPort() == portno) ServerInstance->Config->ports[i]->SetDescription("ssl"); ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno); sslports.append("*:").append(ConvToStr(portno)).append(";"); } else { ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno); } } catch (ModuleException &e) { ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason()); } } } } std::string confdir(ServerInstance->ConfigFileName); // +1 so we the path ends with a / confdir = confdir.substr(0, confdir.find_last_of('/') + 1); cafile = Conf->ReadValue("gnutls", "cafile", 0); crlfile = Conf->ReadValue("gnutls", "crlfile", 0); certfile = Conf->ReadValue("gnutls", "certfile", 0); keyfile = Conf->ReadValue("gnutls", "keyfile", 0); dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false); // Set all the default values needed. if (cafile.empty()) cafile = "ca.pem"; if (crlfile.empty()) crlfile = "crl.pem"; if (certfile.empty()) certfile = "cert.pem"; if (keyfile.empty()) keyfile = "key.pem"; if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096)) dh_bits = 1024; // Prepend relative paths with the path to the config directory. if(cafile[0] != '/') cafile = confdir + cafile; if(crlfile[0] != '/') crlfile = confdir + crlfile; if(certfile[0] != '/') certfile = confdir + certfile; if(keyfile[0] != '/') keyfile = confdir + keyfile; int ret; if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) ServerInstance->Log(DEFAULT, "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->Log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret)); if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) { // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException throw ModuleException("Unable to load GnuTLS server certificate: " + std::string(gnutls_strerror(ret))); } // This may be on a large (once a day or week) timer eventually. GenerateDHParams(); DELETE(Conf); } void GenerateDHParams() { // 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. int ret; if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0) ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret)); } virtual ~ModuleSSLGnuTLS() { gnutls_dh_params_deinit(dh_params); gnutls_certificate_free_credentials(x509_cred); gnutls_global_deinit(); } virtual void OnCleanup(int target_type, void* item) { if(target_type == TYPE_USER) { userrec* user = (userrec*)item; if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports)) { // 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->GlobalCulls.AddItem(user, "SSL module unloading"); } if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports)) { ssl_cert* tofree; user->GetExt("ssl_cert", tofree); delete tofree; user->Shrink("ssl_cert"); } } } virtual void OnUnloadModule(Module* mod, const std::string &name) { if(mod == this) { for(unsigned int i = 0; i < listenports.size(); i++) { ServerInstance->Config->DelIOHook(listenports[i]); for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++) if (ServerInstance->Config->ports[j]->GetPort() == listenports[i]) ServerInstance->Config->ports[j]->SetDescription("plaintext"); } } } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } void Implements(char* List) { List[I_On005Numeric] = List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1; List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1; } virtual void On005Numeric(std::string &output) { output.append(" SSL=" + sslports); } virtual char* OnRequest(Request* request) { ISHRequest* ISR = (ISHRequest*)request; if (strcmp("IS_NAME", request->GetId()) == 0) { return "gnutls"; } else if (strcmp("IS_HOOK", request->GetId()) == 0) { char* ret = "OK"; try { ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } catch (ModuleException &e) { return NULL; } return ret; } else if (strcmp("IS_UNHOOK", request->GetId()) == 0) { return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } else if (strcmp("IS_HSDONE", request->GetId()) == 0) { if (ISR->Sock->GetFd() < 0) return (char*)"OK"; issl_session* session = &sessions[ISR->Sock->GetFd()]; return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : (char*)"OK"; } else if (strcmp("IS_ATTACH", request->GetId()) == 0) { if (ISR->Sock->GetFd() > -1) { issl_session* session = &sessions[ISR->Sock->GetFd()]; if (session->sess) { if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock)) { VerifyCertificate(session, (InspSocket*)ISR->Sock); return "OK"; } } } } return NULL; } virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) { issl_session* session = &sessions[fd]; session->fd = fd; session->inbuf = new char[inbufsize]; session->inbufoffset = 0; gnutls_init(&session->sess, GNUTLS_SERVER); gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate. gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred); gnutls_dh_set_prime_bits(session->sess, dh_bits); /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes * This needs testing, but it's easy enough to rollback if need be * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket. * * With testing this seems to...not work :/ */ gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any. Handshake(session); } virtual void OnRawSocketConnect(int fd) { issl_session* session = &sessions[fd]; session->fd = fd; session->inbuf = new char[inbufsize]; session->inbufoffset = 0; gnutls_init(&session->sess, GNUTLS_CLIENT); gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate. gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred); gnutls_dh_set_prime_bits(session->sess, dh_bits); gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. Handshake(session); } virtual void OnRawSocketClose(int fd) { CloseSession(&sessions[fd]); EventHandler* user = ServerInstance->SE->GetRef(fd); if ((user) && (user->GetExt("ssl_cert", dummy))) { ssl_cert* tofree; user->GetExt("ssl_cert", tofree); delete tofree; user->Shrink("ssl_cert"); } } virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { issl_session* session = &sessions[fd]; if (!session->sess) { readresult = 0; CloseSession(session); return 1; } if (session->status == ISSL_HANDSHAKING_READ) { // The handshake isn't finished, try to finish it. if(!Handshake(session)) { // Couldn't resume handshake. return -1; } } else if (session->status == ISSL_HANDSHAKING_WRITE) { errno = EAGAIN; return -1; } // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN. if (session->status == ISSL_HANDSHAKEN) { // Is this right? Not sure if the unencrypted data is garaunteed to be the same length. // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet. int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset); if (ret == 0) { // Client closed connection. readresult = 0; CloseSession(session); return 1; } else if (ret < 0) { if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { errno = EAGAIN; return -1; } else { readresult = 0; CloseSession(session); } } else { // Read successfully 'ret' bytes into inbuf + inbufoffset // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf' // 'buffer' is 'count' long unsigned int length = ret + session->inbufoffset; if(count <= length) { memcpy(buffer, session->inbuf, count); // Move the stuff left in inbuf to the beginning of it memcpy(session->inbuf, session->inbuf + count, (length - count)); // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp. session->inbufoffset = length - count; // Insp uses readresult as the count of how much data there is in buffer, so: readresult = count; } else { // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing. memcpy(buffer, session->inbuf, length); // Zero the offset, as there's nothing there.. session->inbufoffset = 0; // As above readresult = length; } } } else if(session->status == ISSL_CLOSING) readresult = 0; return 1; } virtual int OnRawSocketWrite(int fd, const char* buffer, int count) { if (!count) return 0; issl_session* session = &sessions[fd]; const char* sendbuffer = buffer; if (!session->sess) { ServerInstance->Log(DEBUG,"No session"); CloseSession(session); return 1; } session->outbuf.append(sendbuffer, count); sendbuffer = session->outbuf.c_str(); count = session->outbuf.size(); if (session->status == ISSL_HANDSHAKING_WRITE) { // The handshake isn't finished, try to finish it. ServerInstance->Log(DEBUG,"Finishing handshake"); Handshake(session); errno = EAGAIN; return -1; } int ret = 0; if (session->status == ISSL_HANDSHAKEN) { ServerInstance->Log(DEBUG,"Send record"); ret = gnutls_record_send(session->sess, sendbuffer, count); ServerInstance->Log(DEBUG,"Return: %d", ret); if (ret == 0) { CloseSession(session); } else if (ret < 0) { if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) { ServerInstance->Log(DEBUG,"Not egain or interrupt, close session"); CloseSession(session); } else { ServerInstance->Log(DEBUG,"Again please"); errno = EAGAIN; return -1; } } else { ServerInstance->Log(DEBUG,"Trim buffer"); session->outbuf = session->outbuf.substr(ret); } } /* Who's smart idea was it to return 1 when we havent written anything? * This fucks the buffer up in InspSocket :p */ return ret < 1 ? 0 : ret; } // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection virtual void OnWhois(userrec* source, userrec* dest) { if (!clientactive) return; // Bugfix, only send this numeric for *our* SSL users if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports))) { ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick); } } virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) { // check if the linking module wants to know about OUR metadata if(extname == "ssl") { // check if this user has an swhois field to send if(user->GetExt(extname, dummy)) { // call this function in the linking module, let it format the data how it // sees fit, and send it on its way. We dont need or want to know how. proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON"); } } } virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) { // check if its our metadata key, and its associated with a user if ((target_type == TYPE_USER) && (extname == "ssl")) { userrec* dest = (userrec*)target; // if they dont already have an ssl flag, accept the remote server's if (!dest->GetExt(extname, dummy)) { dest->Extend(extname, "ON"); } } } bool Handshake(issl_session* session) { int ret = gnutls_handshake(session->sess); if (ret < 0) { if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { // Handshake needs resuming later, read() or write() would have blocked. if(gnutls_record_get_direction(session->sess) == 0) { // gnutls_handshake() wants to read() again. session->status = ISSL_HANDSHAKING_READ; } else { // gnutls_handshake() wants to write() again. session->status = ISSL_HANDSHAKING_WRITE; MakePollWrite(session); } } else { // Handshake failed. CloseSession(session); session->status = ISSL_CLOSING; } return false; } else { // Handshake complete. // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater. userrec* extendme = ServerInstance->FindDescriptor(session->fd); if (extendme) { if (!extendme->GetExt("ssl", dummy)) extendme->Extend("ssl", "ON"); } // Change the seesion state session->status = ISSL_HANDSHAKEN; // Finish writing, if any left MakePollWrite(session); return true; } } virtual void OnPostConnect(userrec* user) { // This occurs AFTER OnUserConnect so we can be sure the // protocol module has propogated the NICK message. if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user))) { // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW. std::deque* metadata = new std::deque; metadata->push_back(user->nick); metadata->push_back("ssl"); // The metadata id metadata->push_back("ON"); // The value to send Event* event = new Event((char*)metadata,(Module*)this,"send_metadata"); event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up. DELETE(event); DELETE(metadata); VerifyCertificate(&sessions[user->GetFd()],user); if (sessions[user->GetFd()].sess) { std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess)); cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-"); cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess))); user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, cipher.c_str()); } } } void MakePollWrite(issl_session* session) { OnRawSocketWrite(session->fd, NULL, 0); } void CloseSession(issl_session* session) { if(session->sess) { gnutls_bye(session->sess, GNUTLS_SHUT_WR); gnutls_deinit(session->sess); } if(session->inbuf) { delete[] session->inbuf; } session->outbuf.clear(); session->inbuf = NULL; session->sess = NULL; session->status = ISSL_NONE; } void VerifyCertificate(issl_session* session, Extensible* user) { if (!session->sess || !user) return; unsigned int status; 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]; size_t digest_size = sizeof(digest); size_t name_size = sizeof(name); ssl_cert* certinfo = new ssl_cert; user->Extend("ssl_cert",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); if (ret < 0) { certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret)))); return; } if (status & GNUTLS_CERT_INVALID) { certinfo->data.insert(std::make_pair("invalid",ConvToStr(1))); } else { certinfo->data.insert(std::make_pair("invalid",ConvToStr(0))); } if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) { certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1))); } else { certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0))); } if (status & GNUTLS_CERT_REVOKED) { certinfo->data.insert(std::make_pair("revoked",ConvToStr(1))); } else { certinfo->data.insert(std::make_pair("revoked",ConvToStr(0))); } if (status & GNUTLS_CERT_SIGNER_NOT_CA) { certinfo->data.insert(std::make_pair("trusted",ConvToStr(0))); } else { certinfo->data.insert(std::make_pair("trusted",ConvToStr(1))); } /* 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) { certinfo->data.insert(std::make_pair("error","No X509 keys sent")); return; } ret = gnutls_x509_crt_init(&cert); if (ret < 0) { certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); return; } cert_list_size = 0; cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size); if (cert_list == NULL) { certinfo->data.insert(std::make_pair("error","No certificate was found")); return; } /* This is not a real world example, since we only check the first * certificate in the given chain. */ ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER); if (ret < 0) { certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); return; } gnutls_x509_crt_get_dn(cert, name, &name_size); certinfo->data.insert(std::make_pair("dn",name)); gnutls_x509_crt_get_issuer_dn(cert, name, &name_size); certinfo->data.insert(std::make_pair("issuer",name)); if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0) { certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); } else { certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size))); } /* Beware here we do not check for errors. */ if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0))) { certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate")); } gnutls_x509_crt_deinit(cert); return; } }; MODULE_INIT(ModuleSSLGnuTLS); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" + +#include +#include + +#include "inspircd_config.h" +#include "configreader.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "socket.h" +#include "hashcomp.h" +#include "transport.h" + +#ifdef WINDOWS +#pragma comment(lib, "libgnutls-13.lib") +#undef MAX_DESCRIPTORS +#define MAX_DESCRIPTORS 10000 +#endif + +/* $ModDesc: Provides SSL support for clients */ +/* $CompileFlags: exec("libgnutls-config --cflags") */ +/* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */ +/* $ModDep: transport.h */ + + +enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED }; + +bool isin(int port, const std::vector &portlist) +{ + for(unsigned int i = 0; i < portlist.size(); i++) + if(portlist[i] == port) + return true; + + return false; +} + +/** Represents an SSL user's extra data + */ +class issl_session : public classbase +{ +public: + gnutls_session_t sess; + issl_status status; + std::string outbuf; + int inbufoffset; + char* inbuf; + int fd; +}; + +class ModuleSSLGnuTLS : public Module +{ + + ConfigReader* Conf; + + char* dummy; + + std::vector listenports; + + int inbufsize; + issl_session sessions[MAX_DESCRIPTORS]; + + gnutls_certificate_credentials x509_cred; + gnutls_dh_params dh_params; + + std::string keyfile; + std::string certfile; + std::string cafile; + std::string crlfile; + std::string sslports; + int dh_bits; + + int clientactive; + + public: + + ModuleSSLGnuTLS(InspIRCd* Me) + : Module(Me) + { + ServerInstance->PublishInterface("InspSocketHook", this); + + // Not rehashable...because I cba to reduce all the sizes of existing buffers. + inbufsize = ServerInstance->Config->NetBufferSize; + + gnutls_global_init(); // This must be called once in the program + + if(gnutls_certificate_allocate_credentials(&x509_cred) != 0) + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials"); + + // Guessing return meaning + if(gnutls_dh_params_init(&dh_params) < 0) + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters"); + + // Needs the flag as it ignores a plain /rehash + OnRehash(NULL,"ssl"); + + // Void return, guess we assume success + gnutls_certificate_set_dh_params(x509_cred, dh_params); + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + if(param != "ssl") + return; + + Conf = new ConfigReader(ServerInstance); + + for(unsigned int i = 0; i < listenports.size(); i++) + { + ServerInstance->Config->DelIOHook(listenports[i]); + } + + listenports.clear(); + clientactive = 0; + sslports.clear(); + + for(int i = 0; i < Conf->Enumerate("bind"); i++) + { + // For each tag + std::string x = Conf->ReadValue("bind", "type", i); + if(((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls")) + { + // Get the port we're meant to be listening on with SSL + std::string port = Conf->ReadValue("bind", "port", i); + irc::portparser portrange(port, false); + long portno = -1; + while ((portno = portrange.GetToken())) + { + clientactive++; + try + { + if (ServerInstance->Config->AddIOHook(portno, this)) + { + listenports.push_back(portno); + for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++) + if (ServerInstance->Config->ports[i]->GetPort() == portno) + ServerInstance->Config->ports[i]->SetDescription("ssl"); + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno); + sslports.append("*:").append(ConvToStr(portno)).append(";"); + } + else + { + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno); + } + } + catch (ModuleException &e) + { + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason()); + } + } + } + } + + std::string confdir(ServerInstance->ConfigFileName); + // +1 so we the path ends with a / + confdir = confdir.substr(0, confdir.find_last_of('/') + 1); + + cafile = Conf->ReadValue("gnutls", "cafile", 0); + crlfile = Conf->ReadValue("gnutls", "crlfile", 0); + certfile = Conf->ReadValue("gnutls", "certfile", 0); + keyfile = Conf->ReadValue("gnutls", "keyfile", 0); + dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false); + + // Set all the default values needed. + if (cafile.empty()) + cafile = "ca.pem"; + + if (crlfile.empty()) + crlfile = "crl.pem"; + + if (certfile.empty()) + certfile = "cert.pem"; + + if (keyfile.empty()) + keyfile = "key.pem"; + + if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096)) + dh_bits = 1024; + + // Prepend relative paths with the path to the config directory. + if(cafile[0] != '/') + cafile = confdir + cafile; + + if(crlfile[0] != '/') + crlfile = confdir + crlfile; + + if(certfile[0] != '/') + certfile = confdir + certfile; + + if(keyfile[0] != '/') + keyfile = confdir + keyfile; + + int ret; + + if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) + ServerInstance->Log(DEFAULT, "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->Log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret)); + + if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0) + { + // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException + throw ModuleException("Unable to load GnuTLS server certificate: " + std::string(gnutls_strerror(ret))); + } + + // This may be on a large (once a day or week) timer eventually. + GenerateDHParams(); + + DELETE(Conf); + } + + void GenerateDHParams() + { + // 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. + + int ret; + + if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0) + ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret)); + } + + virtual ~ModuleSSLGnuTLS() + { + gnutls_dh_params_deinit(dh_params); + gnutls_certificate_free_credentials(x509_cred); + gnutls_global_deinit(); + } + + virtual void OnCleanup(int target_type, void* item) + { + if(target_type == TYPE_USER) + { + userrec* user = (userrec*)item; + + if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports)) + { + // 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->GlobalCulls.AddItem(user, "SSL module unloading"); + } + if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports)) + { + ssl_cert* tofree; + user->GetExt("ssl_cert", tofree); + delete tofree; + user->Shrink("ssl_cert"); + } + } + } + + virtual void OnUnloadModule(Module* mod, const std::string &name) + { + if(mod == this) + { + for(unsigned int i = 0; i < listenports.size(); i++) + { + ServerInstance->Config->DelIOHook(listenports[i]); + for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++) + if (ServerInstance->Config->ports[j]->GetPort() == listenports[i]) + ServerInstance->Config->ports[j]->SetDescription("plaintext"); + } + } + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + List[I_On005Numeric] = List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1; + List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1; + } + + virtual void On005Numeric(std::string &output) + { + output.append(" SSL=" + sslports); + } + + virtual char* OnRequest(Request* request) + { + ISHRequest* ISR = (ISHRequest*)request; + if (strcmp("IS_NAME", request->GetId()) == 0) + { + return "gnutls"; + } + else if (strcmp("IS_HOOK", request->GetId()) == 0) + { + char* ret = "OK"; + try + { + ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + catch (ModuleException &e) + { + return NULL; + } + return ret; + } + else if (strcmp("IS_UNHOOK", request->GetId()) == 0) + { + return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + else if (strcmp("IS_HSDONE", request->GetId()) == 0) + { + if (ISR->Sock->GetFd() < 0) + return (char*)"OK"; + + issl_session* session = &sessions[ISR->Sock->GetFd()]; + return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : (char*)"OK"; + } + else if (strcmp("IS_ATTACH", request->GetId()) == 0) + { + if (ISR->Sock->GetFd() > -1) + { + issl_session* session = &sessions[ISR->Sock->GetFd()]; + if (session->sess) + { + if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock)) + { + VerifyCertificate(session, (InspSocket*)ISR->Sock); + return "OK"; + } + } + } + } + return NULL; + } + + + virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) + { + issl_session* session = &sessions[fd]; + + session->fd = fd; + session->inbuf = new char[inbufsize]; + session->inbufoffset = 0; + + gnutls_init(&session->sess, GNUTLS_SERVER); + + gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate. + gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred); + gnutls_dh_set_prime_bits(session->sess, dh_bits); + + /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes + * This needs testing, but it's easy enough to rollback if need be + * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. + * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket. + * + * With testing this seems to...not work :/ + */ + + gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. + + gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any. + + Handshake(session); + } + + virtual void OnRawSocketConnect(int fd) + { + issl_session* session = &sessions[fd]; + + session->fd = fd; + session->inbuf = new char[inbufsize]; + session->inbufoffset = 0; + + gnutls_init(&session->sess, GNUTLS_CLIENT); + + gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate. + gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred); + gnutls_dh_set_prime_bits(session->sess, dh_bits); + gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket. + + Handshake(session); + } + + virtual void OnRawSocketClose(int fd) + { + CloseSession(&sessions[fd]); + + EventHandler* user = ServerInstance->SE->GetRef(fd); + + if ((user) && (user->GetExt("ssl_cert", dummy))) + { + ssl_cert* tofree; + user->GetExt("ssl_cert", tofree); + delete tofree; + user->Shrink("ssl_cert"); + } + } + + virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) + { + issl_session* session = &sessions[fd]; + + if (!session->sess) + { + readresult = 0; + CloseSession(session); + return 1; + } + + if (session->status == ISSL_HANDSHAKING_READ) + { + // The handshake isn't finished, try to finish it. + + if(!Handshake(session)) + { + // Couldn't resume handshake. + return -1; + } + } + else if (session->status == ISSL_HANDSHAKING_WRITE) + { + errno = EAGAIN; + return -1; + } + + // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN. + + if (session->status == ISSL_HANDSHAKEN) + { + // Is this right? Not sure if the unencrypted data is garaunteed to be the same length. + // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet. + int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset); + + if (ret == 0) + { + // Client closed connection. + readresult = 0; + CloseSession(session); + return 1; + } + else if (ret < 0) + { + if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) + { + errno = EAGAIN; + return -1; + } + else + { + readresult = 0; + CloseSession(session); + } + } + else + { + // Read successfully 'ret' bytes into inbuf + inbufoffset + // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf' + // 'buffer' is 'count' long + + unsigned int length = ret + session->inbufoffset; + + if(count <= length) + { + memcpy(buffer, session->inbuf, count); + // Move the stuff left in inbuf to the beginning of it + memcpy(session->inbuf, session->inbuf + count, (length - count)); + // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp. + session->inbufoffset = length - count; + // Insp uses readresult as the count of how much data there is in buffer, so: + readresult = count; + } + else + { + // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing. + memcpy(buffer, session->inbuf, length); + // Zero the offset, as there's nothing there.. + session->inbufoffset = 0; + // As above + readresult = length; + } + } + } + else if(session->status == ISSL_CLOSING) + readresult = 0; + + return 1; + } + + virtual int OnRawSocketWrite(int fd, const char* buffer, int count) + { + if (!count) + return 0; + + issl_session* session = &sessions[fd]; + const char* sendbuffer = buffer; + + if (!session->sess) + { + ServerInstance->Log(DEBUG,"No session"); + CloseSession(session); + return 1; + } + + session->outbuf.append(sendbuffer, count); + sendbuffer = session->outbuf.c_str(); + count = session->outbuf.size(); + + if (session->status == ISSL_HANDSHAKING_WRITE) + { + // The handshake isn't finished, try to finish it. + ServerInstance->Log(DEBUG,"Finishing handshake"); + Handshake(session); + errno = EAGAIN; + return -1; + } + + int ret = 0; + + if (session->status == ISSL_HANDSHAKEN) + { + ServerInstance->Log(DEBUG,"Send record"); + ret = gnutls_record_send(session->sess, sendbuffer, count); + ServerInstance->Log(DEBUG,"Return: %d", ret); + + if (ret == 0) + { + CloseSession(session); + } + else if (ret < 0) + { + if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) + { + ServerInstance->Log(DEBUG,"Not egain or interrupt, close session"); + CloseSession(session); + } + else + { + ServerInstance->Log(DEBUG,"Again please"); + errno = EAGAIN; + return -1; + } + } + else + { + ServerInstance->Log(DEBUG,"Trim buffer"); + session->outbuf = session->outbuf.substr(ret); + } + } + + /* Who's smart idea was it to return 1 when we havent written anything? + * This fucks the buffer up in InspSocket :p + */ + return ret < 1 ? 0 : ret; + } + + // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection + virtual void OnWhois(userrec* source, userrec* dest) + { + if (!clientactive) + return; + + // Bugfix, only send this numeric for *our* SSL users + if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports))) + { + ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick); + } + } + + virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) + { + // check if the linking module wants to know about OUR metadata + if(extname == "ssl") + { + // check if this user has an swhois field to send + if(user->GetExt(extname, dummy)) + { + // call this function in the linking module, let it format the data how it + // sees fit, and send it on its way. We dont need or want to know how. + proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON"); + } + } + } + + virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) + { + // check if its our metadata key, and its associated with a user + if ((target_type == TYPE_USER) && (extname == "ssl")) + { + userrec* dest = (userrec*)target; + // if they dont already have an ssl flag, accept the remote server's + if (!dest->GetExt(extname, dummy)) + { + dest->Extend(extname, "ON"); + } + } + } + + bool Handshake(issl_session* session) + { + int ret = gnutls_handshake(session->sess); + + if (ret < 0) + { + if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) + { + // Handshake needs resuming later, read() or write() would have blocked. + + if(gnutls_record_get_direction(session->sess) == 0) + { + // gnutls_handshake() wants to read() again. + session->status = ISSL_HANDSHAKING_READ; + } + else + { + // gnutls_handshake() wants to write() again. + session->status = ISSL_HANDSHAKING_WRITE; + MakePollWrite(session); + } + } + else + { + // Handshake failed. + CloseSession(session); + session->status = ISSL_CLOSING; + } + + return false; + } + else + { + // Handshake complete. + // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater. + userrec* extendme = ServerInstance->FindDescriptor(session->fd); + if (extendme) + { + if (!extendme->GetExt("ssl", dummy)) + extendme->Extend("ssl", "ON"); + } + + // Change the seesion state + session->status = ISSL_HANDSHAKEN; + + // Finish writing, if any left + MakePollWrite(session); + + return true; + } + } + + virtual void OnPostConnect(userrec* user) + { + // This occurs AFTER OnUserConnect so we can be sure the + // protocol module has propogated the NICK message. + if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user))) + { + // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW. + std::deque* metadata = new std::deque; + metadata->push_back(user->nick); + metadata->push_back("ssl"); // The metadata id + metadata->push_back("ON"); // The value to send + Event* event = new Event((char*)metadata,(Module*)this,"send_metadata"); + event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up. + DELETE(event); + DELETE(metadata); + + VerifyCertificate(&sessions[user->GetFd()],user); + if (sessions[user->GetFd()].sess) + { + std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess)); + cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-"); + cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess))); + user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, cipher.c_str()); + } + } + } + + void MakePollWrite(issl_session* session) + { + OnRawSocketWrite(session->fd, NULL, 0); + } + + void CloseSession(issl_session* session) + { + if(session->sess) + { + gnutls_bye(session->sess, GNUTLS_SHUT_WR); + gnutls_deinit(session->sess); + } + + if(session->inbuf) + { + delete[] session->inbuf; + } + + session->outbuf.clear(); + session->inbuf = NULL; + session->sess = NULL; + session->status = ISSL_NONE; + } + + void VerifyCertificate(issl_session* session, Extensible* user) + { + if (!session->sess || !user) + return; + + unsigned int status; + 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]; + size_t digest_size = sizeof(digest); + size_t name_size = sizeof(name); + ssl_cert* certinfo = new ssl_cert; + + user->Extend("ssl_cert",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); + + if (ret < 0) + { + certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret)))); + return; + } + + if (status & GNUTLS_CERT_INVALID) + { + certinfo->data.insert(std::make_pair("invalid",ConvToStr(1))); + } + else + { + certinfo->data.insert(std::make_pair("invalid",ConvToStr(0))); + } + if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) + { + certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1))); + } + else + { + certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0))); + } + if (status & GNUTLS_CERT_REVOKED) + { + certinfo->data.insert(std::make_pair("revoked",ConvToStr(1))); + } + else + { + certinfo->data.insert(std::make_pair("revoked",ConvToStr(0))); + } + if (status & GNUTLS_CERT_SIGNER_NOT_CA) + { + certinfo->data.insert(std::make_pair("trusted",ConvToStr(0))); + } + else + { + certinfo->data.insert(std::make_pair("trusted",ConvToStr(1))); + } + + /* 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) + { + certinfo->data.insert(std::make_pair("error","No X509 keys sent")); + return; + } + + ret = gnutls_x509_crt_init(&cert); + if (ret < 0) + { + certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); + return; + } + + cert_list_size = 0; + cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size); + if (cert_list == NULL) + { + certinfo->data.insert(std::make_pair("error","No certificate was found")); + return; + } + + /* This is not a real world example, since we only check the first + * certificate in the given chain. + */ + + ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER); + if (ret < 0) + { + certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); + return; + } + + gnutls_x509_crt_get_dn(cert, name, &name_size); + + certinfo->data.insert(std::make_pair("dn",name)); + + gnutls_x509_crt_get_issuer_dn(cert, name, &name_size); + + certinfo->data.insert(std::make_pair("issuer",name)); + + if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0) + { + certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret))); + } + else + { + certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size))); + } + + /* Beware here we do not check for errors. + */ + if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0))) + { + certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate")); + } + + gnutls_x509_crt_deinit(cert); + + return; + } + +}; + +MODULE_INIT(ModuleSSLGnuTLS); + diff --git a/src/modules/extra/m_ssl_openssl.cpp b/src/modules/extra/m_ssl_openssl.cpp index 43dc43aea..ffd9d4032 100644 --- a/src/modules/extra/m_ssl_openssl.cpp +++ b/src/modules/extra/m_ssl_openssl.cpp @@ -1 +1,901 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #ifdef WINDOWS #include #endif #include "configreader.h" #include "users.h" #include "channels.h" #include "modules.h" #include "socket.h" #include "hashcomp.h" #include "transport.h" #ifdef WINDOWS #pragma comment(lib, "libeay32MTd") #pragma comment(lib, "ssleay32MTd") #undef MAX_DESCRIPTORS #define MAX_DESCRIPTORS 10000 #endif /* $ModDesc: Provides SSL support for clients */ /* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */ /* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */ /* $ModDep: transport.h */ enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN }; enum issl_io_status { ISSL_WRITE, ISSL_READ }; static bool SelfSigned = false; bool isin(int port, const std::vector &portlist) { for(unsigned int i = 0; i < portlist.size(); i++) if(portlist[i] == port) return true; return false; } char* get_error() { return ERR_error_string(ERR_get_error(), NULL); } static int error_callback(const char *str, size_t len, void *u); /** Represents an SSL user's extra data */ class issl_session : public classbase { public: SSL* sess; issl_status status; issl_io_status rstat; issl_io_status wstat; unsigned int inbufoffset; char* inbuf; // Buffer OpenSSL reads into. std::string outbuf; // Buffer for outgoing data that OpenSSL will not take. int fd; bool outbound; issl_session() { outbound = false; rstat = ISSL_READ; wstat = ISSL_WRITE; } }; 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); SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT); return 1; } class ModuleSSLOpenSSL : public Module { ConfigReader* Conf; std::vector listenports; int inbufsize; issl_session sessions[MAX_DESCRIPTORS]; SSL_CTX* ctx; SSL_CTX* clictx; char* dummy; char cipher[MAXBUF]; std::string keyfile; std::string certfile; std::string cafile; // std::string crlfile; std::string dhfile; std::string sslports; int clientactive; public: InspIRCd* PublicInstance; ModuleSSLOpenSSL(InspIRCd* Me) : Module(Me), PublicInstance(Me) { ServerInstance->PublishInterface("InspSocketHook", this); // Not rehashable...because I cba to reduce all the sizes of existing buffers. inbufsize = ServerInstance->Config->NetBufferSize; /* Global SSL library initialization*/ SSL_library_init(); SSL_load_error_strings(); /* Build our SSL contexts: * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK. */ ctx = SSL_CTX_new( SSLv23_server_method() ); clictx = SSL_CTX_new( SSLv23_client_method() ); 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); // Needs the flag as it ignores a plain /rehash OnRehash(NULL,"ssl"); } virtual void OnRehash(userrec* user, const std::string ¶m) { if (param != "ssl") return; Conf = new ConfigReader(ServerInstance); for (unsigned int i = 0; i < listenports.size(); i++) { ServerInstance->Config->DelIOHook(listenports[i]); } listenports.clear(); clientactive = 0; sslports.clear(); for (int i = 0; i < Conf->Enumerate("bind"); i++) { // For each tag std::string x = Conf->ReadValue("bind", "type", i); if (((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl")) { // Get the port we're meant to be listening on with SSL std::string port = Conf->ReadValue("bind", "port", i); irc::portparser portrange(port, false); long portno = -1; while ((portno = portrange.GetToken())) { clientactive++; try { if (ServerInstance->Config->AddIOHook(portno, this)) { listenports.push_back(portno); for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++) if (ServerInstance->Config->ports[i]->GetPort() == portno) ServerInstance->Config->ports[i]->SetDescription("ssl"); ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno); sslports.append("*:").append(ConvToStr(portno)).append(";"); } else { ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno); } } catch (ModuleException &e) { ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have another SSL or similar module loaded?", portno, e.GetReason()); } } } } if (!sslports.empty()) sslports.erase(sslports.end() - 1); std::string confdir(ServerInstance->ConfigFileName); // +1 so we the path ends with a / confdir = confdir.substr(0, confdir.find_last_of('/') + 1); cafile = Conf->ReadValue("openssl", "cafile", 0); certfile = Conf->ReadValue("openssl", "certfile", 0); keyfile = Conf->ReadValue("openssl", "keyfile", 0); dhfile = Conf->ReadValue("openssl", "dhfile", 0); // Set all the default values needed. if (cafile.empty()) cafile = "ca.pem"; if (certfile.empty()) certfile = "cert.pem"; if (keyfile.empty()) keyfile = "key.pem"; if (dhfile.empty()) dhfile = "dhparams.pem"; // Prepend relative paths with the path to the config directory. if (cafile[0] != '/') cafile = confdir + cafile; if (certfile[0] != '/') certfile = confdir + certfile; if (keyfile[0] != '/') keyfile = confdir + keyfile; if (dhfile[0] != '/') dhfile = confdir + dhfile; /* Load our keys and certificates * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck. */ if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str()))) { ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno)); ERR_print_errors_cb(error_callback, this); } 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->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno)); ERR_print_errors_cb(error_callback, this); } /* Load the CAs we trust*/ if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0))) { ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno)); ERR_print_errors_cb(error_callback, this); } FILE* dhpfile = fopen(dhfile.c_str(), "r"); DH* ret; if (dhpfile == NULL) { ServerInstance->Log(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 { ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL); if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0)) { ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str()); ERR_print_errors_cb(error_callback, this); } } fclose(dhpfile); DELETE(Conf); } virtual void On005Numeric(std::string &output) { output.append(" SSL=" + sslports); } virtual ~ModuleSSLOpenSSL() { SSL_CTX_free(ctx); SSL_CTX_free(clictx); } virtual void OnCleanup(int target_type, void* item) { if (target_type == TYPE_USER) { userrec* user = (userrec*)item; if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports)) { // 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->GlobalCulls.AddItem(user, "SSL module unloading"); } if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports)) { ssl_cert* tofree; user->GetExt("ssl_cert", tofree); delete tofree; user->Shrink("ssl_cert"); } } } virtual void OnUnloadModule(Module* mod, const std::string &name) { if (mod == this) { for(unsigned int i = 0; i < listenports.size(); i++) { ServerInstance->Config->DelIOHook(listenports[i]); for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++) if (ServerInstance->Config->ports[j]->GetPort() == listenports[i]) ServerInstance->Config->ports[j]->SetDescription("plaintext"); } } } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } void Implements(char* List) { List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = List[I_On005Numeric] = 1; List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1; } virtual char* OnRequest(Request* request) { ISHRequest* ISR = (ISHRequest*)request; if (strcmp("IS_NAME", request->GetId()) == 0) { return "openssl"; } else if (strcmp("IS_HOOK", request->GetId()) == 0) { char* ret = "OK"; try { ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } catch (ModuleException &e) { return NULL; } return ret; } else if (strcmp("IS_UNHOOK", request->GetId()) == 0) { return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } else if (strcmp("IS_HSDONE", request->GetId()) == 0) { ServerInstance->Log(DEBUG,"Module checking if handshake is done"); if (ISR->Sock->GetFd() < 0) return (char*)"OK"; issl_session* session = &sessions[ISR->Sock->GetFd()]; return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK"; } else if (strcmp("IS_ATTACH", request->GetId()) == 0) { issl_session* session = &sessions[ISR->Sock->GetFd()]; if (session->sess) { VerifyCertificate(session, (InspSocket*)ISR->Sock); return "OK"; } } return NULL; } virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) { issl_session* session = &sessions[fd]; session->fd = fd; session->inbuf = new char[inbufsize]; session->inbufoffset = 0; session->sess = SSL_new(ctx); session->status = ISSL_NONE; session->outbound = false; if (session->sess == NULL) return; if (SSL_set_fd(session->sess, fd) == 0) { ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); return; } Handshake(session); } virtual void OnRawSocketConnect(int fd) { ServerInstance->Log(DEBUG,"OnRawSocketConnect connecting"); issl_session* session = &sessions[fd]; session->fd = fd; session->inbuf = new char[inbufsize]; session->inbufoffset = 0; session->sess = SSL_new(clictx); session->status = ISSL_NONE; session->outbound = true; if (session->sess == NULL) return; if (SSL_set_fd(session->sess, fd) == 0) { ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); return; } Handshake(session); ServerInstance->Log(DEBUG,"Exiting OnRawSocketConnect"); } virtual void OnRawSocketClose(int fd) { CloseSession(&sessions[fd]); EventHandler* user = ServerInstance->SE->GetRef(fd); if ((user) && (user->GetExt("ssl_cert", dummy))) { ssl_cert* tofree; user->GetExt("ssl_cert", tofree); delete tofree; user->Shrink("ssl_cert"); } } virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { issl_session* session = &sessions[fd]; ServerInstance->Log(DEBUG,"OnRawSocketRead"); if (!session->sess) { ServerInstance->Log(DEBUG,"OnRawSocketRead has no session"); readresult = 0; CloseSession(session); return 1; } if (session->status == ISSL_HANDSHAKING) { if (session->rstat == ISSL_READ || session->wstat == ISSL_READ) { ServerInstance->Log(DEBUG,"Resume handshake in read"); // The handshake isn't finished and it wants to read, try to finish it. if (!Handshake(session)) { ServerInstance->Log(DEBUG,"Cant resume handshake in read"); // Couldn't resume handshake. return -1; } } else { errno = EAGAIN; return -1; } } // If we resumed the handshake then session->status will be ISSL_OPEN if (session->status == ISSL_OPEN) { if (session->wstat == ISSL_READ) { if(DoWrite(session) == 0) return 0; } if (session->rstat == ISSL_READ) { int ret = DoRead(session); if (ret > 0) { if (count <= session->inbufoffset) { memcpy(buffer, session->inbuf, count); // Move the stuff left in inbuf to the beginning of it memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count)); // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp. session->inbufoffset -= count; // Insp uses readresult as the count of how much data there is in buffer, so: readresult = count; } else { // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing. memcpy(buffer, session->inbuf, session->inbufoffset); readresult = session->inbufoffset; // Zero the offset, as there's nothing there.. session->inbufoffset = 0; } return 1; } else { return ret; } } } return -1; } virtual int OnRawSocketWrite(int fd, const char* buffer, int count) { issl_session* session = &sessions[fd]; if (!session->sess) { ServerInstance->Log(DEBUG,"Close session missing sess"); CloseSession(session); return -1; } session->outbuf.append(buffer, count); if (session->status == ISSL_HANDSHAKING) { // The handshake isn't finished, try to finish it. if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE) { ServerInstance->Log(DEBUG,"Handshake resume"); Handshake(session); } } if (session->status == ISSL_OPEN) { if (session->rstat == ISSL_WRITE) { ServerInstance->Log(DEBUG,"DoRead"); DoRead(session); } if (session->wstat == ISSL_WRITE) { ServerInstance->Log(DEBUG,"DoWrite"); return DoWrite(session); } } return 1; } int DoWrite(issl_session* session) { if (!session->outbuf.size()) return -1; int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size()); if (ret == 0) { ServerInstance->Log(DEBUG,"Oops, got 0 from SSL_write"); CloseSession(session); return 0; } else if (ret < 0) { int err = SSL_get_error(session->sess, ret); if (err == SSL_ERROR_WANT_WRITE) { session->wstat = ISSL_WRITE; return -1; } else if (err == SSL_ERROR_WANT_READ) { session->wstat = ISSL_READ; return -1; } else { ServerInstance->Log(DEBUG,"Close due to returned -1 in SSL_Write"); CloseSession(session); return 0; } } else { session->outbuf = session->outbuf.substr(ret); return ret; } } int DoRead(issl_session* session) { // Is this right? Not sure if the unencrypted data is garaunteed to be the same length. // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet. ServerInstance->Log(DEBUG,"DoRead"); int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset); if (ret == 0) { // Client closed connection. ServerInstance->Log(DEBUG,"Oops, got 0 from SSL_read"); CloseSession(session); return 0; } else if (ret < 0) { int err = SSL_get_error(session->sess, ret); if (err == SSL_ERROR_WANT_READ) { session->rstat = ISSL_READ; ServerInstance->Log(DEBUG,"Setting want_read"); return -1; } else if (err == SSL_ERROR_WANT_WRITE) { session->rstat = ISSL_WRITE; ServerInstance->Log(DEBUG,"Setting want_write"); return -1; } else { ServerInstance->Log(DEBUG,"Closed due to returned -1 in SSL_Read"); CloseSession(session); return 0; } } else { // Read successfully 'ret' bytes into inbuf + inbufoffset // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf' // 'buffer' is 'count' long session->inbufoffset += ret; return ret; } } // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection virtual void OnWhois(userrec* source, userrec* dest) { if (!clientactive) return; // Bugfix, only send this numeric for *our* SSL users if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports))) { ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick); } } virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) { // check if the linking module wants to know about OUR metadata if (extname == "ssl") { // check if this user has an swhois field to send if(user->GetExt(extname, dummy)) { // call this function in the linking module, let it format the data how it // sees fit, and send it on its way. We dont need or want to know how. proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON"); } } } virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) { // check if its our metadata key, and its associated with a user if ((target_type == TYPE_USER) && (extname == "ssl")) { userrec* dest = (userrec*)target; // if they dont already have an ssl flag, accept the remote server's if (!dest->GetExt(extname, dummy)) { dest->Extend(extname, "ON"); } } } bool Handshake(issl_session* session) { ServerInstance->Log(DEBUG,"Handshake"); int ret; if (session->outbound) { ServerInstance->Log(DEBUG,"SSL_connect"); ret = SSL_connect(session->sess); } else ret = SSL_accept(session->sess); if (ret < 0) { int err = SSL_get_error(session->sess, ret); if (err == SSL_ERROR_WANT_READ) { ServerInstance->Log(DEBUG,"Want read, handshaking"); session->rstat = ISSL_READ; session->status = ISSL_HANDSHAKING; return true; } else if (err == SSL_ERROR_WANT_WRITE) { ServerInstance->Log(DEBUG,"Want write, handshaking"); session->wstat = ISSL_WRITE; session->status = ISSL_HANDSHAKING; MakePollWrite(session); return true; } else { ServerInstance->Log(DEBUG,"Handshake failed"); CloseSession(session); } return false; } else if (ret > 0) { // Handshake complete. // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater. userrec* u = ServerInstance->FindDescriptor(session->fd); if (u) { if (!u->GetExt("ssl", dummy)) u->Extend("ssl", "ON"); } session->status = ISSL_OPEN; MakePollWrite(session); return true; } else if (ret == 0) { int ssl_err = SSL_get_error(session->sess, ret); char buf[1024]; ERR_print_errors_fp(stderr); ServerInstance->Log(DEBUG,"Handshake fail 2: %d: %s", ssl_err, ERR_error_string(ssl_err,buf)); CloseSession(session); return true; } return true; } virtual void OnPostConnect(userrec* user) { // This occurs AFTER OnUserConnect so we can be sure the // protocol module has propogated the NICK message. if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user))) { // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW. std::deque* metadata = new std::deque; metadata->push_back(user->nick); metadata->push_back("ssl"); // The metadata id metadata->push_back("ON"); // The value to send Event* event = new Event((char*)metadata,(Module*)this,"send_metadata"); event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up. DELETE(event); DELETE(metadata); VerifyCertificate(&sessions[user->GetFd()], user); if (sessions[user->GetFd()].sess) user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess)); } } void MakePollWrite(issl_session* session) { OnRawSocketWrite(session->fd, NULL, 0); //EventHandler* eh = ServerInstance->FindDescriptor(session->fd); //if (eh) // ServerInstance->SE->WantWrite(eh); } void CloseSession(issl_session* session) { if (session->sess) { SSL_shutdown(session->sess); SSL_free(session->sess); } if (session->inbuf) { delete[] session->inbuf; } session->outbuf.clear(); session->inbuf = NULL; session->sess = NULL; session->status = ISSL_NONE; } void VerifyCertificate(issl_session* session, Extensible* user) { if (!session->sess || !user) return; X509* cert; ssl_cert* certinfo = new ssl_cert; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; const EVP_MD *digest = EVP_md5(); user->Extend("ssl_cert",certinfo); cert = SSL_get_peer_certificate((SSL*)session->sess); if (!cert) { certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error()))); return; } certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0))); if (SelfSigned) { certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0))); certinfo->data.insert(std::make_pair("trusted",ConvToStr(1))); } else { certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1))); certinfo->data.insert(std::make_pair("trusted",ConvToStr(0))); } certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0)))); certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0)))); if (!X509_digest(cert, digest, md, &n)) { certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint")); } else { certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n))); } if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0)) { certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate")); } X509_free(cert); } }; static int error_callback(const char *str, size_t len, void *u) { ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u; mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1)); return 0; } MODULE_INIT(ModuleSSLOpenSSL); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" + +#include +#include + +#ifdef WINDOWS +#include +#endif + +#include "configreader.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +#include "socket.h" +#include "hashcomp.h" + +#include "transport.h" + +#ifdef WINDOWS +#pragma comment(lib, "libeay32MTd") +#pragma comment(lib, "ssleay32MTd") +#undef MAX_DESCRIPTORS +#define MAX_DESCRIPTORS 10000 +#endif + +/* $ModDesc: Provides SSL support for clients */ +/* $CompileFlags: pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */ +/* $LinkerFlags: rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */ +/* $ModDep: transport.h */ + +enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN }; +enum issl_io_status { ISSL_WRITE, ISSL_READ }; + +static bool SelfSigned = false; + +bool isin(int port, const std::vector &portlist) +{ + for(unsigned int i = 0; i < portlist.size(); i++) + if(portlist[i] == port) + return true; + + return false; +} + +char* get_error() +{ + return ERR_error_string(ERR_get_error(), NULL); +} + +static int error_callback(const char *str, size_t len, void *u); + +/** Represents an SSL user's extra data + */ +class issl_session : public classbase +{ +public: + SSL* sess; + issl_status status; + issl_io_status rstat; + issl_io_status wstat; + + unsigned int inbufoffset; + char* inbuf; // Buffer OpenSSL reads into. + std::string outbuf; // Buffer for outgoing data that OpenSSL will not take. + int fd; + bool outbound; + + issl_session() + { + outbound = false; + rstat = ISSL_READ; + wstat = ISSL_WRITE; + } +}; + +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); + + SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT); + + return 1; +} + +class ModuleSSLOpenSSL : public Module +{ + + ConfigReader* Conf; + + std::vector listenports; + + int inbufsize; + issl_session sessions[MAX_DESCRIPTORS]; + + SSL_CTX* ctx; + SSL_CTX* clictx; + + char* dummy; + char cipher[MAXBUF]; + + std::string keyfile; + std::string certfile; + std::string cafile; + // std::string crlfile; + std::string dhfile; + std::string sslports; + + int clientactive; + + public: + + InspIRCd* PublicInstance; + + ModuleSSLOpenSSL(InspIRCd* Me) + : Module(Me), PublicInstance(Me) + { + ServerInstance->PublishInterface("InspSocketHook", this); + + // Not rehashable...because I cba to reduce all the sizes of existing buffers. + inbufsize = ServerInstance->Config->NetBufferSize; + + /* Global SSL library initialization*/ + SSL_library_init(); + SSL_load_error_strings(); + + /* Build our SSL contexts: + * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK. + */ + ctx = SSL_CTX_new( SSLv23_server_method() ); + clictx = SSL_CTX_new( SSLv23_client_method() ); + + 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); + + // Needs the flag as it ignores a plain /rehash + OnRehash(NULL,"ssl"); + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + if (param != "ssl") + return; + + Conf = new ConfigReader(ServerInstance); + + for (unsigned int i = 0; i < listenports.size(); i++) + { + ServerInstance->Config->DelIOHook(listenports[i]); + } + + listenports.clear(); + clientactive = 0; + sslports.clear(); + + for (int i = 0; i < Conf->Enumerate("bind"); i++) + { + // For each tag + std::string x = Conf->ReadValue("bind", "type", i); + if (((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl")) + { + // Get the port we're meant to be listening on with SSL + std::string port = Conf->ReadValue("bind", "port", i); + irc::portparser portrange(port, false); + long portno = -1; + while ((portno = portrange.GetToken())) + { + clientactive++; + try + { + if (ServerInstance->Config->AddIOHook(portno, this)) + { + listenports.push_back(portno); + for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++) + if (ServerInstance->Config->ports[i]->GetPort() == portno) + ServerInstance->Config->ports[i]->SetDescription("ssl"); + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno); + sslports.append("*:").append(ConvToStr(portno)).append(";"); + } + else + { + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno); + } + } + catch (ModuleException &e) + { + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have another SSL or similar module loaded?", portno, e.GetReason()); + } + } + } + } + + if (!sslports.empty()) + sslports.erase(sslports.end() - 1); + + std::string confdir(ServerInstance->ConfigFileName); + // +1 so we the path ends with a / + confdir = confdir.substr(0, confdir.find_last_of('/') + 1); + + cafile = Conf->ReadValue("openssl", "cafile", 0); + certfile = Conf->ReadValue("openssl", "certfile", 0); + keyfile = Conf->ReadValue("openssl", "keyfile", 0); + dhfile = Conf->ReadValue("openssl", "dhfile", 0); + + // Set all the default values needed. + if (cafile.empty()) + cafile = "ca.pem"; + + if (certfile.empty()) + certfile = "cert.pem"; + + if (keyfile.empty()) + keyfile = "key.pem"; + + if (dhfile.empty()) + dhfile = "dhparams.pem"; + + // Prepend relative paths with the path to the config directory. + if (cafile[0] != '/') + cafile = confdir + cafile; + + if (certfile[0] != '/') + certfile = confdir + certfile; + + if (keyfile[0] != '/') + keyfile = confdir + keyfile; + + if (dhfile[0] != '/') + dhfile = confdir + dhfile; + + /* Load our keys and certificates + * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck. + */ + if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str()))) + { + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno)); + ERR_print_errors_cb(error_callback, this); + } + + 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->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno)); + ERR_print_errors_cb(error_callback, this); + } + + /* Load the CAs we trust*/ + if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0))) + { + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno)); + ERR_print_errors_cb(error_callback, this); + } + + FILE* dhpfile = fopen(dhfile.c_str(), "r"); + DH* ret; + + if (dhpfile == NULL) + { + ServerInstance->Log(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 + { + ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL); + if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0)) + { + ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str()); + ERR_print_errors_cb(error_callback, this); + } + } + + fclose(dhpfile); + + DELETE(Conf); + } + + virtual void On005Numeric(std::string &output) + { + output.append(" SSL=" + sslports); + } + + virtual ~ModuleSSLOpenSSL() + { + SSL_CTX_free(ctx); + SSL_CTX_free(clictx); + } + + virtual void OnCleanup(int target_type, void* item) + { + if (target_type == TYPE_USER) + { + userrec* user = (userrec*)item; + + if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports)) + { + // 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->GlobalCulls.AddItem(user, "SSL module unloading"); + } + if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports)) + { + ssl_cert* tofree; + user->GetExt("ssl_cert", tofree); + delete tofree; + user->Shrink("ssl_cert"); + } + } + } + + virtual void OnUnloadModule(Module* mod, const std::string &name) + { + if (mod == this) + { + for(unsigned int i = 0; i < listenports.size(); i++) + { + ServerInstance->Config->DelIOHook(listenports[i]); + for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++) + if (ServerInstance->Config->ports[j]->GetPort() == listenports[i]) + ServerInstance->Config->ports[j]->SetDescription("plaintext"); + } + } + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = List[I_On005Numeric] = 1; + List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1; + } + + virtual char* OnRequest(Request* request) + { + ISHRequest* ISR = (ISHRequest*)request; + if (strcmp("IS_NAME", request->GetId()) == 0) + { + return "openssl"; + } + else if (strcmp("IS_HOOK", request->GetId()) == 0) + { + char* ret = "OK"; + try + { + ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + catch (ModuleException &e) + { + return NULL; + } + + return ret; + } + else if (strcmp("IS_UNHOOK", request->GetId()) == 0) + { + return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + else if (strcmp("IS_HSDONE", request->GetId()) == 0) + { + ServerInstance->Log(DEBUG,"Module checking if handshake is done"); + if (ISR->Sock->GetFd() < 0) + return (char*)"OK"; + + issl_session* session = &sessions[ISR->Sock->GetFd()]; + return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK"; + } + else if (strcmp("IS_ATTACH", request->GetId()) == 0) + { + issl_session* session = &sessions[ISR->Sock->GetFd()]; + if (session->sess) + { + VerifyCertificate(session, (InspSocket*)ISR->Sock); + return "OK"; + } + } + return NULL; + } + + + virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) + { + issl_session* session = &sessions[fd]; + + session->fd = fd; + session->inbuf = new char[inbufsize]; + session->inbufoffset = 0; + session->sess = SSL_new(ctx); + session->status = ISSL_NONE; + session->outbound = false; + + if (session->sess == NULL) + return; + + if (SSL_set_fd(session->sess, fd) == 0) + { + ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); + return; + } + + Handshake(session); + } + + virtual void OnRawSocketConnect(int fd) + { + ServerInstance->Log(DEBUG,"OnRawSocketConnect connecting"); + issl_session* session = &sessions[fd]; + + session->fd = fd; + session->inbuf = new char[inbufsize]; + session->inbufoffset = 0; + session->sess = SSL_new(clictx); + session->status = ISSL_NONE; + session->outbound = true; + + if (session->sess == NULL) + return; + + if (SSL_set_fd(session->sess, fd) == 0) + { + ServerInstance->Log(DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd); + return; + } + + Handshake(session); + ServerInstance->Log(DEBUG,"Exiting OnRawSocketConnect"); + } + + virtual void OnRawSocketClose(int fd) + { + CloseSession(&sessions[fd]); + + EventHandler* user = ServerInstance->SE->GetRef(fd); + + if ((user) && (user->GetExt("ssl_cert", dummy))) + { + ssl_cert* tofree; + user->GetExt("ssl_cert", tofree); + delete tofree; + user->Shrink("ssl_cert"); + } + } + + virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) + { + issl_session* session = &sessions[fd]; + + ServerInstance->Log(DEBUG,"OnRawSocketRead"); + + if (!session->sess) + { + ServerInstance->Log(DEBUG,"OnRawSocketRead has no session"); + readresult = 0; + CloseSession(session); + return 1; + } + + if (session->status == ISSL_HANDSHAKING) + { + if (session->rstat == ISSL_READ || session->wstat == ISSL_READ) + { + ServerInstance->Log(DEBUG,"Resume handshake in read"); + // The handshake isn't finished and it wants to read, try to finish it. + if (!Handshake(session)) + { + ServerInstance->Log(DEBUG,"Cant resume handshake in read"); + // Couldn't resume handshake. + return -1; + } + } + else + { + errno = EAGAIN; + return -1; + } + } + + // If we resumed the handshake then session->status will be ISSL_OPEN + + if (session->status == ISSL_OPEN) + { + if (session->wstat == ISSL_READ) + { + if(DoWrite(session) == 0) + return 0; + } + + if (session->rstat == ISSL_READ) + { + int ret = DoRead(session); + + if (ret > 0) + { + if (count <= session->inbufoffset) + { + memcpy(buffer, session->inbuf, count); + // Move the stuff left in inbuf to the beginning of it + memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count)); + // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp. + session->inbufoffset -= count; + // Insp uses readresult as the count of how much data there is in buffer, so: + readresult = count; + } + else + { + // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing. + memcpy(buffer, session->inbuf, session->inbufoffset); + + readresult = session->inbufoffset; + // Zero the offset, as there's nothing there.. + session->inbufoffset = 0; + } + + return 1; + } + else + { + return ret; + } + } + } + + return -1; + } + + virtual int OnRawSocketWrite(int fd, const char* buffer, int count) + { + issl_session* session = &sessions[fd]; + + if (!session->sess) + { + ServerInstance->Log(DEBUG,"Close session missing sess"); + CloseSession(session); + return -1; + } + + session->outbuf.append(buffer, count); + + if (session->status == ISSL_HANDSHAKING) + { + // The handshake isn't finished, try to finish it. + if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE) + { + ServerInstance->Log(DEBUG,"Handshake resume"); + Handshake(session); + } + } + + if (session->status == ISSL_OPEN) + { + if (session->rstat == ISSL_WRITE) + { + ServerInstance->Log(DEBUG,"DoRead"); + DoRead(session); + } + + if (session->wstat == ISSL_WRITE) + { + ServerInstance->Log(DEBUG,"DoWrite"); + return DoWrite(session); + } + } + + return 1; + } + + int DoWrite(issl_session* session) + { + if (!session->outbuf.size()) + return -1; + + int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size()); + + if (ret == 0) + { + ServerInstance->Log(DEBUG,"Oops, got 0 from SSL_write"); + CloseSession(session); + return 0; + } + else if (ret < 0) + { + int err = SSL_get_error(session->sess, ret); + + if (err == SSL_ERROR_WANT_WRITE) + { + session->wstat = ISSL_WRITE; + return -1; + } + else if (err == SSL_ERROR_WANT_READ) + { + session->wstat = ISSL_READ; + return -1; + } + else + { + ServerInstance->Log(DEBUG,"Close due to returned -1 in SSL_Write"); + CloseSession(session); + return 0; + } + } + else + { + session->outbuf = session->outbuf.substr(ret); + return ret; + } + } + + int DoRead(issl_session* session) + { + // Is this right? Not sure if the unencrypted data is garaunteed to be the same length. + // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet. + + ServerInstance->Log(DEBUG,"DoRead"); + + int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset); + + if (ret == 0) + { + // Client closed connection. + ServerInstance->Log(DEBUG,"Oops, got 0 from SSL_read"); + CloseSession(session); + return 0; + } + else if (ret < 0) + { + int err = SSL_get_error(session->sess, ret); + + if (err == SSL_ERROR_WANT_READ) + { + session->rstat = ISSL_READ; + ServerInstance->Log(DEBUG,"Setting want_read"); + return -1; + } + else if (err == SSL_ERROR_WANT_WRITE) + { + session->rstat = ISSL_WRITE; + ServerInstance->Log(DEBUG,"Setting want_write"); + return -1; + } + else + { + ServerInstance->Log(DEBUG,"Closed due to returned -1 in SSL_Read"); + CloseSession(session); + return 0; + } + } + else + { + // Read successfully 'ret' bytes into inbuf + inbufoffset + // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf' + // 'buffer' is 'count' long + + session->inbufoffset += ret; + + return ret; + } + } + + // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection + virtual void OnWhois(userrec* source, userrec* dest) + { + if (!clientactive) + return; + + // Bugfix, only send this numeric for *our* SSL users + if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) && isin(dest->GetPort(), listenports))) + { + ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick); + } + } + + virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) + { + // check if the linking module wants to know about OUR metadata + if (extname == "ssl") + { + // check if this user has an swhois field to send + if(user->GetExt(extname, dummy)) + { + // call this function in the linking module, let it format the data how it + // sees fit, and send it on its way. We dont need or want to know how. + proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON"); + } + } + } + + virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) + { + // check if its our metadata key, and its associated with a user + if ((target_type == TYPE_USER) && (extname == "ssl")) + { + userrec* dest = (userrec*)target; + // if they dont already have an ssl flag, accept the remote server's + if (!dest->GetExt(extname, dummy)) + { + dest->Extend(extname, "ON"); + } + } + } + + bool Handshake(issl_session* session) + { + ServerInstance->Log(DEBUG,"Handshake"); + int ret; + + if (session->outbound) + { + ServerInstance->Log(DEBUG,"SSL_connect"); + ret = SSL_connect(session->sess); + } + else + ret = SSL_accept(session->sess); + + if (ret < 0) + { + int err = SSL_get_error(session->sess, ret); + + if (err == SSL_ERROR_WANT_READ) + { + ServerInstance->Log(DEBUG,"Want read, handshaking"); + session->rstat = ISSL_READ; + session->status = ISSL_HANDSHAKING; + return true; + } + else if (err == SSL_ERROR_WANT_WRITE) + { + ServerInstance->Log(DEBUG,"Want write, handshaking"); + session->wstat = ISSL_WRITE; + session->status = ISSL_HANDSHAKING; + MakePollWrite(session); + return true; + } + else + { + ServerInstance->Log(DEBUG,"Handshake failed"); + CloseSession(session); + } + + return false; + } + else if (ret > 0) + { + // Handshake complete. + // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater. + userrec* u = ServerInstance->FindDescriptor(session->fd); + if (u) + { + if (!u->GetExt("ssl", dummy)) + u->Extend("ssl", "ON"); + } + + session->status = ISSL_OPEN; + + MakePollWrite(session); + + return true; + } + else if (ret == 0) + { + int ssl_err = SSL_get_error(session->sess, ret); + char buf[1024]; + ERR_print_errors_fp(stderr); + ServerInstance->Log(DEBUG,"Handshake fail 2: %d: %s", ssl_err, ERR_error_string(ssl_err,buf)); + CloseSession(session); + return true; + } + + return true; + } + + virtual void OnPostConnect(userrec* user) + { + // This occurs AFTER OnUserConnect so we can be sure the + // protocol module has propogated the NICK message. + if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user))) + { + // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW. + std::deque* metadata = new std::deque; + metadata->push_back(user->nick); + metadata->push_back("ssl"); // The metadata id + metadata->push_back("ON"); // The value to send + Event* event = new Event((char*)metadata,(Module*)this,"send_metadata"); + event->Send(ServerInstance); // Trigger the event. We don't care what module picks it up. + DELETE(event); + DELETE(metadata); + + VerifyCertificate(&sessions[user->GetFd()], user); + if (sessions[user->GetFd()].sess) + user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, SSL_get_cipher(sessions[user->GetFd()].sess)); + } + } + + void MakePollWrite(issl_session* session) + { + OnRawSocketWrite(session->fd, NULL, 0); + //EventHandler* eh = ServerInstance->FindDescriptor(session->fd); + //if (eh) + // ServerInstance->SE->WantWrite(eh); + } + + void CloseSession(issl_session* session) + { + if (session->sess) + { + SSL_shutdown(session->sess); + SSL_free(session->sess); + } + + if (session->inbuf) + { + delete[] session->inbuf; + } + + session->outbuf.clear(); + session->inbuf = NULL; + session->sess = NULL; + session->status = ISSL_NONE; + } + + void VerifyCertificate(issl_session* session, Extensible* user) + { + if (!session->sess || !user) + return; + + X509* cert; + ssl_cert* certinfo = new ssl_cert; + unsigned int n; + unsigned char md[EVP_MAX_MD_SIZE]; + const EVP_MD *digest = EVP_md5(); + + user->Extend("ssl_cert",certinfo); + + cert = SSL_get_peer_certificate((SSL*)session->sess); + + if (!cert) + { + certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error()))); + return; + } + + certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0))); + + if (SelfSigned) + { + certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0))); + certinfo->data.insert(std::make_pair("trusted",ConvToStr(1))); + } + else + { + certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1))); + certinfo->data.insert(std::make_pair("trusted",ConvToStr(0))); + } + + certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0)))); + certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0)))); + + if (!X509_digest(cert, digest, md, &n)) + { + certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint")); + } + else + { + certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n))); + } + + if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0)) + { + certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate")); + } + + X509_free(cert); + } +}; + +static int error_callback(const char *str, size_t len, void *u) +{ + ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u; + mssl->PublicInstance->Log(DEFAULT, "SSL error: " + std::string(str, len - 1)); + return 0; +} + +MODULE_INIT(ModuleSSLOpenSSL); + diff --git a/src/modules/extra/m_ssl_oper_cert.cpp b/src/modules/extra/m_ssl_oper_cert.cpp index 7b1c90868..c67b50c8c 100644 --- a/src/modules/extra/m_ssl_oper_cert.cpp +++ b/src/modules/extra/m_ssl_oper_cert.cpp @@ -1 +1,180 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ /* $ModDesc: Allows for MD5 encrypted oper passwords */ /* $ModDep: transport.h */ #include "inspircd.h" #include "inspircd_config.h" #include "users.h" #include "channels.h" #include "modules.h" #include "transport.h" #include "wildcard.h" /** Handle /FINGERPRINT */ class cmd_fingerprint : public command_t { public: cmd_fingerprint (InspIRCd* Instance) : command_t(Instance,"FINGERPRINT", 0, 1) { this->source = "m_ssl_oper_cert.so"; syntax = ""; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { userrec* target = ServerInstance->FindNick(parameters[0]); if (target) { ssl_cert* cert; if (target->GetExt("ssl_cert",cert)) { if (cert->GetFingerprint().length()) { user->WriteServ("NOTICE %s :Certificate fingerprint for %s is %s",user->nick,target->nick,cert->GetFingerprint().c_str()); return CMD_SUCCESS; } else { user->WriteServ("NOTICE %s :Certificate fingerprint for %s does not exist!", user->nick,target->nick); return CMD_FAILURE; } } else { user->WriteServ("NOTICE %s :Certificate fingerprint for %s does not exist!", user->nick, target->nick); return CMD_FAILURE; } } else { user->WriteServ("401 %s %s :No such nickname", user->nick, parameters[0]); return CMD_FAILURE; } } }; class ModuleOperSSLCert : public Module { ssl_cert* cert; bool HasCert; cmd_fingerprint* mycommand; ConfigReader* cf; public: ModuleOperSSLCert(InspIRCd* Me) : Module(Me) { mycommand = new cmd_fingerprint(ServerInstance); ServerInstance->AddCommand(mycommand); cf = new ConfigReader(ServerInstance); } virtual ~ModuleOperSSLCert() { delete cf; } void Implements(char* List) { List[I_OnPreCommand] = List[I_OnRehash] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { delete cf; cf = new ConfigReader(ServerInstance); } bool OneOfMatches(const char* host, const char* ip, const char* hostlist) { std::stringstream hl(hostlist); std::string xhost; while (hl >> xhost) { if (match(host,xhost.c_str()) || match(ip,xhost.c_str(),true)) { return true; } } return false; } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { irc::string cmd = command.c_str(); if ((cmd == "OPER") && (validated)) { char TheHost[MAXBUF]; char TheIP[MAXBUF]; std::string LoginName; std::string Password; std::string OperType; std::string HostName; std::string FingerPrint; bool SSLOnly; char* dummy; snprintf(TheHost,MAXBUF,"%s@%s",user->ident,user->host); snprintf(TheIP, MAXBUF,"%s@%s",user->ident,user->GetIPString()); HasCert = user->GetExt("ssl_cert",cert); for (int i = 0; i < cf->Enumerate("oper"); i++) { LoginName = cf->ReadValue("oper", "name", i); Password = cf->ReadValue("oper", "password", i); OperType = cf->ReadValue("oper", "type", i); HostName = cf->ReadValue("oper", "host", i); FingerPrint = cf->ReadValue("oper", "fingerprint", i); SSLOnly = cf->ReadFlag("oper", "sslonly", i); if (SSLOnly || !FingerPrint.empty()) { if ((!strcmp(LoginName.c_str(),parameters[0])) && (!ServerInstance->OperPassCompare(Password.c_str(),parameters[1],i)) && (OneOfMatches(TheHost,TheIP,HostName.c_str()))) { if (SSLOnly && !user->GetExt("ssl", dummy)) { user->WriteServ("491 %s :This oper login name requires an SSL connection.", user->nick); return 1; } /* This oper would match */ if ((!cert) || (cert->GetFingerprint() != FingerPrint)) { user->WriteServ("491 %s :This oper login name requires a matching key fingerprint.",user->nick); ServerInstance->SNO->WriteToSnoMask('o',"'%s' cannot oper, does not match fingerprint", user->nick); ServerInstance->Log(DEFAULT,"OPER: Failed oper attempt by %s!%s@%s: credentials valid, but wrong fingerprint.",user->nick,user->ident,user->host); return 1; } } } } } return 0; } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleOperSSLCert); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +/* $ModDesc: Allows for MD5 encrypted oper passwords */ +/* $ModDep: transport.h */ + +#include "inspircd.h" +#include "inspircd_config.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "transport.h" +#include "wildcard.h" + +/** Handle /FINGERPRINT + */ +class cmd_fingerprint : public command_t +{ + public: + cmd_fingerprint (InspIRCd* Instance) : command_t(Instance,"FINGERPRINT", 0, 1) + { + this->source = "m_ssl_oper_cert.so"; + syntax = ""; + } + + CmdResult Handle (const char** parameters, int pcnt, userrec *user) + { + userrec* target = ServerInstance->FindNick(parameters[0]); + if (target) + { + ssl_cert* cert; + if (target->GetExt("ssl_cert",cert)) + { + if (cert->GetFingerprint().length()) + { + user->WriteServ("NOTICE %s :Certificate fingerprint for %s is %s",user->nick,target->nick,cert->GetFingerprint().c_str()); + return CMD_SUCCESS; + } + else + { + user->WriteServ("NOTICE %s :Certificate fingerprint for %s does not exist!", user->nick,target->nick); + return CMD_FAILURE; + } + } + else + { + user->WriteServ("NOTICE %s :Certificate fingerprint for %s does not exist!", user->nick, target->nick); + return CMD_FAILURE; + } + } + else + { + user->WriteServ("401 %s %s :No such nickname", user->nick, parameters[0]); + return CMD_FAILURE; + } + } +}; + + + +class ModuleOperSSLCert : public Module +{ + ssl_cert* cert; + bool HasCert; + cmd_fingerprint* mycommand; + ConfigReader* cf; + public: + + ModuleOperSSLCert(InspIRCd* Me) + : Module(Me) + { + mycommand = new cmd_fingerprint(ServerInstance); + ServerInstance->AddCommand(mycommand); + cf = new ConfigReader(ServerInstance); + } + + virtual ~ModuleOperSSLCert() + { + delete cf; + } + + void Implements(char* List) + { + List[I_OnPreCommand] = List[I_OnRehash] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + delete cf; + cf = new ConfigReader(ServerInstance); + } + + bool OneOfMatches(const char* host, const char* ip, const char* hostlist) + { + std::stringstream hl(hostlist); + std::string xhost; + while (hl >> xhost) + { + if (match(host,xhost.c_str()) || match(ip,xhost.c_str(),true)) + { + return true; + } + } + return false; + } + + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + irc::string cmd = command.c_str(); + + if ((cmd == "OPER") && (validated)) + { + char TheHost[MAXBUF]; + char TheIP[MAXBUF]; + std::string LoginName; + std::string Password; + std::string OperType; + std::string HostName; + std::string FingerPrint; + bool SSLOnly; + char* dummy; + + snprintf(TheHost,MAXBUF,"%s@%s",user->ident,user->host); + snprintf(TheIP, MAXBUF,"%s@%s",user->ident,user->GetIPString()); + + HasCert = user->GetExt("ssl_cert",cert); + + for (int i = 0; i < cf->Enumerate("oper"); i++) + { + LoginName = cf->ReadValue("oper", "name", i); + Password = cf->ReadValue("oper", "password", i); + OperType = cf->ReadValue("oper", "type", i); + HostName = cf->ReadValue("oper", "host", i); + FingerPrint = cf->ReadValue("oper", "fingerprint", i); + SSLOnly = cf->ReadFlag("oper", "sslonly", i); + + if (SSLOnly || !FingerPrint.empty()) + { + if ((!strcmp(LoginName.c_str(),parameters[0])) && (!ServerInstance->OperPassCompare(Password.c_str(),parameters[1],i)) && (OneOfMatches(TheHost,TheIP,HostName.c_str()))) + { + if (SSLOnly && !user->GetExt("ssl", dummy)) + { + user->WriteServ("491 %s :This oper login name requires an SSL connection.", user->nick); + return 1; + } + + /* This oper would match */ + if ((!cert) || (cert->GetFingerprint() != FingerPrint)) + { + user->WriteServ("491 %s :This oper login name requires a matching key fingerprint.",user->nick); + ServerInstance->SNO->WriteToSnoMask('o',"'%s' cannot oper, does not match fingerprint", user->nick); + ServerInstance->Log(DEFAULT,"OPER: Failed oper attempt by %s!%s@%s: credentials valid, but wrong fingerprint.",user->nick,user->ident,user->host); + return 1; + } + } + } + } + } + return 0; + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } +}; + +MODULE_INIT(ModuleOperSSLCert); + diff --git a/src/modules/extra/m_sslinfo.cpp b/src/modules/extra/m_sslinfo.cpp index 83de798c8..dc9274f1e 100644 --- a/src/modules/extra/m_sslinfo.cpp +++ b/src/modules/extra/m_sslinfo.cpp @@ -1 +1,94 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "transport.h" #include "wildcard.h" #include "dns.h" /* $ModDesc: Provides /sslinfo command used to test who a mask matches */ /* $ModDep: transport.h */ /** Handle /SSLINFO */ class cmd_sslinfo : public command_t { public: cmd_sslinfo (InspIRCd* Instance) : command_t(Instance,"SSLINFO", 0, 1) { this->source = "m_sslinfo.so"; this->syntax = ""; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { userrec* target = ServerInstance->FindNick(parameters[0]); ssl_cert* cert; if (target) { if (target->GetExt("ssl_cert", cert)) { if (cert->GetError().length()) { user->WriteServ("NOTICE %s :*** Error: %s", user->nick, cert->GetError().c_str()); } user->WriteServ("NOTICE %s :*** Distinguised Name: %s", user->nick, cert->GetDN().c_str()); user->WriteServ("NOTICE %s :*** Issuer: %s", user->nick, cert->GetIssuer().c_str()); user->WriteServ("NOTICE %s :*** Key Fingerprint: %s", user->nick, cert->GetFingerprint().c_str()); return CMD_SUCCESS; } else { user->WriteServ("NOTICE %s :*** No SSL certificate information for this user.", user->nick); return CMD_FAILURE; } } else user->WriteServ("401 %s %s :No such nickname", user->nick, parameters[0]); return CMD_FAILURE; } }; class ModuleSSLInfo : public Module { cmd_sslinfo* newcommand; public: ModuleSSLInfo(InspIRCd* Me) : Module(Me) { newcommand = new cmd_sslinfo(ServerInstance); ServerInstance->AddCommand(newcommand); } void Implements(char* List) { } virtual ~ModuleSSLInfo() { } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } }; MODULE_INIT(ModuleSSLInfo); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "transport.h" +#include "wildcard.h" +#include "dns.h" + +/* $ModDesc: Provides /sslinfo command used to test who a mask matches */ +/* $ModDep: transport.h */ + +/** Handle /SSLINFO + */ +class cmd_sslinfo : public command_t +{ + public: + cmd_sslinfo (InspIRCd* Instance) : command_t(Instance,"SSLINFO", 0, 1) + { + this->source = "m_sslinfo.so"; + this->syntax = ""; + } + + CmdResult Handle (const char** parameters, int pcnt, userrec *user) + { + userrec* target = ServerInstance->FindNick(parameters[0]); + ssl_cert* cert; + + if (target) + { + if (target->GetExt("ssl_cert", cert)) + { + if (cert->GetError().length()) + { + user->WriteServ("NOTICE %s :*** Error: %s", user->nick, cert->GetError().c_str()); + } + user->WriteServ("NOTICE %s :*** Distinguised Name: %s", user->nick, cert->GetDN().c_str()); + user->WriteServ("NOTICE %s :*** Issuer: %s", user->nick, cert->GetIssuer().c_str()); + user->WriteServ("NOTICE %s :*** Key Fingerprint: %s", user->nick, cert->GetFingerprint().c_str()); + return CMD_SUCCESS; + } + else + { + user->WriteServ("NOTICE %s :*** No SSL certificate information for this user.", user->nick); + return CMD_FAILURE; + } + } + else + user->WriteServ("401 %s %s :No such nickname", user->nick, parameters[0]); + + return CMD_FAILURE; + } +}; + +class ModuleSSLInfo : public Module +{ + cmd_sslinfo* newcommand; + public: + ModuleSSLInfo(InspIRCd* Me) + : Module(Me) + { + + newcommand = new cmd_sslinfo(ServerInstance); + ServerInstance->AddCommand(newcommand); + } + + void Implements(char* List) + { + } + + virtual ~ModuleSSLInfo() + { + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } +}; + +MODULE_INIT(ModuleSSLInfo); + diff --git a/src/modules/extra/m_testclient.cpp b/src/modules/extra/m_testclient.cpp index a867dad20..f4e58b7b5 100644 --- a/src/modules/extra/m_testclient.cpp +++ b/src/modules/extra/m_testclient.cpp @@ -1 +1,110 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" #include "m_sqlv2.h" class ModuleTestClient : public Module { private: public: ModuleTestClient(InspIRCd* Me) : Module::Module(Me) { } void Implements(char* List) { List[I_OnRequest] = List[I_OnBackgroundTimer] = 1; } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } virtual void OnBackgroundTimer(time_t foo) { Module* target = ServerInstance->FindFeature("SQL"); if(target) { SQLrequest foo = SQLreq(this, target, "foo", "UPDATE rawr SET foo = '?' WHERE bar = 42", ConvToStr(time(NULL))); if(foo.Send()) { ServerInstance->Log(DEBUG, "Sent query, got given ID %lu", foo.id); } else { ServerInstance->Log(DEBUG, "SQLrequest failed: %s", foo.error.Str()); } } } virtual char* OnRequest(Request* request) { if(strcmp(SQLRESID, request->GetId()) == 0) { ServerInstance->Log(DEBUG, "Got SQL result (%s)", request->GetId()); SQLresult* res = (SQLresult*)request; if (res->error.Id() == NO_ERROR) { if(res->Cols()) { ServerInstance->Log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols()); for (int r = 0; r < res->Rows(); r++) { ServerInstance->Log(DEBUG, "Row %d:", r); for(int i = 0; i < res->Cols(); i++) { ServerInstance->Log(DEBUG, "\t[%s]: %s", res->ColName(i).c_str(), res->GetValue(r, i).d.c_str()); } } } else { ServerInstance->Log(DEBUG, "%d rows affected in query", res->Rows()); } } else { ServerInstance->Log(DEBUG, "SQLrequest failed: %s", res->error.Str()); } return SQLSUCCESS; } ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId()); return NULL; } virtual ~ModuleTestClient() { } }; MODULE_INIT(ModuleTestClient); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" +#include "m_sqlv2.h" + +class ModuleTestClient : public Module +{ +private: + + +public: + ModuleTestClient(InspIRCd* Me) + : Module::Module(Me) + { + } + + void Implements(char* List) + { + List[I_OnRequest] = List[I_OnBackgroundTimer] = 1; + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + virtual void OnBackgroundTimer(time_t foo) + { + Module* target = ServerInstance->FindFeature("SQL"); + + if(target) + { + SQLrequest foo = SQLreq(this, target, "foo", "UPDATE rawr SET foo = '?' WHERE bar = 42", ConvToStr(time(NULL))); + + if(foo.Send()) + { + ServerInstance->Log(DEBUG, "Sent query, got given ID %lu", foo.id); + } + else + { + ServerInstance->Log(DEBUG, "SQLrequest failed: %s", foo.error.Str()); + } + } + } + + virtual char* OnRequest(Request* request) + { + if(strcmp(SQLRESID, request->GetId()) == 0) + { + ServerInstance->Log(DEBUG, "Got SQL result (%s)", request->GetId()); + + SQLresult* res = (SQLresult*)request; + + if (res->error.Id() == NO_ERROR) + { + if(res->Cols()) + { + ServerInstance->Log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols()); + + for (int r = 0; r < res->Rows(); r++) + { + ServerInstance->Log(DEBUG, "Row %d:", r); + + for(int i = 0; i < res->Cols(); i++) + { + ServerInstance->Log(DEBUG, "\t[%s]: %s", res->ColName(i).c_str(), res->GetValue(r, i).d.c_str()); + } + } + } + else + { + ServerInstance->Log(DEBUG, "%d rows affected in query", res->Rows()); + } + } + else + { + ServerInstance->Log(DEBUG, "SQLrequest failed: %s", res->error.Str()); + + } + + return SQLSUCCESS; + } + + ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId()); + + return NULL; + } + + virtual ~ModuleTestClient() + { + } +}; + +MODULE_INIT(ModuleTestClient); + diff --git a/src/modules/extra/m_ziplink.cpp b/src/modules/extra/m_ziplink.cpp index 2a127258d..e815d1042 100644 --- a/src/modules/extra/m_ziplink.cpp +++ b/src/modules/extra/m_ziplink.cpp @@ -1 +1,452 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include "users.h" #include "channels.h" #include "modules.h" #include "socket.h" #include "hashcomp.h" #include "transport.h" /* $ModDesc: Provides zlib link support for servers */ /* $LinkerFlags: -lz */ /* $ModDep: transport.h */ /* * Compressed data is transmitted across the link in the following format: * * 0 1 2 3 4 ... n * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * | n | Z0 -> Zn | * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ * * Where: n is the size of a frame, in network byte order, 4 bytes. * Z0 through Zn are Zlib compressed data, n bytes in length. * * If the module fails to read the entire frame, then it will buffer * the portion of the last frame it received, then attempt to read * the next part of the frame next time a write notification arrives. * * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with * a flush after each frame. A frame may contain multiple lines * and should be treated as raw binary data. * */ /* Status of a connection */ enum izip_status { IZIP_OPEN, IZIP_CLOSED }; /* Maximum transfer size per read operation */ const unsigned int CHUNK = 128 * 1024; /* This class manages a compressed chunk of data preceeded by * a length count. * * It can handle having multiple chunks of data in the buffer * at any time. */ class CountedBuffer : public classbase { std::string buffer; /* Current buffer contents */ unsigned int amount_expected; /* Amount of data expected */ public: CountedBuffer() { amount_expected = 0; } /** Adds arbitrary compressed data to the buffer. * - Binsry safe, of course. */ void AddData(unsigned char* data, int data_length) { buffer.append((const char*)data, data_length); this->NextFrameSize(); } /** Works out the size of the next compressed frame */ void NextFrameSize() { if ((!amount_expected) && (buffer.length() >= 4)) { /* We have enough to read an int - * Yes, this is safe, but its ugly. Give me * a nicer way to read 4 bytes from a binary * stream, and push them into a 32 bit int, * and i'll consider replacing this. */ amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]); buffer = buffer.substr(4); } } /** Gets the next frame and returns its size, or returns * zero if there isnt one available yet. * A frame can contain multiple plaintext lines. * - Binary safe. */ int GetFrame(unsigned char* frame, int maxsize) { if (amount_expected) { /* We know how much we're expecting... * Do we have enough yet? */ if (buffer.length() >= amount_expected) { int j = 0; for (unsigned int i = 0; i < amount_expected; i++, j++) frame[i] = buffer[i]; buffer = buffer.substr(j); amount_expected = 0; NextFrameSize(); return j; } } /* Not enough for a frame yet, COME AGAIN! */ return 0; } }; /** Represents an zipped connections extra data */ class izip_session : public classbase { public: z_stream c_stream; /* compression stream */ z_stream d_stream; /* decompress stream */ izip_status status; /* Connection status */ int fd; /* File descriptor */ CountedBuffer* inbuf; /* Holds input buffer */ std::string outbuf; /* Holds output buffer */ }; class ModuleZLib : public Module { izip_session sessions[MAX_DESCRIPTORS]; /* Used for stats z extensions */ float total_out_compressed; float total_in_compressed; float total_out_uncompressed; float total_in_uncompressed; public: ModuleZLib(InspIRCd* Me) : Module::Module(Me) { ServerInstance->PublishInterface("InspSocketHook", this); total_out_compressed = total_in_compressed = 0; total_out_uncompressed = total_out_uncompressed = 0; } virtual ~ModuleZLib() { ServerInstance->UnpublishInterface("InspSocketHook", this); } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } void Implements(char* List) { List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1; List[I_OnStats] = List[I_OnRequest] = 1; } /* Handle InspSocketHook API requests */ virtual char* OnRequest(Request* request) { ISHRequest* ISR = (ISHRequest*)request; if (strcmp("IS_NAME", request->GetId()) == 0) { /* Return name */ return "zip"; } else if (strcmp("IS_HOOK", request->GetId()) == 0) { /* Attach to an inspsocket */ char* ret = "OK"; try { ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } catch (ModuleException& e) { return NULL; } return ret; } else if (strcmp("IS_UNHOOK", request->GetId()) == 0) { /* Detatch from an inspsocket */ return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; } else if (strcmp("IS_HSDONE", request->GetId()) == 0) { /* Check for completion of handshake * (actually, this module doesnt handshake) */ return "OK"; } else if (strcmp("IS_ATTACH", request->GetId()) == 0) { /* Attach certificate data to the inspsocket * (this module doesnt do that, either) */ return NULL; } return NULL; } /* Handle stats z (misc stats) */ virtual int OnStats(char symbol, userrec* user, string_list &results) { if (symbol == 'z') { std::string sn = ServerInstance->Config->ServerName; /* Yeah yeah, i know, floats are ew. * We used them here because we'd be casting to float anyway to do this maths, * and also only floating point numbers can deal with the pretty large numbers * involved in the total throughput of a server over a large period of time. * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats * can still hold more. */ float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100); float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100); float total_compressed = total_in_compressed + total_out_compressed; float total_uncompressed = total_in_uncompressed + total_out_uncompressed; float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100); char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF]; sprintf(outbound_ratio, "%3.2f%%", outbound_r); sprintf(inbound_ratio, "%3.2f%%", inbound_r); sprintf(combined_ratio, "%3.2f%%", total_r); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed)); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed)); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed)); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed)); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio); results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio); return 0; } return 0; } virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) { izip_session* session = &sessions[fd]; /* allocate state and buffers */ session->fd = fd; session->status = IZIP_OPEN; session->inbuf = new CountedBuffer(); session->c_stream.zalloc = (alloc_func)0; session->c_stream.zfree = (free_func)0; session->c_stream.opaque = (voidpf)0; session->d_stream.zalloc = (alloc_func)0; session->d_stream.zfree = (free_func)0; session->d_stream.opaque = (voidpf)0; } virtual void OnRawSocketConnect(int fd) { /* Nothing special needs doing here compared to accept() */ OnRawSocketAccept(fd, "", 0); } virtual void OnRawSocketClose(int fd) { CloseSession(&sessions[fd]); } virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { /* Find the sockets session */ izip_session* session = &sessions[fd]; if (session->status == IZIP_CLOSED) return 0; unsigned char compr[CHUNK + 4]; unsigned int offset = 0; unsigned int total_size = 0; /* Read CHUNK bytes at a time to the buffer (usually 128k) */ readresult = read(fd, compr, CHUNK); /* Did we get anything? */ if (readresult > 0) { /* Add it to the frame queue */ session->inbuf->AddData(compr, readresult); total_in_compressed += readresult; /* Parse all completed frames */ int size = 0; while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0) { session->d_stream.next_in = (Bytef*)compr; session->d_stream.avail_in = 0; session->d_stream.next_out = (Bytef*)(buffer + offset); /* If we cant call this, well, we're boned. */ if (inflateInit(&session->d_stream) != Z_OK) return 0; while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size)) { session->d_stream.avail_in = session->d_stream.avail_out = 1; if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END) break; } /* Stick a fork in me, i'm done */ inflateEnd(&session->d_stream); /* Update counters and offsets */ total_size += session->d_stream.total_out; total_in_uncompressed += session->d_stream.total_out; offset += session->d_stream.total_out; } /* Null-terminate the buffer -- this doesnt harm binary data */ buffer[total_size] = 0; /* Set the read size to the correct total size */ readresult = total_size; } return (readresult > 0); } virtual int OnRawSocketWrite(int fd, const char* buffer, int count) { izip_session* session = &sessions[fd]; int ocount = count; if (!count) /* Nothing to do! */ return 0; if(session->status != IZIP_OPEN) { /* Seriously, wtf? */ CloseSession(session); return 0; } unsigned char compr[CHUNK + 4]; /* Gentlemen, start your engines! */ if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK) { CloseSession(session); return 0; } /* Set buffer sizes (we reserve 4 bytes at the start of the * buffer for the length counters) */ session->c_stream.next_in = (Bytef*)buffer; session->c_stream.next_out = compr + 4; /* Compress the text */ while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK)) { session->c_stream.avail_in = session->c_stream.avail_out = 1; if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK) { CloseSession(session); return 0; } } /* Finish the stream */ for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1); deflateEnd(&session->c_stream); total_out_uncompressed += ocount; total_out_compressed += session->c_stream.total_out; /** Assemble the frame length onto the frame, in network byte order */ compr[0] = (session->c_stream.total_out >> 24); compr[1] = (session->c_stream.total_out >> 16); compr[2] = (session->c_stream.total_out >> 8); compr[3] = (session->c_stream.total_out & 0xFF); /* Add compressed data plus leading length to the output buffer - * Note, we may have incomplete half-sent frames in here. */ session->outbuf.append((const char*)compr, session->c_stream.total_out + 4); /* Lets see how much we can send out */ int ret = write(fd, session->outbuf.data(), session->outbuf.length()); /* Check for errors, and advance the buffer if any was sent */ if (ret > 0) session->outbuf = session->outbuf.substr(ret); else if (ret < 1) { if (ret == -1) { if (errno == EAGAIN) return 0; else { session->outbuf.clear(); return 0; } } else { session->outbuf.clear(); return 0; } } /* ALL LIES the lot of it, we havent really written * this amount, but the layer above doesnt need to know. */ return ocount; } void CloseSession(izip_session* session) { if (session->status == IZIP_OPEN) { session->status = IZIP_CLOSED; session->outbuf.clear(); delete session->inbuf; } } }; MODULE_INIT(ModuleZLib); \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "socket.h" +#include "hashcomp.h" +#include "transport.h" + +/* $ModDesc: Provides zlib link support for servers */ +/* $LinkerFlags: -lz */ +/* $ModDep: transport.h */ + +/* + * Compressed data is transmitted across the link in the following format: + * + * 0 1 2 3 4 ... n + * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + * | n | Z0 -> Zn | + * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ + * + * Where: n is the size of a frame, in network byte order, 4 bytes. + * Z0 through Zn are Zlib compressed data, n bytes in length. + * + * If the module fails to read the entire frame, then it will buffer + * the portion of the last frame it received, then attempt to read + * the next part of the frame next time a write notification arrives. + * + * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with + * a flush after each frame. A frame may contain multiple lines + * and should be treated as raw binary data. + * + */ + +/* Status of a connection */ +enum izip_status { IZIP_OPEN, IZIP_CLOSED }; + +/* Maximum transfer size per read operation */ +const unsigned int CHUNK = 128 * 1024; + +/* This class manages a compressed chunk of data preceeded by + * a length count. + * + * It can handle having multiple chunks of data in the buffer + * at any time. + */ +class CountedBuffer : public classbase +{ + std::string buffer; /* Current buffer contents */ + unsigned int amount_expected; /* Amount of data expected */ + public: + CountedBuffer() + { + amount_expected = 0; + } + + /** Adds arbitrary compressed data to the buffer. + * - Binsry safe, of course. + */ + void AddData(unsigned char* data, int data_length) + { + buffer.append((const char*)data, data_length); + this->NextFrameSize(); + } + + /** Works out the size of the next compressed frame + */ + void NextFrameSize() + { + if ((!amount_expected) && (buffer.length() >= 4)) + { + /* We have enough to read an int - + * Yes, this is safe, but its ugly. Give me + * a nicer way to read 4 bytes from a binary + * stream, and push them into a 32 bit int, + * and i'll consider replacing this. + */ + amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]); + buffer = buffer.substr(4); + } + } + + /** Gets the next frame and returns its size, or returns + * zero if there isnt one available yet. + * A frame can contain multiple plaintext lines. + * - Binary safe. + */ + int GetFrame(unsigned char* frame, int maxsize) + { + if (amount_expected) + { + /* We know how much we're expecting... + * Do we have enough yet? + */ + if (buffer.length() >= amount_expected) + { + int j = 0; + for (unsigned int i = 0; i < amount_expected; i++, j++) + frame[i] = buffer[i]; + + buffer = buffer.substr(j); + amount_expected = 0; + NextFrameSize(); + return j; + } + } + /* Not enough for a frame yet, COME AGAIN! */ + return 0; + } +}; + +/** Represents an zipped connections extra data + */ +class izip_session : public classbase +{ + public: + z_stream c_stream; /* compression stream */ + z_stream d_stream; /* decompress stream */ + izip_status status; /* Connection status */ + int fd; /* File descriptor */ + CountedBuffer* inbuf; /* Holds input buffer */ + std::string outbuf; /* Holds output buffer */ +}; + +class ModuleZLib : public Module +{ + izip_session sessions[MAX_DESCRIPTORS]; + + /* Used for stats z extensions */ + float total_out_compressed; + float total_in_compressed; + float total_out_uncompressed; + float total_in_uncompressed; + + public: + + ModuleZLib(InspIRCd* Me) + : Module::Module(Me) + { + ServerInstance->PublishInterface("InspSocketHook", this); + + total_out_compressed = total_in_compressed = 0; + total_out_uncompressed = total_out_uncompressed = 0; + } + + virtual ~ModuleZLib() + { + ServerInstance->UnpublishInterface("InspSocketHook", this); + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1; + List[I_OnStats] = List[I_OnRequest] = 1; + } + + /* Handle InspSocketHook API requests */ + virtual char* OnRequest(Request* request) + { + ISHRequest* ISR = (ISHRequest*)request; + if (strcmp("IS_NAME", request->GetId()) == 0) + { + /* Return name */ + return "zip"; + } + else if (strcmp("IS_HOOK", request->GetId()) == 0) + { + /* Attach to an inspsocket */ + char* ret = "OK"; + try + { + ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + catch (ModuleException& e) + { + return NULL; + } + return ret; + } + else if (strcmp("IS_UNHOOK", request->GetId()) == 0) + { + /* Detatch from an inspsocket */ + return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL; + } + else if (strcmp("IS_HSDONE", request->GetId()) == 0) + { + /* Check for completion of handshake + * (actually, this module doesnt handshake) + */ + return "OK"; + } + else if (strcmp("IS_ATTACH", request->GetId()) == 0) + { + /* Attach certificate data to the inspsocket + * (this module doesnt do that, either) + */ + return NULL; + } + return NULL; + } + + /* Handle stats z (misc stats) */ + virtual int OnStats(char symbol, userrec* user, string_list &results) + { + if (symbol == 'z') + { + std::string sn = ServerInstance->Config->ServerName; + + /* Yeah yeah, i know, floats are ew. + * We used them here because we'd be casting to float anyway to do this maths, + * and also only floating point numbers can deal with the pretty large numbers + * involved in the total throughput of a server over a large period of time. + * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats + * can still hold more. + */ + float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100); + float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100); + + float total_compressed = total_in_compressed + total_out_compressed; + float total_uncompressed = total_in_uncompressed + total_out_uncompressed; + + float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100); + + char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF]; + + sprintf(outbound_ratio, "%3.2f%%", outbound_r); + sprintf(inbound_ratio, "%3.2f%%", inbound_r); + sprintf(combined_ratio, "%3.2f%%", total_r); + + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed)); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed)); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed)); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed)); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio); + results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio); + return 0; + } + + return 0; + } + + virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport) + { + izip_session* session = &sessions[fd]; + + /* allocate state and buffers */ + session->fd = fd; + session->status = IZIP_OPEN; + session->inbuf = new CountedBuffer(); + + session->c_stream.zalloc = (alloc_func)0; + session->c_stream.zfree = (free_func)0; + session->c_stream.opaque = (voidpf)0; + + session->d_stream.zalloc = (alloc_func)0; + session->d_stream.zfree = (free_func)0; + session->d_stream.opaque = (voidpf)0; + } + + virtual void OnRawSocketConnect(int fd) + { + /* Nothing special needs doing here compared to accept() */ + OnRawSocketAccept(fd, "", 0); + } + + virtual void OnRawSocketClose(int fd) + { + CloseSession(&sessions[fd]); + } + + virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) + { + /* Find the sockets session */ + izip_session* session = &sessions[fd]; + + if (session->status == IZIP_CLOSED) + return 0; + + unsigned char compr[CHUNK + 4]; + unsigned int offset = 0; + unsigned int total_size = 0; + + /* Read CHUNK bytes at a time to the buffer (usually 128k) */ + readresult = read(fd, compr, CHUNK); + + /* Did we get anything? */ + if (readresult > 0) + { + /* Add it to the frame queue */ + session->inbuf->AddData(compr, readresult); + total_in_compressed += readresult; + + /* Parse all completed frames */ + int size = 0; + while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0) + { + session->d_stream.next_in = (Bytef*)compr; + session->d_stream.avail_in = 0; + session->d_stream.next_out = (Bytef*)(buffer + offset); + + /* If we cant call this, well, we're boned. */ + if (inflateInit(&session->d_stream) != Z_OK) + return 0; + + while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size)) + { + session->d_stream.avail_in = session->d_stream.avail_out = 1; + if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END) + break; + } + + /* Stick a fork in me, i'm done */ + inflateEnd(&session->d_stream); + + /* Update counters and offsets */ + total_size += session->d_stream.total_out; + total_in_uncompressed += session->d_stream.total_out; + offset += session->d_stream.total_out; + } + + /* Null-terminate the buffer -- this doesnt harm binary data */ + buffer[total_size] = 0; + + /* Set the read size to the correct total size */ + readresult = total_size; + + } + return (readresult > 0); + } + + virtual int OnRawSocketWrite(int fd, const char* buffer, int count) + { + izip_session* session = &sessions[fd]; + int ocount = count; + + if (!count) /* Nothing to do! */ + return 0; + + if(session->status != IZIP_OPEN) + { + /* Seriously, wtf? */ + CloseSession(session); + return 0; + } + + unsigned char compr[CHUNK + 4]; + + /* Gentlemen, start your engines! */ + if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK) + { + CloseSession(session); + return 0; + } + + /* Set buffer sizes (we reserve 4 bytes at the start of the + * buffer for the length counters) + */ + session->c_stream.next_in = (Bytef*)buffer; + session->c_stream.next_out = compr + 4; + + /* Compress the text */ + while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK)) + { + session->c_stream.avail_in = session->c_stream.avail_out = 1; + if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK) + { + CloseSession(session); + return 0; + } + } + /* Finish the stream */ + for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1); + deflateEnd(&session->c_stream); + + total_out_uncompressed += ocount; + total_out_compressed += session->c_stream.total_out; + + /** Assemble the frame length onto the frame, in network byte order */ + compr[0] = (session->c_stream.total_out >> 24); + compr[1] = (session->c_stream.total_out >> 16); + compr[2] = (session->c_stream.total_out >> 8); + compr[3] = (session->c_stream.total_out & 0xFF); + + /* Add compressed data plus leading length to the output buffer - + * Note, we may have incomplete half-sent frames in here. + */ + session->outbuf.append((const char*)compr, session->c_stream.total_out + 4); + + /* Lets see how much we can send out */ + int ret = write(fd, session->outbuf.data(), session->outbuf.length()); + + /* Check for errors, and advance the buffer if any was sent */ + if (ret > 0) + session->outbuf = session->outbuf.substr(ret); + else if (ret < 1) + { + if (ret == -1) + { + if (errno == EAGAIN) + return 0; + else + { + session->outbuf.clear(); + return 0; + } + } + else + { + session->outbuf.clear(); + return 0; + } + } + + /* ALL LIES the lot of it, we havent really written + * this amount, but the layer above doesnt need to know. + */ + return ocount; + } + + void CloseSession(izip_session* session) + { + if (session->status == IZIP_OPEN) + { + session->status = IZIP_CLOSED; + session->outbuf.clear(); + delete session->inbuf; + } + } + +}; + +MODULE_INIT(ModuleZLib); + diff --git a/src/modules/httpclient.h b/src/modules/httpclient.h index 109bfa666..c5e84261f 100644 --- a/src/modules/httpclient.h +++ b/src/modules/httpclient.h @@ -1 +1,127 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "base.h" #ifndef HTTPCLIENT_H__ #define HTTPCLIENT_H__ #include #include typedef std::map HeaderMap; const char* HTTP_CLIENT_RESPONSE = "HTTPCLIENT_RESPONSE"; const char* HTTP_CLIENT_REQUEST = "HTTPCLIENT_REQUEST"; /** This class represents an outgoing HTTP request */ class HTTPClientRequest : public Request { protected: std::string url; InspIRCd *Instance; Module *src; HeaderMap Headers; public: HTTPClientRequest(InspIRCd *Instance, Module *src, Module* target, const std::string &url) : Request(src, target, HTTP_CLIENT_REQUEST), url(url), Instance(Instance), src(src) { Headers["User-Agent"] = "InspIRCd (m_http_client.so)"; Headers["Connection"] = "Close"; Headers["Accept"] = "*/*"; } HTTPClientRequest() : Request(NULL, NULL, HTTP_CLIENT_REQUEST) { } const std::string &GetURL() { return url; } void AddHeader(std::string &header, std::string &data) { Headers[header] = data; } void DeleteHeader(std::string &header) { Headers.erase(header); } HeaderMap GetHeaders() { return Headers; } }; class HTTPClientResponse : public Request { protected: friend class HTTPSocket; std::string url; std::string data; int response; std::string responsestr; HeaderMap Headers; public: HTTPClientResponse(Module* src, Module* target, std::string &url, int response, std::string responsestr) : Request(src, target, HTTP_CLIENT_RESPONSE), url(url), response(response), responsestr(responsestr) { } HTTPClientResponse() : Request(NULL, NULL, HTTP_CLIENT_RESPONSE) { } void SetData(const std::string &ndata) { data = ndata; } void AddHeader(const std::string &header, const std::string &data) { Headers[header] = data; } const std::string &GetURL() { return url; } const std::string &GetData() { return data; } int GetResponse(std::string &str) { str = responsestr; return response; } std::string GetHeader(const std::string &header) { HeaderMap::iterator i = Headers.find(header); if (i != Headers.end()) return i->second; else return ""; } }; #endif \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "base.h" + +#ifndef HTTPCLIENT_H__ +#define HTTPCLIENT_H__ + +#include +#include + +typedef std::map HeaderMap; + +const char* HTTP_CLIENT_RESPONSE = "HTTPCLIENT_RESPONSE"; +const char* HTTP_CLIENT_REQUEST = "HTTPCLIENT_REQUEST"; + +/** This class represents an outgoing HTTP request + */ +class HTTPClientRequest : public Request +{ + protected: + std::string url; + InspIRCd *Instance; + Module *src; + HeaderMap Headers; + public: + HTTPClientRequest(InspIRCd *Instance, Module *src, Module* target, const std::string &url) + : Request(src, target, HTTP_CLIENT_REQUEST), url(url), Instance(Instance), src(src) + { + Headers["User-Agent"] = "InspIRCd (m_http_client.so)"; + Headers["Connection"] = "Close"; + Headers["Accept"] = "*/*"; + } + + HTTPClientRequest() : Request(NULL, NULL, HTTP_CLIENT_REQUEST) + { + } + + const std::string &GetURL() + { + return url; + } + + void AddHeader(std::string &header, std::string &data) + { + Headers[header] = data; + } + + void DeleteHeader(std::string &header) + { + Headers.erase(header); + } + + HeaderMap GetHeaders() + { + return Headers; + } +}; + +class HTTPClientResponse : public Request +{ + protected: + friend class HTTPSocket; + + std::string url; + std::string data; + int response; + std::string responsestr; + HeaderMap Headers; + public: + HTTPClientResponse(Module* src, Module* target, std::string &url, int response, std::string responsestr) + : Request(src, target, HTTP_CLIENT_RESPONSE), url(url), response(response), responsestr(responsestr) + { + } + + HTTPClientResponse() : Request(NULL, NULL, HTTP_CLIENT_RESPONSE) + { + } + + void SetData(const std::string &ndata) + { + data = ndata; + } + + void AddHeader(const std::string &header, const std::string &data) + { + Headers[header] = data; + } + + const std::string &GetURL() + { + return url; + } + + const std::string &GetData() + { + return data; + } + + int GetResponse(std::string &str) + { + str = responsestr; + return response; + } + + std::string GetHeader(const std::string &header) + { + HeaderMap::iterator i = Headers.find(header); + + if (i != Headers.end()) + return i->second; + else + return ""; + } +}; + +#endif diff --git a/src/modules/httpd.h b/src/modules/httpd.h index 32bac757f..a8b0bafcd 100644 --- a/src/modules/httpd.h +++ b/src/modules/httpd.h @@ -1 +1,166 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "base.h" #ifndef __HTTPD_H__ #define __HTTPD_H__ #include #include /** This class represents a HTTP request. * It will be sent to all modules as the data section of * an Event. */ class HTTPRequest : public classbase { protected: std::string type; std::string document; std::string ipaddr; std::string postdata; std::stringstream* headers; public: /** A socket pointer, which you must return in your HTTPDocument class * if you reply to this request. */ void* 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(const std::string &request_type, const std::string &uri, std::stringstream* hdr, void* opaque, const std::string &ip, const std::string &pdata) : type(request_type), document(uri), ipaddr(ip), postdata(pdata), headers(hdr), sock(opaque) { } /** Get headers. * All the headers for the web request are returned, as a pointer to a stringstream. * @return The header information */ std::stringstream* GetHeaders() { return headers; } /** 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 HTTPDocument : public classbase { protected: std::stringstream* document; int responsecode; std::string extraheaders; public: /** The socket pointer from an earlier HTTPRequest */ void* sock; /** 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. */ HTTPDocument(void* opaque, std::stringstream* doc, int response, const std::string &extra) : document(doc), responsecode(response), extraheaders(extra), sock(opaque) { } /** Get the document text. * @return The document text */ std::stringstream* GetDocument() { return this->document; } /** Get the document size. * @return the size of the document text in bytes */ unsigned long GetDocumentSize() { return this->document->str().length(); } /** Get the response code. * @return The response code */ int GetResponseCode() { return this->responsecode; } /** Get the headers. * @return The header text, headers seperated by carriage return and linefeed. */ std::string& GetExtraHeaders() { return this->extraheaders; } }; #endif \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "base.h" + +#ifndef __HTTPD_H__ +#define __HTTPD_H__ + +#include +#include + +/** This class represents a HTTP request. + * It will be sent to all modules as the data section of + * an Event. + */ +class HTTPRequest : public classbase +{ + protected: + + std::string type; + std::string document; + std::string ipaddr; + std::string postdata; + std::stringstream* headers; + + public: + + /** A socket pointer, which you must return in your HTTPDocument class + * if you reply to this request. + */ + void* 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(const std::string &request_type, const std::string &uri, std::stringstream* hdr, void* opaque, const std::string &ip, const std::string &pdata) + : type(request_type), document(uri), ipaddr(ip), postdata(pdata), headers(hdr), sock(opaque) + { + } + + /** Get headers. + * All the headers for the web request are returned, as a pointer to a stringstream. + * @return The header information + */ + std::stringstream* GetHeaders() + { + return headers; + } + + /** 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 HTTPDocument : public classbase +{ + protected: + + std::stringstream* document; + int responsecode; + std::string extraheaders; + + public: + + /** The socket pointer from an earlier HTTPRequest + */ + void* sock; + + /** 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. + */ + HTTPDocument(void* opaque, std::stringstream* doc, int response, const std::string &extra) : document(doc), responsecode(response), extraheaders(extra), sock(opaque) + { + } + + /** Get the document text. + * @return The document text + */ + std::stringstream* GetDocument() + { + return this->document; + } + + /** Get the document size. + * @return the size of the document text in bytes + */ + unsigned long GetDocumentSize() + { + return this->document->str().length(); + } + + /** Get the response code. + * @return The response code + */ + int GetResponseCode() + { + return this->responsecode; + } + + /** Get the headers. + * @return The header text, headers seperated by carriage return and linefeed. + */ + std::string& GetExtraHeaders() + { + return this->extraheaders; + } +}; + +#endif + diff --git a/src/modules/m_alias.cpp b/src/modules/m_alias.cpp index 039aeed92..94c64b405 100644 --- a/src/modules/m_alias.cpp +++ b/src/modules/m_alias.cpp @@ -1 +1,272 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "wildcard.h" /* $ModDesc: Provides aliases of commands. */ /** An alias definition */ class Alias : public classbase { public: /** The text of the alias command */ irc::string text; /** Text to replace with */ std::string replace_with; /** Nickname required to perform alias */ std::string requires; /** Alias requires ulined server */ bool uline; /** Requires oper? */ bool operonly; /* is case sensitive params */ bool case_sensitive; /** Format that must be matched for use */ std::string format; }; class ModuleAlias : public Module { private: /** We cant use a map, there may be multiple aliases with the same name */ std::vector Aliases; std::map AliasMap; std::vector pars; virtual void ReadAliases() { ConfigReader MyConf(ServerInstance); Aliases.clear(); AliasMap.clear(); for (int i = 0; i < MyConf.Enumerate("alias"); i++) { Alias a; std::string txt; txt = MyConf.ReadValue("alias", "text", i); a.text = txt.c_str(); a.replace_with = MyConf.ReadValue("alias", "replace", i, true); a.requires = MyConf.ReadValue("alias", "requires", i); a.uline = MyConf.ReadFlag("alias", "uline", i); a.operonly = MyConf.ReadFlag("alias", "operonly", i); a.format = MyConf.ReadValue("alias", "format", i); a.case_sensitive = MyConf.ReadFlag("alias", "matchcase", i); Aliases.push_back(a); AliasMap[txt] = 1; } } public: ModuleAlias(InspIRCd* Me) : Module(Me) { ReadAliases(); pars.resize(127); } void Implements(char* List) { List[I_OnPreCommand] = List[I_OnRehash] = 1; } virtual ~ModuleAlias() { } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } std::string GetVar(std::string varname, const std::string &original_line) { irc::spacesepstream ss(original_line); varname.erase(varname.begin()); int index = *(varname.begin()) - 48; varname.erase(varname.begin()); bool everything_after = (varname == "-"); std::string word; for (int j = 0; j < index; j++) word = ss.GetToken(); if (everything_after) { std::string more = "*"; while ((more = ss.GetToken()) != "") { word.append(" "); word.append(more); } } return word; } void SearchAndReplace(std::string& newline, const std::string &find, const std::string &replace) { std::string::size_type x = newline.find(find); while (x != std::string::npos) { newline.erase(x, find.length()); newline.insert(x, replace); x = newline.find(find); } } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { userrec *u = NULL; /* If theyre not registered yet, we dont want * to know. */ if (user->registered != REG_ALL) return 0; /* We dont have any commands looking like this, dont bother with the loop */ if (AliasMap.find(command) == AliasMap.end()) return 0; 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()); while (*(compare.c_str()) == ' ') compare.erase(compare.begin()); std::string safe(original_line); /* Escape out any $ symbols in the user provided text */ SearchAndReplace(safe, "$", "\r"); for (unsigned int i = 0; i < Aliases.size(); i++) { if (Aliases[i].text == c) { /* Does it match the pattern? */ if (!Aliases[i].format.empty()) { if (!match(Aliases[i].case_sensitive, compare.c_str(), Aliases[i].format.c_str())) continue; } if ((Aliases[i].operonly) && (!IS_OPER(user))) return 0; if (!Aliases[i].requires.empty()) { u = ServerInstance->FindNick(Aliases[i].requires); if (!u) { user->WriteServ("401 "+std::string(user->nick)+" "+Aliases[i].requires+" :is currently unavailable. Please try again later."); return 1; } } if ((u != NULL) && (!Aliases[i].requires.empty()) && (Aliases[i].uline)) { if (!ServerInstance->ULine(u->server)) { ServerInstance->WriteOpers("*** NOTICE -- Service "+Aliases[i].requires+" required by alias "+std::string(Aliases[i].text.c_str())+" is not on a u-lined server, possibly underhanded antics detected!"); user->WriteServ("401 "+std::string(user->nick)+" "+Aliases[i].requires+" :is an imposter! Please inform an IRC operator as soon as possible."); return 1; } } /* Now, search and replace in a copy of the original_line, replacing $1 through $9 and $1- etc */ std::string::size_type crlf = Aliases[i].replace_with.find('\n'); if (crlf == std::string::npos) { DoCommand(Aliases[i].replace_with, user, safe); return 1; } else { irc::sepstream commands(Aliases[i].replace_with, '\n'); std::string command = "*"; while ((command = commands.GetToken()) != "") { DoCommand(command, user, safe); } return 1; } } } return 0; } void DoCommand(std::string newline, userrec* user, const std::string &original_line) { for (int v = 1; v < 10; v++) { std::string var = "$"; var.append(ConvToStr(v)); var.append("-"); std::string::size_type x = newline.find(var); while (x != std::string::npos) { newline.erase(x, var.length()); newline.insert(x, GetVar(var, original_line)); x = newline.find(var); } var = "$"; var.append(ConvToStr(v)); x = newline.find(var); while (x != std::string::npos) { newline.erase(x, var.length()); newline.insert(x, GetVar(var, original_line)); x = newline.find(var); } } /* Special variables */ SearchAndReplace(newline, "$nick", user->nick); SearchAndReplace(newline, "$ident", user->ident); SearchAndReplace(newline, "$host", user->host); SearchAndReplace(newline, "$vhost", user->dhost); /* Unescape any variable names in the user text before sending */ SearchAndReplace(newline, "\r", "$"); irc::tokenstream ss(newline); const char* parv[127]; int x = 0; while (ss.GetToken(pars[x])) { parv[x] = pars[x].c_str(); x++; } ServerInstance->Parser->CallHandler(parv[0], &parv[1], x-1, user); } virtual void OnRehash(userrec* user, const std::string ¶meter) { ReadAliases(); } }; MODULE_INIT(ModuleAlias) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "wildcard.h" + +/* $ModDesc: Provides aliases of commands. */ + +/** An alias definition + */ +class Alias : public classbase +{ + public: + /** The text of the alias command */ + irc::string text; + /** Text to replace with */ + std::string replace_with; + /** Nickname required to perform alias */ + std::string requires; + /** Alias requires ulined server */ + bool uline; + /** Requires oper? */ + bool operonly; + /* is case sensitive params */ + bool case_sensitive; + /** Format that must be matched for use */ + std::string format; +}; + +class ModuleAlias : public Module +{ + private: + /** We cant use a map, there may be multiple aliases with the same name */ + std::vector Aliases; + std::map AliasMap; + std::vector pars; + + virtual void ReadAliases() + { + ConfigReader MyConf(ServerInstance); + + Aliases.clear(); + AliasMap.clear(); + for (int i = 0; i < MyConf.Enumerate("alias"); i++) + { + Alias a; + std::string txt; + txt = MyConf.ReadValue("alias", "text", i); + a.text = txt.c_str(); + a.replace_with = MyConf.ReadValue("alias", "replace", i, true); + a.requires = MyConf.ReadValue("alias", "requires", i); + a.uline = MyConf.ReadFlag("alias", "uline", i); + a.operonly = MyConf.ReadFlag("alias", "operonly", i); + a.format = MyConf.ReadValue("alias", "format", i); + a.case_sensitive = MyConf.ReadFlag("alias", "matchcase", i); + Aliases.push_back(a); + AliasMap[txt] = 1; + } + } + + public: + + ModuleAlias(InspIRCd* Me) + : Module(Me) + { + ReadAliases(); + pars.resize(127); + } + + void Implements(char* List) + { + List[I_OnPreCommand] = List[I_OnRehash] = 1; + } + + virtual ~ModuleAlias() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + + std::string GetVar(std::string varname, const std::string &original_line) + { + irc::spacesepstream ss(original_line); + varname.erase(varname.begin()); + int index = *(varname.begin()) - 48; + varname.erase(varname.begin()); + bool everything_after = (varname == "-"); + std::string word; + + for (int j = 0; j < index; j++) + word = ss.GetToken(); + + if (everything_after) + { + std::string more = "*"; + while ((more = ss.GetToken()) != "") + { + word.append(" "); + word.append(more); + } + } + + return word; + } + + void SearchAndReplace(std::string& newline, const std::string &find, const std::string &replace) + { + std::string::size_type x = newline.find(find); + while (x != std::string::npos) + { + newline.erase(x, find.length()); + newline.insert(x, replace); + x = newline.find(find); + } + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + userrec *u = NULL; + + /* If theyre not registered yet, we dont want + * to know. + */ + if (user->registered != REG_ALL) + return 0; + + /* We dont have any commands looking like this, dont bother with the loop */ + if (AliasMap.find(command) == AliasMap.end()) + return 0; + + 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()); + while (*(compare.c_str()) == ' ') + compare.erase(compare.begin()); + + std::string safe(original_line); + + /* Escape out any $ symbols in the user provided text */ + + SearchAndReplace(safe, "$", "\r"); + + for (unsigned int i = 0; i < Aliases.size(); i++) + { + if (Aliases[i].text == c) + { + /* Does it match the pattern? */ + if (!Aliases[i].format.empty()) + { + if (!match(Aliases[i].case_sensitive, compare.c_str(), Aliases[i].format.c_str())) + continue; + } + + if ((Aliases[i].operonly) && (!IS_OPER(user))) + return 0; + + if (!Aliases[i].requires.empty()) + { + u = ServerInstance->FindNick(Aliases[i].requires); + if (!u) + { + user->WriteServ("401 "+std::string(user->nick)+" "+Aliases[i].requires+" :is currently unavailable. Please try again later."); + return 1; + } + } + if ((u != NULL) && (!Aliases[i].requires.empty()) && (Aliases[i].uline)) + { + if (!ServerInstance->ULine(u->server)) + { + ServerInstance->WriteOpers("*** NOTICE -- Service "+Aliases[i].requires+" required by alias "+std::string(Aliases[i].text.c_str())+" is not on a u-lined server, possibly underhanded antics detected!"); + user->WriteServ("401 "+std::string(user->nick)+" "+Aliases[i].requires+" :is an imposter! Please inform an IRC operator as soon as possible."); + return 1; + } + } + + /* Now, search and replace in a copy of the original_line, replacing $1 through $9 and $1- etc */ + + std::string::size_type crlf = Aliases[i].replace_with.find('\n'); + + if (crlf == std::string::npos) + { + DoCommand(Aliases[i].replace_with, user, safe); + return 1; + } + else + { + irc::sepstream commands(Aliases[i].replace_with, '\n'); + std::string command = "*"; + while ((command = commands.GetToken()) != "") + { + DoCommand(command, user, safe); + } + return 1; + } + } + } + return 0; + } + + void DoCommand(std::string newline, userrec* user, const std::string &original_line) + { + for (int v = 1; v < 10; v++) + { + std::string var = "$"; + var.append(ConvToStr(v)); + var.append("-"); + std::string::size_type x = newline.find(var); + + while (x != std::string::npos) + { + newline.erase(x, var.length()); + newline.insert(x, GetVar(var, original_line)); + x = newline.find(var); + } + + var = "$"; + var.append(ConvToStr(v)); + x = newline.find(var); + + while (x != std::string::npos) + { + newline.erase(x, var.length()); + newline.insert(x, GetVar(var, original_line)); + x = newline.find(var); + } + } + + /* Special variables */ + SearchAndReplace(newline, "$nick", user->nick); + SearchAndReplace(newline, "$ident", user->ident); + SearchAndReplace(newline, "$host", user->host); + SearchAndReplace(newline, "$vhost", user->dhost); + + /* Unescape any variable names in the user text before sending */ + SearchAndReplace(newline, "\r", "$"); + + irc::tokenstream ss(newline); + const char* parv[127]; + int x = 0; + + while (ss.GetToken(pars[x])) + { + parv[x] = pars[x].c_str(); + x++; + } + + ServerInstance->Parser->CallHandler(parv[0], &parv[1], x-1, user); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ReadAliases(); + } +}; + +MODULE_INIT(ModuleAlias) diff --git a/src/modules/m_alltime.cpp b/src/modules/m_alltime.cpp index 6a3f27ba8..97ab6a3fe 100644 --- a/src/modules/m_alltime.cpp +++ b/src/modules/m_alltime.cpp @@ -1 +1,83 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "modules.h" /* $ModDesc: Display timestamps from all servers connected to the network */ class cmd_alltime : public command_t { public: cmd_alltime(InspIRCd *Instance) : command_t(Instance, "ALLTIME", 'o', 0) { this->source = "m_alltime.so"; syntax.clear(); } CmdResult Handle(const char **parameters, int pcnt, userrec *user) { char fmtdate[64]; char fmtdate2[64]; time_t now = ServerInstance->Time(false); strftime(fmtdate, sizeof(fmtdate), "%F %T", gmtime(&now)); now = ServerInstance->Time(true); strftime(fmtdate2, sizeof(fmtdate2), "%F %T", gmtime(&now)); int delta = ServerInstance->GetTimeDelta(); string msg = ":" + string(ServerInstance->Config->ServerName) + " NOTICE " + user->nick + " :System time for " + ServerInstance->Config->ServerName + " is: " + fmtdate + " (delta " + ConvToStr(delta) + " seconds): Time with delta: "+ fmtdate2; if (IS_LOCAL(user)) { user->Write(msg); } else { deque params; params.push_back(user->nick); params.push_back(msg); Event ev((char *) ¶ms, NULL, "send_push"); ev.Send(ServerInstance); } /* we want this routed out! */ return CMD_SUCCESS; } }; class Modulealltime : public Module { cmd_alltime *mycommand; public: Modulealltime(InspIRCd *Me) : Module(Me) { mycommand = new cmd_alltime(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~Modulealltime() { } virtual Version GetVersion() { return Version(1, 0, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); } }; MODULE_INIT(Modulealltime) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "modules.h" + +/* $ModDesc: Display timestamps from all servers connected to the network */ + +class cmd_alltime : public command_t +{ + public: + cmd_alltime(InspIRCd *Instance) : command_t(Instance, "ALLTIME", 'o', 0) + { + this->source = "m_alltime.so"; + syntax.clear(); + } + + CmdResult Handle(const char **parameters, int pcnt, userrec *user) + { + char fmtdate[64]; + char fmtdate2[64]; + time_t now = ServerInstance->Time(false); + strftime(fmtdate, sizeof(fmtdate), "%F %T", gmtime(&now)); + now = ServerInstance->Time(true); + strftime(fmtdate2, sizeof(fmtdate2), "%F %T", gmtime(&now)); + + int delta = ServerInstance->GetTimeDelta(); + + string msg = ":" + string(ServerInstance->Config->ServerName) + " NOTICE " + user->nick + " :System time for " + + ServerInstance->Config->ServerName + " is: " + fmtdate + " (delta " + ConvToStr(delta) + " seconds): Time with delta: "+ fmtdate2; + + if (IS_LOCAL(user)) + { + user->Write(msg); + } + else + { + deque params; + params.push_back(user->nick); + params.push_back(msg); + Event ev((char *) ¶ms, NULL, "send_push"); + ev.Send(ServerInstance); + } + + /* we want this routed out! */ + return CMD_SUCCESS; + } +}; + + +class Modulealltime : public Module +{ + cmd_alltime *mycommand; + public: + Modulealltime(InspIRCd *Me) + : Module(Me) + { + mycommand = new cmd_alltime(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~Modulealltime() + { + } + + virtual Version GetVersion() + { + return Version(1, 0, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); + } + +}; + +MODULE_INIT(Modulealltime) diff --git a/src/modules/m_antibear.cpp b/src/modules/m_antibear.cpp index d95c70282..2718cbb4c 100644 --- a/src/modules/m_antibear.cpp +++ b/src/modules/m_antibear.cpp @@ -1 +1,78 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "xline.h" /* $ModDesc: Sends a numeric on connect which cripples a common type of trojan/spambot */ class ModuleAntiBear : public Module { private: public: ModuleAntiBear(InspIRCd* Me) : Module(Me) { } virtual ~ModuleAntiBear() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } void Implements(char* List) { List[I_OnUserRegister] = List[I_OnPreCommand] = 1; } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { if (command == "NOTICE" && !validated && pcnt > 1 && user->GetExt("antibear_timewait")) { if (!strncmp(parameters[1], "\1TIME Mon May 01 18:54:20 2006", 30)) { if (ServerInstance->XLines->add_zline(86400, ServerInstance->Config->ServerName, "Unless you're stuck in a time warp, you appear to be a bear bot!", user->MakeHostIP())) { ServerInstance->XLines->apply_lines(APPLY_ZLINES); FOREACH_MOD(I_OnAddGLine,OnAddZLine(86400, NULL, "Unless you're stuck in a time warp, you appear to be a bear bot!", user->MakeHostIP())); return 1; } } user->Shrink("antibear_timewait"); // Block the command, so the user doesn't receive a no such nick notice return 1; } return 0; } virtual int OnUserRegister(userrec* user) { user->WriteServ("439 %s :This server has anti-spambot mechanisms enabled.", user->nick); user->WriteServ("931 %s :Malicious bots, spammers, and other automated systems of dubious origin are NOT welcome here.", user->nick); user->WriteServ("PRIVMSG %s :\1TIME\1", user->nick); user->Extend("antibear_timewait"); return 0; } }; MODULE_INIT(ModuleAntiBear) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "xline.h" + +/* $ModDesc: Sends a numeric on connect which cripples a common type of trojan/spambot */ + +class ModuleAntiBear : public Module +{ + private: + + public: + ModuleAntiBear(InspIRCd* Me) : Module(Me) + { + + } + + virtual ~ModuleAntiBear() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + + void Implements(char* List) + { + List[I_OnUserRegister] = List[I_OnPreCommand] = 1; + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + if (command == "NOTICE" && !validated && pcnt > 1 && user->GetExt("antibear_timewait")) + { + if (!strncmp(parameters[1], "\1TIME Mon May 01 18:54:20 2006", 30)) + { + if (ServerInstance->XLines->add_zline(86400, ServerInstance->Config->ServerName, "Unless you're stuck in a time warp, you appear to be a bear bot!", user->MakeHostIP())) + { + ServerInstance->XLines->apply_lines(APPLY_ZLINES); + FOREACH_MOD(I_OnAddGLine,OnAddZLine(86400, NULL, "Unless you're stuck in a time warp, you appear to be a bear bot!", user->MakeHostIP())); + return 1; + } + } + + user->Shrink("antibear_timewait"); + // Block the command, so the user doesn't receive a no such nick notice + return 1; + } + + return 0; + } + + virtual int OnUserRegister(userrec* user) + { + user->WriteServ("439 %s :This server has anti-spambot mechanisms enabled.", user->nick); + user->WriteServ("931 %s :Malicious bots, spammers, and other automated systems of dubious origin are NOT welcome here.", user->nick); + user->WriteServ("PRIVMSG %s :\1TIME\1", user->nick); + user->Extend("antibear_timewait"); + return 0; + } +}; + +MODULE_INIT(ModuleAntiBear) diff --git a/src/modules/m_antibottler.cpp b/src/modules/m_antibottler.cpp index 907cfb39d..3aa5592cc 100644 --- a/src/modules/m_antibottler.cpp +++ b/src/modules/m_antibottler.cpp @@ -1 +1,99 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Changes the ident of connecting bottler clients to 'bottler' */ class ModuleAntiBottler : public Module { public: ModuleAntiBottler(InspIRCd* Me) : Module(Me) { } void Implements(char* List) { List[I_OnPreCommand] = 1; } virtual ~ModuleAntiBottler() { } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { char data[MAXBUF]; strlcpy(data,original_line.c_str(),MAXBUF); bool not_bottler = false; if (!strncmp(data,"user ",5)) { for (char* j = data; *j; j++) { if (*j == ':') break; if (*j == '"') { not_bottler = true; } } // Bug Fix (#14) -- FCS if (!(data) || !(*data)) return 0; strtok(data," "); char *ident = strtok(NULL," "); char *local = strtok(NULL," "); char *remote = strtok(NULL," :"); char *gecos = strtok(NULL,"\r\n"); if (!ident || !local || !remote || !gecos) return 0; for (char* j = remote; *j; j++) { if (((*j < '0') || (*j > '9')) && (*j != '.')) { not_bottler = true; } } if (!not_bottler) { std::string strgecos = std::string(gecos) + "[Possible bottler, ident: " + std::string(ident) + "]"; const char* modified[4]; modified[0] = "bottler"; modified[1] = local; modified[2] = remote; modified[3] = strgecos.c_str(); ServerInstance->Parser->CallHandler("USER", modified, 4, user); return 1; } } return 0; } }; MODULE_INIT(ModuleAntiBottler) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Changes the ident of connecting bottler clients to 'bottler' */ + +class ModuleAntiBottler : public Module +{ + public: + ModuleAntiBottler(InspIRCd* Me) + : Module(Me) + { + + } + + void Implements(char* List) + { + List[I_OnPreCommand] = 1; + } + + + virtual ~ModuleAntiBottler() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + char data[MAXBUF]; + strlcpy(data,original_line.c_str(),MAXBUF); + bool not_bottler = false; + if (!strncmp(data,"user ",5)) + { + for (char* j = data; *j; j++) + { + if (*j == ':') + break; + + if (*j == '"') + { + not_bottler = true; + } + } + // Bug Fix (#14) -- FCS + if (!(data) || !(*data)) + return 0; + + strtok(data," "); + char *ident = strtok(NULL," "); + char *local = strtok(NULL," "); + char *remote = strtok(NULL," :"); + char *gecos = strtok(NULL,"\r\n"); + + if (!ident || !local || !remote || !gecos) + return 0; + + for (char* j = remote; *j; j++) + { + if (((*j < '0') || (*j > '9')) && (*j != '.')) + { + not_bottler = true; + } + } + + if (!not_bottler) + { + std::string strgecos = std::string(gecos) + "[Possible bottler, ident: " + std::string(ident) + "]"; + const char* modified[4]; + modified[0] = "bottler"; + modified[1] = local; + modified[2] = remote; + modified[3] = strgecos.c_str(); + ServerInstance->Parser->CallHandler("USER", modified, 4, user); + return 1; + } + } + return 0; + } +}; + +MODULE_INIT(ModuleAntiBottler) diff --git a/src/modules/m_auditorium.cpp b/src/modules/m_auditorium.cpp index 419738ea7..6d709e431 100644 --- a/src/modules/m_auditorium.cpp +++ b/src/modules/m_auditorium.cpp @@ -1 +1,191 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Allows for auditorium channels (+u) where nobody can see others joining and parting or the nick list */ class AuditoriumMode : public ModeHandler { public: AuditoriumMode(InspIRCd* Instance) : ModeHandler(Instance, 'u', 0, 0, false, MODETYPE_CHANNEL, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (channel->IsModeSet('u') != adding) { if (IS_LOCAL(source) && (channel->GetStatus(source) < STATUS_OP)) { source->WriteServ("482 %s %s :Only channel operators may %sset channel mode +u", source->nick, channel->name, adding ? "" : "un"); return MODEACTION_DENY; } else { channel->SetMode('u', adding); return MODEACTION_ALLOW; } } else { return MODEACTION_DENY; } } }; class ModuleAuditorium : public Module { private: AuditoriumMode* aum; bool ShowOps; CUList nl; CUList except_list; public: ModuleAuditorium(InspIRCd* Me) : Module(Me) { aum = new AuditoriumMode(ServerInstance); if (!ServerInstance->AddMode(aum, 'u')) throw ModuleException("Could not add new modes!"); OnRehash(NULL, ""); } virtual ~ModuleAuditorium() { ServerInstance->Modes->DelMode(aum); DELETE(aum); } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader conf(ServerInstance); ShowOps = conf.ReadFlag("auditorium", "showops", 0); } Priority Prioritize() { /* To ensure that we get priority over namesx for names list generation on +u channels */ return (Priority)ServerInstance->PriorityBefore("m_namesx.so"); } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); } void Implements(char* List) { List[I_OnUserJoin] = List[I_OnUserPart] = List[I_OnUserKick] = List[I_OnUserQuit] = List[I_OnUserList] = List[I_OnRehash] = 1; } virtual int OnUserList(userrec* user, chanrec* Ptr, CUList* &nameslist) { if (Ptr->IsModeSet('u')) { if (ShowOps) { /* Leave the names list alone, theyre an op * doing /names on the channel after joining it */ if (Ptr->GetStatus(user) >= STATUS_OP) { nameslist = Ptr->GetUsers(); return 0; } /* Show all the opped users */ nl = *(Ptr->GetOppedUsers()); nl[user] = user->nick; nameslist = &nl; return 0; } else { /* HELLOOO, IS ANYBODY THERE? -- nope, just us. */ user->WriteServ("353 %s = %s :%s", user->nick, Ptr->name, user->nick); user->WriteServ("366 %s %s :End of /NAMES list.", user->nick, Ptr->name); return 1; } } return 0; } virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) { if (channel->IsModeSet('u')) { silent = true; /* Because we silenced the event, make sure it reaches the user whos joining (but only them of course) */ user->WriteFrom(user, "JOIN %s", channel->name); if (ShowOps) channel->WriteAllExcept(user, false, channel->GetStatus(user) >= STATUS_OP ? 0 : '@', except_list, "JOIN %s", channel->name); } } void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent) { if (channel->IsModeSet('u')) { silent = true; /* Because we silenced the event, make sure it reaches the user whos leaving (but only them of course) */ user->WriteFrom(user, "PART %s%s%s", channel->name, partmessage.empty() ? "" : " :", partmessage.empty() ? "" : partmessage.c_str()); if (ShowOps) { channel->WriteAllExcept(user, false, channel->GetStatus(user) >= STATUS_OP ? 0 : '@', except_list, "PART %s%s%s", channel->name, partmessage.empty() ? "" : " :", partmessage.empty() ? "" : partmessage.c_str()); } } } void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent) { if (chan->IsModeSet('u')) { silent = true; /* Send silenced event only to the user being kicked and the user doing the kick */ source->WriteFrom(source, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); if (ShowOps) chan->WriteAllExcept(source, false, chan->GetStatus(source) >= STATUS_OP ? 0 : '@', except_list, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); else user->WriteFrom(source, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); } } void OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message) { command_t* parthandler = ServerInstance->Parser->GetHandler("PART"); std::vector to_leave; const char* parameters[2]; if (parthandler) { for (UCListIter f = user->chans.begin(); f != user->chans.end(); f++) { if (f->first->IsModeSet('u')) to_leave.push_back(f->first->name); } /* We cant do this neatly in one loop, as we are modifying the map we are iterating */ for (std::vector::iterator n = to_leave.begin(); n != to_leave.end(); n++) { parameters[0] = n->c_str(); /* This triggers our OnUserPart, above, making the PART silent */ parthandler->Handle(parameters, 1, user); } } } }; MODULE_INIT(ModuleAuditorium) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Allows for auditorium channels (+u) where nobody can see others joining and parting or the nick list */ + +class AuditoriumMode : public ModeHandler +{ + public: + AuditoriumMode(InspIRCd* Instance) : ModeHandler(Instance, 'u', 0, 0, false, MODETYPE_CHANNEL, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (channel->IsModeSet('u') != adding) + { + if (IS_LOCAL(source) && (channel->GetStatus(source) < STATUS_OP)) + { + source->WriteServ("482 %s %s :Only channel operators may %sset channel mode +u", source->nick, channel->name, adding ? "" : "un"); + return MODEACTION_DENY; + } + else + { + channel->SetMode('u', adding); + return MODEACTION_ALLOW; + } + } + else + { + return MODEACTION_DENY; + } + } +}; + +class ModuleAuditorium : public Module +{ + private: + AuditoriumMode* aum; + bool ShowOps; + CUList nl; + CUList except_list; + public: + ModuleAuditorium(InspIRCd* Me) + : Module(Me) + { + aum = new AuditoriumMode(ServerInstance); + if (!ServerInstance->AddMode(aum, 'u')) + throw ModuleException("Could not add new modes!"); + OnRehash(NULL, ""); + } + + virtual ~ModuleAuditorium() + { + ServerInstance->Modes->DelMode(aum); + DELETE(aum); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader conf(ServerInstance); + ShowOps = conf.ReadFlag("auditorium", "showops", 0); + } + + Priority Prioritize() + { + /* To ensure that we get priority over namesx for names list generation on +u channels */ + return (Priority)ServerInstance->PriorityBefore("m_namesx.so"); + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + List[I_OnUserJoin] = List[I_OnUserPart] = List[I_OnUserKick] = List[I_OnUserQuit] = List[I_OnUserList] = List[I_OnRehash] = 1; + } + + virtual int OnUserList(userrec* user, chanrec* Ptr, CUList* &nameslist) + { + if (Ptr->IsModeSet('u')) + { + if (ShowOps) + { + /* Leave the names list alone, theyre an op + * doing /names on the channel after joining it + */ + if (Ptr->GetStatus(user) >= STATUS_OP) + { + nameslist = Ptr->GetUsers(); + return 0; + } + + /* Show all the opped users */ + nl = *(Ptr->GetOppedUsers()); + nl[user] = user->nick; + nameslist = &nl; + return 0; + } + else + { + /* HELLOOO, IS ANYBODY THERE? -- nope, just us. */ + user->WriteServ("353 %s = %s :%s", user->nick, Ptr->name, user->nick); + user->WriteServ("366 %s %s :End of /NAMES list.", user->nick, Ptr->name); + return 1; + } + } + return 0; + } + + virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) + { + if (channel->IsModeSet('u')) + { + silent = true; + /* Because we silenced the event, make sure it reaches the user whos joining (but only them of course) */ + user->WriteFrom(user, "JOIN %s", channel->name); + if (ShowOps) + channel->WriteAllExcept(user, false, channel->GetStatus(user) >= STATUS_OP ? 0 : '@', except_list, "JOIN %s", channel->name); + } + } + + void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent) + { + if (channel->IsModeSet('u')) + { + silent = true; + /* Because we silenced the event, make sure it reaches the user whos leaving (but only them of course) */ + user->WriteFrom(user, "PART %s%s%s", channel->name, + partmessage.empty() ? "" : " :", + partmessage.empty() ? "" : partmessage.c_str()); + if (ShowOps) + { + channel->WriteAllExcept(user, false, channel->GetStatus(user) >= STATUS_OP ? 0 : '@', except_list, "PART %s%s%s", channel->name, partmessage.empty() ? "" : " :", + partmessage.empty() ? "" : partmessage.c_str()); + } + } + } + + void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent) + { + if (chan->IsModeSet('u')) + { + silent = true; + /* Send silenced event only to the user being kicked and the user doing the kick */ + source->WriteFrom(source, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); + if (ShowOps) + chan->WriteAllExcept(source, false, chan->GetStatus(source) >= STATUS_OP ? 0 : '@', except_list, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); + else + user->WriteFrom(source, "KICK %s %s %s", chan->name, user->nick, reason.c_str()); + } + } + + void OnUserQuit(userrec* user, const std::string &reason, const std::string &oper_message) + { + command_t* parthandler = ServerInstance->Parser->GetHandler("PART"); + std::vector to_leave; + const char* parameters[2]; + if (parthandler) + { + for (UCListIter f = user->chans.begin(); f != user->chans.end(); f++) + { + if (f->first->IsModeSet('u')) + to_leave.push_back(f->first->name); + } + /* We cant do this neatly in one loop, as we are modifying the map we are iterating */ + for (std::vector::iterator n = to_leave.begin(); n != to_leave.end(); n++) + { + parameters[0] = n->c_str(); + /* This triggers our OnUserPart, above, making the PART silent */ + parthandler->Handle(parameters, 1, user); + } + } + } +}; + +MODULE_INIT(ModuleAuditorium) diff --git a/src/modules/m_banexception.cpp b/src/modules/m_banexception.cpp index 8a73e6070..0cd03a08b 100644 --- a/src/modules/m_banexception.cpp +++ b/src/modules/m_banexception.cpp @@ -1 +1,153 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "mode.h" #include "u_listmode.h" #include "wildcard.h" /* $ModDesc: Provides support for the +e channel mode */ /* $ModDep: ../../include/u_listmode.h */ /* Written by Om, April 2005. */ /* Rewritten to use the listmode utility by Om, December 2005 */ /* Adapted from m_exception, which was originally based on m_chanprotect and m_silence */ // The +e channel mode takes a nick!ident@host, glob patterns allowed, // and if a user matches an entry on the +e list then they can join the channel, overriding any (+b) bans set on them // Now supports CIDR and IP addresses -- Brain /** Handles +e channel mode */ class BanException : public ListModeBase { public: BanException(InspIRCd* Instance) : ListModeBase(Instance, 'e', "End of Channel Exception List", "348", "349", true) { } }; class ModuleBanException : public Module { BanException* be; public: ModuleBanException(InspIRCd* Me) : Module(Me) { be = new BanException(ServerInstance); if (!ServerInstance->AddMode(be, 'e')) throw ModuleException("Could not add new modes!"); ServerInstance->PublishInterface("ChannelBanList", this); } virtual void Implements(char* List) { be->DoImplements(List); List[I_OnRehash] = List[I_OnRequest] = List[I_On005Numeric] = List[I_OnCheckBan] = 1; } virtual void On005Numeric(std::string &output) { output.append(" EXCEPTS=e"); } virtual int OnCheckBan(userrec* user, chanrec* chan) { if (chan != NULL) { modelist* list; chan->GetExt(be->GetInfoKey(), list); if (list) { char mask[MAXBUF]; snprintf(mask, MAXBUF, "%s!%s@%s", user->nick, user->ident, user->GetIPString()); for (modelist::iterator it = list->begin(); it != list->end(); it++) { if (match(user->GetFullRealHost(), it->mask.c_str()) || match(user->GetFullHost(), it->mask.c_str()) || (match(mask, it->mask.c_str(), true))) { // They match an entry on the list, so let them in. return 1; } } return 0; } // or if there wasn't a list, there can't be anyone on it, so we don't need to do anything. } return 0; } virtual void OnCleanup(int target_type, void* item) { be->DoCleanup(target_type, item); } virtual void OnSyncChannel(chanrec* chan, Module* proto, void* opaque) { be->DoSyncChannel(chan, proto, opaque); } virtual void OnChannelDelete(chanrec* chan) { be->DoChannelDelete(chan); } virtual void OnRehash(userrec* user, const std::string ¶m) { be->DoRehash(); } virtual char* OnRequest(Request* request) { ListModeRequest* LM = (ListModeRequest*)request; if (strcmp("LM_CHECKLIST", request->GetId()) == 0) { modelist* list; LM->chan->GetExt(be->GetInfoKey(), list); if (list) { char mask[MAXBUF]; snprintf(mask, MAXBUF, "%s!%s@%s", LM->user->nick, LM->user->ident, LM->user->GetIPString()); for (modelist::iterator it = list->begin(); it != list->end(); it++) { if (match(LM->user->GetFullRealHost(), it->mask.c_str()) || match(LM->user->GetFullHost(), it->mask.c_str()) || (match(mask, it->mask.c_str(), true))) { // They match an entry return (char*)it->mask.c_str(); } } return NULL; } } return NULL; } virtual Version GetVersion() { return Version(1, 1, 0, 3, VF_COMMON | VF_VENDOR, API_VERSION); } virtual ~ModuleBanException() { ServerInstance->Modes->DelMode(be); DELETE(be); ServerInstance->UnpublishInterface("ChannelBanList", this); } }; MODULE_INIT(ModuleBanException) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "mode.h" +#include "u_listmode.h" +#include "wildcard.h" + +/* $ModDesc: Provides support for the +e channel mode */ +/* $ModDep: ../../include/u_listmode.h */ + +/* Written by Om, April 2005. */ +/* Rewritten to use the listmode utility by Om, December 2005 */ +/* Adapted from m_exception, which was originally based on m_chanprotect and m_silence */ + +// The +e channel mode takes a nick!ident@host, glob patterns allowed, +// and if a user matches an entry on the +e list then they can join the channel, overriding any (+b) bans set on them +// Now supports CIDR and IP addresses -- Brain + + +/** Handles +e channel mode + */ +class BanException : public ListModeBase +{ + public: + BanException(InspIRCd* Instance) : ListModeBase(Instance, 'e', "End of Channel Exception List", "348", "349", true) { } +}; + + +class ModuleBanException : public Module +{ + BanException* be; + + +public: + ModuleBanException(InspIRCd* Me) + : Module(Me) + { + be = new BanException(ServerInstance); + if (!ServerInstance->AddMode(be, 'e')) + throw ModuleException("Could not add new modes!"); + ServerInstance->PublishInterface("ChannelBanList", this); + } + + virtual void Implements(char* List) + { + be->DoImplements(List); + List[I_OnRehash] = List[I_OnRequest] = List[I_On005Numeric] = List[I_OnCheckBan] = 1; + } + + virtual void On005Numeric(std::string &output) + { + output.append(" EXCEPTS=e"); + } + + virtual int OnCheckBan(userrec* user, chanrec* chan) + { + if (chan != NULL) + { + modelist* list; + chan->GetExt(be->GetInfoKey(), list); + + if (list) + { + char mask[MAXBUF]; + snprintf(mask, MAXBUF, "%s!%s@%s", user->nick, user->ident, user->GetIPString()); + for (modelist::iterator it = list->begin(); it != list->end(); it++) + { + if (match(user->GetFullRealHost(), it->mask.c_str()) || match(user->GetFullHost(), it->mask.c_str()) || (match(mask, it->mask.c_str(), true))) + { + // They match an entry on the list, so let them in. + return 1; + } + } + return 0; + } + // or if there wasn't a list, there can't be anyone on it, so we don't need to do anything. + } + return 0; + } + + virtual void OnCleanup(int target_type, void* item) + { + be->DoCleanup(target_type, item); + } + + virtual void OnSyncChannel(chanrec* chan, Module* proto, void* opaque) + { + be->DoSyncChannel(chan, proto, opaque); + } + + virtual void OnChannelDelete(chanrec* chan) + { + be->DoChannelDelete(chan); + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + be->DoRehash(); + } + + virtual char* OnRequest(Request* request) + { + ListModeRequest* LM = (ListModeRequest*)request; + if (strcmp("LM_CHECKLIST", request->GetId()) == 0) + { + modelist* list; + LM->chan->GetExt(be->GetInfoKey(), list); + if (list) + { + char mask[MAXBUF]; + snprintf(mask, MAXBUF, "%s!%s@%s", LM->user->nick, LM->user->ident, LM->user->GetIPString()); + for (modelist::iterator it = list->begin(); it != list->end(); it++) + { + if (match(LM->user->GetFullRealHost(), it->mask.c_str()) || match(LM->user->GetFullHost(), it->mask.c_str()) || (match(mask, it->mask.c_str(), true))) + { + // They match an entry + return (char*)it->mask.c_str(); + } + } + return NULL; + } + } + return NULL; + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 3, VF_COMMON | VF_VENDOR, API_VERSION); + } + + virtual ~ModuleBanException() + { + ServerInstance->Modes->DelMode(be); + DELETE(be); + ServerInstance->UnpublishInterface("ChannelBanList", this); + } +}; + +MODULE_INIT(ModuleBanException) diff --git a/src/modules/m_banredirect.cpp b/src/modules/m_banredirect.cpp index 2a0ed2ded..1764e6f56 100644 --- a/src/modules/m_banredirect.cpp +++ b/src/modules/m_banredirect.cpp @@ -1 +1,343 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "mode.h" #include "users.h" #include "channels.h" #include "modules.h" #include "u_listmode.h" /* $ModDesc: Allows an extended ban (+b) syntax redirecting banned users to another channel */ /* Originally written by Om, January 2007 */ class BanRedirectEntry { public: std::string targetchan; std::string banmask; BanRedirectEntry(const std::string &target = "", const std::string &mask = "") : targetchan(target), banmask(mask) { } }; typedef std::vector BanRedirectList; typedef std::deque StringDeque; class BanRedirect : public ModeWatcher { private: InspIRCd* Srv; public: BanRedirect(InspIRCd* Instance) : ModeWatcher(Instance, 'b', MODETYPE_CHANNEL), Srv(Instance) { } bool BeforeMode(userrec* source, userrec* dest, chanrec* channel, std::string ¶m, bool adding, ModeType type) { /* nick!ident@host -> nick!ident@host * nick!ident@host#chan -> nick!ident@host#chan * nick@host#chan -> nick!*@host#chan * nick!ident#chan -> nick!ident@*#chan * nick#chan -> nick!*@*#chan */ if(channel && (type == MODETYPE_CHANNEL) && param.length()) { 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(channel->bans.size() > static_cast(maxbans)) { source->WriteServ("478 %s %s :Channel ban list for %s is full (maximum entries for this channel is %d)", source->nick, channel->name, channel->name, maxbans); return false; } for(std::string::iterator curr = start_pos; curr != param.end(); curr++) { switch(*curr) { case '!': mask[current].assign(start_pos, curr); current = IDENT; start_pos = curr+1; break; case '@': mask[current].assign(start_pos, curr); current = HOST; start_pos = curr+1; break; case '#': mask[current].assign(start_pos, curr); current = CHAN; start_pos = curr; break; } } if(mask[current].empty()) { mask[current].assign(start_pos, param.end()); } /* nick@host wants to be changed to *!nick@host rather than nick!*@host... */ if(mask[NICK].length() && mask[HOST].length() && mask[IDENT].empty()) { /* std::string::swap() is fast - it runs in constant time */ mask[NICK].swap(mask[IDENT]); } for(int i = 0; i < 3; i++) { if(mask[i].empty()) { mask[i].assign("*"); } } param.assign(mask[NICK]).append(1, '!').append(mask[IDENT]).append(1, '@').append(mask[HOST]); if(mask[CHAN].length()) { if(Srv->IsChannel(mask[CHAN].c_str())) { if(irc::string(channel->name) == irc::string(mask[CHAN].c_str())) { source->WriteServ("690 %s %s :You cannot set a ban redirection to the channel the ban is on", source->nick, channel->name); return false; } else { if(adding) { /* It's a properly valid redirecting ban, and we're adding it */ if(!channel->GetExt("banredirects", redirects)) { redirects = new BanRedirectList; channel->Extend("banredirects", redirects); } /* Here 'param' doesn't have the channel on it yet */ redirects->push_back(BanRedirectEntry(mask[CHAN].c_str(), param.c_str())); /* Now it does */ param.append(mask[CHAN]); } else { /* Removing a ban, if there's no extensible there are no redirecting bans and we're fine. */ if(channel->GetExt("banredirects", redirects)) { /* But there were, so we need to remove the matching one if there is one */ for(BanRedirectList::iterator redir = redirects->begin(); redir != redirects->end(); redir++) { /* Ugly as fuck */ if((irc::string(redir->targetchan.c_str()) == irc::string(mask[CHAN].c_str())) && (irc::string(redir->banmask.c_str()) == irc::string(param.c_str()))) { redirects->erase(redir); if(redirects->empty()) { DELETE(redirects); channel->Shrink("banredirects"); } break; } } } /* Append the channel so the default +b handler can remove the entry too */ param.append(mask[CHAN]); } } } else { source->WriteServ("403 %s %s :Invalid channel name in redirection (%s)", source->nick, channel->name, mask[CHAN].c_str()); return false; } } } return true; } }; class ModuleBanRedirect : public Module { BanRedirect* re; bool nofollow; Module* ExceptionModule; public: ModuleBanRedirect(InspIRCd* Me) : Module(Me) { re = new BanRedirect(Me); nofollow = false; if(!ServerInstance->AddModeWatcher(re)) throw ModuleException("Could not add mode watcher"); OnRehash(NULL, ""); } void Implements(char* List) { List[I_OnRehash] = List[I_OnUserPreJoin] = List[I_OnChannelDelete] = List[I_OnCleanup] = 1; } virtual void OnChannelDelete(chanrec* chan) { OnCleanup(TYPE_CHANNEL, chan); } virtual void OnCleanup(int target_type, void* item) { if(target_type == TYPE_CHANNEL) { chanrec* chan = static_cast(item); BanRedirectList* redirects; if(chan->GetExt("banredirects", redirects)) { irc::modestacker modestack(false); StringDeque stackresult; const char* mode_junk[MAXMODES+2]; userrec* myhorriblefakeuser = new userrec(ServerInstance); myhorriblefakeuser->SetFd(FD_MAGIC_NUMBER); mode_junk[0] = chan->name; for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) { modestack.Push('b', i->targetchan.insert(0, i->banmask)); } for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) { modestack.PushPlus(); modestack.Push('b', i->banmask); } while(modestack.GetStackedLine(stackresult)) { for(StringDeque::size_type i = 0; i < stackresult.size(); i++) { mode_junk[i+1] = stackresult[i].c_str(); } ServerInstance->SendMode(mode_junk, stackresult.size() + 1, myhorriblefakeuser); } DELETE(myhorriblefakeuser); DELETE(redirects); chan->Shrink("banredirects"); } } } virtual void OnRehash(userrec* user, const std::string ¶m) { ExceptionModule = ServerInstance->FindModule("m_banexception.so"); } virtual int OnUserPreJoin(userrec* user, chanrec* chan, const char* cname, std::string &privs) { /* This prevents recursion when a user sets multiple ban redirects in a chain * (thanks Potter) */ if (nofollow) return 0; /* Return 1 to prevent the join, 0 to allow it */ if (chan) { BanRedirectList* redirects; if(chan->GetExt("banredirects", redirects)) { /* We actually had some ban redirects to check */ /* This was replaced with user->MakeHostIP() when I had a snprintf(), but MakeHostIP() doesn't seem to add the nick. * Maybe we should have a GetFullIPHost() or something to match GetFullHost() and GetFullRealHost? */ if (ExceptionModule) { ListModeRequest n(this, ExceptionModule, user, chan); /* Users with ban exceptions are allowed to join without being redirected */ if (n.Send()) return 0; } std::string ipmask(user->nick); ipmask.append(1, '!').append(user->MakeHostIP()); for(BanRedirectList::iterator redir = redirects->begin(); redir != redirects->end(); redir++) { if(ServerInstance->MatchText(user->GetFullRealHost(), redir->banmask) || ServerInstance->MatchText(user->GetFullHost(), redir->banmask) || ServerInstance->MatchText(ipmask, redir->banmask)) { /* tell them they're banned and are being transferred */ chanrec* destchan = ServerInstance->FindChan(redir->targetchan); if(destchan && ServerInstance->FindModule("m_redirect.so") && destchan->IsModeSet('L') && destchan->limit && (destchan->GetUserCounter() >= destchan->limit)) { user->WriteServ("474 %s %s :Cannot join channel (You are banned)", user->nick, chan->name); return 1; } else { user->WriteServ("470 %s :You are banned from %s. You are being automatically redirected to %s", user->nick, chan->name, redir->targetchan.c_str()); nofollow = true; chanrec::JoinUser(ServerInstance, user, redir->targetchan.c_str(), false, "", ServerInstance->Time(true)); nofollow = false; return 1; } } } } } return 0; } virtual ~ModuleBanRedirect() { ServerInstance->Modes->DelModeWatcher(re); DELETE(re); } virtual Version GetVersion() { return Version(1, 0, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); } Priority Prioritize() { return (Priority)ServerInstance->PriorityBefore("m_banexception.so"); } }; MODULE_INIT(ModuleBanRedirect) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "mode.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "u_listmode.h" + +/* $ModDesc: Allows an extended ban (+b) syntax redirecting banned users to another channel */ + +/* Originally written by Om, January 2007 + */ + +class BanRedirectEntry +{ + public: + std::string targetchan; + std::string banmask; + + BanRedirectEntry(const std::string &target = "", const std::string &mask = "") + : targetchan(target), banmask(mask) + { + } +}; + +typedef std::vector BanRedirectList; +typedef std::deque StringDeque; + +class BanRedirect : public ModeWatcher +{ + private: + InspIRCd* Srv; + public: + BanRedirect(InspIRCd* Instance) + : ModeWatcher(Instance, 'b', MODETYPE_CHANNEL), Srv(Instance) + { + } + + bool BeforeMode(userrec* source, userrec* dest, chanrec* channel, std::string ¶m, bool adding, ModeType type) + { + /* nick!ident@host -> nick!ident@host + * nick!ident@host#chan -> nick!ident@host#chan + * nick@host#chan -> nick!*@host#chan + * nick!ident#chan -> nick!ident@*#chan + * nick#chan -> nick!*@*#chan + */ + + if(channel && (type == MODETYPE_CHANNEL) && param.length()) + { + 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(channel->bans.size() > static_cast(maxbans)) + { + source->WriteServ("478 %s %s :Channel ban list for %s is full (maximum entries for this channel is %d)", source->nick, channel->name, channel->name, maxbans); + return false; + } + + for(std::string::iterator curr = start_pos; curr != param.end(); curr++) + { + switch(*curr) + { + case '!': + mask[current].assign(start_pos, curr); + current = IDENT; + start_pos = curr+1; + break; + case '@': + mask[current].assign(start_pos, curr); + current = HOST; + start_pos = curr+1; + break; + case '#': + mask[current].assign(start_pos, curr); + current = CHAN; + start_pos = curr; + break; + } + } + + if(mask[current].empty()) + { + mask[current].assign(start_pos, param.end()); + } + + /* nick@host wants to be changed to *!nick@host rather than nick!*@host... */ + if(mask[NICK].length() && mask[HOST].length() && mask[IDENT].empty()) + { + /* std::string::swap() is fast - it runs in constant time */ + mask[NICK].swap(mask[IDENT]); + } + + for(int i = 0; i < 3; i++) + { + if(mask[i].empty()) + { + mask[i].assign("*"); + } + } + + param.assign(mask[NICK]).append(1, '!').append(mask[IDENT]).append(1, '@').append(mask[HOST]); + + if(mask[CHAN].length()) + { + if(Srv->IsChannel(mask[CHAN].c_str())) + { + if(irc::string(channel->name) == irc::string(mask[CHAN].c_str())) + { + source->WriteServ("690 %s %s :You cannot set a ban redirection to the channel the ban is on", source->nick, channel->name); + return false; + } + else + { + if(adding) + { + /* It's a properly valid redirecting ban, and we're adding it */ + if(!channel->GetExt("banredirects", redirects)) + { + redirects = new BanRedirectList; + channel->Extend("banredirects", redirects); + } + + /* Here 'param' doesn't have the channel on it yet */ + redirects->push_back(BanRedirectEntry(mask[CHAN].c_str(), param.c_str())); + + /* Now it does */ + param.append(mask[CHAN]); + } + else + { + /* Removing a ban, if there's no extensible there are no redirecting bans and we're fine. */ + if(channel->GetExt("banredirects", redirects)) + { + /* But there were, so we need to remove the matching one if there is one */ + + for(BanRedirectList::iterator redir = redirects->begin(); redir != redirects->end(); redir++) + { + /* Ugly as fuck */ + if((irc::string(redir->targetchan.c_str()) == irc::string(mask[CHAN].c_str())) && (irc::string(redir->banmask.c_str()) == irc::string(param.c_str()))) + { + redirects->erase(redir); + + if(redirects->empty()) + { + DELETE(redirects); + channel->Shrink("banredirects"); + } + + break; + } + } + } + + /* Append the channel so the default +b handler can remove the entry too */ + param.append(mask[CHAN]); + } + } + } + else + { + source->WriteServ("403 %s %s :Invalid channel name in redirection (%s)", source->nick, channel->name, mask[CHAN].c_str()); + return false; + } + } + } + + return true; + } +}; + +class ModuleBanRedirect : public Module +{ + BanRedirect* re; + bool nofollow; + Module* ExceptionModule; + + public: + ModuleBanRedirect(InspIRCd* Me) + : Module(Me) + { + re = new BanRedirect(Me); + nofollow = false; + + if(!ServerInstance->AddModeWatcher(re)) + throw ModuleException("Could not add mode watcher"); + + OnRehash(NULL, ""); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnUserPreJoin] = List[I_OnChannelDelete] = List[I_OnCleanup] = 1; + } + + virtual void OnChannelDelete(chanrec* chan) + { + OnCleanup(TYPE_CHANNEL, chan); + } + + virtual void OnCleanup(int target_type, void* item) + { + if(target_type == TYPE_CHANNEL) + { + chanrec* chan = static_cast(item); + BanRedirectList* redirects; + + if(chan->GetExt("banredirects", redirects)) + { + irc::modestacker modestack(false); + StringDeque stackresult; + const char* mode_junk[MAXMODES+2]; + userrec* myhorriblefakeuser = new userrec(ServerInstance); + myhorriblefakeuser->SetFd(FD_MAGIC_NUMBER); + + mode_junk[0] = chan->name; + + for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) + { + modestack.Push('b', i->targetchan.insert(0, i->banmask)); + } + + for(BanRedirectList::iterator i = redirects->begin(); i != redirects->end(); i++) + { + modestack.PushPlus(); + modestack.Push('b', i->banmask); + } + + while(modestack.GetStackedLine(stackresult)) + { + for(StringDeque::size_type i = 0; i < stackresult.size(); i++) + { + mode_junk[i+1] = stackresult[i].c_str(); + } + + ServerInstance->SendMode(mode_junk, stackresult.size() + 1, myhorriblefakeuser); + } + + DELETE(myhorriblefakeuser); + DELETE(redirects); + chan->Shrink("banredirects"); + } + } + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + ExceptionModule = ServerInstance->FindModule("m_banexception.so"); + } + + virtual int OnUserPreJoin(userrec* user, chanrec* chan, const char* cname, std::string &privs) + { + /* This prevents recursion when a user sets multiple ban redirects in a chain + * (thanks Potter) + */ + if (nofollow) + return 0; + + /* Return 1 to prevent the join, 0 to allow it */ + if (chan) + { + BanRedirectList* redirects; + + if(chan->GetExt("banredirects", redirects)) + { + /* We actually had some ban redirects to check */ + + /* This was replaced with user->MakeHostIP() when I had a snprintf(), but MakeHostIP() doesn't seem to add the nick. + * Maybe we should have a GetFullIPHost() or something to match GetFullHost() and GetFullRealHost? + */ + + if (ExceptionModule) + { + ListModeRequest n(this, ExceptionModule, user, chan); + /* Users with ban exceptions are allowed to join without being redirected */ + if (n.Send()) + return 0; + } + + std::string ipmask(user->nick); + ipmask.append(1, '!').append(user->MakeHostIP()); + + for(BanRedirectList::iterator redir = redirects->begin(); redir != redirects->end(); redir++) + { + if(ServerInstance->MatchText(user->GetFullRealHost(), redir->banmask) || ServerInstance->MatchText(user->GetFullHost(), redir->banmask) || ServerInstance->MatchText(ipmask, redir->banmask)) + { + /* tell them they're banned and are being transferred */ + chanrec* destchan = ServerInstance->FindChan(redir->targetchan); + + if(destchan && ServerInstance->FindModule("m_redirect.so") && destchan->IsModeSet('L') && destchan->limit && (destchan->GetUserCounter() >= destchan->limit)) + { + user->WriteServ("474 %s %s :Cannot join channel (You are banned)", user->nick, chan->name); + return 1; + } + else + { + user->WriteServ("470 %s :You are banned from %s. You are being automatically redirected to %s", user->nick, chan->name, redir->targetchan.c_str()); + nofollow = true; + chanrec::JoinUser(ServerInstance, user, redir->targetchan.c_str(), false, "", ServerInstance->Time(true)); + nofollow = false; + return 1; + } + } + } + } + } + return 0; + } + + virtual ~ModuleBanRedirect() + { + ServerInstance->Modes->DelModeWatcher(re); + DELETE(re); + } + + virtual Version GetVersion() + { + return Version(1, 0, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); + } + + Priority Prioritize() + { + return (Priority)ServerInstance->PriorityBefore("m_banexception.so"); + } +}; + + +MODULE_INIT(ModuleBanRedirect) diff --git a/src/modules/m_blockamsg.cpp b/src/modules/m_blockamsg.cpp index 5ff0c1100..69e99d0bb 100644 --- a/src/modules/m_blockamsg.cpp +++ b/src/modules/m_blockamsg.cpp @@ -1 +1,191 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "hashcomp.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. * IBLOCK_SILENT - Generate no output, silently drop messages. * IBLOCK_KILL - Kill the user with the reason "Global message (/amsg or /ame) detected". * IBLOCK_KILLOPERS - As above, but send an oper notice as well. This is the default. */ /** Holds a blocked message's details */ class BlockedMessage : public classbase { 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) { } }; class ModuleBlockAmsg : public Module { int ForgetDelay; BlockAction action; public: ModuleBlockAmsg(InspIRCd* Me) : Module(Me) { this->OnRehash(NULL,""); } void Implements(char* List) { List[I_OnRehash] = List[I_OnPreCommand] = List[I_OnCleanup] = 1; } virtual ~ModuleBlockAmsg() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader Conf(ServerInstance); ForgetDelay = Conf.ReadInteger("blockamsg", "delay", 0, false); if(Conf.GetError() == CONF_VALUE_NOT_FOUND) ForgetDelay = -1; std::string act = Conf.ReadValue("blockamsg", "action", 0); if(act == "notice") action = IBLOCK_NOTICE; else if(act == "noticeopers") action = IBLOCK_NOTICEOPERS; else if(act == "silent") action = IBLOCK_SILENT; else if(act == "kill") action = IBLOCK_KILL; else action = IBLOCK_KILLOPERS; } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { // Don't do anything with unregistered users, or remote ones. if(!user || (user->registered != REG_ALL) || !IS_LOCAL(user)) return 0; // We want case insensitive command comparison. // Add std::string contructor for irc::string :x irc::string cmd = command.c_str(); if(validated && (cmd == "PRIVMSG" || cmd == "NOTICE") && (pcnt >= 2)) { // 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... int targets = 1; int userchans = 0; if(*parameters[0] != '#') { // Decrement if the first target wasn't a channel. targets--; } for(const char* c = parameters[0]; *c; c++) if((*c == ',') && *(c+1) && (*(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) { return 0; } userchans = user->chans.size(); // Check that this message wasn't already sent within a few seconds. BlockedMessage* m; user->GetExt("amsgblock", m); // If the message is identical and within the time. // We check the target is *not* identical, that'd straying into the realms of flood control. Which isn't what we're doing... // 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))) { // Block it... if(action == IBLOCK_KILLOPERS || action == IBLOCK_NOTICEOPERS) ServerInstance->WriteOpers("*** %s had an /amsg or /ame denied", user->nick); if(action == IBLOCK_KILL || action == IBLOCK_KILLOPERS) userrec::QuitUser(ServerInstance, user, "Global message (/amsg or /ame) detected"); else if(action == IBLOCK_NOTICE || action == IBLOCK_NOTICEOPERS) user->WriteServ( "NOTICE %s :Global message (/amsg or /ame) detected", user->nick); return 1; } if(m) { // If there's already a BlockedMessage allocated, use it. m->message = parameters[1]; m->target = parameters[0]; m->sent = ServerInstance->Time(); } else { m = new BlockedMessage(parameters[1], parameters[0], ServerInstance->Time()); user->Extend("amsgblock", (char*)m); } } return 0; } void OnCleanup(int target_type, void* item) { if(target_type == TYPE_USER) { userrec* user = (userrec*)item; BlockedMessage* m; user->GetExt("amsgblock", m); if(m) { DELETE(m); user->Shrink("amsgblock"); } } } }; MODULE_INIT(ModuleBlockAmsg) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "hashcomp.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. + * IBLOCK_SILENT - Generate no output, silently drop messages. + * IBLOCK_KILL - Kill the user with the reason "Global message (/amsg or /ame) detected". + * IBLOCK_KILLOPERS - As above, but send an oper notice as well. This is the default. + */ + +/** Holds a blocked message's details + */ +class BlockedMessage : public classbase +{ +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) + { + } +}; + +class ModuleBlockAmsg : public Module +{ + int ForgetDelay; + BlockAction action; + + public: + ModuleBlockAmsg(InspIRCd* Me) + : Module(Me) + { + + this->OnRehash(NULL,""); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnPreCommand] = List[I_OnCleanup] = 1; + } + + virtual ~ModuleBlockAmsg() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader Conf(ServerInstance); + + ForgetDelay = Conf.ReadInteger("blockamsg", "delay", 0, false); + + if(Conf.GetError() == CONF_VALUE_NOT_FOUND) + ForgetDelay = -1; + + std::string act = Conf.ReadValue("blockamsg", "action", 0); + + if(act == "notice") + action = IBLOCK_NOTICE; + else if(act == "noticeopers") + action = IBLOCK_NOTICEOPERS; + else if(act == "silent") + action = IBLOCK_SILENT; + else if(act == "kill") + action = IBLOCK_KILL; + else + action = IBLOCK_KILLOPERS; + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) + { + // Don't do anything with unregistered users, or remote ones. + if(!user || (user->registered != REG_ALL) || !IS_LOCAL(user)) + return 0; + + // We want case insensitive command comparison. + // Add std::string contructor for irc::string :x + irc::string cmd = command.c_str(); + + if(validated && (cmd == "PRIVMSG" || cmd == "NOTICE") && (pcnt >= 2)) + { + // 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... + + int targets = 1; + int userchans = 0; + + if(*parameters[0] != '#') + { + // Decrement if the first target wasn't a channel. + targets--; + } + + for(const char* c = parameters[0]; *c; c++) + if((*c == ',') && *(c+1) && (*(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) + { + return 0; + } + + userchans = user->chans.size(); + + // Check that this message wasn't already sent within a few seconds. + BlockedMessage* m; + user->GetExt("amsgblock", m); + + // If the message is identical and within the time. + // We check the target is *not* identical, that'd straying into the realms of flood control. Which isn't what we're doing... + // 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))) + { + // Block it... + if(action == IBLOCK_KILLOPERS || action == IBLOCK_NOTICEOPERS) + ServerInstance->WriteOpers("*** %s had an /amsg or /ame denied", user->nick); + + if(action == IBLOCK_KILL || action == IBLOCK_KILLOPERS) + userrec::QuitUser(ServerInstance, user, "Global message (/amsg or /ame) detected"); + else if(action == IBLOCK_NOTICE || action == IBLOCK_NOTICEOPERS) + user->WriteServ( "NOTICE %s :Global message (/amsg or /ame) detected", user->nick); + + return 1; + } + + if(m) + { + // If there's already a BlockedMessage allocated, use it. + m->message = parameters[1]; + m->target = parameters[0]; + m->sent = ServerInstance->Time(); + } + else + { + m = new BlockedMessage(parameters[1], parameters[0], ServerInstance->Time()); + user->Extend("amsgblock", (char*)m); + } + } + return 0; + } + + void OnCleanup(int target_type, void* item) + { + if(target_type == TYPE_USER) + { + userrec* user = (userrec*)item; + BlockedMessage* m; + user->GetExt("amsgblock", m); + if(m) + { + DELETE(m); + user->Shrink("amsgblock"); + } + } + } +}; + + +MODULE_INIT(ModuleBlockAmsg) diff --git a/src/modules/m_blockcaps.cpp b/src/modules/m_blockcaps.cpp index 8713f8c0d..9197a8f11 100644 --- a/src/modules/m_blockcaps.cpp +++ b/src/modules/m_blockcaps.cpp @@ -1 +1,143 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "mode.h" /* $ModDesc: Provides support for channel mode +P to block all-CAPS channel messages and notices */ /** Handles the +P channel mode */ class BlockCaps : public ModeHandler { public: BlockCaps(InspIRCd* Instance) : ModeHandler(Instance, 'P', 0, 0, false, MODETYPE_CHANNEL, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* 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('P',false); return MODEACTION_ALLOW; } } return MODEACTION_DENY; } }; class ModuleBlockCAPS : public Module { BlockCaps* bc; int percent; unsigned int minlen; char capsmap[256]; public: ModuleBlockCAPS(InspIRCd* Me) : Module(Me) { OnRehash(NULL,""); bc = new BlockCaps(ServerInstance); if (!ServerInstance->AddMode(bc, 'P')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = List[I_OnRehash] = 1; } virtual void OnRehash(userrec* user, const std::string ¶m) { ReadConf(); } virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) { if (target_type == TYPE_CHANNEL) { if ((!IS_LOCAL(user)) || (text.length() < minlen)) return 0; chanrec* c = (chanrec*)dest; if (c->IsModeSet('P')) { int caps = 0; for (std::string::iterator i = text.begin(); i != text.end(); i++) caps += capsmap[(unsigned char)*i]; if ( ((caps*100)/(int)text.length()) >= percent ) { user->WriteServ( "404 %s %s :Your line cannot be more than %d%% capital letters if it is %d or more letters long", user->nick, c->name, percent, minlen); return 1; } } } return 0; } virtual int OnUserPreNotice(userrec* 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() { ConfigReader Conf(ServerInstance); percent = Conf.ReadInteger("blockcaps", "percent", "100", 0, true); minlen = Conf.ReadInteger("blockcaps", "minlen", "0", 0, true); std::string hmap = Conf.ReadValue("blockcaps", "capsmap", 0); if (hmap.empty()) hmap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; memset(&capsmap, 0, 255); for (std::string::iterator n = hmap.begin(); n != hmap.end(); n++) capsmap[(unsigned char)*n] = 1; if (percent < 0 || percent > 100) { ServerInstance->Log(DEFAULT, " out of range, setting to default of 100."); percent = 100; } if (minlen < 0 || minlen > MAXBUF-1) { ServerInstance->Log(DEFAULT, " out of range, setting to default of 0."); minlen = 0; } } virtual ~ModuleBlockCAPS() { ServerInstance->Modes->DelMode(bc); DELETE(bc); } virtual Version GetVersion() { return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleBlockCAPS) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "mode.h" + +/* $ModDesc: Provides support for channel mode +P to block all-CAPS channel messages and notices */ + + +/** Handles the +P channel mode + */ +class BlockCaps : public ModeHandler +{ + public: + BlockCaps(InspIRCd* Instance) : ModeHandler(Instance, 'P', 0, 0, false, MODETYPE_CHANNEL, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* 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('P',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_DENY; + } +}; + +class ModuleBlockCAPS : public Module +{ + BlockCaps* bc; + int percent; + unsigned int minlen; + char capsmap[256]; +public: + + ModuleBlockCAPS(InspIRCd* Me) : Module(Me) + { + OnRehash(NULL,""); + bc = new BlockCaps(ServerInstance); + if (!ServerInstance->AddMode(bc, 'P')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = List[I_OnRehash] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + ReadConf(); + } + + virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + { + if (target_type == TYPE_CHANNEL) + { + if ((!IS_LOCAL(user)) || (text.length() < minlen)) + return 0; + + chanrec* c = (chanrec*)dest; + + if (c->IsModeSet('P')) + { + int caps = 0; + for (std::string::iterator i = text.begin(); i != text.end(); i++) + caps += capsmap[(unsigned char)*i]; + if ( ((caps*100)/(int)text.length()) >= percent ) + { + user->WriteServ( "404 %s %s :Your line cannot be more than %d%% capital letters if it is %d or more letters long", user->nick, c->name, percent, minlen); + return 1; + } + } + } + return 0; + } + + virtual int OnUserPreNotice(userrec* 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() + { + ConfigReader Conf(ServerInstance); + percent = Conf.ReadInteger("blockcaps", "percent", "100", 0, true); + minlen = Conf.ReadInteger("blockcaps", "minlen", "0", 0, true); + std::string hmap = Conf.ReadValue("blockcaps", "capsmap", 0); + if (hmap.empty()) + hmap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + memset(&capsmap, 0, 255); + for (std::string::iterator n = hmap.begin(); n != hmap.end(); n++) + capsmap[(unsigned char)*n] = 1; + if (percent < 0 || percent > 100) + { + ServerInstance->Log(DEFAULT, " out of range, setting to default of 100."); + percent = 100; + } + if (minlen < 0 || minlen > MAXBUF-1) + { + ServerInstance->Log(DEFAULT, " out of range, setting to default of 0."); + minlen = 0; + } + } + + virtual ~ModuleBlockCAPS() + { + ServerInstance->Modes->DelMode(bc); + DELETE(bc); + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); + } +}; + +MODULE_INIT(ModuleBlockCAPS) diff --git a/src/modules/m_blockcolor.cpp b/src/modules/m_blockcolor.cpp index 0646caa0b..69b0e4686 100644 --- a/src/modules/m_blockcolor.cpp +++ b/src/modules/m_blockcolor.cpp @@ -1 +1,118 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Provides support for unreal-style channel mode +c */ /** Handles the +c channel mode */ class BlockColor : public ModeHandler { public: BlockColor(InspIRCd* Instance) : ModeHandler(Instance, 'c', 0, 0, false, MODETYPE_CHANNEL, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (adding) { if (!channel->IsModeSet('c')) { channel->SetMode('c',true); return MODEACTION_ALLOW; } } else { if (channel->IsModeSet('c')) { channel->SetMode('c',false); return MODEACTION_ALLOW; } } return MODEACTION_DENY; } }; class ModuleBlockColour : public Module { bool AllowChanOps; BlockColor *bc; public: ModuleBlockColour(InspIRCd* Me) : Module(Me) { bc = new BlockColor(ServerInstance); if (!ServerInstance->AddMode(bc, 'c')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = 1; } virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) { if ((target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) { chanrec* c = (chanrec*)dest; if(c->IsModeSet('c')) { if (!CHANOPS_EXEMPT(ServerInstance, 'c') || CHANOPS_EXEMPT(ServerInstance, 'c') && c->GetStatus(user) != STATUS_OP) { for (std::string::iterator i = text.begin(); i != text.end(); i++) { switch (*i) { case 2: case 3: case 15: case 21: case 22: case 31: user->WriteServ("404 %s %s :Can't send colours to channel (+c set)",user->nick, c->name); return 1; break; } } } } } return 0; } virtual int OnUserPreNotice(userrec* 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 ~ModuleBlockColour() { ServerInstance->Modes->DelMode(bc); DELETE(bc); } virtual Version GetVersion() { return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleBlockColour) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Provides support for unreal-style channel mode +c */ + +/** Handles the +c channel mode + */ +class BlockColor : public ModeHandler +{ + public: + BlockColor(InspIRCd* Instance) : ModeHandler(Instance, 'c', 0, 0, false, MODETYPE_CHANNEL, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (adding) + { + if (!channel->IsModeSet('c')) + { + channel->SetMode('c',true); + return MODEACTION_ALLOW; + } + } + else + { + if (channel->IsModeSet('c')) + { + channel->SetMode('c',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_DENY; + } +}; + +class ModuleBlockColour : public Module +{ + bool AllowChanOps; + BlockColor *bc; + public: + + ModuleBlockColour(InspIRCd* Me) : Module(Me) + { + bc = new BlockColor(ServerInstance); + if (!ServerInstance->AddMode(bc, 'c')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = 1; + } + + + virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + { + if ((target_type == TYPE_CHANNEL) && (IS_LOCAL(user))) + { + chanrec* c = (chanrec*)dest; + + if(c->IsModeSet('c')) + { + if (!CHANOPS_EXEMPT(ServerInstance, 'c') || CHANOPS_EXEMPT(ServerInstance, 'c') && c->GetStatus(user) != STATUS_OP) + { + for (std::string::iterator i = text.begin(); i != text.end(); i++) + { + switch (*i) + { + case 2: + case 3: + case 15: + case 21: + case 22: + case 31: + user->WriteServ("404 %s %s :Can't send colours to channel (+c set)",user->nick, c->name); + return 1; + break; + } + } + } + } + } + return 0; + } + + virtual int OnUserPreNotice(userrec* 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 ~ModuleBlockColour() + { + ServerInstance->Modes->DelMode(bc); + DELETE(bc); + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); + } +}; + +MODULE_INIT(ModuleBlockColour) diff --git a/src/modules/m_botmode.cpp b/src/modules/m_botmode.cpp index 8cc999f12..a6cad9577 100644 --- a/src/modules/m_botmode.cpp +++ b/src/modules/m_botmode.cpp @@ -1 +1,95 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" /* $ModDesc: Provides support for unreal-style umode +B */ /** Handles user mode +B */ class BotMode : public ModeHandler { public: BotMode(InspIRCd* Instance) : ModeHandler(Instance, 'B', 0, 0, false, MODETYPE_USER, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (adding) { if (!dest->IsModeSet('B')) { dest->SetMode('B',true); return MODEACTION_ALLOW; } } else { if (dest->IsModeSet('B')) { dest->SetMode('B',false); return MODEACTION_ALLOW; } } return MODEACTION_DENY; } }; class ModuleBotMode : public Module { BotMode* bm; public: ModuleBotMode(InspIRCd* Me) : Module(Me) { bm = new BotMode(ServerInstance); if (!ServerInstance->AddMode(bm, 'B')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { List[I_OnWhois] = 1; } virtual ~ModuleBotMode() { ServerInstance->Modes->DelMode(bm); DELETE(bm); } virtual Version GetVersion() { return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); } virtual void OnWhois(userrec* src, userrec* dst) { if (dst->IsModeSet('B')) { ServerInstance->SendWhoisLine(src, dst, 335, std::string(src->nick)+" "+std::string(dst->nick)+" :is a bot on "+ServerInstance->Config->Network); } } }; MODULE_INIT(ModuleBotMode) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" + +/* $ModDesc: Provides support for unreal-style umode +B */ + +/** Handles user mode +B + */ +class BotMode : public ModeHandler +{ + public: + BotMode(InspIRCd* Instance) : ModeHandler(Instance, 'B', 0, 0, false, MODETYPE_USER, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (adding) + { + if (!dest->IsModeSet('B')) + { + dest->SetMode('B',true); + return MODEACTION_ALLOW; + } + } + else + { + if (dest->IsModeSet('B')) + { + dest->SetMode('B',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_DENY; + } +}; + +class ModuleBotMode : public Module +{ + + BotMode* bm; + public: + ModuleBotMode(InspIRCd* Me) + : Module(Me) + { + + bm = new BotMode(ServerInstance); + if (!ServerInstance->AddMode(bm, 'B')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + List[I_OnWhois] = 1; + } + + virtual ~ModuleBotMode() + { + ServerInstance->Modes->DelMode(bm); + DELETE(bm); + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); + } + + virtual void OnWhois(userrec* src, userrec* dst) + { + if (dst->IsModeSet('B')) + { + ServerInstance->SendWhoisLine(src, dst, 335, std::string(src->nick)+" "+std::string(dst->nick)+" :is a bot on "+ServerInstance->Config->Network); + } + } + +}; + + +MODULE_INIT(ModuleBotMode) diff --git a/src/modules/m_cban.cpp b/src/modules/m_cban.cpp index 65be0d9bb..c8e6a86b9 100644 --- a/src/modules/m_cban.cpp +++ b/src/modules/m_cban.cpp @@ -1 +1,251 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include #include "users.h" #include "channels.h" #include "modules.h" #include "configreader.h" /* $ModDesc: Gives /cban, aka C:lines. Think Q:lines, for channels. */ /** Holds a CBAN item */ class CBan : public classbase { public: irc::string chname; std::string set_by; time_t set_on; long length; std::string reason; CBan() { } CBan(irc::string cn, std::string sb, time_t so, long ln, std::string rs) : chname(cn), set_by(sb), set_on(so), length(ln), reason(rs) { } }; bool CBanComp(const CBan &ban1, const CBan &ban2); typedef std::vector cbanlist; /* cbans is declared here, as our type is right above. Don't try move it. */ cbanlist cbans; /** Handle /CBAN */ class cmd_cban : public command_t { public: cmd_cban(InspIRCd* Me) : command_t(Me, "CBAN", 'o', 1) { this->source = "m_cban.so"; this->syntax = " [ :]"; } CmdResult Handle(const char** parameters, int pcnt, userrec *user) { /* syntax: CBAN #channel time :reason goes here */ /* 'time' is a human-readable timestring, like 2d3h2s. */ if(pcnt == 1) { /* form: CBAN #channel removes a CBAN */ for (cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) { if (parameters[0] == iter->chname) { long remaining = iter->length + ServerInstance->Time(); user->WriteServ("386 %s %s :Removed CBAN due to expire at %s (%s)", user->nick, iter->chname.c_str(), ServerInstance->TimeString(remaining).c_str(), iter->reason.c_str()); cbans.erase(iter); break; } } } else if (pcnt >= 2) { /* full form to add a CBAN */ if (ServerInstance->IsChannel(parameters[0])) { // parameters[0] = #channel // parameters[1] = 1h3m2s // parameters[2] = Tortoise abuser long length = ServerInstance->Duration(parameters[1]); std::string reason = (pcnt > 2) ? parameters[2] : "No reason supplied"; cbans.push_back(CBan(parameters[0], user->nick, ServerInstance->Time(), length, reason)); std::sort(cbans.begin(), cbans.end(), CBanComp); if(length > 0) { user->WriteServ("385 %s %s :Added %lu second channel ban (%s)", user->nick, parameters[0], length, reason.c_str()); ServerInstance->WriteOpers("*** %s added %lu second channel ban on %s (%s)", user->nick, length, parameters[0], reason.c_str()); } else { user->WriteServ("385 %s %s :Added permanent channel ban (%s)", user->nick, parameters[0], reason.c_str()); ServerInstance->WriteOpers("*** %s added permanent channel ban on %s (%s)", user->nick, parameters[0], reason.c_str()); } } else { user->WriteServ("403 %s %s :Invalid channel name", user->nick, parameters[0]); return CMD_FAILURE; } } /* we want this routed! */ return CMD_SUCCESS; } }; bool CBanComp(const CBan &ban1, const CBan &ban2) { return ((ban1.set_on + ban1.length) < (ban2.set_on + ban2.length)); } class ModuleCBan : public Module { cmd_cban* mycommand; public: ModuleCBan(InspIRCd* Me) : Module(Me) { mycommand = new cmd_cban(Me); ServerInstance->AddCommand(mycommand); } void Implements(char* List) { List[I_OnUserPreJoin] = List[I_OnSyncOtherMetaData] = List[I_OnDecodeMetaData] = List[I_OnStats] = 1; } virtual int OnStats(char symbol, userrec* user, string_list &results) { ExpireBans(); if(symbol == 'C') { for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) { unsigned long remaining = (iter->set_on + iter->length) - ServerInstance->Time(); results.push_back(std::string(ServerInstance->Config->ServerName)+" 210 "+user->nick+" "+iter->chname.c_str()+" "+iter->set_by+" "+ConvToStr(iter->set_on)+" "+ConvToStr(iter->length)+" "+ConvToStr(remaining)+" :"+iter->reason); } } return 0; } virtual int OnUserPreJoin(userrec *user, chanrec *chan, const char *cname, std::string &privs) { ExpireBans(); /* check cbans in here, and apply as necessary. */ for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) { if(iter->chname == cname && !user->modes[UM_OPERATOR]) { // Channel is banned. user->WriteServ( "384 %s %s :Cannot join channel, CBANed (%s)", user->nick, cname, iter->reason.c_str()); ServerInstance->WriteOpers("*** %s tried to join %s which is CBANed (%s)", user->nick, cname, iter->reason.c_str()); return 1; } } return 0; } virtual void OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable) { for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) { proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "cban", EncodeCBan(*iter)); } } virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) { if((target_type == TYPE_OTHER) && (extname == "cban")) { cbans.push_back(DecodeCBan(extdata)); std::sort(cbans.begin(), cbans.end(), CBanComp); } } virtual ~ModuleCBan() { } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } std::string EncodeCBan(const CBan &ban) { std::ostringstream stream; stream << ban.chname << " " << ban.set_by << " " << ban.set_on << " " << ban.length << " :" << ban.reason; return stream.str(); } CBan DecodeCBan(const std::string &data) { CBan res; int set_on; irc::tokenstream tokens(data); tokens.GetToken(res.chname); tokens.GetToken(res.set_by); tokens.GetToken(set_on); res.set_on = set_on; tokens.GetToken(res.length); tokens.GetToken(res.reason); return res; } void ExpireBans() { bool go_again = true; while (go_again) { go_again = false; for (cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) { /* 0 == permanent, don't mess with them! -- w00t */ if (iter->length != 0) { if (iter->set_on + iter->length <= ServerInstance->Time()) { ServerInstance->WriteOpers("*** %li second CBAN on %s (%s) set on %s expired", iter->length, iter->chname.c_str(), iter->reason.c_str(), ServerInstance->TimeString(iter->set_on).c_str()); cbans.erase(iter); go_again = true; } } if (go_again == true) break; } } } }; MODULE_INIT(ModuleCBan) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "configreader.h" + +/* $ModDesc: Gives /cban, aka C:lines. Think Q:lines, for channels. */ + +/** Holds a CBAN item + */ +class CBan : public classbase +{ +public: + irc::string chname; + std::string set_by; + time_t set_on; + long length; + std::string reason; + + CBan() + { + } + + CBan(irc::string cn, std::string sb, time_t so, long ln, std::string rs) : chname(cn), set_by(sb), set_on(so), length(ln), reason(rs) + { + } +}; + +bool CBanComp(const CBan &ban1, const CBan &ban2); + +typedef std::vector cbanlist; + +/* cbans is declared here, as our type is right above. Don't try move it. */ +cbanlist cbans; + +/** Handle /CBAN + */ +class cmd_cban : public command_t +{ + public: + cmd_cban(InspIRCd* Me) : command_t(Me, "CBAN", 'o', 1) + { + this->source = "m_cban.so"; + this->syntax = " [ :]"; + } + + CmdResult Handle(const char** parameters, int pcnt, userrec *user) + { + /* syntax: CBAN #channel time :reason goes here */ + /* 'time' is a human-readable timestring, like 2d3h2s. */ + + if(pcnt == 1) + { + /* form: CBAN #channel removes a CBAN */ + for (cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) + { + if (parameters[0] == iter->chname) + { + long remaining = iter->length + ServerInstance->Time(); + user->WriteServ("386 %s %s :Removed CBAN due to expire at %s (%s)", user->nick, iter->chname.c_str(), ServerInstance->TimeString(remaining).c_str(), iter->reason.c_str()); + cbans.erase(iter); + break; + } + } + } + else if (pcnt >= 2) + { + /* full form to add a CBAN */ + if (ServerInstance->IsChannel(parameters[0])) + { + // parameters[0] = #channel + // parameters[1] = 1h3m2s + // parameters[2] = Tortoise abuser + long length = ServerInstance->Duration(parameters[1]); + std::string reason = (pcnt > 2) ? parameters[2] : "No reason supplied"; + + cbans.push_back(CBan(parameters[0], user->nick, ServerInstance->Time(), length, reason)); + + std::sort(cbans.begin(), cbans.end(), CBanComp); + + if(length > 0) + { + user->WriteServ("385 %s %s :Added %lu second channel ban (%s)", user->nick, parameters[0], length, reason.c_str()); + ServerInstance->WriteOpers("*** %s added %lu second channel ban on %s (%s)", user->nick, length, parameters[0], reason.c_str()); + } + else + { + user->WriteServ("385 %s %s :Added permanent channel ban (%s)", user->nick, parameters[0], reason.c_str()); + ServerInstance->WriteOpers("*** %s added permanent channel ban on %s (%s)", user->nick, parameters[0], reason.c_str()); + } + } + else + { + user->WriteServ("403 %s %s :Invalid channel name", user->nick, parameters[0]); + return CMD_FAILURE; + } + } + + /* we want this routed! */ + return CMD_SUCCESS; + } +}; + +bool CBanComp(const CBan &ban1, const CBan &ban2) +{ + return ((ban1.set_on + ban1.length) < (ban2.set_on + ban2.length)); +} + +class ModuleCBan : public Module +{ + cmd_cban* mycommand; + + + public: + ModuleCBan(InspIRCd* Me) : Module(Me) + { + + mycommand = new cmd_cban(Me); + ServerInstance->AddCommand(mycommand); + } + + void Implements(char* List) + { + List[I_OnUserPreJoin] = List[I_OnSyncOtherMetaData] = List[I_OnDecodeMetaData] = List[I_OnStats] = 1; + } + + virtual int OnStats(char symbol, userrec* user, string_list &results) + { + ExpireBans(); + + if(symbol == 'C') + { + for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) + { + unsigned long remaining = (iter->set_on + iter->length) - ServerInstance->Time(); + results.push_back(std::string(ServerInstance->Config->ServerName)+" 210 "+user->nick+" "+iter->chname.c_str()+" "+iter->set_by+" "+ConvToStr(iter->set_on)+" "+ConvToStr(iter->length)+" "+ConvToStr(remaining)+" :"+iter->reason); + } + } + + return 0; + } + + virtual int OnUserPreJoin(userrec *user, chanrec *chan, const char *cname, std::string &privs) + { + ExpireBans(); + + /* check cbans in here, and apply as necessary. */ + for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) + { + if(iter->chname == cname && !user->modes[UM_OPERATOR]) + { + // Channel is banned. + user->WriteServ( "384 %s %s :Cannot join channel, CBANed (%s)", user->nick, cname, iter->reason.c_str()); + ServerInstance->WriteOpers("*** %s tried to join %s which is CBANed (%s)", user->nick, cname, iter->reason.c_str()); + return 1; + } + } + return 0; + } + + virtual void OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable) + { + for(cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) + { + proto->ProtoSendMetaData(opaque, TYPE_OTHER, NULL, "cban", EncodeCBan(*iter)); + } + } + + virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) + { + if((target_type == TYPE_OTHER) && (extname == "cban")) + { + cbans.push_back(DecodeCBan(extdata)); + std::sort(cbans.begin(), cbans.end(), CBanComp); + } + } + + virtual ~ModuleCBan() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + + std::string EncodeCBan(const CBan &ban) + { + std::ostringstream stream; + stream << ban.chname << " " << ban.set_by << " " << ban.set_on << " " << ban.length << " :" << ban.reason; + return stream.str(); + } + + CBan DecodeCBan(const std::string &data) + { + CBan res; + int set_on; + irc::tokenstream tokens(data); + tokens.GetToken(res.chname); + tokens.GetToken(res.set_by); + tokens.GetToken(set_on); + res.set_on = set_on; + tokens.GetToken(res.length); + tokens.GetToken(res.reason); + return res; + } + + void ExpireBans() + { + bool go_again = true; + + while (go_again) + { + go_again = false; + + for (cbanlist::iterator iter = cbans.begin(); iter != cbans.end(); iter++) + { + /* 0 == permanent, don't mess with them! -- w00t */ + if (iter->length != 0) + { + if (iter->set_on + iter->length <= ServerInstance->Time()) + { + ServerInstance->WriteOpers("*** %li second CBAN on %s (%s) set on %s expired", iter->length, iter->chname.c_str(), iter->reason.c_str(), ServerInstance->TimeString(iter->set_on).c_str()); + cbans.erase(iter); + go_again = true; + } + } + + if (go_again == true) + break; + } + } + } +}; + +MODULE_INIT(ModuleCBan) + diff --git a/src/modules/m_censor.cpp b/src/modules/m_censor.cpp index a7aa2f8b1..f4a5bd620 100644 --- a/src/modules/m_censor.cpp +++ b/src/modules/m_censor.cpp @@ -1 +1,196 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" typedef std::map censor_t; /* $ModDesc: Provides user and channel +G mode */ /** Handles usermode +G */ class CensorUser : public ModeHandler { public: CensorUser(InspIRCd* Instance) : ModeHandler(Instance, 'G', 0, 0, false, MODETYPE_USER, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (adding) { if (!dest->IsModeSet('G')) { dest->SetMode('G',true); return MODEACTION_ALLOW; } } else { if (dest->IsModeSet('G')) { dest->SetMode('G',false); return MODEACTION_ALLOW; } } return MODEACTION_DENY; } }; /** Handles channel mode +G */ class CensorChannel : public ModeHandler { public: CensorChannel(InspIRCd* Instance) : ModeHandler(Instance, 'G', 0, 0, false, MODETYPE_CHANNEL, false) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (adding) { if (!channel->IsModeSet('G')) { channel->SetMode('G',true); return MODEACTION_ALLOW; } } else { if (channel->IsModeSet('G')) { channel->SetMode('G',false); return MODEACTION_ALLOW; } } return MODEACTION_ALLOW; } }; class ModuleCensor : public Module { censor_t censors; CensorUser *cu; CensorChannel *cc; public: ModuleCensor(InspIRCd* Me) : Module(Me) { /* Read the configuration file on startup. */ OnRehash(NULL,""); cu = new CensorUser(ServerInstance); cc = new CensorChannel(ServerInstance); if (!ServerInstance->AddMode(cu, 'G') || !ServerInstance->AddMode(cc, 'G')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { List[I_OnRehash] = List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = 1; } virtual ~ModuleCensor() { ServerInstance->Modes->DelMode(cu); ServerInstance->Modes->DelMode(cc); DELETE(cu); DELETE(cc); } virtual void ReplaceLine(irc::string &text, irc::string pattern, irc::string replace) { if ((!pattern.empty()) && (!text.empty())) { std::string::size_type pos; while ((pos = text.find(pattern)) != irc::string::npos) { text.erase(pos,pattern.length()); text.insert(pos,replace); } } } // format of a config entry is virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) { if (!IS_LOCAL(user)) return 0; bool active = false; if (target_type == TYPE_USER) active = ((userrec*)dest)->IsModeSet('G'); else if (target_type == TYPE_CHANNEL) active = ((chanrec*)dest)->IsModeSet('G'); if (!active) return 0; irc::string text2 = text.c_str(); for (censor_t::iterator index = censors.begin(); index != censors.end(); index++) { if (text2.find(index->first) != irc::string::npos) { if (index->second.empty()) { user->WriteServ("936 %s %s %s :Your message contained a censored word, and was blocked", user->nick, ((chanrec*)dest)->name, index->first.c_str()); return 1; } this->ReplaceLine(text2,index->first,index->second); } } text = text2.c_str(); return 0; } virtual int OnUserPreNotice(userrec* 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(userrec* user, const std::string ¶meter) { /* * reload our config file on rehash - we must destroy and re-allocate the classes * to call the constructor again and re-read our data. */ ConfigReader* MyConf = new ConfigReader(ServerInstance); censors.clear(); for (int index = 0; index < MyConf->Enumerate("badword"); index++) { irc::string pattern = (MyConf->ReadValue("badword","text",index)).c_str(); irc::string replace = (MyConf->ReadValue("badword","replace",index)).c_str(); censors[pattern] = replace; } DELETE(MyConf); } virtual Version GetVersion() { return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleCensor) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#define _CRT_SECURE_NO_DEPRECATE +#define _SCL_SECURE_NO_DEPRECATE + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +typedef std::map censor_t; + +/* $ModDesc: Provides user and channel +G mode */ + +/** Handles usermode +G + */ +class CensorUser : public ModeHandler +{ + public: + CensorUser(InspIRCd* Instance) : ModeHandler(Instance, 'G', 0, 0, false, MODETYPE_USER, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (adding) + { + if (!dest->IsModeSet('G')) + { + dest->SetMode('G',true); + return MODEACTION_ALLOW; + } + } + else + { + if (dest->IsModeSet('G')) + { + dest->SetMode('G',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_DENY; + } +}; + +/** Handles channel mode +G + */ +class CensorChannel : public ModeHandler +{ + public: + CensorChannel(InspIRCd* Instance) : ModeHandler(Instance, 'G', 0, 0, false, MODETYPE_CHANNEL, false) { } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (adding) + { + if (!channel->IsModeSet('G')) + { + channel->SetMode('G',true); + return MODEACTION_ALLOW; + } + } + else + { + if (channel->IsModeSet('G')) + { + channel->SetMode('G',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_ALLOW; + } +}; + +class ModuleCensor : public Module +{ + + + censor_t censors; + CensorUser *cu; + CensorChannel *cc; + + public: + ModuleCensor(InspIRCd* Me) + : Module(Me) + { + /* Read the configuration file on startup. + */ + OnRehash(NULL,""); + cu = new CensorUser(ServerInstance); + cc = new CensorChannel(ServerInstance); + if (!ServerInstance->AddMode(cu, 'G') || !ServerInstance->AddMode(cc, 'G')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = 1; + } + + virtual ~ModuleCensor() + { + ServerInstance->Modes->DelMode(cu); + ServerInstance->Modes->DelMode(cc); + DELETE(cu); + DELETE(cc); + } + + virtual void ReplaceLine(irc::string &text, irc::string pattern, irc::string replace) + { + if ((!pattern.empty()) && (!text.empty())) + { + std::string::size_type pos; + while ((pos = text.find(pattern)) != irc::string::npos) + { + text.erase(pos,pattern.length()); + text.insert(pos,replace); + } + } + } + + // format of a config entry is + virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + { + if (!IS_LOCAL(user)) + return 0; + + bool active = false; + + if (target_type == TYPE_USER) + active = ((userrec*)dest)->IsModeSet('G'); + else if (target_type == TYPE_CHANNEL) + active = ((chanrec*)dest)->IsModeSet('G'); + + if (!active) + return 0; + + irc::string text2 = text.c_str(); + for (censor_t::iterator index = censors.begin(); index != censors.end(); index++) + { + if (text2.find(index->first) != irc::string::npos) + { + if (index->second.empty()) + { + user->WriteServ("936 %s %s %s :Your message contained a censored word, and was blocked", user->nick, ((chanrec*)dest)->name, index->first.c_str()); + return 1; + } + + this->ReplaceLine(text2,index->first,index->second); + } + } + text = text2.c_str(); + return 0; + } + + virtual int OnUserPreNotice(userrec* 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(userrec* user, const std::string ¶meter) + { + /* + * reload our config file on rehash - we must destroy and re-allocate the classes + * to call the constructor again and re-read our data. + */ + ConfigReader* MyConf = new ConfigReader(ServerInstance); + censors.clear(); + for (int index = 0; index < MyConf->Enumerate("badword"); index++) + { + irc::string pattern = (MyConf->ReadValue("badword","text",index)).c_str(); + irc::string replace = (MyConf->ReadValue("badword","replace",index)).c_str(); + censors[pattern] = replace; + } + DELETE(MyConf); + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_COMMON|VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleCensor) diff --git a/src/modules/m_cgiirc.cpp b/src/modules/m_cgiirc.cpp index 64fd6c69f..290f55d22 100644 --- a/src/modules/m_cgiirc.cpp +++ b/src/modules/m_cgiirc.cpp @@ -1 +1,511 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "modules.h" #include "dns.h" #ifndef WINDOWS #include #include #include #endif /* $ModDesc: Change user's hosts connecting from known CGI:IRC hosts */ enum CGItype { PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC }; /** Holds a CGI site's details */ class CGIhost : public classbase { public: std::string hostmask; CGItype type; std::string password; CGIhost(const std::string &mask = "", CGItype t = IDENTFIRST, const std::string &password ="") : hostmask(mask), type(t), password(password) { } }; typedef std::vector CGIHostlist; class cmd_webirc : public command_t { InspIRCd* Me; CGIHostlist Hosts; bool notify; public: cmd_webirc(InspIRCd* Me, CGIHostlist &Hosts, bool notify) : command_t(Me, "WEBIRC", 0, 4, true), Hosts(Hosts), notify(notify) { this->source = "m_cgiirc.so"; this->syntax = "password client hostname ip"; } CmdResult Handle(const char** parameters, int pcnt, userrec *user) { if(user->registered == REG_ALL) return CMD_FAILURE; for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++) { if(ServerInstance->MatchText(user->host, iter->hostmask) || ServerInstance->MatchText(user->GetIPString(), iter->hostmask)) { if(iter->type == WEBIRC && parameters[0] == iter->password) { user->Extend("cgiirc_realhost", new std::string(user->host)); user->Extend("cgiirc_realip", new std::string(user->GetIPString())); if (notify) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick, user->host, parameters[2], user->host); user->Extend("cgiirc_webirc_hostname", new std::string(parameters[2])); user->Extend("cgiirc_webirc_ip", new std::string(parameters[3])); return CMD_LOCALONLY; } } } return CMD_FAILURE; } }; /** Resolver for CGI:IRC hostnames encoded in ident/GECOS */ class CGIResolver : public Resolver { std::string typ; int theirfd; userrec* them; bool notify; public: CGIResolver(Module* me, InspIRCd* ServerInstance, bool NotifyOpers, const std::string &source, bool forward, userrec* u, int userfd, const std::string &type, bool &cached) : Resolver(ServerInstance, source, forward ? DNS_QUERY_A : DNS_QUERY_PTR4, cached, me), typ(type), theirfd(userfd), them(u), notify(NotifyOpers) { } virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) { /* Check the user still exists */ if ((them) && (them == ServerInstance->SE->GetRef(theirfd))) { if (notify) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick, them->host, result.c_str(), typ.c_str()); strlcpy(them->host, result.c_str(), 63); strlcpy(them->dhost, result.c_str(), 63); strlcpy(them->ident, "~cgiirc", 8); them->InvalidateCache(); } } virtual void OnError(ResolverError e, const std::string &errormessage) { if ((them) && (them == ServerInstance->SE->GetRef(theirfd))) { if (notify) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick, them->host,typ.c_str()); } } virtual ~CGIResolver() { } }; class ModuleCgiIRC : public Module { cmd_webirc* mycommand; bool NotifyOpers; CGIHostlist Hosts; public: ModuleCgiIRC(InspIRCd* Me) : Module(Me) { OnRehash(NULL,""); mycommand=new cmd_webirc(Me, Hosts, NotifyOpers); ServerInstance->AddCommand(mycommand); } void Implements(char* List) { List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCleanup] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUserQuit] = List[I_OnUserConnect] = 1; } virtual Priority Prioritize() { // We want to get here before m_cloaking and m_hostchange etc return PRIORITY_FIRST; } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader Conf(ServerInstance); NotifyOpers = Conf.ReadFlag("cgiirc", "opernotice", 0); // If we send an oper notice when a CGI:IRC has their host changed. if(Conf.GetError() == CONF_VALUE_NOT_FOUND) NotifyOpers = true; for(int i = 0; i < Conf.Enumerate("cgihost"); i++) { std::string hostmask = Conf.ReadValue("cgihost", "mask", i); // An allowed CGI:IRC host std::string type = Conf.ReadValue("cgihost", "type", i); // What type of user-munging we do on this host. std::string password = Conf.ReadValue("cgihost", "password", i); if(hostmask.length()) { if(type == "webirc" && !password.length()) { ServerInstance->Log(DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str()); } else { CGItype cgitype; if(type == "pass") cgitype = PASS; else if(type == "ident") cgitype = IDENT; else if(type == "passfirst") cgitype = PASSFIRST; else if(type == "webirc") { cgitype = WEBIRC; } Hosts.push_back(CGIhost(hostmask,cgitype, password.length() ? password : "" )); } } else { ServerInstance->Log(DEFAULT, "m_cgiirc.so: Invalid value in config: %s", hostmask.c_str()); continue; } } } virtual void OnCleanup(int target_type, void* item) { if(target_type == TYPE_USER) { userrec* user = (userrec*)item; std::string* realhost; std::string* realip; if(user->GetExt("cgiirc_realhost", realhost)) { delete realhost; user->Shrink("cgiirc_realhost"); } if(user->GetExt("cgiirc_realip", realip)) { delete realip; user->Shrink("cgiirc_realip"); } } } virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) { if((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) { std::string* data; if(user->GetExt(extname, data)) { proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *data); } } } virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) { if(target_type == TYPE_USER) { userrec* dest = (userrec*)target; std::string* bleh; if(((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) && (!dest->GetExt(extname, bleh))) { dest->Extend(extname, new std::string(extdata)); } } } virtual void OnUserQuit(userrec* user, const std::string &message, const std::string &oper_message) { OnCleanup(TYPE_USER, user); } virtual int OnUserRegister(userrec* user) { for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++) { if(ServerInstance->MatchText(user->host, iter->hostmask) || ServerInstance->MatchText(user->GetIPString(), iter->hostmask)) { // Deal with it... if(iter->type == PASS) { CheckPass(user); // We do nothing if it fails so... } else if(iter->type == PASSFIRST && !CheckPass(user)) { // If the password lookup failed, try the ident CheckIdent(user); // If this fails too, do nothing } else if(iter->type == IDENT) { CheckIdent(user); // Nothing on failure. } else if(iter->type == IDENTFIRST && !CheckIdent(user)) { // If the ident lookup fails, try the password. CheckPass(user); } else if(iter->type == WEBIRC) { // We don't need to do anything here } return 0; } } return 0; } virtual void OnUserConnect(userrec* user) { std::string *webirc_hostname, *webirc_ip; if(user->GetExt("cgiirc_webirc_hostname", webirc_hostname)) { strlcpy(user->host,webirc_hostname->c_str(),63); strlcpy(user->dhost,webirc_hostname->c_str(),63); delete webirc_hostname; user->InvalidateCache(); user->Shrink("cgiirc_webirc_hostname"); } if(user->GetExt("cgiirc_webirc_ip", webirc_ip)) { bool valid=false; user->RemoveCloneCounts(); #ifdef IPV6 valid = (inet_pton(AF_INET6, webirc_ip->c_str(), &((sockaddr_in6*)user->ip)->sin6_addr) > 0); if(!valid) valid = (inet_aton(webirc_ip->c_str(), &((sockaddr_in*)user->ip)->sin_addr)); #else if (inet_aton(webirc_ip->c_str(), &((sockaddr_in*)user->ip)->sin_addr)) valid = true; #endif delete webirc_ip; user->InvalidateCache(); user->Shrink("cgiirc_webirc_ip"); ServerInstance->AddLocalClone(user); ServerInstance->AddGlobalClone(user); user->CheckClass(); } } bool CheckPass(userrec* user) { if(IsValidHost(user->password)) { user->Extend("cgiirc_realhost", new std::string(user->host)); user->Extend("cgiirc_realip", new std::string(user->GetIPString())); strlcpy(user->host, user->password, 64); strlcpy(user->dhost, user->password, 64); user->InvalidateCache(); bool valid = false; user->RemoveCloneCounts(); #ifdef IPV6 if (user->GetProtocolFamily() == AF_INET6) valid = (inet_pton(AF_INET6, user->password, &((sockaddr_in6*)user->ip)->sin6_addr) > 0); else valid = (inet_aton(user->password, &((sockaddr_in*)user->ip)->sin_addr)); #else if (inet_aton(user->password, &((sockaddr_in*)user->ip)->sin_addr)) valid = true; #endif ServerInstance->AddLocalClone(user); ServerInstance->AddGlobalClone(user); user->CheckClass(); if (valid) { /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */ if(NotifyOpers) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from PASS", user->nick, user->host, user->password); } else { /* We got as resolved hostname in the password. */ try { bool cached; CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached); ServerInstance->AddResolver(r, cached); } catch (...) { if (NotifyOpers) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but i could not resolve their hostname!", user->nick, user->host); } } *user->password = 0; /*if(NotifyOpers) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from PASS", user->nick, user->host, user->password);*/ return true; } return false; } bool CheckIdent(userrec* user) { int ip[4]; char* ident; char newip[16]; int len = strlen(user->ident); if(len == 8) ident = user->ident; else if(len == 9 && *user->ident == '~') ident = user->ident+1; else return false; for(int i = 0; i < 4; i++) if(!HexToInt(ip[i], ident + i*2)) return false; snprintf(newip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); user->Extend("cgiirc_realhost", new std::string(user->host)); user->Extend("cgiirc_realip", new std::string(user->GetIPString())); user->RemoveCloneCounts(); #ifdef IPV6 if (user->GetProtocolFamily() == AF_INET6) inet_pton(AF_INET6, newip, &((sockaddr_in6*)user->ip)->sin6_addr); else #endif inet_aton(newip, &((sockaddr_in*)user->ip)->sin_addr); ServerInstance->AddLocalClone(user); ServerInstance->AddGlobalClone(user); user->CheckClass(); try { strlcpy(user->host, newip, 16); strlcpy(user->dhost, newip, 16); strlcpy(user->ident, "~cgiirc", 8); bool cached; CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newip, false, user, user->GetFd(), "IDENT", cached); ServerInstance->AddResolver(r, cached); } catch (...) { strlcpy(user->host, newip, 16); strlcpy(user->dhost, newip, 16); strlcpy(user->ident, "~cgiirc", 8); user->InvalidateCache(); if(NotifyOpers) ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but i could not resolve their hostname!", user->nick, user->host); } /*strlcpy(user->host, newip, 16); strlcpy(user->dhost, newip, 16); strlcpy(user->ident, "~cgiirc", 8);*/ return true; } bool IsValidHost(const std::string &host) { if(!host.size()) return false; for(unsigned int i = 0; i < host.size(); i++) { if( ((host[i] >= '0') && (host[i] <= '9')) || ((host[i] >= 'A') && (host[i] <= 'Z')) || ((host[i] >= 'a') && (host[i] <= 'z')) || ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) || ((host[i] == '.') && (i > 0) && (i+1 < host.size())) ) continue; else return false; } return true; } bool IsValidIP(const std::string &ip) { if(ip.size() < 7 || ip.size() > 15) return false; short sincedot = 0; short dots = 0; for(unsigned int i = 0; i < ip.size(); i++) { if((dots <= 3) && (sincedot <= 3)) { if((ip[i] >= '0') && (ip[i] <= '9')) { sincedot++; } else if(ip[i] == '.') { sincedot = 0; dots++; } } else { return false; } } if(dots != 3) return false; return true; } bool HexToInt(int &out, const char* in) { char ip[3]; ip[0] = in[0]; ip[1] = in[1]; ip[2] = 0; out = strtol(ip, NULL, 16); if(out > 255 || out < 0) return false; return true; } virtual ~ModuleCgiIRC() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleCgiIRC) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "modules.h" +#include "dns.h" +#ifndef WINDOWS +#include +#include +#include +#endif + +/* $ModDesc: Change user's hosts connecting from known CGI:IRC hosts */ + +enum CGItype { PASS, IDENT, PASSFIRST, IDENTFIRST, WEBIRC }; + + +/** Holds a CGI site's details + */ +class CGIhost : public classbase +{ +public: + std::string hostmask; + CGItype type; + std::string password; + + CGIhost(const std::string &mask = "", CGItype t = IDENTFIRST, const std::string &password ="") + : hostmask(mask), type(t), password(password) + { + } +}; +typedef std::vector CGIHostlist; + +class cmd_webirc : public command_t +{ + InspIRCd* Me; + CGIHostlist Hosts; + bool notify; + public: + cmd_webirc(InspIRCd* Me, CGIHostlist &Hosts, bool notify) : command_t(Me, "WEBIRC", 0, 4, true), Hosts(Hosts), notify(notify) + { + this->source = "m_cgiirc.so"; + this->syntax = "password client hostname ip"; + } + CmdResult Handle(const char** parameters, int pcnt, userrec *user) + { + if(user->registered == REG_ALL) + return CMD_FAILURE; + + for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++) + { + if(ServerInstance->MatchText(user->host, iter->hostmask) || ServerInstance->MatchText(user->GetIPString(), iter->hostmask)) + { + if(iter->type == WEBIRC && parameters[0] == iter->password) + { + user->Extend("cgiirc_realhost", new std::string(user->host)); + user->Extend("cgiirc_realip", new std::string(user->GetIPString())); + if (notify) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", user->nick, user->host, parameters[2], user->host); + user->Extend("cgiirc_webirc_hostname", new std::string(parameters[2])); + user->Extend("cgiirc_webirc_ip", new std::string(parameters[3])); + return CMD_LOCALONLY; + } + } + } + return CMD_FAILURE; + } +}; + + +/** Resolver for CGI:IRC hostnames encoded in ident/GECOS + */ +class CGIResolver : public Resolver +{ + std::string typ; + int theirfd; + userrec* them; + bool notify; + public: + CGIResolver(Module* me, InspIRCd* ServerInstance, bool NotifyOpers, const std::string &source, bool forward, userrec* u, int userfd, const std::string &type, bool &cached) + : Resolver(ServerInstance, source, forward ? DNS_QUERY_A : DNS_QUERY_PTR4, cached, me), typ(type), theirfd(userfd), them(u), notify(NotifyOpers) { } + + virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached) + { + /* Check the user still exists */ + if ((them) && (them == ServerInstance->SE->GetRef(theirfd))) + { + if (notify) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from %s", them->nick, them->host, result.c_str(), typ.c_str()); + + strlcpy(them->host, result.c_str(), 63); + strlcpy(them->dhost, result.c_str(), 63); + strlcpy(them->ident, "~cgiirc", 8); + them->InvalidateCache(); + } + } + + virtual void OnError(ResolverError e, const std::string &errormessage) + { + if ((them) && (them == ServerInstance->SE->GetRef(theirfd))) + { + if (notify) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but their host can't be resolved from their %s!", them->nick, them->host,typ.c_str()); + } + } + + virtual ~CGIResolver() + { + } +}; + +class ModuleCgiIRC : public Module +{ + cmd_webirc* mycommand; + bool NotifyOpers; + CGIHostlist Hosts; +public: + ModuleCgiIRC(InspIRCd* Me) : Module(Me) + { + + OnRehash(NULL,""); + mycommand=new cmd_webirc(Me, Hosts, NotifyOpers); + ServerInstance->AddCommand(mycommand); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCleanup] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUserQuit] = List[I_OnUserConnect] = 1; + } + + virtual Priority Prioritize() + { + // We want to get here before m_cloaking and m_hostchange etc + return PRIORITY_FIRST; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader Conf(ServerInstance); + + NotifyOpers = Conf.ReadFlag("cgiirc", "opernotice", 0); // If we send an oper notice when a CGI:IRC has their host changed. + + if(Conf.GetError() == CONF_VALUE_NOT_FOUND) + NotifyOpers = true; + + for(int i = 0; i < Conf.Enumerate("cgihost"); i++) + { + std::string hostmask = Conf.ReadValue("cgihost", "mask", i); // An allowed CGI:IRC host + std::string type = Conf.ReadValue("cgihost", "type", i); // What type of user-munging we do on this host. + std::string password = Conf.ReadValue("cgihost", "password", i); + + if(hostmask.length()) + { + if(type == "webirc" && !password.length()) { + ServerInstance->Log(DEFAULT, "m_cgiirc: Missing password in config: %s", hostmask.c_str()); + } else { + CGItype cgitype; + if(type == "pass") + cgitype = PASS; + else if(type == "ident") + cgitype = IDENT; + else if(type == "passfirst") + cgitype = PASSFIRST; + else if(type == "webirc") { + cgitype = WEBIRC; + } + Hosts.push_back(CGIhost(hostmask,cgitype, password.length() ? password : "" )); + } + } + else + { + ServerInstance->Log(DEFAULT, "m_cgiirc.so: Invalid value in config: %s", hostmask.c_str()); + continue; + } + } + } + + virtual void OnCleanup(int target_type, void* item) + { + if(target_type == TYPE_USER) + { + userrec* user = (userrec*)item; + std::string* realhost; + std::string* realip; + + if(user->GetExt("cgiirc_realhost", realhost)) + { + delete realhost; + user->Shrink("cgiirc_realhost"); + } + + if(user->GetExt("cgiirc_realip", realip)) + { + delete realip; + user->Shrink("cgiirc_realip"); + } + } + } + + virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname, bool displayable) + { + if((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) + { + std::string* data; + + if(user->GetExt(extname, data)) + { + proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, *data); + } + } + } + + virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) + { + if(target_type == TYPE_USER) + { + userrec* dest = (userrec*)target; + std::string* bleh; + if(((extname == "cgiirc_realhost") || (extname == "cgiirc_realip")) && (!dest->GetExt(extname, bleh))) + { + dest->Extend(extname, new std::string(extdata)); + } + } + } + + virtual void OnUserQuit(userrec* user, const std::string &message, const std::string &oper_message) + { + OnCleanup(TYPE_USER, user); + } + + + virtual int OnUserRegister(userrec* user) + { + for(CGIHostlist::iterator iter = Hosts.begin(); iter != Hosts.end(); iter++) + { + if(ServerInstance->MatchText(user->host, iter->hostmask) || ServerInstance->MatchText(user->GetIPString(), iter->hostmask)) + { + // Deal with it... + if(iter->type == PASS) + { + CheckPass(user); // We do nothing if it fails so... + } + else if(iter->type == PASSFIRST && !CheckPass(user)) + { + // If the password lookup failed, try the ident + CheckIdent(user); // If this fails too, do nothing + } + else if(iter->type == IDENT) + { + CheckIdent(user); // Nothing on failure. + } + else if(iter->type == IDENTFIRST && !CheckIdent(user)) + { + // If the ident lookup fails, try the password. + CheckPass(user); + } + else if(iter->type == WEBIRC) + { + // We don't need to do anything here + } + return 0; + } + } + return 0; + } + + virtual void OnUserConnect(userrec* user) + { + std::string *webirc_hostname, *webirc_ip; + if(user->GetExt("cgiirc_webirc_hostname", webirc_hostname)) + { + strlcpy(user->host,webirc_hostname->c_str(),63); + strlcpy(user->dhost,webirc_hostname->c_str(),63); + delete webirc_hostname; + user->InvalidateCache(); + user->Shrink("cgiirc_webirc_hostname"); + } + if(user->GetExt("cgiirc_webirc_ip", webirc_ip)) + { + bool valid=false; + user->RemoveCloneCounts(); +#ifdef IPV6 + valid = (inet_pton(AF_INET6, webirc_ip->c_str(), &((sockaddr_in6*)user->ip)->sin6_addr) > 0); + + if(!valid) + valid = (inet_aton(webirc_ip->c_str(), &((sockaddr_in*)user->ip)->sin_addr)); +#else + if (inet_aton(webirc_ip->c_str(), &((sockaddr_in*)user->ip)->sin_addr)) + valid = true; +#endif + + delete webirc_ip; + user->InvalidateCache(); + user->Shrink("cgiirc_webirc_ip"); + ServerInstance->AddLocalClone(user); + ServerInstance->AddGlobalClone(user); + user->CheckClass(); + } + } + + bool CheckPass(userrec* user) + { + if(IsValidHost(user->password)) + { + user->Extend("cgiirc_realhost", new std::string(user->host)); + user->Extend("cgiirc_realip", new std::string(user->GetIPString())); + strlcpy(user->host, user->password, 64); + strlcpy(user->dhost, user->password, 64); + user->InvalidateCache(); + + bool valid = false; + user->RemoveCloneCounts(); +#ifdef IPV6 + if (user->GetProtocolFamily() == AF_INET6) + valid = (inet_pton(AF_INET6, user->password, &((sockaddr_in6*)user->ip)->sin6_addr) > 0); + else + valid = (inet_aton(user->password, &((sockaddr_in*)user->ip)->sin_addr)); +#else + if (inet_aton(user->password, &((sockaddr_in*)user->ip)->sin_addr)) + valid = true; +#endif + ServerInstance->AddLocalClone(user); + ServerInstance->AddGlobalClone(user); + user->CheckClass(); + + if (valid) + { + /* We were given a IP in the password, we don't do DNS so they get this is as their host as well. */ + if(NotifyOpers) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from PASS", user->nick, user->host, user->password); + } + else + { + /* We got as resolved hostname in the password. */ + try + { + + bool cached; + CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, user->password, false, user, user->GetFd(), "PASS", cached); + ServerInstance->AddResolver(r, cached); + } + catch (...) + { + if (NotifyOpers) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but i could not resolve their hostname!", user->nick, user->host); + } + } + + *user->password = 0; + + /*if(NotifyOpers) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), changing real host to %s from PASS", user->nick, user->host, user->password);*/ + + return true; + } + + return false; + } + + bool CheckIdent(userrec* user) + { + int ip[4]; + char* ident; + char newip[16]; + int len = strlen(user->ident); + + if(len == 8) + ident = user->ident; + else if(len == 9 && *user->ident == '~') + ident = user->ident+1; + else + return false; + + for(int i = 0; i < 4; i++) + if(!HexToInt(ip[i], ident + i*2)) + return false; + + snprintf(newip, 16, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + + user->Extend("cgiirc_realhost", new std::string(user->host)); + user->Extend("cgiirc_realip", new std::string(user->GetIPString())); + user->RemoveCloneCounts(); +#ifdef IPV6 + if (user->GetProtocolFamily() == AF_INET6) + inet_pton(AF_INET6, newip, &((sockaddr_in6*)user->ip)->sin6_addr); + else +#endif + inet_aton(newip, &((sockaddr_in*)user->ip)->sin_addr); + ServerInstance->AddLocalClone(user); + ServerInstance->AddGlobalClone(user); + user->CheckClass(); + try + { + strlcpy(user->host, newip, 16); + strlcpy(user->dhost, newip, 16); + strlcpy(user->ident, "~cgiirc", 8); + + bool cached; + CGIResolver* r = new CGIResolver(this, ServerInstance, NotifyOpers, newip, false, user, user->GetFd(), "IDENT", cached); + ServerInstance->AddResolver(r, cached); + } + catch (...) + { + strlcpy(user->host, newip, 16); + strlcpy(user->dhost, newip, 16); + strlcpy(user->ident, "~cgiirc", 8); + user->InvalidateCache(); + + if(NotifyOpers) + ServerInstance->WriteOpers("*** Connecting user %s detected as using CGI:IRC (%s), but i could not resolve their hostname!", user->nick, user->host); + } + /*strlcpy(user->host, newip, 16); + strlcpy(user->dhost, newip, 16); + strlcpy(user->ident, "~cgiirc", 8);*/ + + return true; + } + + bool IsValidHost(const std::string &host) + { + if(!host.size()) + return false; + + for(unsigned int i = 0; i < host.size(); i++) + { + if( ((host[i] >= '0') && (host[i] <= '9')) || + ((host[i] >= 'A') && (host[i] <= 'Z')) || + ((host[i] >= 'a') && (host[i] <= 'z')) || + ((host[i] == '-') && (i > 0) && (i+1 < host.size()) && (host[i-1] != '.') && (host[i+1] != '.')) || + ((host[i] == '.') && (i > 0) && (i+1 < host.size())) ) + + continue; + else + return false; + } + + return true; + } + + bool IsValidIP(const std::string &ip) + { + if(ip.size() < 7 || ip.size() > 15) + return false; + + short sincedot = 0; + short dots = 0; + + for(unsigned int i = 0; i < ip.size(); i++) + { + if((dots <= 3) && (sincedot <= 3)) + { + if((ip[i] >= '0') && (ip[i] <= '9')) + { + sincedot++; + } + else if(ip[i] == '.') + { + sincedot = 0; + dots++; + } + } + else + { + return false; + + } + } + + if(dots != 3) + return false; + + return true; + } + + bool HexToInt(int &out, const char* in) + { + char ip[3]; + ip[0] = in[0]; + ip[1] = in[1]; + ip[2] = 0; + out = strtol(ip, NULL, 16); + + if(out > 255 || out < 0) + return false; + + return true; + } + + virtual ~ModuleCgiIRC() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleCgiIRC) diff --git a/src/modules/m_chancreate.cpp b/src/modules/m_chancreate.cpp index 8837db9c5..915e7c8cb 100644 --- a/src/modules/m_chancreate.cpp +++ b/src/modules/m_chancreate.cpp @@ -1 +1,55 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Creates a snomask with notices whenever a new channel is created */ class ModuleChanCreate : public Module { private: public: ModuleChanCreate(InspIRCd* Me) : Module(Me) { ServerInstance->SNO->EnableSnomask('j', "CHANCREATE"); } virtual ~ModuleChanCreate() { ServerInstance->SNO->DisableSnomask('j'); } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } void Implements(char* List) { List[I_OnUserJoin] = 1; } virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) { if (channel->GetUserCounter() == 1) { ServerInstance->SNO->WriteToSnoMask('j', "Channel %s created by %s!%s@%s", channel->name, user->nick, user->ident, user->host); } } }; MODULE_INIT(ModuleChanCreate) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Creates a snomask with notices whenever a new channel is created */ + +class ModuleChanCreate : public Module +{ + private: + public: + ModuleChanCreate(InspIRCd* Me) + : Module(Me) + { + ServerInstance->SNO->EnableSnomask('j', "CHANCREATE"); + } + + virtual ~ModuleChanCreate() + { + ServerInstance->SNO->DisableSnomask('j'); + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + + void Implements(char* List) + { + List[I_OnUserJoin] = 1; + } + + virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) + { + if (channel->GetUserCounter() == 1) + { + ServerInstance->SNO->WriteToSnoMask('j', "Channel %s created by %s!%s@%s", channel->name, user->nick, user->ident, user->host); + } + } +}; + +MODULE_INIT(ModuleChanCreate) diff --git a/src/modules/m_chanfilter.cpp b/src/modules/m_chanfilter.cpp index 44aac9dae..375fbce9c 100644 --- a/src/modules/m_chanfilter.cpp +++ b/src/modules/m_chanfilter.cpp @@ -1 +1,155 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "hashcomp.h" #include "u_listmode.h" /* $ModDesc: Provides channel-specific censor lists (like mode +G but varies from channel to channel) */ /* $ModDep: ../../include/u_listmode.h */ /** Handles channel mode +g */ class ChanFilter : public ListModeBase { public: ChanFilter(InspIRCd* Instance) : ListModeBase(Instance, 'g', "End of channel spamfilter list", "941", "940", false, "chanfilter") { } virtual bool ValidateParam(userrec* user, chanrec* chan, std::string &word) { if ((word.length() > 35) || (word.empty())) { user->WriteServ("935 %s %s %s :word is too %s for censor list",user->nick, chan->name,word.c_str(), (word.empty() ? "short" : "long")); return false; } return true; } virtual bool TellListTooLong(userrec* user, chanrec* chan, std::string &word) { user->WriteServ("939 %s %s %s :Channel spamfilter list is full",user->nick, chan->name, word.c_str()); return true; } virtual void TellAlreadyOnList(userrec* user, chanrec* chan, std::string &word) { user->WriteServ("937 %s %s :The word %s is already on the spamfilter list",user->nick, chan->name,word.c_str()); } virtual void TellNotSet(userrec* user, chanrec* chan, std::string &word) { user->WriteServ("938 %s %s :No such spamfilter word is set",user->nick, chan->name); } }; class ModuleChanFilter : public Module { ChanFilter* cf; public: ModuleChanFilter(InspIRCd* Me) : Module(Me) { cf = new ChanFilter(ServerInstance); if (!ServerInstance->AddMode(cf, 'g')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { cf->DoImplements(List); List[I_OnCleanup] = List[I_OnChannelDelete] = List[I_OnRehash] = List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = List[I_OnSyncChannel] = 1; } virtual void OnChannelDelete(chanrec* chan) { cf->DoChannelDelete(chan); } virtual void OnRehash(userrec* user, const std::string ¶meter) { cf->DoRehash(); } virtual int ProcessMessages(userrec* user,chanrec* chan,std::string &text) { if (!IS_LOCAL(user) || CHANOPS_EXEMPT(ServerInstance, 'g') && chan->GetStatus(user) == STATUS_OP) return 0; // Create a copy of the string in irc::string irc::string line = text.c_str(); modelist* list; chan->GetExt(cf->GetInfoKey(), list); if (list) { for (modelist::iterator i = list->begin(); i != list->end(); i++) { if (line.find(i->mask.c_str()) != std::string::npos) { user->WriteServ("936 %s %s %s :Your message contained a censored word, and was blocked",user->nick, chan->name, i->mask.c_str()); return 1; } } } return 0; } virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) { if (target_type == TYPE_CHANNEL) { return ProcessMessages(user,(chanrec*)dest,text); } else return 0; } virtual void OnCleanup(int target_type, void* item) { cf->DoCleanup(target_type, item); } virtual int OnUserPreNotice(userrec* 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(chanrec* chan, Module* proto, void* opaque) { cf->DoSyncChannel(chan, proto, opaque); } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); } virtual ~ModuleChanFilter() { ServerInstance->Modes->DelMode(cf); DELETE(cf); } }; MODULE_INIT(ModuleChanFilter) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#define _CRT_SECURE_NO_DEPRECATE +#define _SCL_SECURE_NO_DEPRECATE + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "hashcomp.h" +#include "u_listmode.h" + +/* $ModDesc: Provides channel-specific censor lists (like mode +G but varies from channel to channel) */ +/* $ModDep: ../../include/u_listmode.h */ + +/** Handles channel mode +g + */ +class ChanFilter : public ListModeBase +{ + public: + ChanFilter(InspIRCd* Instance) : ListModeBase(Instance, 'g', "End of channel spamfilter list", "941", "940", false, "chanfilter") { } + + virtual bool ValidateParam(userrec* user, chanrec* chan, std::string &word) + { + if ((word.length() > 35) || (word.empty())) + { + user->WriteServ("935 %s %s %s :word is too %s for censor list",user->nick, chan->name,word.c_str(), (word.empty() ? "short" : "long")); + return false; + } + + return true; + } + + virtual bool TellListTooLong(userrec* user, chanrec* chan, std::string &word) + { + user->WriteServ("939 %s %s %s :Channel spamfilter list is full",user->nick, chan->name, word.c_str()); + return true; + } + + virtual void TellAlreadyOnList(userrec* user, chanrec* chan, std::string &word) + { + user->WriteServ("937 %s %s :The word %s is already on the spamfilter list",user->nick, chan->name,word.c_str()); + } + + virtual void TellNotSet(userrec* user, chanrec* chan, std::string &word) + { + user->WriteServ("938 %s %s :No such spamfilter word is set",user->nick, chan->name); + } +}; + +class ModuleChanFilter : public Module +{ + + ChanFilter* cf; + + public: + + ModuleChanFilter(InspIRCd* Me) + : Module(Me) + { + cf = new ChanFilter(ServerInstance); + if (!ServerInstance->AddMode(cf, 'g')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + cf->DoImplements(List); + List[I_OnCleanup] = List[I_OnChannelDelete] = List[I_OnRehash] = List[I_OnUserPreMessage] = List[I_OnUserPreNotice] = List[I_OnSyncChannel] = 1; + } + + virtual void OnChannelDelete(chanrec* chan) + { + cf->DoChannelDelete(chan); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + cf->DoRehash(); + } + + virtual int ProcessMessages(userrec* user,chanrec* chan,std::string &text) + { + if (!IS_LOCAL(user) || CHANOPS_EXEMPT(ServerInstance, 'g') && chan->GetStatus(user) == STATUS_OP) + return 0; + + // Create a copy of the string in irc::string + irc::string line = text.c_str(); + + modelist* list; + chan->GetExt(cf->GetInfoKey(), list); + + if (list) + { + for (modelist::iterator i = list->begin(); i != list->end(); i++) + { + if (line.find(i->mask.c_str()) != std::string::npos) + { + user->WriteServ("936 %s %s %s :Your message contained a censored word, and was blocked",user->nick, chan->name, i->mask.c_str()); + return 1; + } + } + } + + return 0; + } + + virtual int OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text, char status, CUList &exempt_list) + { + if (target_type == TYPE_CHANNEL) + { + return ProcessMessages(user,(chanrec*)dest,text); + } + else return 0; + } + + virtual void OnCleanup(int target_type, void* item) + { + cf->DoCleanup(target_type, item); + } + + virtual int OnUserPreNotice(userrec* 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(chanrec* chan, Module* proto, void* opaque) + { + cf->DoSyncChannel(chan, proto, opaque); + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); + } + + virtual ~ModuleChanFilter() + { + ServerInstance->Modes->DelMode(cf); + DELETE(cf); + } +}; + +MODULE_INIT(ModuleChanFilter) diff --git a/src/modules/m_chanprotect.cpp b/src/modules/m_chanprotect.cpp index 74640fe52..87bc1ca4c 100644 --- a/src/modules/m_chanprotect.cpp +++ b/src/modules/m_chanprotect.cpp @@ -1 +1,531 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Provides channel modes +a and +q */ /* $ModDep: ../../include/u_listmode.h */ #define PROTECT_VALUE 40000 #define FOUNDER_VALUE 50000 const char* fakevalue = "on"; /* When this is set to true, no restrictions apply to setting or * removal of +qa. This is used while unloading so that the server * can freely clear all of its users of the modes. */ bool unload_kludge = false; /** Handles basic operation of +qa channel modes */ class FounderProtectBase { private: InspIRCd* MyInstance; std::string extend; std::string type; int list; int end; char* dummyptr; protected: bool& remove_own_privs; bool& remove_other_privs; public: FounderProtectBase(InspIRCd* Instance, const std::string &ext, const std::string &mtype, int l, int e, bool &remove_own, bool &remove_others) : MyInstance(Instance), extend(ext), type(mtype), list(l), end(e), remove_own_privs(remove_own), remove_other_privs(remove_others) { } ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) { userrec* x = MyInstance->FindNick(parameter); if (x) { if (!channel->HasUser(x)) { return std::make_pair(false, parameter); } else { std::string item = extend+std::string(channel->name); if (x->GetExt(item,dummyptr)) { return std::make_pair(true, x->nick); } else { return std::make_pair(false, parameter); } } } return std::make_pair(false, parameter); } void RemoveMode(chanrec* channel, char mc) { unload_kludge = true; CUList* cl = channel->GetUsers(); std::string item = extend + std::string(channel->name); const char* mode_junk[MAXMODES+2]; userrec* n = new userrec(MyInstance); n->SetFd(FD_MAGIC_NUMBER); mode_junk[0] = channel->name; irc::modestacker modestack(false); std::deque stackresult; for (CUList::iterator i = cl->begin(); i != cl->end(); i++) { if (i->first->GetExt(item, dummyptr)) { modestack.Push(mc, i->first->nick); } } while (modestack.GetStackedLine(stackresult)) { for (size_t j = 0; j < stackresult.size(); j++) { mode_junk[j+1] = stackresult[j].c_str(); } MyInstance->SendMode(mode_junk, stackresult.size() + 1, n); } delete n; unload_kludge = false; } void DisplayList(userrec* user, chanrec* channel) { CUList* cl = channel->GetUsers(); std::string item = extend+std::string(channel->name); for (CUList::reverse_iterator i = cl->rbegin(); i != cl->rend(); ++i) { if (i->first->GetExt(item, dummyptr)) { user->WriteServ("%d %s %s %s", list, user->nick, channel->name,i->first->nick); } } user->WriteServ("%d %s %s :End of channel %s list", end, user->nick, channel->name, type.c_str()); } userrec* FindAndVerify(std::string ¶meter, chanrec* channel) { userrec* theuser = MyInstance->FindNick(parameter); if ((!theuser) || (!channel->HasUser(theuser))) { parameter.clear(); return NULL; } return theuser; } bool CanRemoveOthers(userrec* u1, userrec* u2, chanrec* c) { std::string item = extend+std::string(c->name); return (u1->GetExt(item, dummyptr) && u2->GetExt(item, dummyptr)); } ModeAction HandleChange(userrec* source, userrec* theuser, bool adding, chanrec* channel, std::string ¶meter) { std::string item = extend+std::string(channel->name); if (adding) { if (!theuser->GetExt(item, dummyptr)) { theuser->Extend(item, fakevalue); parameter = theuser->nick; return MODEACTION_ALLOW; } } else { if (theuser->GetExt(item, dummyptr)) { theuser->Shrink(item); parameter = theuser->nick; return MODEACTION_ALLOW; } } return MODEACTION_DENY; } }; /** Abstraction of FounderProtectBase for channel mode +q */ class ChanFounder : public ModeHandler, public FounderProtectBase { char* dummyptr; public: ChanFounder(InspIRCd* Instance, bool using_prefixes, bool &depriv_self, bool &depriv_others) : ModeHandler(Instance, 'q', 1, 1, true, MODETYPE_CHANNEL, false, using_prefixes ? '~' : 0), FounderProtectBase(Instance, "cm_founder_", "founder", 386, 387, depriv_self, depriv_others) { } unsigned int GetPrefixRank() { return FOUNDER_VALUE; } ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) { return FounderProtectBase::ModeSet(source, dest, channel, parameter); } void RemoveMode(chanrec* channel) { FounderProtectBase::RemoveMode(channel, this->GetModeChar()); } void RemoveMode(userrec* user) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { userrec* theuser = FounderProtectBase::FindAndVerify(parameter, channel); if (!theuser) { return MODEACTION_DENY; } if ((!adding) && FounderProtectBase::CanRemoveOthers(source, theuser, channel)) { return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); } // source is a server, or ulined, we'll let them +-q the user. if ((unload_kludge) || ((source == theuser) && (!adding) && (FounderProtectBase::remove_own_privs)) || (ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server) || (!IS_LOCAL(source))) { return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); } else { // whoops, someones being naughty! source->WriteServ("468 %s %s :Only servers may set channel mode +q",source->nick, channel->name); parameter.clear(); return MODEACTION_DENY; } } void DisplayList(userrec* user, chanrec* channel) { FounderProtectBase::DisplayList(user,channel); } }; /** Abstraction of FounderProtectBase for channel mode +a */ class ChanProtect : public ModeHandler, public FounderProtectBase { char* dummyptr; public: ChanProtect(InspIRCd* Instance, bool using_prefixes, bool &depriv_self, bool &depriv_others) : ModeHandler(Instance, 'a', 1, 1, true, MODETYPE_CHANNEL, false, using_prefixes ? '&' : 0), FounderProtectBase(Instance,"cm_protect_","protected user", 388, 389, depriv_self, depriv_others) { } unsigned int GetPrefixRank() { return PROTECT_VALUE; } ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) { return FounderProtectBase::ModeSet(source, dest, channel, parameter); } void RemoveMode(chanrec* channel) { FounderProtectBase::RemoveMode(channel, this->GetModeChar()); } void RemoveMode(userrec* user) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { userrec* theuser = FounderProtectBase::FindAndVerify(parameter, channel); if (!theuser) return MODEACTION_DENY; std::string founder = "cm_founder_"+std::string(channel->name); if ((!adding) && FounderProtectBase::CanRemoveOthers(source, theuser, channel)) { return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); } // source has +q, is a server, or ulined, we'll let them +-a the user. if ((unload_kludge) || ((source == theuser) && (!adding) && (FounderProtectBase::remove_own_privs)) || (ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server) || (source->GetExt(founder,dummyptr)) || (!IS_LOCAL(source))) { return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); } else { // bzzzt, wrong answer! source->WriteServ("482 %s %s :You are not a channel founder",source->nick, channel->name); return MODEACTION_DENY; } } virtual void DisplayList(userrec* user, chanrec* channel) { FounderProtectBase::DisplayList(user, channel); } }; class ModuleChanProtect : public Module { bool FirstInGetsFounder; bool QAPrefixes; bool DeprivSelf; bool DeprivOthers; bool booting; ChanProtect* cp; ChanFounder* cf; char* dummyptr; public: ModuleChanProtect(InspIRCd* Me) : Module(Me), FirstInGetsFounder(false), QAPrefixes(false), DeprivSelf(false), DeprivOthers(false), booting(true) { /* Load config stuff */ OnRehash(NULL,""); booting = false; /* Initialise module variables */ cp = new ChanProtect(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); cf = new ChanFounder(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); if (!ServerInstance->AddMode(cp, 'a') || !ServerInstance->AddMode(cf, 'q')) throw ModuleException("Could not add new modes!"); } void Implements(char* List) { List[I_OnUserKick] = List[I_OnUserPart] = List[I_OnRehash] = List[I_OnUserJoin] = List[I_OnAccessCheck] = List[I_OnSyncChannel] = 1; } virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent) { // FIX: when someone gets kicked from a channel we must remove their Extensibles! user->Shrink("cm_founder_"+std::string(chan->name)); user->Shrink("cm_protect_"+std::string(chan->name)); } virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partreason, bool &silent) { // FIX: when someone parts a channel we must remove their Extensibles! user->Shrink("cm_founder_"+std::string(channel->name)); user->Shrink("cm_protect_"+std::string(channel->name)); } virtual void OnRehash(userrec* user, const std::string ¶meter) { /* Create a configreader class and read our flag, * in old versions this was heap-allocated and the * object was kept between rehashes...now we just * stack-allocate it locally. */ ConfigReader Conf(ServerInstance); bool old_qa = QAPrefixes; FirstInGetsFounder = Conf.ReadFlag("options","noservices",0); QAPrefixes = Conf.ReadFlag("options","qaprefixes",0); DeprivSelf = Conf.ReadFlag("options","deprotectself",0); DeprivOthers = Conf.ReadFlag("options","deprotectothers",0); /* Did the user change the QA prefixes on the fly? * If so, remove all instances of the mode, and reinit * the module with prefixes enabled. */ if ((old_qa != QAPrefixes) && (!booting)) { ServerInstance->Modes->DelMode(cp); ServerInstance->Modes->DelMode(cf); DELETE(cp); DELETE(cf); cp = new ChanProtect(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); cf = new ChanFounder(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); /* These wont fail, we already owned the mode characters before */ ServerInstance->AddMode(cp, 'a'); ServerInstance->AddMode(cf, 'q'); ServerInstance->WriteOpers("*** WARNING: +qa prefixes were enabled or disabled via a REHASH. Clients will probably need to reconnect to pick up this change."); } } virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) { // 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 (FirstInGetsFounder) { if (channel->GetUserCounter() == 1) { // we're using Extensible::Extend to add data into user objects. // this way is best as it adds data thats accessible to other modules // (so long as you document your code properly) without breaking anything // because its encapsulated neatly in a map. // Change requested by katsklaw... when the first in is set to get founder, // to make it clearer that +q has been given, send that one user the +q notice // so that their client's syncronization and their sanity are left intact. user->WriteServ("MODE %s +q %s",channel->name,user->nick); user->Extend("cm_founder_"+std::string(channel->name),fakevalue); } } } virtual int OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) { // here we perform access checks, this is the important bit that actually stops kicking/deopping // etc of protected users. There are many types of access check, we're going to handle // a relatively small number of them relevent to our module using a switch statement. // don't allow action if: // (A) Theyre founder (no matter what) // (B) Theyre protected, and you're not // always allow the action if: // (A) The source is ulined // firstly, if a ulined nick, or a server, is setting the mode, then allow them to set the mode // without any access checks, we're not worthy :p if ((ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server)) return ACR_ALLOW; std::string founder = "cm_founder_"+std::string(channel->name); std::string protect = "cm_protect_"+std::string(channel->name); switch (access_type) { // a user has been deopped. Do we let them? hmmm... case AC_DEOP: if (dest->GetExt(founder,dummyptr)) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't deop "+std::string(dest->nick)+" as they're a channel founder"); return ACR_DENY; } if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't deop "+std::string(dest->nick)+" as they're protected (+a)"); return ACR_DENY; } break; // a user is being kicked. do we chop off the end of the army boot? case AC_KICK: if (dest->GetExt(founder,dummyptr)) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't kick "+std::string(dest->nick)+" as they're a channel founder"); return ACR_DENY; } if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't kick "+std::string(dest->nick)+" as they're protected (+a)"); return ACR_DENY; } break; // a user is being dehalfopped. Yes, we do disallow -h of a +ha user case AC_DEHALFOP: if (dest->GetExt(founder,dummyptr)) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't de-halfop "+std::string(dest->nick)+" as they're a channel founder"); return ACR_DENY; } if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't de-halfop "+std::string(dest->nick)+" as they're protected (+a)"); return ACR_DENY; } break; // same with devoice. case AC_DEVOICE: if (dest->GetExt(founder,dummyptr)) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't devoice "+std::string(dest->nick)+" as they're a channel founder"); return ACR_DENY; } if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) { source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't devoice "+std::string(dest->nick)+" as they're protected (+a)"); return ACR_DENY; } break; } // we dont know what this access check is, or dont care. just carry on, nothing to see here. return ACR_DEFAULT; } virtual ~ModuleChanProtect() { ServerInstance->Modes->DelMode(cp); ServerInstance->Modes->DelMode(cf); DELETE(cp); DELETE(cf); } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); } virtual void OnSyncChannel(chanrec* chan, Module* proto, void* opaque) { /* NOTE: If +qa prefix is on, this is propogated by the channel join, * so we dont need to propogate it manually */ if (!QAPrefixes) { // this is called when the server is linking into a net and wants to sync channel data. // we should send our mode changes for the channel here to ensure that other servers // know whos +q/+a on the channel. CUList* cl = chan->GetUsers(); string_list commands; std::string founder = "cm_founder_"+std::string(chan->name); std::string protect = "cm_protect_"+std::string(chan->name); irc::modestacker modestack(true); std::deque stackresult; for (CUList::iterator i = cl->begin(); i != cl->end(); i++) { if (i->first->GetExt(founder,dummyptr)) { modestack.Push('q',i->first->nick); } if (i->first->GetExt(protect,dummyptr)) { modestack.Push('a',i->first->nick); } } while (modestack.GetStackedLine(stackresult)) { irc::stringjoiner mode_join(" ", stackresult, 0, stackresult.size() - 1); std::string line = mode_join.GetJoined(); proto->ProtoSendMode(opaque,TYPE_CHANNEL,chan, line); } } } }; MODULE_INIT(ModuleChanProtect) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Provides channel modes +a and +q */ +/* $ModDep: ../../include/u_listmode.h */ + +#define PROTECT_VALUE 40000 +#define FOUNDER_VALUE 50000 + +const char* fakevalue = "on"; + +/* When this is set to true, no restrictions apply to setting or + * removal of +qa. This is used while unloading so that the server + * can freely clear all of its users of the modes. + */ +bool unload_kludge = false; + +/** Handles basic operation of +qa channel modes + */ +class FounderProtectBase +{ + private: + InspIRCd* MyInstance; + std::string extend; + std::string type; + int list; + int end; + char* dummyptr; + protected: + bool& remove_own_privs; + bool& remove_other_privs; + public: + FounderProtectBase(InspIRCd* Instance, const std::string &ext, const std::string &mtype, int l, int e, bool &remove_own, bool &remove_others) : + MyInstance(Instance), extend(ext), type(mtype), list(l), end(e), remove_own_privs(remove_own), remove_other_privs(remove_others) + { + } + + ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) + { + userrec* x = MyInstance->FindNick(parameter); + if (x) + { + if (!channel->HasUser(x)) + { + return std::make_pair(false, parameter); + } + else + { + std::string item = extend+std::string(channel->name); + if (x->GetExt(item,dummyptr)) + { + return std::make_pair(true, x->nick); + } + else + { + return std::make_pair(false, parameter); + } + } + } + return std::make_pair(false, parameter); + } + + void RemoveMode(chanrec* channel, char mc) + { + unload_kludge = true; + CUList* cl = channel->GetUsers(); + std::string item = extend + std::string(channel->name); + const char* mode_junk[MAXMODES+2]; + userrec* n = new userrec(MyInstance); + n->SetFd(FD_MAGIC_NUMBER); + mode_junk[0] = channel->name; + irc::modestacker modestack(false); + std::deque stackresult; + for (CUList::iterator i = cl->begin(); i != cl->end(); i++) + { + if (i->first->GetExt(item, dummyptr)) + { + modestack.Push(mc, i->first->nick); + } + } + + while (modestack.GetStackedLine(stackresult)) + { + for (size_t j = 0; j < stackresult.size(); j++) + { + mode_junk[j+1] = stackresult[j].c_str(); + } + MyInstance->SendMode(mode_junk, stackresult.size() + 1, n); + } + + delete n; + unload_kludge = false; + } + + void DisplayList(userrec* user, chanrec* channel) + { + CUList* cl = channel->GetUsers(); + std::string item = extend+std::string(channel->name); + for (CUList::reverse_iterator i = cl->rbegin(); i != cl->rend(); ++i) + { + if (i->first->GetExt(item, dummyptr)) + { + user->WriteServ("%d %s %s %s", list, user->nick, channel->name,i->first->nick); + } + } + user->WriteServ("%d %s %s :End of channel %s list", end, user->nick, channel->name, type.c_str()); + } + + userrec* FindAndVerify(std::string ¶meter, chanrec* channel) + { + userrec* theuser = MyInstance->FindNick(parameter); + if ((!theuser) || (!channel->HasUser(theuser))) + { + parameter.clear(); + return NULL; + } + return theuser; + } + + bool CanRemoveOthers(userrec* u1, userrec* u2, chanrec* c) + { + std::string item = extend+std::string(c->name); + return (u1->GetExt(item, dummyptr) && u2->GetExt(item, dummyptr)); + } + + ModeAction HandleChange(userrec* source, userrec* theuser, bool adding, chanrec* channel, std::string ¶meter) + { + std::string item = extend+std::string(channel->name); + + if (adding) + { + if (!theuser->GetExt(item, dummyptr)) + { + theuser->Extend(item, fakevalue); + parameter = theuser->nick; + return MODEACTION_ALLOW; + } + } + else + { + if (theuser->GetExt(item, dummyptr)) + { + theuser->Shrink(item); + parameter = theuser->nick; + return MODEACTION_ALLOW; + } + } + return MODEACTION_DENY; + } +}; + +/** Abstraction of FounderProtectBase for channel mode +q + */ +class ChanFounder : public ModeHandler, public FounderProtectBase +{ + char* dummyptr; + public: + ChanFounder(InspIRCd* Instance, bool using_prefixes, bool &depriv_self, bool &depriv_others) + : ModeHandler(Instance, 'q', 1, 1, true, MODETYPE_CHANNEL, false, using_prefixes ? '~' : 0), + FounderProtectBase(Instance, "cm_founder_", "founder", 386, 387, depriv_self, depriv_others) { } + + unsigned int GetPrefixRank() + { + return FOUNDER_VALUE; + } + + ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) + { + return FounderProtectBase::ModeSet(source, dest, channel, parameter); + } + + void RemoveMode(chanrec* channel) + { + FounderProtectBase::RemoveMode(channel, this->GetModeChar()); + } + + void RemoveMode(userrec* user) + { + } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + userrec* theuser = FounderProtectBase::FindAndVerify(parameter, channel); + + if (!theuser) + { + return MODEACTION_DENY; + } + + if ((!adding) && FounderProtectBase::CanRemoveOthers(source, theuser, channel)) + { + return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); + } + // source is a server, or ulined, we'll let them +-q the user. + if ((unload_kludge) || ((source == theuser) && (!adding) && (FounderProtectBase::remove_own_privs)) || (ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server) || (!IS_LOCAL(source))) + { + return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); + } + else + { + // whoops, someones being naughty! + source->WriteServ("468 %s %s :Only servers may set channel mode +q",source->nick, channel->name); + parameter.clear(); + return MODEACTION_DENY; + } + } + + void DisplayList(userrec* user, chanrec* channel) + { + FounderProtectBase::DisplayList(user,channel); + } +}; + +/** Abstraction of FounderProtectBase for channel mode +a + */ +class ChanProtect : public ModeHandler, public FounderProtectBase +{ + char* dummyptr; + public: + ChanProtect(InspIRCd* Instance, bool using_prefixes, bool &depriv_self, bool &depriv_others) + : ModeHandler(Instance, 'a', 1, 1, true, MODETYPE_CHANNEL, false, using_prefixes ? '&' : 0), + FounderProtectBase(Instance,"cm_protect_","protected user", 388, 389, depriv_self, depriv_others) { } + + unsigned int GetPrefixRank() + { + return PROTECT_VALUE; + } + + ModePair ModeSet(userrec* source, userrec* dest, chanrec* channel, const std::string ¶meter) + { + return FounderProtectBase::ModeSet(source, dest, channel, parameter); + } + + void RemoveMode(chanrec* channel) + { + FounderProtectBase::RemoveMode(channel, this->GetModeChar()); + } + + void RemoveMode(userrec* user) + { + } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + userrec* theuser = FounderProtectBase::FindAndVerify(parameter, channel); + + if (!theuser) + return MODEACTION_DENY; + + std::string founder = "cm_founder_"+std::string(channel->name); + + if ((!adding) && FounderProtectBase::CanRemoveOthers(source, theuser, channel)) + { + return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); + } + // source has +q, is a server, or ulined, we'll let them +-a the user. + if ((unload_kludge) || ((source == theuser) && (!adding) && (FounderProtectBase::remove_own_privs)) || (ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server) || (source->GetExt(founder,dummyptr)) || (!IS_LOCAL(source))) + { + return FounderProtectBase::HandleChange(source, theuser, adding, channel, parameter); + } + else + { + // bzzzt, wrong answer! + source->WriteServ("482 %s %s :You are not a channel founder",source->nick, channel->name); + return MODEACTION_DENY; + } + } + + virtual void DisplayList(userrec* user, chanrec* channel) + { + FounderProtectBase::DisplayList(user, channel); + } + +}; + +class ModuleChanProtect : public Module +{ + + bool FirstInGetsFounder; + bool QAPrefixes; + bool DeprivSelf; + bool DeprivOthers; + bool booting; + ChanProtect* cp; + ChanFounder* cf; + char* dummyptr; + + public: + + ModuleChanProtect(InspIRCd* Me) + : Module(Me), FirstInGetsFounder(false), QAPrefixes(false), DeprivSelf(false), DeprivOthers(false), booting(true) + { + /* Load config stuff */ + OnRehash(NULL,""); + booting = false; + + /* Initialise module variables */ + + cp = new ChanProtect(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); + cf = new ChanFounder(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); + + if (!ServerInstance->AddMode(cp, 'a') || !ServerInstance->AddMode(cf, 'q')) + throw ModuleException("Could not add new modes!"); + } + + void Implements(char* List) + { + List[I_OnUserKick] = List[I_OnUserPart] = List[I_OnRehash] = List[I_OnUserJoin] = List[I_OnAccessCheck] = List[I_OnSyncChannel] = 1; + } + + virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent) + { + // FIX: when someone gets kicked from a channel we must remove their Extensibles! + user->Shrink("cm_founder_"+std::string(chan->name)); + user->Shrink("cm_protect_"+std::string(chan->name)); + } + + virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partreason, bool &silent) + { + // FIX: when someone parts a channel we must remove their Extensibles! + user->Shrink("cm_founder_"+std::string(channel->name)); + user->Shrink("cm_protect_"+std::string(channel->name)); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + /* Create a configreader class and read our flag, + * in old versions this was heap-allocated and the + * object was kept between rehashes...now we just + * stack-allocate it locally. + */ + ConfigReader Conf(ServerInstance); + + bool old_qa = QAPrefixes; + + FirstInGetsFounder = Conf.ReadFlag("options","noservices",0); + QAPrefixes = Conf.ReadFlag("options","qaprefixes",0); + DeprivSelf = Conf.ReadFlag("options","deprotectself",0); + DeprivOthers = Conf.ReadFlag("options","deprotectothers",0); + + /* Did the user change the QA prefixes on the fly? + * If so, remove all instances of the mode, and reinit + * the module with prefixes enabled. + */ + if ((old_qa != QAPrefixes) && (!booting)) + { + ServerInstance->Modes->DelMode(cp); + ServerInstance->Modes->DelMode(cf); + DELETE(cp); + DELETE(cf); + cp = new ChanProtect(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); + cf = new ChanFounder(ServerInstance,QAPrefixes,DeprivSelf,DeprivOthers); + /* These wont fail, we already owned the mode characters before */ + ServerInstance->AddMode(cp, 'a'); + ServerInstance->AddMode(cf, 'q'); + ServerInstance->WriteOpers("*** WARNING: +qa prefixes were enabled or disabled via a REHASH. Clients will probably need to reconnect to pick up this change."); + } + } + + virtual void OnUserJoin(userrec* user, chanrec* channel, bool &silent) + { + // 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 (FirstInGetsFounder) + { + if (channel->GetUserCounter() == 1) + { + // we're using Extensible::Extend to add data into user objects. + // this way is best as it adds data thats accessible to other modules + // (so long as you document your code properly) without breaking anything + // because its encapsulated neatly in a map. + + // Change requested by katsklaw... when the first in is set to get founder, + // to make it clearer that +q has been given, send that one user the +q notice + // so that their client's syncronization and their sanity are left intact. + user->WriteServ("MODE %s +q %s",channel->name,user->nick); + user->Extend("cm_founder_"+std::string(channel->name),fakevalue); + } + } + } + + virtual int OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) + { + // here we perform access checks, this is the important bit that actually stops kicking/deopping + // etc of protected users. There are many types of access check, we're going to handle + // a relatively small number of them relevent to our module using a switch statement. + // don't allow action if: + // (A) Theyre founder (no matter what) + // (B) Theyre protected, and you're not + // always allow the action if: + // (A) The source is ulined + + + // firstly, if a ulined nick, or a server, is setting the mode, then allow them to set the mode + // without any access checks, we're not worthy :p + if ((ServerInstance->ULine(source->nick)) || (ServerInstance->ULine(source->server)) || (!*source->server)) + return ACR_ALLOW; + + std::string founder = "cm_founder_"+std::string(channel->name); + std::string protect = "cm_protect_"+std::string(channel->name); + + switch (access_type) + { + // a user has been deopped. Do we let them? hmmm... + case AC_DEOP: + if (dest->GetExt(founder,dummyptr)) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't deop "+std::string(dest->nick)+" as they're a channel founder"); + return ACR_DENY; + } + if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't deop "+std::string(dest->nick)+" as they're protected (+a)"); + return ACR_DENY; + } + break; + + // a user is being kicked. do we chop off the end of the army boot? + case AC_KICK: + if (dest->GetExt(founder,dummyptr)) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't kick "+std::string(dest->nick)+" as they're a channel founder"); + return ACR_DENY; + } + if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't kick "+std::string(dest->nick)+" as they're protected (+a)"); + return ACR_DENY; + } + break; + + // a user is being dehalfopped. Yes, we do disallow -h of a +ha user + case AC_DEHALFOP: + if (dest->GetExt(founder,dummyptr)) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't de-halfop "+std::string(dest->nick)+" as they're a channel founder"); + return ACR_DENY; + } + if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't de-halfop "+std::string(dest->nick)+" as they're protected (+a)"); + return ACR_DENY; + } + break; + + // same with devoice. + case AC_DEVOICE: + if (dest->GetExt(founder,dummyptr)) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't devoice "+std::string(dest->nick)+" as they're a channel founder"); + return ACR_DENY; + } + if ((dest->GetExt(protect,dummyptr)) && (!source->GetExt(protect,dummyptr))) + { + source->WriteServ("484 "+std::string(source->nick)+" "+std::string(channel->name)+" :Can't devoice "+std::string(dest->nick)+" as they're protected (+a)"); + return ACR_DENY; + } + break; + } + + // we dont know what this access check is, or dont care. just carry on, nothing to see here. + return ACR_DEFAULT; + } + + virtual ~ModuleChanProtect() + { + ServerInstance->Modes->DelMode(cp); + ServerInstance->Modes->DelMode(cf); + DELETE(cp); + DELETE(cf); + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_COMMON | VF_VENDOR, API_VERSION); + } + + virtual void OnSyncChannel(chanrec* chan, Module* proto, void* opaque) + { + /* NOTE: If +qa prefix is on, this is propogated by the channel join, + * so we dont need to propogate it manually + */ + if (!QAPrefixes) + { + // this is called when the server is linking into a net and wants to sync channel data. + // we should send our mode changes for the channel here to ensure that other servers + // know whos +q/+a on the channel. + CUList* cl = chan->GetUsers(); + string_list commands; + std::string founder = "cm_founder_"+std::string(chan->name); + std::string protect = "cm_protect_"+std::string(chan->name); + irc::modestacker modestack(true); + std::deque stackresult; + for (CUList::iterator i = cl->begin(); i != cl->end(); i++) + { + if (i->first->GetExt(founder,dummyptr)) + { + modestack.Push('q',i->first->nick); + } + if (i->first->GetExt(protect,dummyptr)) + { + modestack.Push('a',i->first->nick); + } + } + while (modestack.GetStackedLine(stackresult)) + { + irc::stringjoiner mode_join(" ", stackresult, 0, stackresult.size() - 1); + std::string line = mode_join.GetJoined(); + proto->ProtoSendMode(opaque,TYPE_CHANNEL,chan, line); + } + } + } + +}; + +MODULE_INIT(ModuleChanProtect) diff --git a/src/modules/m_check.cpp b/src/modules/m_check.cpp index c99e985cc..643af8e15 100644 --- a/src/modules/m_check.cpp +++ b/src/modules/m_check.cpp @@ -1 +1,188 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "wildcard.h" /* $ModDesc: Provides the /check command to retrieve information on a user, channel, or IP address */ /** Handle /CHECK */ class cmd_check : public command_t { public: cmd_check (InspIRCd* Instance) : command_t(Instance,"CHECK", 'o', 1) { this->source = "m_check.so"; syntax = "|||"; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { userrec *targuser; chanrec *targchan; std::string checkstr; std::string chliststr; char timebuf[60]; struct tm *mytime; checkstr = "304 " + std::string(user->nick) + " :CHECK"; targuser = ServerInstance->FindNick(parameters[0]); targchan = ServerInstance->FindChan(parameters[0]); /* * Syntax of a /check reply: * :server.name 304 target :CHECK START * :server.name 304 target :CHECK * :server.name 304 target :CHECK END */ user->WriteServ(checkstr + " START " + parameters[0]); if (targuser) { /* /check on a user */ user->WriteServ(checkstr + " nuh " + targuser->GetFullHost()); user->WriteServ(checkstr + " realnuh " + targuser->GetFullRealHost()); user->WriteServ(checkstr + " realname " + targuser->fullname); user->WriteServ(checkstr + " modes +" + targuser->FormatModes()); user->WriteServ(checkstr + " snomasks +" + targuser->FormatNoticeMasks()); user->WriteServ(checkstr + " server " + targuser->server); if (IS_AWAY(targuser)) { /* user is away */ user->WriteServ(checkstr + " awaymsg " + targuser->awaymsg); } if (IS_OPER(targuser)) { /* user is an oper of type ____ */ user->WriteServ(checkstr + " opertype " + irc::Spacify(targuser->oper)); } if (IS_LOCAL(targuser)) { /* port information is only held for a local user! */ user->WriteServ(checkstr + " onport " + ConvToStr(targuser->GetPort())); } chliststr = targuser->ChannelList(targuser); std::stringstream dump(chliststr); ServerInstance->DumpText(user,checkstr + " onchans ", dump); } else if (targchan) { /* /check on a channel */ time_t creation_time = targchan->created; time_t topic_time = targchan->topicset; mytime = gmtime(&creation_time); strftime(timebuf, 59, "%Y/%m/%d - %H:%M:%S", mytime); user->WriteServ(checkstr + " created " + timebuf); if (targchan->topic[0] != 0) { /* there is a topic, assume topic related information exists */ user->WriteServ(checkstr + " topic " + targchan->topic); user->WriteServ(checkstr + " topic_setby " + targchan->setby); mytime = gmtime(&topic_time); strftime(timebuf, 59, "%Y/%m/%d - %H:%M:%S", mytime); user->WriteServ(checkstr + " topic_setat " + timebuf); } user->WriteServ(checkstr + " modes " + targchan->ChanModes(true)); user->WriteServ(checkstr + " membercount " + ConvToStr(targchan->GetUserCounter())); /* now the ugly bit, spool current members of a channel. :| */ CUList *ulist= targchan->GetUsers(); /* note that unlike /names, we do NOT check +i vs in the channel */ for (CUList::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, "%lu %s%s (%s@%s) %s ", i->first->GlobalCloneCount(), targchan->GetAllPrefixChars(i->first), i->first->nick, i->first->ident, i->first->dhost, i->first->fullname); user->WriteServ(checkstr + " member " + tmpbuf); } } else { /* /check on an IP address, or something that doesn't exist */ long x = 0; /* hostname or other */ for (user_hash::const_iterator a = ServerInstance->clientlist->begin(); a != ServerInstance->clientlist->end(); a++) { if (match(a->second->host, parameters[0]) || match(a->second->dhost, parameters[0])) { /* host or vhost matches mask */ user->WriteServ(checkstr + " match " + ConvToStr(++x) + " " + a->second->GetFullRealHost()); } /* IP address */ else if (match(a->second->GetIPString(), parameters[0], true)) { /* same IP. */ user->WriteServ(checkstr + " match " + ConvToStr(++x) + " " + a->second->GetFullRealHost()); } } user->WriteServ(checkstr + " matches " + ConvToStr(x)); } user->WriteServ(checkstr + " END " + std::string(parameters[0])); return CMD_LOCALONLY; } }; class ModuleCheck : public Module { private: cmd_check *mycommand; public: ModuleCheck(InspIRCd* Me) : Module(Me) { mycommand = new cmd_check(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~ModuleCheck() { } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } void Implements(char* List) { /* we don't hook anything, nothing required */ } }; MODULE_INIT(ModuleCheck) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "wildcard.h" + +/* $ModDesc: Provides the /check command to retrieve information on a user, channel, or IP address */ + +/** Handle /CHECK + */ +class cmd_check : public command_t +{ + public: + cmd_check (InspIRCd* Instance) : command_t(Instance,"CHECK", 'o', 1) + { + this->source = "m_check.so"; + syntax = "|||"; + } + + CmdResult Handle (const char** parameters, int pcnt, userrec *user) + { + userrec *targuser; + chanrec *targchan; + std::string checkstr; + std::string chliststr; + + char timebuf[60]; + struct tm *mytime; + + + checkstr = "304 " + std::string(user->nick) + " :CHECK"; + + targuser = ServerInstance->FindNick(parameters[0]); + targchan = ServerInstance->FindChan(parameters[0]); + + /* + * Syntax of a /check reply: + * :server.name 304 target :CHECK START + * :server.name 304 target :CHECK + * :server.name 304 target :CHECK END + */ + + user->WriteServ(checkstr + " START " + parameters[0]); + + if (targuser) + { + /* /check on a user */ + user->WriteServ(checkstr + " nuh " + targuser->GetFullHost()); + user->WriteServ(checkstr + " realnuh " + targuser->GetFullRealHost()); + user->WriteServ(checkstr + " realname " + targuser->fullname); + user->WriteServ(checkstr + " modes +" + targuser->FormatModes()); + user->WriteServ(checkstr + " snomasks +" + targuser->FormatNoticeMasks()); + user->WriteServ(checkstr + " server " + targuser->server); + + if (IS_AWAY(targuser)) + { + /* user is away */ + user->WriteServ(checkstr + " awaymsg " + targuser->awaymsg); + } + + if (IS_OPER(targuser)) + { + /* user is an oper of type ____ */ + user->WriteServ(checkstr + " opertype " + irc::Spacify(targuser->oper)); + } + + if (IS_LOCAL(targuser)) + { + /* port information is only held for a local user! */ + user->WriteServ(checkstr + " onport " + ConvToStr(targuser->GetPort())); + } + + chliststr = targuser->ChannelList(targuser); + std::stringstream dump(chliststr); + + ServerInstance->DumpText(user,checkstr + " onchans ", dump); + } + else if (targchan) + { + /* /check on a channel */ + time_t creation_time = targchan->created; + time_t topic_time = targchan->topicset; + + mytime = gmtime(&creation_time); + strftime(timebuf, 59, "%Y/%m/%d - %H:%M:%S", mytime); + user->WriteServ(checkstr + " created " + timebuf); + + if (targchan->topic[0] != 0) + { + /* there is a topic, assume topic related information exists */ + user->WriteServ(checkstr + " topic " + targchan->topic); + user->WriteServ(checkstr + " topic_setby " + targchan->setby); + mytime = gmtime(&topic_time); + strftime(timebuf, 59, "%Y/%m/%d - %H:%M:%S", mytime); + user->WriteServ(checkstr + " topic_setat " + timebuf); + } + + user->WriteServ(checkstr + " modes " + targchan->ChanModes(true)); + user->WriteServ(checkstr + " membercount " + ConvToStr(targchan->GetUserCounter())); + + /* now the ugly bit, spool current members of a channel. :| */ + + CUList *ulist= targchan->GetUsers(); + + /* note that unlike /names, we do NOT check +i vs in the channel */ + for (CUList::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, "%lu %s%s (%s@%s) %s ", i->first->GlobalCloneCount(), targchan->GetAllPrefixChars(i->first), i->first->nick, i->first->ident, i->first->dhost, i->first->fullname); + user->WriteServ(checkstr + " member " + tmpbuf); + } + } + else + { + /* /check on an IP address, or something that doesn't exist */ + long x = 0; + + /* hostname or other */ + for (user_hash::const_iterator a = ServerInstance->clientlist->begin(); a != ServerInstance->clientlist->end(); a++) + { + if (match(a->second->host, parameters[0]) || match(a->second->dhost, parameters[0])) + { + /* host or vhost matches mask */ + user->WriteServ(checkstr + " match " + ConvToStr(++x) + " " + a->second->GetFullRealHost()); + } + /* IP address */ + else if (match(a->second->GetIPString(), parameters[0], true)) + { + /* same IP. */ + user->WriteServ(checkstr + " match " + ConvToStr(++x) + " " + a->second->GetFullRealHost()); + } + } + + user->WriteServ(checkstr + " matches " + ConvToStr(x)); + } + + user->WriteServ(checkstr + " END " + std::string(parameters[0])); + + return CMD_LOCALONLY; + } +}; + + +class ModuleCheck : public Module +{ + private: + cmd_check *mycommand; + public: + ModuleCheck(InspIRCd* Me) : Module(Me) + { + + mycommand = new cmd_check(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~ModuleCheck() + { + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + /* we don't hook anything, nothing required */ + } + +}; + +MODULE_INIT(ModuleCheck) diff --git a/src/modules/m_chghost.cpp b/src/modules/m_chghost.cpp index 9fb751b8e..0ec88d7e1 100644 --- a/src/modules/m_chghost.cpp +++ b/src/modules/m_chghost.cpp @@ -1 +1,120 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Provides support for the CHGHOST command */ /** Handle /CHGHOST */ class cmd_chghost : public command_t { private: char* hostmap; public: cmd_chghost (InspIRCd* Instance, char* hmap) : command_t(Instance,"CHGHOST",'o',2), hostmap(hmap) { this->source = "m_chghost.so"; syntax = " "; } CmdResult Handle(const char** parameters, int pcnt, userrec *user) { const char * x = parameters[1]; for (; *x; x++) { if (!hostmap[(unsigned char)*x]) { user->WriteServ("NOTICE "+std::string(user->nick)+" :*** CHGHOST: Invalid characters in hostname"); return CMD_FAILURE; } } if (!*parameters[0]) { user->WriteServ("NOTICE %s :*** CHGHOST: Host must be specified", user->nick); return CMD_FAILURE; } if ((parameters[1] - x) > 63) { user->WriteServ("NOTICE %s :*** CHGHOST: Host too long", user->nick); return CMD_FAILURE; } userrec* dest = ServerInstance->FindNick(parameters[0]); if (!dest) { user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); return CMD_FAILURE; } if ((dest->ChangeDisplayedHost(parameters[1])) && (!ServerInstance->ULine(user->server))) { // fix by brain - ulines set hosts silently ServerInstance->WriteOpers(std::string(user->nick)+" used CHGHOST to make the displayed host of "+dest->nick+" become "+dest->dhost); } /* route it! */ return CMD_SUCCESS; } }; class ModuleChgHost : public Module { cmd_chghost* mycommand; char hostmap[256]; public: ModuleChgHost(InspIRCd* Me) : Module(Me) { OnRehash(NULL,""); mycommand = new cmd_chghost(ServerInstance, hostmap); ServerInstance->AddCommand(mycommand); } void Implements(char* List) { List[I_OnRehash] = 1; } void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader Conf(ServerInstance); std::string hmap = Conf.ReadValue("hostname", "charmap", 0); if (hmap.empty()) hmap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_/0123456789"; memset(&hostmap, 0, 255); for (std::string::iterator n = hmap.begin(); n != hmap.end(); n++) hostmap[(unsigned char)*n] = 1; } ~ModuleChgHost() { } Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } }; MODULE_INIT(ModuleChgHost) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Provides support for the CHGHOST command */ + +/** Handle /CHGHOST + */ +class cmd_chghost : public command_t +{ + private: + char* hostmap; + public: + cmd_chghost (InspIRCd* Instance, char* hmap) : command_t(Instance,"CHGHOST",'o',2), hostmap(hmap) + { + this->source = "m_chghost.so"; + syntax = " "; + } + + CmdResult Handle(const char** parameters, int pcnt, userrec *user) + { + const char * x = parameters[1]; + + for (; *x; x++) + { + if (!hostmap[(unsigned char)*x]) + { + user->WriteServ("NOTICE "+std::string(user->nick)+" :*** CHGHOST: Invalid characters in hostname"); + return CMD_FAILURE; + } + } + if (!*parameters[0]) + { + user->WriteServ("NOTICE %s :*** CHGHOST: Host must be specified", user->nick); + return CMD_FAILURE; + } + + if ((parameters[1] - x) > 63) + { + user->WriteServ("NOTICE %s :*** CHGHOST: Host too long", user->nick); + return CMD_FAILURE; + } + userrec* dest = ServerInstance->FindNick(parameters[0]); + + if (!dest) + { + user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); + return CMD_FAILURE; + } + + if ((dest->ChangeDisplayedHost(parameters[1])) && (!ServerInstance->ULine(user->server))) + { + // fix by brain - ulines set hosts silently + ServerInstance->WriteOpers(std::string(user->nick)+" used CHGHOST to make the displayed host of "+dest->nick+" become "+dest->dhost); + } + + /* route it! */ + return CMD_SUCCESS; + + } +}; + + +class ModuleChgHost : public Module +{ + cmd_chghost* mycommand; + char hostmap[256]; + public: + ModuleChgHost(InspIRCd* Me) + : Module(Me) + { + OnRehash(NULL,""); + mycommand = new cmd_chghost(ServerInstance, hostmap); + ServerInstance->AddCommand(mycommand); + } + + void Implements(char* List) + { + List[I_OnRehash] = 1; + } + + void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader Conf(ServerInstance); + std::string hmap = Conf.ReadValue("hostname", "charmap", 0); + + if (hmap.empty()) + hmap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_/0123456789"; + + memset(&hostmap, 0, 255); + for (std::string::iterator n = hmap.begin(); n != hmap.end(); n++) + hostmap[(unsigned char)*n] = 1; + } + + ~ModuleChgHost() + { + } + + Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + +}; + +MODULE_INIT(ModuleChgHost) diff --git a/src/modules/m_chgident.cpp b/src/modules/m_chgident.cpp index fb909b7ff..168adcc93 100644 --- a/src/modules/m_chgident.cpp +++ b/src/modules/m_chgident.cpp @@ -1 +1,92 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "modules.h" /* $ModDesc: Provides support for the CHGIDENT command */ /** Handle /CHGIDENT */ class cmd_chgident : public command_t { public: cmd_chgident (InspIRCd* Instance) : command_t(Instance,"CHGIDENT", 'o', 2) { this->source = "m_chgident.so"; syntax = " "; } CmdResult Handle(const char** parameters, int pcnt, userrec *user) { userrec* dest = ServerInstance->FindNick(parameters[0]); if (!dest) { user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); return CMD_FAILURE; } if (!*parameters[1]) { user->WriteServ("NOTICE %s :*** CHGIDENT: Ident must be specified", user->nick); return CMD_FAILURE; } if (strlen(parameters[1]) > IDENTMAX) { user->WriteServ("NOTICE %s :*** CHGIDENT: Ident is too long", user->nick); return CMD_FAILURE; } if (!ServerInstance->IsIdent(parameters[1])) { user->WriteServ("NOTICE %s :*** CHGIDENT: Invalid characters in ident", user->nick); return CMD_FAILURE; } dest->ChangeIdent(parameters[1]); ServerInstance->WriteOpers("%s used CHGIDENT to change %s's ident to '%s'", user->nick, dest->nick, dest->ident); /* route it! */ return CMD_SUCCESS; } }; class ModuleChgIdent : public Module { cmd_chgident* mycommand; public: ModuleChgIdent(InspIRCd* Me) : Module(Me) { mycommand = new cmd_chgident(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~ModuleChgIdent() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleChgIdent) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "modules.h" + +/* $ModDesc: Provides support for the CHGIDENT command */ + +/** Handle /CHGIDENT + */ +class cmd_chgident : public command_t +{ + public: + cmd_chgident (InspIRCd* Instance) : command_t(Instance,"CHGIDENT", 'o', 2) + { + this->source = "m_chgident.so"; + syntax = " "; + } + + CmdResult Handle(const char** parameters, int pcnt, userrec *user) + { + userrec* dest = ServerInstance->FindNick(parameters[0]); + + if (!dest) + { + user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); + return CMD_FAILURE; + } + + if (!*parameters[1]) + { + user->WriteServ("NOTICE %s :*** CHGIDENT: Ident must be specified", user->nick); + return CMD_FAILURE; + } + + if (strlen(parameters[1]) > IDENTMAX) + { + user->WriteServ("NOTICE %s :*** CHGIDENT: Ident is too long", user->nick); + return CMD_FAILURE; + } + + if (!ServerInstance->IsIdent(parameters[1])) + { + user->WriteServ("NOTICE %s :*** CHGIDENT: Invalid characters in ident", user->nick); + return CMD_FAILURE; + } + + dest->ChangeIdent(parameters[1]); + ServerInstance->WriteOpers("%s used CHGIDENT to change %s's ident to '%s'", user->nick, dest->nick, dest->ident); + + /* route it! */ + return CMD_SUCCESS; + } +}; + + +class ModuleChgIdent : public Module +{ + cmd_chgident* mycommand; + + +public: + ModuleChgIdent(InspIRCd* Me) : Module(Me) + { + mycommand = new cmd_chgident(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~ModuleChgIdent() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleChgIdent) + diff --git a/src/modules/m_chgname.cpp b/src/modules/m_chgname.cpp index 0bf9004dd..a4a31714b 100644 --- a/src/modules/m_chgname.cpp +++ b/src/modules/m_chgname.cpp @@ -1 +1,89 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "modules.h" /* $ModDesc: Provides support for the CHGNAME command */ /** Handle /CHGNAME */ class cmd_chgname : public command_t { public: cmd_chgname (InspIRCd* Instance) : command_t(Instance,"CHGNAME", 'o', 2) { this->source = "m_chgname.so"; syntax = " "; } CmdResult Handle(const char** parameters, int pcnt, userrec *user) { userrec* dest = ServerInstance->FindNick(parameters[0]); if (!dest) { user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); return CMD_FAILURE; } if (!*parameters[1]) { user->WriteServ("NOTICE %s :*** GECOS must be specified", user->nick); return CMD_FAILURE; } if (strlen(parameters[1]) > MAXGECOS) { user->WriteServ("NOTICE %s :*** GECOS too long", user->nick); return CMD_FAILURE; } if (IS_LOCAL(dest)) { dest->ChangeName(parameters[1]); ServerInstance->WriteOpers("%s used CHGNAME to change %s's real name to '%s'", user->nick, dest->nick, dest->fullname); return CMD_LOCALONLY; /* name change routed by FNAME in spanningtree now */ } /* route it! */ return CMD_SUCCESS; } }; class ModuleChgName : public Module { cmd_chgname* mycommand; public: ModuleChgName(InspIRCd* Me) : Module(Me) { mycommand = new cmd_chgname(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~ModuleChgName() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleChgName) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "modules.h" + +/* $ModDesc: Provides support for the CHGNAME command */ + +/** Handle /CHGNAME + */ +class cmd_chgname : public command_t +{ + public: + cmd_chgname (InspIRCd* Instance) : command_t(Instance,"CHGNAME", 'o', 2) + { + this->source = "m_chgname.so"; + syntax = " "; + } + + CmdResult Handle(const char** parameters, int pcnt, userrec *user) + { + userrec* dest = ServerInstance->FindNick(parameters[0]); + + if (!dest) + { + user->WriteServ("401 %s %s :No such nick/channel", user->nick, parameters[0]); + return CMD_FAILURE; + } + + if (!*parameters[1]) + { + user->WriteServ("NOTICE %s :*** GECOS must be specified", user->nick); + return CMD_FAILURE; + } + + if (strlen(parameters[1]) > MAXGECOS) + { + user->WriteServ("NOTICE %s :*** GECOS too long", user->nick); + return CMD_FAILURE; + } + + if (IS_LOCAL(dest)) + { + dest->ChangeName(parameters[1]); + ServerInstance->WriteOpers("%s used CHGNAME to change %s's real name to '%s'", user->nick, dest->nick, dest->fullname); + return CMD_LOCALONLY; /* name change routed by FNAME in spanningtree now */ + } + + /* route it! */ + return CMD_SUCCESS; + } +}; + + +class ModuleChgName : public Module +{ + cmd_chgname* mycommand; + + +public: + ModuleChgName(InspIRCd* Me) : Module(Me) + { + mycommand = new cmd_chgname(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~ModuleChgName() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleChgName) diff --git a/src/modules/m_cloaking.cpp b/src/modules/m_cloaking.cpp index d7992301c..dfa5ee4e8 100644 --- a/src/modules/m_cloaking.cpp +++ b/src/modules/m_cloaking.cpp @@ -1 +1,315 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "m_hash.h" /* $ModDesc: Provides masking of user hostnames */ /* $ModDep: m_hash.h */ /* Used to vary the output a little more depending on the cloak keys */ static const char* xtab[] = {"F92E45D871BCA630", "A1B9D80C72E653F4", "1ABC078934DEF562", "ABCDEF5678901234"}; /** Handles user mode +x */ class CloakUser : public ModeHandler { std::string prefix; unsigned int key1; unsigned int key2; unsigned int key3; unsigned int key4; Module* Sender; Module* HashProvider; /** 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. * * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org". * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk", * and if it is passed "localhost.localdomain" it will return ".localdomain". * * This is used to ensure a significant part of the host is always cloaked (see Bug #216) */ std::string LastTwoDomainParts(const std::string &host) { int dots = 0; std::string::size_type splitdot = host.length(); for (std::string::size_type x = host.length() - 1; x; --x) { if (host[x] == '.') { splitdot = x; dots++; } if (dots >= 3) break; } if (splitdot == host.length()) return host; else return host.substr(splitdot); } public: CloakUser(InspIRCd* Instance, Module* Source, Module* Hash) : ModeHandler(Instance, 'x', 0, 0, false, MODETYPE_USER, false), Sender(Source), HashProvider(Hash) { } ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) { if (source != dest) return MODEACTION_DENY; /* For remote clients, we dont take any action, we just allow it. * The local server where they are will set their cloak instead. */ if (!IS_LOCAL(dest)) return MODEACTION_ALLOW; if (adding) { if(!dest->IsModeSet('x')) { /* The mode is being turned on - so attempt to * allocate the user a cloaked host using a non-reversible * algorithm (its simple, but its non-reversible so the * simplicity doesnt really matter). This algorithm * will not work if the user has only one level of domain * naming in their hostname (e.g. if they are on a lan or * are connecting via localhost) -- this doesnt matter much. */ char* n1 = strchr(dest->host,'.'); char* n2 = strchr(dest->host,':'); if (n1 || n2) { /* InspIRCd users have two hostnames; A displayed * hostname which can be modified by modules (e.g. * to create vhosts, implement chghost, etc) and a * 'real' hostname which you shouldnt write to. */ unsigned int iv[] = { key1, key2, key3, key4 }; std::string a = LastTwoDomainParts(dest->host); std::string b; /** Reset the Hash module, and send it our IV and hex table */ HashResetRequest(Sender, HashProvider).Send(); HashKeyRequest(Sender, HashProvider, iv).Send(); HashHexRequest(Sender, HashProvider, xtab[(*dest->host) % 4]); /* Generate a cloak using specialized Hash */ std::string hostcloak = prefix + "-" + std::string(HashSumRequest(Sender, HashProvider, dest->host).Send()).substr(0,8) + a; /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes * according to the DNS RFC) then tough titty, they get cloaked as an IP. * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie * vhost. */ #ifdef IPV6 in6_addr testaddr; in_addr testaddr2; if ((dest->GetProtocolFamily() == AF_INET6) && (inet_pton(AF_INET6,dest->host,&testaddr) < 1) && (hostcloak.length() <= 64)) /* Invalid ipv6 address, and ipv6 user (resolved host) */ b = hostcloak; else if ((dest->GetProtocolFamily() == AF_INET) && (inet_aton(dest->host,&testaddr2) < 1) && (hostcloak.length() <= 64)) /* Invalid ipv4 address, and ipv4 user (resolved host) */ b = hostcloak; else /* Valid ipv6 or ipv4 address (not resolved) ipv4 or ipv6 user */ b = ((!strchr(dest->host,':')) ? Cloak4(dest->host) : Cloak6(dest->host)); #else in_addr testaddr; if ((inet_aton(dest->host,&testaddr) < 1) && (hostcloak.length() <= 64)) /* Invalid ipv4 address, and ipv4 user (resolved host) */ b = hostcloak; else /* Valid ipv4 address (not resolved) ipv4 user */ b = Cloak4(dest->host); #endif dest->ChangeDisplayedHost(b.c_str()); } dest->SetMode('x',true); return MODEACTION_ALLOW; } } else { if (dest->IsModeSet('x')) { /* User is removing the mode, so just restore their real host * and make it match the displayed one. */ dest->ChangeDisplayedHost(dest->host); dest->SetMode('x',false); return MODEACTION_ALLOW; } } return MODEACTION_DENY; } std::string Cloak4(const char* ip) { unsigned int iv[] = { key1, key2, key3, key4 }; irc::sepstream seps(ip, '.'); std::string ra[4];; std::string octet[4]; int i[4]; for (int j = 0; j < 4; j++) { octet[j] = seps.GetToken(); 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 */ HashResetRequest(Sender, HashProvider).Send(); HashKeyRequest(Sender, HashProvider, iv).Send(); /* Send the Hash module a different hex table for each octet group's Hash sum */ for (int k = 0; k < 4; k++) { HashHexRequest(Sender, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send(); ra[k] = std::string(HashSumRequest(Sender, HashProvider, octet[k]).Send()).substr(0,6); } /* Stick them all together */ return std::string().append(ra[0]).append(".").append(ra[1]).append(".").append(ra[2]).append(".").append(ra[3]); } std::string Cloak6(const char* ip) { /* Theyre using 4in6 (YUCK). Translate as ipv4 cloak */ if (!strncmp(ip, "0::ffff:", 8)) return Cloak4(ip + 8); /* If we get here, yes it really is an ipv6 ip */ unsigned int iv[] = { key1, key2, key3, key4 }; std::vector hashies; std::string item; int rounds = 0; /* Reset the Hash module and send it our IV */ HashResetRequest(Sender, HashProvider).Send(); HashKeyRequest(Sender, HashProvider, iv).Send(); for (const char* input = ip; *input; input++) { item += *input; if (item.length() > 7) { /* Send the Hash module a different hex table for each octet group's Hash sum */ HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send(); hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8)); item.clear(); } rounds++; } if (!item.empty()) { /* Send the Hash module a different hex table for each octet group's Hash sum */ HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send(); hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8)); item.clear(); } /* Stick them all together */ return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined(); } void DoRehash() { ConfigReader Conf(ServerInstance); key1 = key2 = key3 = key4 = 0; key1 = Conf.ReadInteger("cloak","key1",0,true); key2 = Conf.ReadInteger("cloak","key2",0,true); key3 = Conf.ReadInteger("cloak","key3",0,true); key4 = Conf.ReadInteger("cloak","key4",0,true); prefix = Conf.ReadValue("cloak","prefix",0); if (prefix.empty()) prefix = ServerInstance->Config->Network; if (!key1 && !key2 && !key3 && !key4) throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED!"); } }; class ModuleCloaking : public Module { private: CloakUser* cu; Module* HashModule; public: ModuleCloaking(InspIRCd* Me) : Module(Me) { ServerInstance->UseInterface("HashRequest"); /* Attempt to locate the md5 service provider, bail if we can't find it */ HashModule = ServerInstance->FindModule("m_md5.so"); if (!HashModule) throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so."); /* Create new mode handler object */ cu = new CloakUser(ServerInstance, this, HashModule); /* Register it with the core */ if (!ServerInstance->AddMode(cu, 'x')) throw ModuleException("Could not add new modes!"); OnRehash(NULL,""); } virtual ~ModuleCloaking() { ServerInstance->Modes->DelMode(cu); DELETE(cu); ServerInstance->DoneWithInterface("HashRequest"); } virtual Version GetVersion() { // returns the version number of the module to be // listed in /MODULES return Version(1,1,0,2,VF_COMMON|VF_VENDOR,API_VERSION); } virtual void OnRehash(userrec* user, const std::string ¶meter) { cu->DoRehash(); } void Implements(char* List) { List[I_OnRehash] = 1; } }; MODULE_INIT(ModuleCloaking) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "m_hash.h" + +/* $ModDesc: Provides masking of user hostnames */ +/* $ModDep: m_hash.h */ + +/* Used to vary the output a little more depending on the cloak keys */ +static const char* xtab[] = {"F92E45D871BCA630", "A1B9D80C72E653F4", "1ABC078934DEF562", "ABCDEF5678901234"}; + +/** Handles user mode +x + */ +class CloakUser : public ModeHandler +{ + + std::string prefix; + unsigned int key1; + unsigned int key2; + unsigned int key3; + unsigned int key4; + Module* Sender; + Module* HashProvider; + + /** 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. + * + * For example, if it is passed "svn.inspircd.org" it will return ".inspircd.org". + * If it is passed "brainbox.winbot.co.uk" it will return ".co.uk", + * and if it is passed "localhost.localdomain" it will return ".localdomain". + * + * This is used to ensure a significant part of the host is always cloaked (see Bug #216) + */ + std::string LastTwoDomainParts(const std::string &host) + { + int dots = 0; + std::string::size_type splitdot = host.length(); + + for (std::string::size_type x = host.length() - 1; x; --x) + { + if (host[x] == '.') + { + splitdot = x; + dots++; + } + if (dots >= 3) + break; + } + + if (splitdot == host.length()) + return host; + else + return host.substr(splitdot); + } + + public: + CloakUser(InspIRCd* Instance, Module* Source, Module* Hash) : ModeHandler(Instance, 'x', 0, 0, false, MODETYPE_USER, false), Sender(Source), HashProvider(Hash) + { + } + + ModeAction OnModeChange(userrec* source, userrec* dest, chanrec* channel, std::string ¶meter, bool adding) + { + if (source != dest) + return MODEACTION_DENY; + + /* For remote clients, we dont take any action, we just allow it. + * The local server where they are will set their cloak instead. + */ + if (!IS_LOCAL(dest)) + return MODEACTION_ALLOW; + + if (adding) + { + if(!dest->IsModeSet('x')) + { + /* The mode is being turned on - so attempt to + * allocate the user a cloaked host using a non-reversible + * algorithm (its simple, but its non-reversible so the + * simplicity doesnt really matter). This algorithm + * will not work if the user has only one level of domain + * naming in their hostname (e.g. if they are on a lan or + * are connecting via localhost) -- this doesnt matter much. + */ + + char* n1 = strchr(dest->host,'.'); + char* n2 = strchr(dest->host,':'); + + if (n1 || n2) + { + /* InspIRCd users have two hostnames; A displayed + * hostname which can be modified by modules (e.g. + * to create vhosts, implement chghost, etc) and a + * 'real' hostname which you shouldnt write to. + */ + + unsigned int iv[] = { key1, key2, key3, key4 }; + std::string a = LastTwoDomainParts(dest->host); + std::string b; + + /** Reset the Hash module, and send it our IV and hex table */ + HashResetRequest(Sender, HashProvider).Send(); + HashKeyRequest(Sender, HashProvider, iv).Send(); + HashHexRequest(Sender, HashProvider, xtab[(*dest->host) % 4]); + + /* Generate a cloak using specialized Hash */ + std::string hostcloak = prefix + "-" + std::string(HashSumRequest(Sender, HashProvider, dest->host).Send()).substr(0,8) + a; + + /* Fix by brain - if the cloaked host is > the max length of a host (64 bytes + * according to the DNS RFC) then tough titty, they get cloaked as an IP. + * Their ISP shouldnt go to town on subdomains, or they shouldnt have a kiddie + * vhost. + */ +#ifdef IPV6 + in6_addr testaddr; + in_addr testaddr2; + if ((dest->GetProtocolFamily() == AF_INET6) && (inet_pton(AF_INET6,dest->host,&testaddr) < 1) && (hostcloak.length() <= 64)) + /* Invalid ipv6 address, and ipv6 user (resolved host) */ + b = hostcloak; + else if ((dest->GetProtocolFamily() == AF_INET) && (inet_aton(dest->host,&testaddr2) < 1) && (hostcloak.length() <= 64)) + /* Invalid ipv4 address, and ipv4 user (resolved host) */ + b = hostcloak; + else + /* Valid ipv6 or ipv4 address (not resolved) ipv4 or ipv6 user */ + b = ((!strchr(dest->host,':')) ? Cloak4(dest->host) : Cloak6(dest->host)); +#else + in_addr testaddr; + if ((inet_aton(dest->host,&testaddr) < 1) && (hostcloak.length() <= 64)) + /* Invalid ipv4 address, and ipv4 user (resolved host) */ + b = hostcloak; + else + /* Valid ipv4 address (not resolved) ipv4 user */ + b = Cloak4(dest->host); +#endif + + dest->ChangeDisplayedHost(b.c_str()); + } + + dest->SetMode('x',true); + return MODEACTION_ALLOW; + } + } + else + { + if (dest->IsModeSet('x')) + { + /* User is removing the mode, so just restore their real host + * and make it match the displayed one. + */ + dest->ChangeDisplayedHost(dest->host); + dest->SetMode('x',false); + return MODEACTION_ALLOW; + } + } + + return MODEACTION_DENY; + } + + std::string Cloak4(const char* ip) + { + unsigned int iv[] = { key1, key2, key3, key4 }; + irc::sepstream seps(ip, '.'); + std::string ra[4];; + std::string octet[4]; + int i[4]; + + for (int j = 0; j < 4; j++) + { + octet[j] = seps.GetToken(); + 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 */ + HashResetRequest(Sender, HashProvider).Send(); + HashKeyRequest(Sender, HashProvider, iv).Send(); + + /* Send the Hash module a different hex table for each octet group's Hash sum */ + for (int k = 0; k < 4; k++) + { + HashHexRequest(Sender, HashProvider, xtab[(iv[k]+i[k]) % 4]).Send(); + ra[k] = std::string(HashSumRequest(Sender, HashProvider, octet[k]).Send()).substr(0,6); + } + /* Stick them all together */ + return std::string().append(ra[0]).append(".").append(ra[1]).append(".").append(ra[2]).append(".").append(ra[3]); + } + + std::string Cloak6(const char* ip) + { + /* Theyre using 4in6 (YUCK). Translate as ipv4 cloak */ + if (!strncmp(ip, "0::ffff:", 8)) + return Cloak4(ip + 8); + + /* If we get here, yes it really is an ipv6 ip */ + unsigned int iv[] = { key1, key2, key3, key4 }; + std::vector hashies; + std::string item; + int rounds = 0; + + /* Reset the Hash module and send it our IV */ + HashResetRequest(Sender, HashProvider).Send(); + HashKeyRequest(Sender, HashProvider, iv).Send(); + + for (const char* input = ip; *input; input++) + { + item += *input; + if (item.length() > 7) + { + /* Send the Hash module a different hex table for each octet group's Hash sum */ + HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send(); + hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8)); + item.clear(); + } + rounds++; + } + if (!item.empty()) + { + /* Send the Hash module a different hex table for each octet group's Hash sum */ + HashHexRequest(Sender, HashProvider, xtab[(key1+rounds) % 4]).Send(); + hashies.push_back(std::string(HashSumRequest(Sender, HashProvider, item).Send()).substr(0,8)); + item.clear(); + } + /* Stick them all together */ + return irc::stringjoiner(":", hashies, 0, hashies.size() - 1).GetJoined(); + } + + void DoRehash() + { + ConfigReader Conf(ServerInstance); + key1 = key2 = key3 = key4 = 0; + key1 = Conf.ReadInteger("cloak","key1",0,true); + key2 = Conf.ReadInteger("cloak","key2",0,true); + key3 = Conf.ReadInteger("cloak","key3",0,true); + key4 = Conf.ReadInteger("cloak","key4",0,true); + prefix = Conf.ReadValue("cloak","prefix",0); + + if (prefix.empty()) + prefix = ServerInstance->Config->Network; + + if (!key1 && !key2 && !key3 && !key4) + throw ModuleException("You have not defined cloak keys for m_cloaking!!! THIS IS INSECURE AND SHOULD BE CHECKED!"); + } +}; + + +class ModuleCloaking : public Module +{ + private: + + CloakUser* cu; + Module* HashModule; + + public: + ModuleCloaking(InspIRCd* Me) + : Module(Me) + { + ServerInstance->UseInterface("HashRequest"); + + /* Attempt to locate the md5 service provider, bail if we can't find it */ + HashModule = ServerInstance->FindModule("m_md5.so"); + if (!HashModule) + throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_cloaking.so."); + + /* Create new mode handler object */ + cu = new CloakUser(ServerInstance, this, HashModule); + + /* Register it with the core */ + if (!ServerInstance->AddMode(cu, 'x')) + throw ModuleException("Could not add new modes!"); + + OnRehash(NULL,""); + } + + virtual ~ModuleCloaking() + { + ServerInstance->Modes->DelMode(cu); + DELETE(cu); + ServerInstance->DoneWithInterface("HashRequest"); + } + + virtual Version GetVersion() + { + // returns the version number of the module to be + // listed in /MODULES + return Version(1,1,0,2,VF_COMMON|VF_VENDOR,API_VERSION); + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + cu->DoRehash(); + } + + void Implements(char* List) + { + List[I_OnRehash] = 1; + } +}; + +MODULE_INIT(ModuleCloaking) diff --git a/src/modules/m_clones.cpp b/src/modules/m_clones.cpp index 429b9c2b9..72a7ca7e8 100644 --- a/src/modules/m_clones.cpp +++ b/src/modules/m_clones.cpp @@ -1 +1,100 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "wildcard.h" /* $ModDesc: Provides the /clones command to retrieve information on a user, channel, or IP address */ /** Handle /CHECK */ class cmd_clones : public command_t { public: cmd_clones (InspIRCd* Instance) : command_t(Instance,"CLONES", 'o', 1) { this->source = "m_clones.so"; syntax = ""; } std::string FindMatchingIP(const irc::string &ipaddr) { std::string n = assign(ipaddr); for (user_hash::const_iterator a = ServerInstance->clientlist->begin(); a != ServerInstance->clientlist->end(); a++) if (a->second->GetIPString() == n) return a->second->GetFullRealHost(); return ""; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { std::string clonesstr = "304 " + std::string(user->nick) + " :CLONES"; unsigned long limit = atoi(parameters[0]); /* * Syntax of a /clones reply: * :server.name 304 target :CLONES START * :server.name 304 target :CLONES * :server.name 304 target :CHECK END */ user->WriteServ(clonesstr + " START"); /* hostname or other */ for (clonemap::iterator x = ServerInstance->global_clones.begin(); x != ServerInstance->global_clones.end(); x++) { if (x->second >= limit) user->WriteServ(clonesstr + " "+ ConvToStr(x->second) + " " + assign(x->first) + " " + FindMatchingIP(x->first)); } user->WriteServ(clonesstr + " END"); return CMD_LOCALONLY; } }; class ModuleClones : public Module { private: cmd_clones *mycommand; public: ModuleClones(InspIRCd* Me) : Module(Me) { mycommand = new cmd_clones(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~ModuleClones() { } virtual Version GetVersion() { return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); } void Implements(char* List) { /* we don't hook anything, nothing required */ } }; MODULE_INIT(ModuleClones) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "wildcard.h" + +/* $ModDesc: Provides the /clones command to retrieve information on a user, channel, or IP address */ + +/** Handle /CHECK + */ +class cmd_clones : public command_t +{ + public: + cmd_clones (InspIRCd* Instance) : command_t(Instance,"CLONES", 'o', 1) + { + this->source = "m_clones.so"; + syntax = ""; + } + + std::string FindMatchingIP(const irc::string &ipaddr) + { + std::string n = assign(ipaddr); + for (user_hash::const_iterator a = ServerInstance->clientlist->begin(); a != ServerInstance->clientlist->end(); a++) + if (a->second->GetIPString() == n) + return a->second->GetFullRealHost(); + return ""; + } + + CmdResult Handle (const char** parameters, int pcnt, userrec *user) + { + + std::string clonesstr = "304 " + std::string(user->nick) + " :CLONES"; + + unsigned long limit = atoi(parameters[0]); + + /* + * Syntax of a /clones reply: + * :server.name 304 target :CLONES START + * :server.name 304 target :CLONES + * :server.name 304 target :CHECK END + */ + + user->WriteServ(clonesstr + " START"); + + /* hostname or other */ + for (clonemap::iterator x = ServerInstance->global_clones.begin(); x != ServerInstance->global_clones.end(); x++) + { + if (x->second >= limit) + user->WriteServ(clonesstr + " "+ ConvToStr(x->second) + " " + assign(x->first) + " " + FindMatchingIP(x->first)); + } + + user->WriteServ(clonesstr + " END"); + + return CMD_LOCALONLY; + } +}; + + +class ModuleClones : public Module +{ + private: + cmd_clones *mycommand; + public: + ModuleClones(InspIRCd* Me) : Module(Me) + { + + mycommand = new cmd_clones(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~ModuleClones() + { + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION); + } + + void Implements(char* List) + { + /* we don't hook anything, nothing required */ + } + +}; + +MODULE_INIT(ModuleClones) diff --git a/src/modules/m_conn_join.cpp b/src/modules/m_conn_join.cpp index a8e81fcd8..2d639f310 100644 --- a/src/modules/m_conn_join.cpp +++ b/src/modules/m_conn_join.cpp @@ -1 +1,96 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Forces users to join the specified channel(s) on connect */ class ModuleConnJoin : public Module { private: std::string JoinChan; std::vector Joinchans; int tokenize(const string &str, std::vector &tokens) { // skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(",", 0); // find first "non-delimiter". string::size_type pos = str.find_first_of(",", lastPos); while (string::npos != pos || 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: ModuleConnJoin(InspIRCd* Me) : Module(Me) { OnRehash(NULL, ""); } Priority Prioritize() { return PRIORITY_LAST; } void Implements(char* List) { List[I_OnPostConnect] = List[I_OnRehash] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { ConfigReader* conf = new ConfigReader(ServerInstance); JoinChan = conf->ReadValue("autojoin", "channel", 0); Joinchans.clear(); if (!JoinChan.empty()) tokenize(JoinChan,Joinchans); DELETE(conf); } virtual ~ModuleConnJoin() { } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } virtual void OnPostConnect(userrec* user) { if (!IS_LOCAL(user)) return; for(std::vector::iterator it = Joinchans.begin(); it != Joinchans.end(); it++) if (ServerInstance->IsChannel(it->c_str())) chanrec::JoinUser(ServerInstance, user, it->c_str(), false, "", ServerInstance->Time(true)); } }; MODULE_INIT(ModuleConnJoin) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Forces users to join the specified channel(s) on connect */ + +class ModuleConnJoin : public Module +{ + private: + std::string JoinChan; + std::vector Joinchans; + + + int tokenize(const string &str, std::vector &tokens) + { + // skip delimiters at beginning. + string::size_type lastPos = str.find_first_not_of(",", 0); + // find first "non-delimiter". + string::size_type pos = str.find_first_of(",", lastPos); + + while (string::npos != pos || 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: + ModuleConnJoin(InspIRCd* Me) + : Module(Me) + { + OnRehash(NULL, ""); + } + + Priority Prioritize() + { + return PRIORITY_LAST; + } + + void Implements(char* List) + { + List[I_OnPostConnect] = List[I_OnRehash] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + ConfigReader* conf = new ConfigReader(ServerInstance); + JoinChan = conf->ReadValue("autojoin", "channel", 0); + Joinchans.clear(); + if (!JoinChan.empty()) + tokenize(JoinChan,Joinchans); + DELETE(conf); + } + + virtual ~ModuleConnJoin() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + + virtual void OnPostConnect(userrec* user) + { + if (!IS_LOCAL(user)) + return; + + for(std::vector::iterator it = Joinchans.begin(); it != Joinchans.end(); it++) + if (ServerInstance->IsChannel(it->c_str())) + chanrec::JoinUser(ServerInstance, user, it->c_str(), false, "", ServerInstance->Time(true)); + } + +}; + + +MODULE_INIT(ModuleConnJoin) diff --git a/src/modules/m_conn_umodes.cpp b/src/modules/m_conn_umodes.cpp index f9118a384..3f27eeff5 100644 --- a/src/modules/m_conn_umodes.cpp +++ b/src/modules/m_conn_umodes.cpp @@ -1 +1,104 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" #include "wildcard.h" /* $ModDesc: Sets (and unsets) modes on users when they connect */ class ModuleModesOnConnect : public Module { private: ConfigReader *Conf; public: ModuleModesOnConnect(InspIRCd* Me) : Module(Me) { Conf = new ConfigReader(ServerInstance); } void Implements(char* List) { List[I_OnPostConnect] = List[I_OnRehash] = 1; } virtual void OnRehash(userrec* user, const std::string ¶meter) { DELETE(Conf); Conf = new ConfigReader(ServerInstance); } virtual ~ModuleModesOnConnect() { DELETE(Conf); } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } virtual void OnPostConnect(userrec* user) { if (!IS_LOCAL(user)) return; for (int j = 0; j < Conf->Enumerate("connect"); j++) { std::string hostn = Conf->ReadValue("connect","allow",j); if ((match(user->GetIPString(),hostn.c_str(),true)) || (match(user->host,hostn.c_str()))) { std::string ThisModes = Conf->ReadValue("connect","modes",j); if (!ThisModes.empty()) { std::string buf; stringstream ss(ThisModes); vector tokens; // split ThisUserModes into modes and mode params while (ss >> buf) tokens.push_back(buf); int size = tokens.size() + 1; const char** modes = new const char*[size]; modes[0] = user->nick; modes[1] = tokens[0].c_str(); if (tokens.size() > 1) { // process mode params int i = 2; for (unsigned int k = 1; k < tokens.size(); k++) { modes[i] = tokens[k].c_str(); i++; } } ServerInstance->Parser->CallHandler("MODE", modes, size, user); delete [] modes; } break; } } } }; MODULE_INIT(ModuleModesOnConnect) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" +#include "wildcard.h" + +/* $ModDesc: Sets (and unsets) modes on users when they connect */ + +class ModuleModesOnConnect : public Module +{ + private: + + ConfigReader *Conf; + + public: + ModuleModesOnConnect(InspIRCd* Me) + : Module(Me) + { + + Conf = new ConfigReader(ServerInstance); + } + + void Implements(char* List) + { + List[I_OnPostConnect] = List[I_OnRehash] = 1; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + DELETE(Conf); + Conf = new ConfigReader(ServerInstance); + } + + virtual ~ModuleModesOnConnect() + { + DELETE(Conf); + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + + virtual void OnPostConnect(userrec* user) + { + if (!IS_LOCAL(user)) + return; + + for (int j = 0; j < Conf->Enumerate("connect"); j++) + { + std::string hostn = Conf->ReadValue("connect","allow",j); + if ((match(user->GetIPString(),hostn.c_str(),true)) || (match(user->host,hostn.c_str()))) + { + std::string ThisModes = Conf->ReadValue("connect","modes",j); + if (!ThisModes.empty()) + { + std::string buf; + stringstream ss(ThisModes); + + vector tokens; + + // split ThisUserModes into modes and mode params + while (ss >> buf) + tokens.push_back(buf); + + int size = tokens.size() + 1; + const char** modes = new const char*[size]; + modes[0] = user->nick; + modes[1] = tokens[0].c_str(); + + if (tokens.size() > 1) + { + // process mode params + int i = 2; + for (unsigned int k = 1; k < tokens.size(); k++) + { + modes[i] = tokens[k].c_str(); + i++; + } + } + + ServerInstance->Parser->CallHandler("MODE", modes, size, user); + delete [] modes; + } + break; + } + } + } +}; + +MODULE_INIT(ModuleModesOnConnect) diff --git a/src/modules/m_conn_waitpong.cpp b/src/modules/m_conn_waitpong.cpp index b84533f88..0dd27ddbd 100644 --- a/src/modules/m_conn_waitpong.cpp +++ b/src/modules/m_conn_waitpong.cpp @@ -1 +1,148 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.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; bool killonbadreply; const char* extenstr; public: ModuleWaitPong(InspIRCd* Me) : Module(Me), extenstr("waitpong_pingstr") { OnRehash(NULL,""); } virtual void OnRehash(userrec* user, const std::string ¶m) { ConfigReader Conf(ServerInstance); sendsnotice = Conf.ReadFlag("waitpong", "sendsnotice", 0); if(Conf.GetError() == CONF_VALUE_NOT_FOUND) sendsnotice = true; killonbadreply = Conf.ReadFlag("waitpong", "killonbadreply", 0); if(Conf.GetError() == CONF_VALUE_NOT_FOUND) killonbadreply = true; } void Implements(char* List) { List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnPreCommand] = List[I_OnRehash] = List[I_OnUserDisconnect] = List[I_OnCleanup] = 1; } char* RandString(unsigned int length) { unsigned char* out = new unsigned char[length+1]; for(unsigned int i = 0; i < length; i++) out[i] = ((rand() % 26) + 65); out[length] = '\0'; return (char*)out; } virtual int OnUserRegister(userrec* user) { char* pingrpl = RandString(10); user->Write("PING :%s", pingrpl); 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, pingrpl, pingrpl); user->Extend(extenstr, pingrpl); return 0; } virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec* user, bool validated, const std::string &original_line) { if(command == "PONG") { char* pingrpl; user->GetExt(extenstr, pingrpl); if(pingrpl) { if(strcmp(pingrpl, parameters[0]) == 0) { DELETE(pingrpl); user->Shrink(extenstr); return 1; } else { if(killonbadreply) userrec::QuitUser(ServerInstance, user, "Incorrect ping reply for registration"); return 1; } } } return 0; } virtual bool OnCheckReady(userrec* user) { char* pingrpl; return (!user->GetExt(extenstr, pingrpl)); } virtual void OnUserDisconnect(userrec* user) { char* pingrpl; user->GetExt(extenstr, pingrpl); if(pingrpl) { DELETE(pingrpl); user->Shrink(extenstr); } } virtual void OnCleanup(int target_type, void* item) { if(target_type == TYPE_USER) { userrec* user = (userrec*)item; char* pingrpl; user->GetExt(extenstr, pingrpl); if(pingrpl) { DELETE(pingrpl); user->Shrink(extenstr); } } } virtual ~ModuleWaitPong() { } virtual Version GetVersion() { return Version(1, 1, 0, 1, VF_VENDOR, API_VERSION); } }; MODULE_INIT(ModuleWaitPong) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.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; + bool killonbadreply; + const char* extenstr; + + public: + ModuleWaitPong(InspIRCd* Me) + : Module(Me), extenstr("waitpong_pingstr") + { + OnRehash(NULL,""); + } + + virtual void OnRehash(userrec* user, const std::string ¶m) + { + ConfigReader Conf(ServerInstance); + + sendsnotice = Conf.ReadFlag("waitpong", "sendsnotice", 0); + + if(Conf.GetError() == CONF_VALUE_NOT_FOUND) + sendsnotice = true; + + killonbadreply = Conf.ReadFlag("waitpong", "killonbadreply", 0); + + if(Conf.GetError() == CONF_VALUE_NOT_FOUND) + killonbadreply = true; + } + + void Implements(char* List) + { + List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnPreCommand] = List[I_OnRehash] = List[I_OnUserDisconnect] = List[I_OnCleanup] = 1; + } + + char* RandString(unsigned int length) + { + unsigned char* out = new unsigned char[length+1]; + for(unsigned int i = 0; i < length; i++) + out[i] = ((rand() % 26) + 65); + out[length] = '\0'; + + return (char*)out; + } + + virtual int OnUserRegister(userrec* user) + { + char* pingrpl = RandString(10); + + user->Write("PING :%s", pingrpl); + + 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, pingrpl, pingrpl); + + user->Extend(extenstr, pingrpl); + return 0; + } + + virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec* user, bool validated, const std::string &original_line) + { + if(command == "PONG") + { + char* pingrpl; + user->GetExt(extenstr, pingrpl); + + if(pingrpl) + { + if(strcmp(pingrpl, parameters[0]) == 0) + { + DELETE(pingrpl); + user->Shrink(extenstr); + return 1; + } + else + { + if(killonbadreply) + userrec::QuitUser(ServerInstance, user, "Incorrect ping reply for registration"); + return 1; + } + } + } + return 0; + } + + virtual bool OnCheckReady(userrec* user) + { + char* pingrpl; + return (!user->GetExt(extenstr, pingrpl)); + } + + virtual void OnUserDisconnect(userrec* user) + { + char* pingrpl; + user->GetExt(extenstr, pingrpl); + + if(pingrpl) + { + DELETE(pingrpl); + user->Shrink(extenstr); + } + } + + virtual void OnCleanup(int target_type, void* item) + { + if(target_type == TYPE_USER) + { + userrec* user = (userrec*)item; + char* pingrpl; + user->GetExt(extenstr, pingrpl); + + if(pingrpl) + { + DELETE(pingrpl); + user->Shrink(extenstr); + } + } + } + + virtual ~ModuleWaitPong() + { + } + + virtual Version GetVersion() + { + return Version(1, 1, 0, 1, VF_VENDOR, API_VERSION); + } + +}; + +MODULE_INIT(ModuleWaitPong) diff --git a/src/modules/m_connflood.cpp b/src/modules/m_connflood.cpp index 71e52fd01..47b19fdf4 100644 --- a/src/modules/m_connflood.cpp +++ b/src/modules/m_connflood.cpp @@ -1 +1,120 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "modules.h" /* $ModDesc: Connection throttle */ int conns = 0, throttled = 0; class ModuleConnFlood : public Module { private: int seconds, maxconns, timeout, boot_wait; time_t first; std::string quitmsg; ConfigReader* conf; public: ModuleConnFlood(InspIRCd* Me) : Module(Me) { InitConf(); } virtual ~ModuleConnFlood() { } virtual Version GetVersion() { return Version(1,1,0,0,VF_VENDOR,API_VERSION); } void Implements(char* List) { List[I_OnRehash] = List[I_OnUserRegister] = 1; } void InitConf() { /* read configuration variables */ conf = new ConfigReader(ServerInstance); /* throttle configuration */ seconds = conf->ReadInteger("connflood", "seconds", 0, true); maxconns = conf->ReadInteger("connflood", "maxconns", 0, true); timeout = conf->ReadInteger("connflood", "timeout", 0, true); quitmsg = conf->ReadValue("connflood", "quitmsg", 0); /* seconds to wait when the server just booted */ boot_wait = conf->ReadInteger("connflood", "bootwait", 0, true); first = ServerInstance->Time(); } virtual int OnUserRegister(userrec* user) { time_t next = ServerInstance->Time(); if ((ServerInstance->startup_time + boot_wait) > next) return 0; /* time difference between first and latest connection */ time_t tdiff = next - first; /* increase connection count */ conns++; if (throttled == 1) { if (tdiff > seconds + timeout) { /* expire throttle */ throttled = 0; ServerInstance->WriteOpers("*** Connection throttle deactivated"); return 0; } userrec::QuitUser(ServerInstance, user, quitmsg); return 1; } if (tdiff <= seconds) { if (conns >= maxconns) { throttled = 1; ServerInstance->WriteOpers("*** Connection throttle activated"); userrec::QuitUser(ServerInstance, user, quitmsg); return 1; } } else { conns = 1; first = next; } return 0; } virtual void OnRehash(userrec* user, const std::string ¶meter) { InitConf(); } }; MODULE_INIT(ModuleConnFlood) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "modules.h" + +/* $ModDesc: Connection throttle */ + +int conns = 0, throttled = 0; + +class ModuleConnFlood : public Module +{ +private: + int seconds, maxconns, timeout, boot_wait; + time_t first; + std::string quitmsg; + + ConfigReader* conf; + + +public: + ModuleConnFlood(InspIRCd* Me) : Module(Me) + { + + InitConf(); + } + + virtual ~ModuleConnFlood() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,0,VF_VENDOR,API_VERSION); + } + + void Implements(char* List) + { + List[I_OnRehash] = List[I_OnUserRegister] = 1; + } + + void InitConf() + { + /* read configuration variables */ + conf = new ConfigReader(ServerInstance); + /* throttle configuration */ + seconds = conf->ReadInteger("connflood", "seconds", 0, true); + maxconns = conf->ReadInteger("connflood", "maxconns", 0, true); + timeout = conf->ReadInteger("connflood", "timeout", 0, true); + quitmsg = conf->ReadValue("connflood", "quitmsg", 0); + + /* seconds to wait when the server just booted */ + boot_wait = conf->ReadInteger("connflood", "bootwait", 0, true); + + first = ServerInstance->Time(); + } + + virtual int OnUserRegister(userrec* user) + { + time_t next = ServerInstance->Time(); + + if ((ServerInstance->startup_time + boot_wait) > next) + return 0; + + /* time difference between first and latest connection */ + time_t tdiff = next - first; + + /* increase connection count */ + conns++; + + if (throttled == 1) + { + if (tdiff > seconds + timeout) + { + /* expire throttle */ + throttled = 0; + ServerInstance->WriteOpers("*** Connection throttle deactivated"); + return 0; + } + userrec::QuitUser(ServerInstance, user, quitmsg); + return 1; + } + + if (tdiff <= seconds) + { + if (conns >= maxconns) + { + throttled = 1; + ServerInstance->WriteOpers("*** Connection throttle activated"); + userrec::QuitUser(ServerInstance, user, quitmsg); + return 1; + } + } + else + { + conns = 1; + first = next; + } + return 0; + } + + virtual void OnRehash(userrec* user, const std::string ¶meter) + { + InitConf(); + } + +}; + +MODULE_INIT(ModuleConnFlood) diff --git a/src/modules/m_cycle.cpp b/src/modules/m_cycle.cpp index b1a22941d..eb20f4f99 100644 --- a/src/modules/m_cycle.cpp +++ b/src/modules/m_cycle.cpp @@ -1 +1,99 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Provides support for unreal-style CYCLE command. */ /** Handle /CYCLE */ class cmd_cycle : public command_t { public: cmd_cycle (InspIRCd* Instance) : command_t(Instance,"CYCLE", 0, 1) { this->source = "m_cycle.so"; syntax = " :[reason]"; } CmdResult Handle (const char** parameters, int pcnt, userrec *user) { chanrec* channel = ServerInstance->FindChan(parameters[0]); std::string reason = ConvToStr("Cycling"); if (pcnt > 1) { /* reason provided, use it */ reason = reason + ": " + parameters[1]; } if (channel) { /* * technically, this is only ever sent locally, but pays to be safe ;p */ if (IS_LOCAL(user)) { if (channel->GetStatus(user) < STATUS_VOICE && channel->IsBanned(user)) { /* banned, boned. drop the message. */ user->WriteServ("NOTICE "+std::string(user->nick)+" :*** You may not cycle, as you are banned on channel " + channel->name); return CMD_FAILURE; } /* XXX in the future, this may move to a static chanrec method (the delete.) -- w00t */ if (!channel->PartUser(user, reason.c_str())) delete channel; chanrec::JoinUser(ServerInstance, user, parameters[0], true, "", ServerInstance->Time(true)); } return CMD_LOCALONLY; } else { user->WriteServ("NOTICE %s :*** You are not on this channel", user->nick); } return CMD_FAILURE; } }; class ModuleCycle : public Module { cmd_cycle* mycommand; public: ModuleCycle(InspIRCd* Me) : Module(Me) { mycommand = new cmd_cycle(ServerInstance); ServerInstance->AddCommand(mycommand); } virtual ~ModuleCycle() { } virtual Version GetVersion() { return Version(1,1,0,1,VF_VENDOR,API_VERSION); } }; MODULE_INIT(ModuleCycle) \ No newline at end of file +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd: (C) 2002-2007 InspIRCd Development Team + * See: http://www.inspircd.org/wiki/index.php/Credits + * + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#include "inspircd.h" +#include "users.h" +#include "channels.h" +#include "modules.h" + +/* $ModDesc: Provides support for unreal-style CYCLE command. */ + +/** Handle /CYCLE + */ +class cmd_cycle : public command_t +{ + public: + cmd_cycle (InspIRCd* Instance) : command_t(Instance,"CYCLE", 0, 1) + { + this->source = "m_cycle.so"; + syntax = " :[reason]"; + } + + CmdResult Handle (const char** parameters, int pcnt, userrec *user) + { + chanrec* channel = ServerInstance->FindChan(parameters[0]); + std::string reason = ConvToStr("Cycling"); + + if (pcnt > 1) + { + /* reason provided, use it */ + reason = reason + ": " + parameters[1]; + } + + if (channel) + { + /* + * technically, this is only ever sent locally, but pays to be safe ;p + */ + if (IS_LOCAL(user)) + { + if (channel->GetStatus(user) < STATUS_VOICE && channel->IsBanned(user)) + { + /* banned, boned. drop the message. */ + user->WriteServ("NOTICE "+std::string(user->nick)+" :*** You may not cycle, as you are banned on channel " + channel->name); + return CMD_FAILURE; + } + + /* XXX in the future, this may move to a static chanrec method (the delete.) -- w00t */ + if (!channel->PartUser(user, reason.c_str())) + delete channel; + + chanrec::JoinUser(ServerInstance, user, parameters[0], true, "", ServerInstance->Time(true)); + } + + return CMD_LOCALONLY; + } + else + { + user->WriteServ("NOTICE %s :*** You are not on this channel", user->nick); + } + + return CMD_FAILURE; + } +}; + + +class ModuleCycle : public Module +{ + cmd_cycle* mycommand; + public: + ModuleCycle(InspIRCd* Me) + : Module(Me) + { + + mycommand = new cmd_cycle(ServerInstance); + ServerInstance->AddCommand(mycommand); + } + + virtual ~ModuleCycle() + { + } + + virtual Version GetVersion() + { + return Version(1,1,0,1,VF_VENDOR,API_VERSION); + } + +}; + +MODULE_INIT(ModuleCycle) diff --git a/src/modules/m_dccallow.cpp b/src/modules/m_dccallow.cpp index 61ef90d89..bfec3c5e1 100644 --- a/src/modules/m_dccallow.cpp +++ b/src/modules/m_dccallow.cpp @@ -1 +1,489 @@ -/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2007 InspIRCd Development Team * See: http://www.inspircd.org/wiki/index.php/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "users.h" #include "channels.h" #include "modules.h" /* $ModDesc: Povides support for the /DCCALLOW command */ static ConfigReader *Conf; class BannedFileList { public: std::string filemask; std::string action; }; class DCCAllow { public: std::string nickname; std::string hostmask; time_t set_on; long length; DCCAllow() { } DCCAllow(const std::string &nick, const std::string &hm, const time_t so, const long ln) : nickname(nick), hostmask(hm), set_on(so), length(ln) { } }; typedef std::vector userlist; userlist ul; typedef std::vector dccallowlist; dccallowlist* dl; typedef std::vector bannedfilelist; bannedfilelist bfl; class cmd_dccallow : public command_t { public: cmd_dccallow(InspIRCd* Me) : command_t(Me, "DCCALLOW", 0, 0) { this->source = "m_dccallow.so"; syntax = "{[+|-]