diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..ed804f1b --- /dev/null +++ b/.clang-format @@ -0,0 +1,15 @@ +--- +BasedOnStyle: Google +Standard: Cpp11 + +UseTab: ForIndentation +IndentWidth: 4 +TabWidth: 4 +AccessModifierOffset: -2 + +DerivePointerAlignment: false +PointerAlignment: Left + +# Prevent breaking doxygen, as clang-format doesn't support reflowing of doxygen comments yet (as of 3.5.0). +CommentPragmas: '^\*|^/|^!' +... diff --git a/include/znc/Buffer.h b/include/znc/Buffer.h index 3755b775..7afe58ee 100644 --- a/include/znc/Buffer.h +++ b/include/znc/Buffer.h @@ -28,11 +28,15 @@ class CClient; // !Forward Declarations class CBufLine { -public: - CBufLine() : CBufLine("") { throw 0; } // shouldn't be called, but is needed for compilation + public: + CBufLine() : CBufLine("") { + throw 0; + } // shouldn't be called, but is needed for compilation CBufLine(const CMessage& Format, const CString& sText = ""); /// @deprecated - CBufLine(const CString& sFormat, const CString& sText = "", const timeval* ts = nullptr, const MCString& mssTags = MCString::EmptyMap); + CBufLine(const CString& sFormat, const CString& sText = "", + const timeval* ts = nullptr, + const MCString& mssTags = MCString::EmptyMap); ~CBufLine(); CMessage ToMessage(const CClient& Client, const MCString& mssParams) const; /// @deprecated Use ToMessage() instead @@ -40,7 +44,9 @@ public: /// @deprecated void UpdateTime(); - bool Equals(const CMessage& Format) const { return m_Message.Equals(Format); } + bool Equals(const CMessage& Format) const { + return m_Message.Equals(Format); + } // Setters void SetFormat(const CString& sFormat) { m_Message.Parse(sFormat); } @@ -51,35 +57,44 @@ public: // Getters const CString& GetCommand() const { return m_Message.GetCommand(); } - CString GetFormat() const { return m_Message.ToString(CMessage::ExcludeTags); } + CString GetFormat() const { + return m_Message.ToString(CMessage::ExcludeTags); + } const CString& GetText() const { return m_sText; } timeval GetTime() const { return m_Message.GetTime(); } const MCString& GetTags() const { return m_Message.GetTags(); } // !Getters -private: -protected: + private: + protected: CMessage m_Message; - CString m_sText; + CString m_sText; }; class CBuffer : private std::deque { -public: + public: CBuffer(unsigned int uLineCount = 100); ~CBuffer(); size_type AddLine(const CMessage& Format, const CString& sText = ""); - size_type UpdateLine(const CString& sCommand, const CMessage& Format, const CString& sText = ""); - size_type UpdateExactLine(const CMessage& Format, const CString& sText = ""); + size_type UpdateLine(const CString& sCommand, const CMessage& Format, + const CString& sText = ""); + size_type UpdateExactLine(const CMessage& Format, + const CString& sText = ""); - size_type AddLine(const CString& sFormat, const CString& sText = "", const timeval* ts = nullptr, const MCString& mssTags = MCString::EmptyMap); + size_type AddLine(const CString& sFormat, const CString& sText = "", + const timeval* ts = nullptr, + const MCString& mssTags = MCString::EmptyMap); /// Same as AddLine, but replaces a line whose format string starts with sMatch if there is one. - size_type UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText = ""); + size_type UpdateLine(const CString& sMatch, const CString& sFormat, + const CString& sText = ""); /// Same as UpdateLine, but does nothing if this exact line already exists. /// We need this because "/version" sends us the 005 raws again - size_type UpdateExactLine(const CString& sFormat, const CString& sText = ""); + size_type UpdateExactLine(const CString& sFormat, + const CString& sText = ""); const CBufLine& GetBufLine(unsigned int uIdx) const; - CString GetLine(size_type uIdx, const CClient& Client, const MCString& msParams = MCString::EmptyMap) const; + CString GetLine(size_type uIdx, const CClient& Client, + const MCString& msParams = MCString::EmptyMap) const; size_type Size() const { return size(); } bool IsEmpty() const { return empty(); } void Clear() { clear(); } @@ -91,9 +106,9 @@ public: // Getters unsigned int GetLineCount() const { return m_uLineCount; } // !Getters -private: -protected: + private: + protected: unsigned int m_uLineCount; }; -#endif // !ZNC_BUFFER_H +#endif // !ZNC_BUFFER_H diff --git a/include/znc/Chan.h b/include/znc/Chan.h index b086cb2c..f16552ce 100644 --- a/include/znc/Chan.h +++ b/include/znc/Chan.h @@ -32,31 +32,32 @@ class CFile; // !Forward Declarations class CChan { -public: + public: typedef enum { - Voice = '+', - HalfOp = '%', - Op = '@', - Admin = '!', - Owner = '*' + Voice = '+', + HalfOp = '%', + Op = '@', + Admin = '!', + Owner = '*' } EUserPerms; typedef enum { - M_Private = 'p', - M_Secret = 's', - M_Moderated = 'm', + M_Private = 'p', + M_Secret = 's', + M_Moderated = 'm', M_InviteOnly = 'i', M_NoMessages = 'n', - M_OpTopic = 't', - M_Limit = 'l', - M_Key = 'k', - M_Op = 'o', - M_Voice = 'v', - M_Ban = 'b', - M_Except = 'e' + M_OpTopic = 't', + M_Limit = 'l', + M_Key = 'k', + M_Op = 'o', + M_Voice = 'v', + M_Ban = 'b', + M_Except = 'e' } EModes; - CChan(const CString& sName, CIRCNetwork* pNetwork, bool bInConfig, CConfig *pConfig = nullptr); + CChan(const CString& sName, CIRCNetwork* pNetwork, bool bInConfig, + CConfig* pConfig = nullptr); ~CChan(); CChan(const CChan&) = delete; @@ -70,7 +71,8 @@ public: void AttachUser(CClient* pClient = nullptr); void DetachUser(); - void OnWho(const CString& sNick, const CString& sIdent, const CString& sHost); + void OnWho(const CString& sNick, const CString& sIdent, + const CString& sHost); // Modes void SetModes(const CString& s); @@ -95,12 +97,23 @@ public: // Buffer const CBuffer& GetBuffer() const { return m_Buffer; } unsigned int GetBufferCount() const { return m_Buffer.GetLineCount(); } - bool SetBufferCount(unsigned int u, bool bForce = false) { m_bHasBufferCountSet = true; return m_Buffer.SetLineCount(u, bForce); } - void InheritBufferCount(unsigned int u, bool bForce = false) { if (!m_bHasBufferCountSet) m_Buffer.SetLineCount(u, bForce); } + bool SetBufferCount(unsigned int u, bool bForce = false) { + m_bHasBufferCountSet = true; + return m_Buffer.SetLineCount(u, bForce); + } + void InheritBufferCount(unsigned int u, bool bForce = false) { + if (!m_bHasBufferCountSet) m_Buffer.SetLineCount(u, bForce); + } void ResetBufferCount(); - size_t AddBuffer(const CMessage& Format, const CString& sText = "") { return m_Buffer.AddLine(Format, sText); } + size_t AddBuffer(const CMessage& Format, const CString& sText = "") { + return m_Buffer.AddLine(Format, sText); + } /// @deprecated - size_t AddBuffer(const CString& sFormat, const CString& sText = "", const timeval* ts = nullptr, const MCString& mssTags = MCString::EmptyMap) { return m_Buffer.AddLine(sFormat, sText, ts, mssTags); } + size_t AddBuffer(const CString& sFormat, const CString& sText = "", + const timeval* ts = nullptr, + const MCString& mssTags = MCString::EmptyMap) { + return m_Buffer.AddLine(sFormat, sText, ts, mssTags); + } void ClearBuffer() { m_Buffer.Clear(); } void SendBuffer(CClient* pClient); void SendBuffer(CClient* pClient, const CBuffer& Buffer); @@ -115,7 +128,12 @@ public: // Setters void SetModeKnown(bool b) { m_bModeKnown = b; } - void SetIsOn(bool b) { m_bIsOn = b; if (!b) { Reset(); } } + void SetIsOn(bool b) { + m_bIsOn = b; + if (!b) { + Reset(); + } + } void SetKey(const CString& s); void SetTopic(const CString& s) { m_sTopic = s; } void SetTopicOwner(const CString& s) { m_sTopicOwner = s; } @@ -142,13 +160,15 @@ public: std::map GetPermCounts() const; bool IsOn() const { return m_bIsOn; } const CString& GetName() const { return m_sName; } - const std::map& GetModes() const { return m_musModes; } + const std::map& GetModes() const { + return m_musModes; + } const CString& GetKey() const { return m_sKey; } const CString& GetTopic() const { return m_sTopic; } const CString& GetTopicOwner() const { return m_sTopicOwner; } unsigned long GetTopicDate() const { return m_ulTopicDate; } const CString& GetDefaultModes() const { return m_sDefaultModes; } - const std::map& GetNicks() const { return m_msNicks; } + const std::map& GetNicks() const { return m_msNicks; } size_t GetNickCount() const { return m_msNicks.size(); } bool AutoClearChanBuffer() const { return m_bAutoClearChanBuffer; } bool IsDetached() const { return m_bDetached; } @@ -157,32 +177,34 @@ public: bool IsDisabled() const { return m_bDisabled; } unsigned int GetJoinTries() const { return m_uJoinTries; } bool HasBufferCountSet() const { return m_bHasBufferCountSet; } - bool HasAutoClearChanBufferSet() const { return m_bHasAutoClearChanBufferSet; } + bool HasAutoClearChanBufferSet() const { + return m_bHasAutoClearChanBufferSet; + } // !Getters -private: -protected: - bool m_bDetached; - bool m_bIsOn; - bool m_bAutoClearChanBuffer; - bool m_bInConfig; - bool m_bDisabled; - bool m_bHasBufferCountSet; - bool m_bHasAutoClearChanBufferSet; - CString m_sName; - CString m_sKey; - CString m_sTopic; - CString m_sTopicOwner; - unsigned long m_ulTopicDate; - unsigned long m_ulCreationDate; - CIRCNetwork* m_pNetwork; - CNick m_Nick; - unsigned int m_uJoinTries; - CString m_sDefaultModes; - std::map m_msNicks; // Todo: make this caseless (irc style) - CBuffer m_Buffer; + private: + protected: + bool m_bDetached; + bool m_bIsOn; + bool m_bAutoClearChanBuffer; + bool m_bInConfig; + bool m_bDisabled; + bool m_bHasBufferCountSet; + bool m_bHasAutoClearChanBufferSet; + CString m_sName; + CString m_sKey; + CString m_sTopic; + CString m_sTopicOwner; + unsigned long m_ulTopicDate; + unsigned long m_ulCreationDate; + CIRCNetwork* m_pNetwork; + CNick m_Nick; + unsigned int m_uJoinTries; + CString m_sDefaultModes; + std::map m_msNicks; // Todo: make this caseless (irc style) + CBuffer m_Buffer; - bool m_bModeKnown; + bool m_bModeKnown; std::map m_musModes; }; -#endif // !ZNC_CHAN_H +#endif // !ZNC_CHAN_H diff --git a/include/znc/Client.h b/include/znc/Client.h index aaa9960d..9a4eac1e 100644 --- a/include/znc/Client.h +++ b/include/znc/Client.h @@ -35,17 +35,18 @@ class CChan; // !Forward Declarations class CAuthBase { -public: - CAuthBase(const CString& sUsername, const CString& sPassword, CZNCSock* pSock) : m_sUsername(sUsername), m_sPassword(sPassword), m_pSock(pSock) { - } + public: + CAuthBase(const CString& sUsername, const CString& sPassword, + CZNCSock* pSock) + : m_sUsername(sUsername), m_sPassword(sPassword), m_pSock(pSock) {} virtual ~CAuthBase() {} CAuthBase(const CAuthBase&) = delete; CAuthBase& operator=(const CAuthBase&) = delete; - virtual void SetLoginInfo(const CString& sUsername, const CString& sPassword, - CZNCSock* pSock) { + virtual void SetLoginInfo(const CString& sUsername, + const CString& sPassword, CZNCSock* pSock) { m_sUsername = sUsername; m_sPassword = sPassword; m_pSock = pSock; @@ -56,80 +57,92 @@ public: const CString& GetUsername() const { return m_sUsername; } const CString& GetPassword() const { return m_sPassword; } - Csock *GetSocket() const { return m_pSock; } + Csock* GetSocket() const { return m_pSock; } CString GetRemoteIP() const; // Invalidate this CAuthBase instance which means it will no longer use // m_pSock and AcceptLogin() or RefusedLogin() will have no effect. virtual void Invalidate(); -protected: + protected: virtual void AcceptedLogin(CUser& User) = 0; virtual void RefusedLogin(const CString& sReason) = 0; -private: - CString m_sUsername; - CString m_sPassword; + private: + CString m_sUsername; + CString m_sPassword; CZNCSock* m_pSock; }; - class CClientAuth : public CAuthBase { -public: - CClientAuth(CClient* pClient, const CString& sUsername, const CString& sPassword); + public: + CClientAuth(CClient* pClient, const CString& sUsername, + const CString& sPassword); virtual ~CClientAuth() {} CClientAuth(const CClientAuth&) = delete; CClientAuth& operator=(const CClientAuth&) = delete; - void Invalidate() override { m_pClient = nullptr; CAuthBase::Invalidate(); } + void Invalidate() override { + m_pClient = nullptr; + CAuthBase::Invalidate(); + } void AcceptedLogin(CUser& User) override; void RefusedLogin(const CString& sReason) override; -private: -protected: + + private: + protected: CClient* m_pClient; }; class CClient : public CIRCSocket { -public: + public: CClient() - : CIRCSocket(), - m_bGotPass(false), - m_bGotNick(false), - m_bGotUser(false), - m_bInCap(false), - m_bCapNotify(false), - m_bAwayNotify(false), - m_bAccountNotify(false), - m_bExtendedJoin(false), - m_bNamesx(false), - m_bUHNames(false), - m_bAway(false), - m_bServerTime(false), - m_bBatch(false), - m_bEchoMessage(false), - m_bSelfMessage(false), - m_bPlaybackActive(false), - m_pUser(nullptr), - m_pNetwork(nullptr), - m_sNick("unknown-nick"), - m_sPass(""), - m_sUser(""), - m_sNetwork(""), - m_sIdentifier(""), - m_spAuth(), - m_ssAcceptedCaps(), - m_mCoreCaps({{"multi-prefix", {false, [this](bool bVal) { m_bNamesx = bVal; }}}, - {"userhost-in-names", {false, [this](bool bVal) { m_bUHNames = bVal; }}}, - {"echo-message", {false, [this](bool bVal) { m_bEchoMessage = bVal; }}}, - {"server-time", {false, [this](bool bVal) { m_bServerTime = bVal; }}}, - {"batch", {false, [this](bool bVal) { m_bBatch = bVal; }}}, - {"cap-notify", {false, [this](bool bVal) { m_bCapNotify = bVal; }}}, - {"away-notify", {true, [this](bool bVal) { m_bAwayNotify = bVal; }}}, - {"account-notify", {true, [this](bool bVal) { m_bAccountNotify = bVal; }}}, - {"extended-join", {true, [this](bool bVal) { m_bExtendedJoin = bVal; }}}, - }) - { + : CIRCSocket(), + m_bGotPass(false), + m_bGotNick(false), + m_bGotUser(false), + m_bInCap(false), + m_bCapNotify(false), + m_bAwayNotify(false), + m_bAccountNotify(false), + m_bExtendedJoin(false), + m_bNamesx(false), + m_bUHNames(false), + m_bAway(false), + m_bServerTime(false), + m_bBatch(false), + m_bEchoMessage(false), + m_bSelfMessage(false), + m_bPlaybackActive(false), + m_pUser(nullptr), + m_pNetwork(nullptr), + m_sNick("unknown-nick"), + m_sPass(""), + m_sUser(""), + m_sNetwork(""), + m_sIdentifier(""), + m_spAuth(), + m_ssAcceptedCaps(), + m_mCoreCaps({ + {"multi-prefix", + {false, [this](bool bVal) { m_bNamesx = bVal; }}}, + {"userhost-in-names", + {false, [this](bool bVal) { m_bUHNames = bVal; }}}, + {"echo-message", + {false, [this](bool bVal) { m_bEchoMessage = bVal; }}}, + {"server-time", + {false, [this](bool bVal) { m_bServerTime = bVal; }}}, + {"batch", {false, [this](bool bVal) { m_bBatch = bVal; }}}, + {"cap-notify", + {false, [this](bool bVal) { m_bCapNotify = bVal; }}}, + {"away-notify", + {true, [this](bool bVal) { m_bAwayNotify = bVal; }}}, + {"account-notify", + {true, [this](bool bVal) { m_bAccountNotify = bVal; }}}, + {"extended-join", + {true, [this](bool bVal) { m_bExtendedJoin = bVal; }}}, + }) { EnableReadLine(); // RFC says a line can have 512 chars max, but we are // a little more gentle ;) @@ -138,7 +151,8 @@ public: // For compatibility with older clients m_mCoreCaps["znc.in/server-time-iso"] = m_mCoreCaps["server-time"]; m_mCoreCaps["znc.in/batch"] = m_mCoreCaps["batch"]; - m_mCoreCaps["znc.in/self-message"] = {false, [this](bool bVal) { m_bSelfMessage = bVal; }}; + m_mCoreCaps["znc.in/self-message"] = { + false, [this](bool bVal) { m_bSelfMessage = bVal; }}; } virtual ~CClient(); @@ -240,7 +254,9 @@ public: void PutModule(const CString& sModule, const CString& sLine); void PutModNotice(const CString& sModule, const CString& sLine); - bool IsCapEnabled(const CString& sCap) const { return 1 == m_ssAcceptedCaps.count(sCap); } + bool IsCapEnabled(const CString& sCap) const { + return 1 == m_ssAcceptedCaps.count(sCap); + } void NotifyServerDependentCaps(const SCString& ssCaps); void ClearServerDependentCaps(); @@ -258,13 +274,15 @@ public: void SetNick(const CString& s); void SetAway(bool bAway) { m_bAway = bAway; } CUser* GetUser() const { return m_pUser; } - void SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect=true, bool bReconnect=true); + void SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect = true, + bool bReconnect = true); CIRCNetwork* GetNetwork() const { return m_pNetwork; } const std::vector& GetClients() const; const CIRCSock* GetIRCSock() const; CIRCSock* GetIRCSock(); CString GetFullName() const; -private: + + private: void HandleCap(const CMessage& Message); void RespondCap(const CString& sResponse); void ParsePass(const CString& sAuthLine); @@ -292,41 +310,42 @@ private: bool OnTopicMessage(CTopicMessage& Message); bool OnOtherMessage(CMessage& Message); -protected: - bool m_bGotPass; - bool m_bGotNick; - bool m_bGotUser; - bool m_bInCap; - bool m_bCapNotify; - bool m_bAwayNotify; - bool m_bAccountNotify; - bool m_bExtendedJoin; - bool m_bNamesx; - bool m_bUHNames; - bool m_bAway; - bool m_bServerTime; - bool m_bBatch; - bool m_bEchoMessage; - bool m_bSelfMessage; - bool m_bPlaybackActive; - CUser* m_pUser; - CIRCNetwork* m_pNetwork; - CString m_sNick; - CString m_sPass; - CString m_sUser; - CString m_sNetwork; - CString m_sIdentifier; + protected: + bool m_bGotPass; + bool m_bGotNick; + bool m_bGotUser; + bool m_bInCap; + bool m_bCapNotify; + bool m_bAwayNotify; + bool m_bAccountNotify; + bool m_bExtendedJoin; + bool m_bNamesx; + bool m_bUHNames; + bool m_bAway; + bool m_bServerTime; + bool m_bBatch; + bool m_bEchoMessage; + bool m_bSelfMessage; + bool m_bPlaybackActive; + CUser* m_pUser; + CIRCNetwork* m_pNetwork; + CString m_sNick; + CString m_sPass; + CString m_sUser; + CString m_sNetwork; + CString m_sIdentifier; std::shared_ptr m_spAuth; - SCString m_ssAcceptedCaps; + SCString m_ssAcceptedCaps; // The capabilities supported by the ZNC core - capability names mapped // to a pair which contains a bool describing whether the capability is // server-dependent, and a capability value change handler. - std::map>> m_mCoreCaps; + std::map>> + m_mCoreCaps; // A subset of CIRCSock::GetAcceptedCaps(), the caps that can be listed // in CAP LS and may be notified to the client with CAP NEW (cap-notify). - SCString m_ssServerDependentCaps; + SCString m_ssServerDependentCaps; friend class ClientTest; }; -#endif // !ZNC_CLIENT_H +#endif // !ZNC_CLIENT_H diff --git a/include/znc/Config.h b/include/znc/Config.h index 70f3757d..a0be08e6 100644 --- a/include/znc/Config.h +++ b/include/znc/Config.h @@ -34,7 +34,7 @@ struct CConfigEntry { }; class CConfig { -public: + public: CConfig() : m_ConfigEntries(), m_SubConfigs() {} typedef std::map EntryMap; @@ -44,19 +44,13 @@ public: typedef EntryMap::const_iterator EntryMapIterator; typedef SubConfigMap::const_iterator SubConfigMapIterator; - EntryMapIterator BeginEntries() const { - return m_ConfigEntries.begin(); - } - EntryMapIterator EndEntries() const { - return m_ConfigEntries.end(); - } + EntryMapIterator BeginEntries() const { return m_ConfigEntries.begin(); } + EntryMapIterator EndEntries() const { return m_ConfigEntries.end(); } SubConfigMapIterator BeginSubConfigs() const { return m_SubConfigs.begin(); } - SubConfigMapIterator EndSubConfigs() const { - return m_SubConfigs.end(); - } + SubConfigMapIterator EndSubConfigs() const { return m_SubConfigs.end(); } void AddKeyValuePair(const CString& sName, const CString& sValue) { if (sName.empty() || sValue.empty()) { @@ -66,8 +60,9 @@ public: m_ConfigEntries[sName].push_back(sValue); } - bool AddSubConfig(const CString& sTag, const CString& sName, CConfig Config) { - SubConfig &conf = m_SubConfigs[sTag]; + bool AddSubConfig(const CString& sTag, const CString& sName, + CConfig Config) { + SubConfig& conf = m_SubConfigs[sTag]; SubConfig::const_iterator it = conf.find(sName); if (it != conf.end()) { @@ -78,11 +73,11 @@ public: return true; } - bool FindStringVector(const CString& sName, VCString& vsList, bool bErase = true) { + bool FindStringVector(const CString& sName, VCString& vsList, + bool bErase = true) { EntryMap::iterator it = m_ConfigEntries.find(sName); vsList.clear(); - if (it == m_ConfigEntries.end()) - return false; + if (it == m_ConfigEntries.end()) return false; vsList = it->second; if (bErase) { @@ -92,19 +87,19 @@ public: return true; } - bool FindStringEntry(const CString& sName, CString& sRes, const CString& sDefault = "") { + bool FindStringEntry(const CString& sName, CString& sRes, + const CString& sDefault = "") { EntryMap::iterator it = m_ConfigEntries.find(sName); sRes = sDefault; - if (it == m_ConfigEntries.end() || it->second.empty()) - return false; + if (it == m_ConfigEntries.end() || it->second.empty()) return false; sRes = it->second.front(); it->second.erase(it->second.begin()); - if (it->second.empty()) - m_ConfigEntries.erase(it); + if (it->second.empty()) m_ConfigEntries.erase(it); return true; } - bool FindBoolEntry(const CString& sName, bool& bRes, bool bDefault = false) { + bool FindBoolEntry(const CString& sName, bool& bRes, + bool bDefault = false) { CString s; if (FindStringEntry(sName, s)) { bRes = s.ToBool(); @@ -114,7 +109,8 @@ public: return false; } - bool FindUIntEntry(const CString& sName, unsigned int& uRes, unsigned int uDefault = 0) { + bool FindUIntEntry(const CString& sName, unsigned int& uRes, + unsigned int uDefault = 0) { CString s; if (FindStringEntry(sName, s)) { uRes = s.ToUInt(); @@ -124,7 +120,8 @@ public: return false; } - bool FindUShortEntry(const CString& sName, unsigned short& uRes, unsigned short uDefault = 0) { + bool FindUShortEntry(const CString& sName, unsigned short& uRes, + unsigned short uDefault = 0) { CString s; if (FindStringEntry(sName, s)) { uRes = s.ToUShort(); @@ -134,7 +131,8 @@ public: return false; } - bool FindDoubleEntry(const CString& sName, double& fRes, double fDefault = 0) { + bool FindDoubleEntry(const CString& sName, double& fRes, + double fDefault = 0) { CString s; if (FindStringEntry(sName, s)) { fRes = s.ToDouble(); @@ -144,7 +142,8 @@ public: return false; } - bool FindSubConfig(const CString& sName, SubConfig& Config, bool bErase = true) { + bool FindSubConfig(const CString& sName, SubConfig& Config, + bool bErase = true) { SubConfigMap::iterator it = m_SubConfigs.find(sName); if (it == m_SubConfigs.end()) { Config.clear(); @@ -166,9 +165,9 @@ public: bool Parse(CFile& file, CString& sErrorMsg); void Write(CFile& file, unsigned int iIndentation = 0); -private: + private: EntryMap m_ConfigEntries; SubConfigMap m_SubConfigs; }; -#endif // !ZNC_CONFIG_H +#endif // !ZNC_CONFIG_H diff --git a/include/znc/ExecSock.h b/include/znc/ExecSock.h index 476690aa..55a38a15 100644 --- a/include/znc/ExecSock.h +++ b/include/znc/ExecSock.h @@ -23,19 +23,18 @@ //! @author imaginos@imaginos.net class CExecSock : public CZNCSock { -public: + public: CExecSock() : CZNCSock(0), m_iPid(-1) {} - int Execute(const CString & sExec) { + int Execute(const CString& sExec) { int iReadFD, iWriteFD; m_iPid = popen2(iReadFD, iWriteFD, sExec); if (m_iPid != -1) { ConnectFD(iReadFD, iWriteFD, "0.0.0.0:0"); } - return(m_iPid); + return (m_iPid); } - void Kill(int iSignal) - { + void Kill(int iSignal) { kill(m_iPid, iSignal); Close(); } @@ -45,11 +44,11 @@ public: SetWSock(-1); } - int popen2(int & iReadFD, int & iWriteFD, const CString & sCommand); + int popen2(int& iReadFD, int& iWriteFD, const CString& sCommand); void close2(int iPid, int iReadFD, int iWriteFD); -private: - int m_iPid; + private: + int m_iPid; }; -#endif // !ZNC_EXECSOCK_H +#endif // !ZNC_EXECSOCK_H diff --git a/include/znc/FileUtils.h b/include/znc/FileUtils.h index b16e572e..bd0d763f 100644 --- a/include/znc/FileUtils.h +++ b/include/znc/FileUtils.h @@ -28,7 +28,7 @@ #include class CFile { -public: + public: CFile(); CFile(const CString& sLongName); ~CFile(); @@ -61,16 +61,10 @@ public: bool IsSock(bool bUseLstat = false) const; // for gettin file types, using fstat instead - static bool FType(const CString& sFileName, EFileTypes eType, bool bUseLstat = false); + static bool FType(const CString& sFileName, EFileTypes eType, + bool bUseLstat = false); - enum EFileAttr { - FA_Name, - FA_Size, - FA_ATime, - FA_MTime, - FA_CTime, - FA_UID - }; + enum EFileAttr { FA_Name, FA_Size, FA_ATime, FA_MTime, FA_CTime, FA_UID }; // // Functions to retrieve file information @@ -100,20 +94,23 @@ public: bool Copy(const CString& sNewFileName, bool bOverwrite = false); static bool Delete(const CString& sFileName); - static bool Move(const CString& sOldFileName, const CString& sNewFileName, bool bOverwrite = false); - static bool Copy(const CString& sOldFileName, const CString& sNewFileName, bool bOverwrite = false); + static bool Move(const CString& sOldFileName, const CString& sNewFileName, + bool bOverwrite = false); + static bool Copy(const CString& sOldFileName, const CString& sNewFileName, + bool bOverwrite = false); bool Chmod(mode_t mode); static bool Chmod(const CString& sFile, mode_t mode); bool Seek(off_t uPos); bool Truncate(); bool Sync(); - bool Open(const CString& sFileName, int iFlags = O_RDONLY, mode_t iMode = 0644); + bool Open(const CString& sFileName, int iFlags = O_RDONLY, + mode_t iMode = 0644); bool Open(int iFlags = O_RDONLY, mode_t iMode = 0644); - ssize_t Read(char *pszBuffer, int iBytes); - bool ReadLine(CString & sData, const CString & sDelimiter = "\n"); + ssize_t Read(char* pszBuffer, int iBytes); + bool ReadLine(CString& sData, const CString& sDelimiter = "\n"); bool ReadFile(CString& sData, size_t iMaxSize = 512 * 1024); - ssize_t Write(const char *pszBuffer, size_t iBytes); - ssize_t Write(const CString & sData); + ssize_t Write(const char* pszBuffer, size_t iBytes); + ssize_t Write(const CString& sData); void Close(); void ClearBuffer(); @@ -133,34 +130,30 @@ public: static void InitHomePath(const CString& sFallback); static const CString& GetHomePath() { return m_sHomePath; } -private: + private: // fcntl() locking wrapper bool Lock(short iType, bool bBlocking); CString m_sBuffer; - int m_iFD; - bool m_bHadError; + int m_iFD; + bool m_bHadError; static CString m_sHomePath; -protected: - CString m_sLongName; //!< Absolute filename (m_sPath + "/" + m_sShortName) - CString m_sShortName; //!< Filename alone, without path + protected: + CString m_sLongName; //!< Absolute filename (m_sPath + "/" + m_sShortName) + CString m_sShortName; //!< Filename alone, without path }; class CDir : public std::vector { -public: - + public: CDir(const CString& sDir) : m_eSortAttr(CFile::FA_Name), m_bDesc(false) { Fill(sDir); } - CDir() : m_eSortAttr(CFile::FA_Name), m_bDesc(false) { - } + CDir() : m_eSortAttr(CFile::FA_Name), m_bDesc(false) {} - ~CDir() { - CleanUp(); - } + ~CDir() { CleanUp(); } void CleanUp() { for (unsigned int a = 0; a < size(); a++) { @@ -170,9 +163,7 @@ public: clear(); } - size_t Fill(const CString& sDir) { - return FillByWildcard(sDir, "*"); - } + size_t Fill(const CString& sDir) { return FillByWildcard(sDir, "*"); } size_t FillByWildcard(const CString& sDir, const CString& sWildcard) { CleanUp(); @@ -182,17 +173,23 @@ public: return 0; } - struct dirent * de; + struct dirent* de; while ((de = readdir(dir)) != nullptr) { - if ((strcmp(de->d_name, ".") == 0) || (strcmp(de->d_name, "..") == 0)) { + if ((strcmp(de->d_name, ".") == 0) || + (strcmp(de->d_name, "..") == 0)) { continue; } - if ((!sWildcard.empty()) && (!CString(de->d_name).WildCmp(sWildcard))) { + if ((!sWildcard.empty()) && + (!CString(de->d_name).WildCmp(sWildcard))) { continue; } - CFile *file = new CFile(sDir.TrimSuffix_n("/") + "/" + de->d_name/*, this*/); // @todo need to pass pointer to 'this' if we want to do Sort() + CFile* file = + new CFile(sDir.TrimSuffix_n("/") + "/" + + de->d_name /*, this*/); // @todo need to pass pointer + // to 'this' if we want to do + // Sort() push_back(file); } @@ -200,7 +197,8 @@ public: return size(); } - static unsigned int Chmod(mode_t mode, const CString& sWildcard, const CString& sDir = ".") { + static unsigned int Chmod(mode_t mode, const CString& sWildcard, + const CString& sDir = ".") { CDir cDir; cDir.FillByWildcard(sDir, sWildcard); return cDir.Chmod(mode); @@ -217,7 +215,8 @@ public: return uRet; } - static unsigned int Delete(const CString& sWildcard, const CString& sDir = ".") { + static unsigned int Delete(const CString& sWildcard, + const CString& sDir = ".") { CDir cDir; cDir.FillByWildcard(sDir, sWildcard); return cDir.Delete(); @@ -239,13 +238,15 @@ public: // Check if sPath + "/" + sAdd (~/ is handled) is an absolute path which // resides under sPath. Returns absolute path on success, else "". - static CString CheckPathPrefix(const CString& sPath, const CString& sAdd, const CString& sHomeDir = ""); - static CString ChangeDir(const CString& sPath, const CString& sAdd, const CString& sHomeDir = ""); + static CString CheckPathPrefix(const CString& sPath, const CString& sAdd, + const CString& sHomeDir = ""); + static CString ChangeDir(const CString& sPath, const CString& sAdd, + const CString& sHomeDir = ""); static bool MakeDir(const CString& sPath, mode_t iMode = 0700); static CString GetCWD() { CString sRet; - char * pszCurDir = getcwd(nullptr, 0); + char* pszCurDir = getcwd(nullptr, 0); if (pszCurDir) { sRet = pszCurDir; free(pszCurDir); @@ -254,9 +255,9 @@ public: return sRet; } -private: -protected: + private: + protected: CFile::EFileAttr m_eSortAttr; - bool m_bDesc; + bool m_bDesc; }; -#endif // !ZNC_FILEUTILS_H +#endif // !ZNC_FILEUTILS_H diff --git a/include/znc/HTTPSock.h b/include/znc/HTTPSock.h index 76d06cee..ef66b9a8 100644 --- a/include/znc/HTTPSock.h +++ b/include/znc/HTTPSock.h @@ -24,9 +24,11 @@ class CModule; class CHTTPSock : public CSocket { -public: - CHTTPSock(CModule *pMod, const CString& sURIPrefix); - CHTTPSock(CModule *pMod, const CString& sURIPrefix, const CString& sHostname, unsigned short uPort, int iTimeout = 60); + public: + CHTTPSock(CModule* pMod, const CString& sURIPrefix); + CHTTPSock(CModule* pMod, const CString& sURIPrefix, + const CString& sHostname, unsigned short uPort, + int iTimeout = 60); virtual ~CHTTPSock(); // Csocket derived members @@ -38,21 +40,26 @@ public: // Hooks virtual bool ForceLogin(); - virtual bool OnLogin(const CString& sUser, const CString& sPass, bool bBasic); + virtual bool OnLogin(const CString& sUser, const CString& sPass, + bool bBasic); virtual void OnPageRequest(const CString& sURI) = 0; virtual bool PrintFile(const CString& sFileName, CString sContentType = ""); // !Hooks void CheckPost(); bool SentHeader() const; - bool PrintHeader(off_t uContentLength, const CString& sContentType = "", unsigned int uStatusId = 200, const CString& sStatusMsg = "OK"); + bool PrintHeader(off_t uContentLength, const CString& sContentType = "", + unsigned int uStatusId = 200, + const CString& sStatusMsg = "OK"); void AddHeader(const CString& sName, const CString& sValue); void SetContentType(const CString& sContentType); bool PrintNotFound(); bool Redirect(const CString& sURL); - bool PrintErrorPage(unsigned int uStatusId, const CString& sStatusMsg, const CString& sMessage); - static void ParseParams(const CString& sParams, std::map& msvsParams); + bool PrintErrorPage(unsigned int uStatusId, const CString& sStatusMsg, + const CString& sMessage); + static void ParseParams(const CString& sParams, + std::map& msvsParams); void ParseURI(); void GetPage(); static CString GetDate(time_t tm = 0); @@ -81,49 +88,61 @@ public: // !Getters // Parameter access - CString GetParam(const CString& sName, bool bPost = true, const CString& sFilter = "\r\n") const; + CString GetParam(const CString& sName, bool bPost = true, + const CString& sFilter = "\r\n") const; CString GetRawParam(const CString& sName, bool bPost = true) const; bool HasParam(const CString& sName, bool bPost = true) const; const std::map& GetParams(bool bPost = true) const; - size_t GetParamValues(const CString& sName, VCString& vsRet, bool bPost = true, const CString& sFilter = "\r\n") const; - size_t GetParamValues(const CString& sName, std::set& ssRet, bool bPost = true, const CString& sFilter = "\r\n") const; + size_t GetParamValues(const CString& sName, VCString& vsRet, + bool bPost = true, + const CString& sFilter = "\r\n") const; + size_t GetParamValues(const CString& sName, std::set& ssRet, + bool bPost = true, + const CString& sFilter = "\r\n") const; // !Parameter access -private: - static CString GetRawParam(const CString& sName, const std::map& msvsParams); - static CString GetParam(const CString& sName, const std::map& msvsParams, const CString& sFilter); - static size_t GetParamValues(const CString& sName, VCString& vsRet, const std::map& msvsParams, const CString& sFilter); - static size_t GetParamValues(const CString& sName, std::set& ssRet, const std::map& msvsParams, const CString& sFilter); + private: + static CString GetRawParam(const CString& sName, + const std::map& msvsParams); + static CString GetParam(const CString& sName, + const std::map& msvsParams, + const CString& sFilter); + static size_t GetParamValues(const CString& sName, VCString& vsRet, + const std::map& msvsParams, + const CString& sFilter); + static size_t GetParamValues(const CString& sName, std::set& ssRet, + const std::map& msvsParams, + const CString& sFilter); void WriteFileUncompressed(CFile& File); void WriteFileGzipped(CFile& File); -protected: + protected: void PrintPage(const CString& sPage); void Init(); - bool m_bSentHeader; - bool m_bGotHeader; - bool m_bLoggedIn; - bool m_bPost; - bool m_bDone; - bool m_bBasicAuth; - unsigned long m_uPostLen; - CString m_sPostData; - CString m_sURI; - CString m_sUser; - CString m_sPass; - CString m_sContentType; - CString m_sDocRoot; - CString m_sForwardedIP; - std::map m_msvsPOSTParams; - std::map m_msvsGETParams; - MCString m_msHeaders; - bool m_bHTTP10Client; - CString m_sIfNoneMatch; - bool m_bAcceptGzip; - MCString m_msRequestCookies; - MCString m_msResponseCookies; - CString m_sURIPrefix; + bool m_bSentHeader; + bool m_bGotHeader; + bool m_bLoggedIn; + bool m_bPost; + bool m_bDone; + bool m_bBasicAuth; + unsigned long m_uPostLen; + CString m_sPostData; + CString m_sURI; + CString m_sUser; + CString m_sPass; + CString m_sContentType; + CString m_sDocRoot; + CString m_sForwardedIP; + std::map m_msvsPOSTParams; + std::map m_msvsGETParams; + MCString m_msHeaders; + bool m_bHTTP10Client; + CString m_sIfNoneMatch; + bool m_bAcceptGzip; + MCString m_msRequestCookies; + MCString m_msResponseCookies; + CString m_sURIPrefix; }; -#endif // !ZNC_HTTPSOCK_H +#endif // !ZNC_HTTPSOCK_H diff --git a/include/znc/IRCNetwork.h b/include/znc/IRCNetwork.h index 71a5f280..f4c43c5a 100644 --- a/include/znc/IRCNetwork.h +++ b/include/znc/IRCNetwork.h @@ -38,11 +38,11 @@ class CIRCNetworkJoinTimer; class CMessage; class CIRCNetwork { -public: + public: static bool IsValidNetwork(const CString& sNetwork); - CIRCNetwork(CUser *pUser, const CString& sName); - CIRCNetwork(CUser *pUser, const CIRCNetwork& Network); + CIRCNetwork(CUser* pUser, const CString& sName); + CIRCNetwork(CUser* pUser, const CIRCNetwork& Network); ~CIRCNetwork(); CIRCNetwork(const CIRCNetwork&) = delete; @@ -66,15 +66,15 @@ public: void DelServers(); - bool ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade = false); + bool ParseConfig(CConfig* pConfig, CString& sError, bool bUpgrade = false); CConfig ToConfig() const; void BounceAllClients(); bool IsUserAttached() const { return !m_vClients.empty(); } bool IsUserOnline() const; - void ClientConnected(CClient *pClient); - void ClientDisconnected(CClient *pClient); + void ClientConnected(CClient* pClient); + void ClientDisconnected(CClient* pClient); CUser* GetUser() const; const CString& GetName() const; @@ -82,7 +82,7 @@ public: const std::vector& GetClients() const { return m_vClients; } std::vector FindClients(const CString& sIdentifier) const; - void SetUser(CUser *pUser); + void SetUser(CUser* pUser); bool SetName(const CString& sName); // Modules @@ -90,10 +90,14 @@ public: const CModules& GetModules() const { return *m_pModules; } // !Modules - bool PutUser(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutUser(const CMessage& Message, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutStatus(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutModule(const CString& sModule, const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); + bool PutUser(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutUser(const CMessage& Message, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutStatus(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutModule(const CString& sModule, const CString& sLine, + CClient* pClient = nullptr, CClient* pSkipClient = nullptr); const std::vector& GetChans() const; CChan* FindChan(CString sName) const; @@ -117,18 +121,27 @@ public: const std::vector& GetServers() const; bool HasServers() const { return !m_vServers.empty(); } CServer* FindServer(const CString& sName) const; - bool DelServer(const CString& sName, unsigned short uPort, const CString& sPass); + bool DelServer(const CString& sName, unsigned short uPort, + const CString& sPass); bool AddServer(const CString& sName); - bool AddServer(const CString& sName, unsigned short uPort, const CString& sPass = "", bool bSSL = false); + bool AddServer(const CString& sName, unsigned short uPort, + const CString& sPass = "", bool bSSL = false); CServer* GetNextServer(bool bAdvance = true); CServer* GetCurrentServer() const; void SetIRCServer(const CString& s); bool SetNextServer(const CServer* pServer); bool IsLastServer() const; - const SCString& GetTrustedFingerprints() const { return m_ssTrustedFingerprints; } - void AddTrustedFingerprint(const CString& sFP) { m_ssTrustedFingerprints.insert(sFP.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON)); } - void DelTrustedFingerprint(const CString& sFP) { m_ssTrustedFingerprints.erase(sFP); } + const SCString& GetTrustedFingerprints() const { + return m_ssTrustedFingerprints; + } + void AddTrustedFingerprint(const CString& sFP) { + m_ssTrustedFingerprints.insert( + sFP.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON)); + } + void DelTrustedFingerprint(const CString& sFP) { + m_ssTrustedFingerprints.erase(sFP); + } void ClearTrustedFingerprints() { m_ssTrustedFingerprints.clear(); } void SetIRCConnectEnabled(bool b); @@ -155,35 +168,71 @@ public: bool PutIRC(const CString& sLine); // Buffers - void AddRawBuffer(const CMessage& Format, const CString& sText = "") { m_RawBuffer.AddLine(Format, sText); } - void UpdateRawBuffer(const CString& sCommand, const CMessage& Format, const CString& sText = "") { m_RawBuffer.UpdateLine(sCommand, Format, sText); } - void UpdateExactRawBuffer(const CMessage& Format, const CString& sText = "") { m_RawBuffer.UpdateExactLine(Format, sText); } + void AddRawBuffer(const CMessage& Format, const CString& sText = "") { + m_RawBuffer.AddLine(Format, sText); + } + void UpdateRawBuffer(const CString& sCommand, const CMessage& Format, + const CString& sText = "") { + m_RawBuffer.UpdateLine(sCommand, Format, sText); + } + void UpdateExactRawBuffer(const CMessage& Format, + const CString& sText = "") { + m_RawBuffer.UpdateExactLine(Format, sText); + } void ClearRawBuffer() { m_RawBuffer.Clear(); } /// @deprecated - void AddRawBuffer(const CString& sFormat, const CString& sText = "") { m_RawBuffer.AddLine(sFormat, sText); } + void AddRawBuffer(const CString& sFormat, const CString& sText = "") { + m_RawBuffer.AddLine(sFormat, sText); + } /// @deprecated - void UpdateRawBuffer(const CString& sMatch, const CString& sFormat, const CString& sText = "") { m_RawBuffer.UpdateLine(sMatch, sFormat, sText); } + void UpdateRawBuffer(const CString& sMatch, const CString& sFormat, + const CString& sText = "") { + m_RawBuffer.UpdateLine(sMatch, sFormat, sText); + } /// @deprecated - void UpdateExactRawBuffer(const CString& sFormat, const CString& sText = "") { m_RawBuffer.UpdateExactLine(sFormat, sText); } + void UpdateExactRawBuffer(const CString& sFormat, + const CString& sText = "") { + m_RawBuffer.UpdateExactLine(sFormat, sText); + } - void AddMotdBuffer(const CMessage& Format, const CString& sText = "") { m_MotdBuffer.AddLine(Format, sText); } - void UpdateMotdBuffer(const CString& sCommand, const CMessage& Format, const CString& sText = "") { m_MotdBuffer.UpdateLine(sCommand, Format, sText); } + void AddMotdBuffer(const CMessage& Format, const CString& sText = "") { + m_MotdBuffer.AddLine(Format, sText); + } + void UpdateMotdBuffer(const CString& sCommand, const CMessage& Format, + const CString& sText = "") { + m_MotdBuffer.UpdateLine(sCommand, Format, sText); + } void ClearMotdBuffer() { m_MotdBuffer.Clear(); } /// @deprecated - void AddMotdBuffer(const CString& sFormat, const CString& sText = "") { m_MotdBuffer.AddLine(sFormat, sText); } + void AddMotdBuffer(const CString& sFormat, const CString& sText = "") { + m_MotdBuffer.AddLine(sFormat, sText); + } /// @deprecated - void UpdateMotdBuffer(const CString& sMatch, const CString& sFormat, const CString& sText = "") { m_MotdBuffer.UpdateLine(sMatch, sFormat, sText); } + void UpdateMotdBuffer(const CString& sMatch, const CString& sFormat, + const CString& sText = "") { + m_MotdBuffer.UpdateLine(sMatch, sFormat, sText); + } - void AddNoticeBuffer(const CMessage& Format, const CString& sText = "") { m_NoticeBuffer.AddLine(Format, sText); } - void UpdateNoticeBuffer(const CString& sCommand, const CMessage& Format, const CString& sText = "") { m_NoticeBuffer.UpdateLine(sCommand, Format, sText); } + void AddNoticeBuffer(const CMessage& Format, const CString& sText = "") { + m_NoticeBuffer.AddLine(Format, sText); + } + void UpdateNoticeBuffer(const CString& sCommand, const CMessage& Format, + const CString& sText = "") { + m_NoticeBuffer.UpdateLine(sCommand, Format, sText); + } void ClearNoticeBuffer() { m_NoticeBuffer.Clear(); } /// @deprecated - void AddNoticeBuffer(const CString& sFormat, const CString& sText = "") { m_NoticeBuffer.AddLine(sFormat, sText); } + void AddNoticeBuffer(const CString& sFormat, const CString& sText = "") { + m_NoticeBuffer.AddLine(sFormat, sText); + } /// @deprecated - void UpdateNoticeBuffer(const CString& sMatch, const CString& sFormat, const CString& sText = "") { m_NoticeBuffer.UpdateLine(sMatch, sFormat, sText); } + void UpdateNoticeBuffer(const CString& sMatch, const CString& sFormat, + const CString& sText = "") { + m_NoticeBuffer.UpdateLine(sMatch, sFormat, sText); + } void ClearQueryBuffer(); // !Buffers @@ -208,10 +257,14 @@ public: double GetFloodRate() const { return m_fFloodRate; } unsigned short int GetFloodBurst() const { return m_uFloodBurst; } void SetFloodRate(double fFloodRate) { m_fFloodRate = fFloodRate; } - void SetFloodBurst(unsigned short int uFloodBurst) { m_uFloodBurst = uFloodBurst; } + void SetFloodBurst(unsigned short int uFloodBurst) { + m_uFloodBurst = uFloodBurst; + } unsigned short int GetJoinDelay() const { return m_uJoinDelay; } - void SetJoinDelay(unsigned short int uJoinDelay) { m_uJoinDelay = uJoinDelay; } + void SetJoinDelay(unsigned short int uJoinDelay) { + m_uJoinDelay = uJoinDelay; + } unsigned long long BytesRead() const { return m_uBytesRead; } unsigned long long BytesWritten() const { return m_uBytesWritten; } @@ -221,48 +274,50 @@ public: CString ExpandString(const CString& sStr) const; CString& ExpandString(const CString& sStr, CString& sRet) const; -private: + + private: bool JoinChan(CChan* pChan); - bool LoadModule(const CString& sModName, const CString& sArgs, const CString& sNotice, CString& sError); + bool LoadModule(const CString& sModName, const CString& sArgs, + const CString& sNotice, CString& sError); -protected: - CString m_sName; - CUser* m_pUser; + protected: + CString m_sName; + CUser* m_pUser; - CString m_sNick; - CString m_sAltNick; - CString m_sIdent; - CString m_sRealName; - CString m_sBindHost; - CString m_sEncoding; - CString m_sQuitMsg; - SCString m_ssTrustedFingerprints; + CString m_sNick; + CString m_sAltNick; + CString m_sIdent; + CString m_sRealName; + CString m_sBindHost; + CString m_sEncoding; + CString m_sQuitMsg; + SCString m_ssTrustedFingerprints; - CModules* m_pModules; + CModules* m_pModules; - std::vector m_vClients; + std::vector m_vClients; - CIRCSock* m_pIRCSock; + CIRCSock* m_pIRCSock; - std::vector m_vChans; - std::vector m_vQueries; + std::vector m_vChans; + std::vector m_vQueries; - CString m_sChanPrefixes; + CString m_sChanPrefixes; - bool m_bIRCConnectEnabled; - CString m_sIRCServer; - std::vector m_vServers; - size_t m_uServerIdx; ///< Index in m_vServers of our current server + 1 + bool m_bIRCConnectEnabled; + CString m_sIRCServer; + std::vector m_vServers; + size_t m_uServerIdx; ///< Index in m_vServers of our current server + 1 - CNick m_IRCNick; - bool m_bIRCAway; + CNick m_IRCNick; + bool m_bIRCAway; - double m_fFloodRate; ///< Set to -1 to disable protection. + double m_fFloodRate; ///< Set to -1 to disable protection. unsigned short int m_uFloodBurst; - CBuffer m_RawBuffer; - CBuffer m_MotdBuffer; - CBuffer m_NoticeBuffer; + CBuffer m_RawBuffer; + CBuffer m_MotdBuffer; + CBuffer m_NoticeBuffer; CIRCNetworkPingTimer* m_pPingTimer; CIRCNetworkJoinTimer* m_pJoinTimer; @@ -272,4 +327,4 @@ protected: unsigned long long m_uBytesWritten; }; -#endif // !ZNC_IRCNETWORK_H +#endif // !ZNC_IRCNETWORK_H diff --git a/include/znc/IRCSock.h b/include/znc/IRCSock.h index ddce660b..42ed0f5c 100644 --- a/include/znc/IRCSock.h +++ b/include/znc/IRCSock.h @@ -33,7 +33,7 @@ class CClient; // TODO: This class needs new name class CIRCSock : public CIRCSocket { -public: + public: CIRCSock(CIRCNetwork* pNetwork); virtual ~CIRCSock(); @@ -41,11 +41,12 @@ public: CIRCSock& operator=(const CIRCSock&) = delete; typedef enum { - // These values must line up with their position in the CHANMODE argument to raw 005 - ListArg = 0, - HasArg = 1, + // These values must line up with their position in the CHANMODE + // argument to raw 005 + ListArg = 0, + HasArg = 1, ArgWhenSet = 2, - NoArg = 3 + NoArg = 3 } EChanModeArgs; void ReadLine(const CString& sData) override; @@ -57,7 +58,7 @@ public: void ReachedMaxBuffer() override; void PutIRC(const CString& sLine); - void PutIRCQuick(const CString& sLine); //!< Should be used for PONG only + void PutIRCQuick(const CString& sLine); //!< Should be used for PONG only void ResetChans(); void Quit(const CString& sQuitMsg = ""); @@ -79,9 +80,15 @@ public: unsigned int GetMaxNickLen() const { return m_uMaxNickLen; } EChanModeArgs GetModeType(unsigned char uMode) const; unsigned char GetPermFromMode(unsigned char uMode) const; - const std::map& GetChanModes() const { return m_mueChanModes; } - bool IsPermChar(const char c) const { return (c != '\0' && GetPerms().find(c) != CString::npos); } - bool IsPermMode(const char c) const { return (c != '\0' && GetPermModes().find(c) != CString::npos); } + const std::map& GetChanModes() const { + return m_mueChanModes; + } + bool IsPermChar(const char c) const { + return (c != '\0' && GetPerms().find(c) != CString::npos); + } + bool IsPermMode(const char c) const { + return (c != '\0' && GetPermModes().find(c) != CString::npos); + } const CString& GetPerms() const { return m_sPerms; } const CString& GetPermModes() const { return m_sPermModes; } CString GetNickMask() const { return m_Nick.GetNickMask(); } @@ -94,19 +101,24 @@ public: bool HasAccountNotify() const { return m_bAccountNotify; } bool HasExtendedJoin() const { return m_bExtendedJoin; } bool HasServerTime() const { return m_bServerTime; } - const std::set& GetUserModes() const { return m_scUserModes; } + const std::set& GetUserModes() const { + return m_scUserModes; + } // This is true if we are past raw 001 bool IsAuthed() const { return m_bAuthed; } const SCString& GetAcceptedCaps() const { return m_ssAcceptedCaps; } - bool IsCapAccepted(const CString& sCap) { return 1 == m_ssAcceptedCaps.count(sCap); } + bool IsCapAccepted(const CString& sCap) { + return 1 == m_ssAcceptedCaps.count(sCap); + } const MCString& GetISupport() const { return m_mISupport; } - CString GetISupport(const CString& sKey, const CString& sDefault = "") const; + CString GetISupport(const CString& sKey, + const CString& sDefault = "") const; // !Getters // TODO move this function to CIRCNetwork and make it non-static? static bool IsFloodProtected(double fRate); -private: + private: // Message Handlers bool OnAccountMessage(CMessage& Message); bool OnActionMessage(CActionMessage& Message); @@ -137,38 +149,39 @@ private: void SendAltNick(const CString& sBadNick); void SendNextCap(); void TrySend(); -protected: - bool m_bAuthed; - bool m_bNamesx; - bool m_bUHNames; - bool m_bAwayNotify; - bool m_bAccountNotify; - bool m_bExtendedJoin; - bool m_bServerTime; - CString m_sPerms; - CString m_sPermModes; - std::set m_scUserModes; - std::map m_mueChanModes; - CIRCNetwork* m_pNetwork; - CNick m_Nick; - CString m_sPass; - std::map m_msChans; - unsigned int m_uMaxNickLen; - unsigned int m_uCapPaused; - SCString m_ssAcceptedCaps; - SCString m_ssPendingCaps; - time_t m_lastCTCP; - unsigned int m_uNumCTCP; - static const time_t m_uCTCPFloodTime; - static const unsigned int m_uCTCPFloodCount; - MCString m_mISupport; - std::deque m_vsSendQueue; - short int m_iSendsAllowed; - unsigned short int m_uFloodBurst; - double m_fFloodRate; - bool m_bFloodProtection; + + protected: + bool m_bAuthed; + bool m_bNamesx; + bool m_bUHNames; + bool m_bAwayNotify; + bool m_bAccountNotify; + bool m_bExtendedJoin; + bool m_bServerTime; + CString m_sPerms; + CString m_sPermModes; + std::set m_scUserModes; + std::map m_mueChanModes; + CIRCNetwork* m_pNetwork; + CNick m_Nick; + CString m_sPass; + std::map m_msChans; + unsigned int m_uMaxNickLen; + unsigned int m_uCapPaused; + SCString m_ssAcceptedCaps; + SCString m_ssPendingCaps; + time_t m_lastCTCP; + unsigned int m_uNumCTCP; + static const time_t m_uCTCPFloodTime; + static const unsigned int m_uCTCPFloodCount; + MCString m_mISupport; + std::deque m_vsSendQueue; + short int m_iSendsAllowed; + unsigned short int m_uFloodBurst; + double m_fFloodRate; + bool m_bFloodProtection; friend class CIRCFloodTimer; }; -#endif // !ZNC_IRCSOCK_H +#endif // !ZNC_IRCSOCK_H diff --git a/include/znc/Listener.h b/include/znc/Listener.h index 4a825984..43492657 100644 --- a/include/znc/Listener.h +++ b/include/znc/Listener.h @@ -25,22 +25,19 @@ class CRealListener; // !Forward Declarations class CListener { -public: - typedef enum { - ACCEPT_IRC, - ACCEPT_HTTP, - ACCEPT_ALL - } EAcceptType; + public: + typedef enum { ACCEPT_IRC, ACCEPT_HTTP, ACCEPT_ALL } EAcceptType; - CListener(unsigned short uPort, const CString& sBindHost, const CString& sURIPrefix, bool bSSL, EAddrType eAddr, EAcceptType eAccept) - : m_bSSL(bSSL), - m_eAddr(eAddr), - m_uPort(uPort), - m_sBindHost(sBindHost), - m_sURIPrefix(sURIPrefix), - m_pListener(nullptr), - m_eAcceptType(eAccept) { - } + CListener(unsigned short uPort, const CString& sBindHost, + const CString& sURIPrefix, bool bSSL, EAddrType eAddr, + EAcceptType eAccept) + : m_bSSL(bSSL), + m_eAddr(eAddr), + m_uPort(uPort), + m_sBindHost(sBindHost), + m_sURIPrefix(sURIPrefix), + m_pListener(nullptr), + m_eAcceptType(eAccept) {} ~CListener(); @@ -64,19 +61,19 @@ public: bool Listen(); void ResetRealListener(); -private: -protected: - bool m_bSSL; - EAddrType m_eAddr; - unsigned short m_uPort; - CString m_sBindHost; - CString m_sURIPrefix; - CRealListener* m_pListener; - EAcceptType m_eAcceptType; + private: + protected: + bool m_bSSL; + EAddrType m_eAddr; + unsigned short m_uPort; + CString m_sBindHost; + CString m_sURIPrefix; + CRealListener* m_pListener; + EAcceptType m_eAcceptType; }; class CRealListener : public CZNCSock { -public: + public: CRealListener(CListener& listener) : CZNCSock(), m_Listener(listener) {} virtual ~CRealListener(); @@ -84,20 +81,22 @@ public: Csock* GetSockObj(const CString& sHost, unsigned short uPort) override; void SockError(int iErrno, const CString& sDescription) override; -private: + private: CListener& m_Listener; }; class CIncomingConnection : public CZNCSock { -public: - CIncomingConnection(const CString& sHostname, unsigned short uPort, CListener::EAcceptType eAcceptType, const CString& sURIPrefix); + public: + CIncomingConnection(const CString& sHostname, unsigned short uPort, + CListener::EAcceptType eAcceptType, + const CString& sURIPrefix); virtual ~CIncomingConnection() {} void ReadLine(const CString& sData) override; void ReachedMaxBuffer() override; -private: + private: CListener::EAcceptType m_eAcceptType; const CString m_sURIPrefix; }; -#endif // !ZNC_LISTENER_H +#endif // !ZNC_LISTENER_H diff --git a/include/znc/MD5.h b/include/znc/MD5.h index 11655b40..624d1a83 100644 --- a/include/znc/MD5.h +++ b/include/znc/MD5.h @@ -8,50 +8,42 @@ using std::string; #ifndef uint8 -#define uint8 unsigned char +#define uint8 unsigned char #endif #ifndef uint32 #define uint32 unsigned long int #endif -typedef struct -{ - uint32 total[2]; - uint32 state[4]; - uint8 buffer[64]; -} -md5_context; +typedef struct { + uint32 total[2]; + uint32 state[4]; + uint8 buffer[64]; +} md5_context; class CMD5 { -protected: + protected: char m_szMD5[33]; -public: + public: CMD5(); CMD5(const string& sText); CMD5(const char* szText, uint32 nTextLen); ~CMD5(); - operator string() const - { - return (string) m_szMD5; - } + operator string() const { return (string)m_szMD5; } - operator char*() const - { - return (char*)m_szMD5; - } + operator char*() const { return (char*)m_szMD5; } char* MakeHash(const char* szText, uint32 nTextLen); -protected: - void md5_starts( md5_context *ctx ) const; - void md5_update( md5_context *ctx, const uint8 *input, uint32 length ) const; - void md5_finish( md5_context *ctx, uint8 digest[16] ) const; + protected: + void md5_starts(md5_context* ctx) const; + void md5_update(md5_context* ctx, const uint8* input, uint32 length) const; + void md5_finish(md5_context* ctx, uint8 digest[16]) const; -private: - void md5_process( md5_context *ctx, const uint8 data[64] ) const; + private: + void md5_process(md5_context* ctx, const uint8 data[64]) const; }; #endif /* ZNC_MD5_H */ diff --git a/include/znc/Message.h b/include/znc/Message.h index b2958c4f..386155ab 100644 --- a/include/znc/Message.h +++ b/include/znc/Message.h @@ -19,13 +19,15 @@ // Remove this after Feb 2016 when Debian 7 is EOL #if __cpp_ref_qualifiers >= 200710 -# define ZNC_LVREFQUAL & +#define ZNC_LVREFQUAL & #elif defined(__clang__) -# define ZNC_LVREFQUAL & -#elif __GNUC__ > 4 || __GNUC__ == 4 && (__GNUC_MINOR__ > 8 || __GNUC_MINOR__ == 8 && __GNUC_PATCHLEVEL__ >= 1) -# define ZNC_LVREFQUAL & +#define ZNC_LVREFQUAL & +#elif __GNUC__ > 4 || \ + __GNUC__ == 4 && (__GNUC_MINOR__ > 8 || \ + __GNUC_MINOR__ == 8 && __GNUC_PATCHLEVEL__ >= 1) +#define ZNC_LVREFQUAL & #else -# define ZNC_LVREFQUAL +#define ZNC_LVREFQUAL #endif #include @@ -38,9 +40,11 @@ class CClient; class CIRCNetwork; class CMessage { -public: + public: explicit CMessage(const CString& sMessage = ""); - CMessage(const CNick& Nick, const CString& sCommand, const VCString& vsParams = VCString(), const MCString& mssTags = MCString::EmptyMap); + CMessage(const CNick& Nick, const CString& sCommand, + const VCString& vsParams = VCString(), + const MCString& mssTags = MCString::EmptyMap); enum class Type { Unknown, @@ -113,101 +117,118 @@ public: CString ToString(unsigned int uFlags = IncludeAll) const; void Parse(CString sMessage); - // Implicit and explicit conversion to a subclass reference. +// Implicit and explicit conversion to a subclass reference. #ifndef SWIG template M& As() ZNC_LVREFQUAL { - static_assert(std::is_base_of{}, "Must be subclass of CMessage"); - static_assert(sizeof(M) == sizeof(CMessage), "No data members allowed in CMessage subclasses."); + static_assert(std::is_base_of{}, + "Must be subclass of CMessage"); + static_assert(sizeof(M) == sizeof(CMessage), + "No data members allowed in CMessage subclasses."); return static_cast(*this); } template const M& As() const ZNC_LVREFQUAL { - static_assert(std::is_base_of{}, "Must be subclass of CMessage"); - static_assert(sizeof(M) == sizeof(CMessage), "No data members allowed in CMessage subclasses."); + static_assert(std::is_base_of{}, + "Must be subclass of CMessage"); + static_assert(sizeof(M) == sizeof(CMessage), + "No data members allowed in CMessage subclasses."); return static_cast(*this); } - template {}>::type> + template {}>::type> operator M&() ZNC_LVREFQUAL { return As(); } - template {}>::type> + template {}>::type> operator const M&() const ZNC_LVREFQUAL { return As(); } - // REGISTER_ZNC_MESSAGE allows SWIG to instantiate correct .As<> calls. +// REGISTER_ZNC_MESSAGE allows SWIG to instantiate correct .As<> calls. #define REGISTER_ZNC_MESSAGE(M) #else - // SWIG (as of 3.0.7) doesn't parse ref-qualifiers, and doesn't differentiate constness. - template M& As(); + // SWIG (as of 3.0.7) doesn't parse ref-qualifiers, and doesn't + // differentiate constness. + template + M& As(); #endif -private: + private: void InitTime(); void InitType(); - CNick m_Nick; - CString m_sCommand; - VCString m_vsParams; - MCString m_mssTags; - timeval m_time; + CNick m_Nick; + CString m_sCommand; + VCString m_vsParams; + MCString m_mssTags; + timeval m_time; CIRCNetwork* m_pNetwork = nullptr; - CClient* m_pClient = nullptr; - CChan* m_pChan = nullptr; - Type m_eType = Type::Unknown; - bool m_bColon = false; + CClient* m_pClient = nullptr; + CChan* m_pChan = nullptr; + Type m_eType = Type::Unknown; + bool m_bColon = false; }; // For gtest #ifdef GTEST_FAIL -template {}>::type> +template {}>::type> inline ::std::ostream& operator<<(::std::ostream& os, const M& msg) { return os << msg.ToString().Escape_n(CString::EDEBUG); } #endif -// The various CMessage subclasses are "mutable views" to the data held by CMessage. -// They provide convenient access to message type speficic attributes, but are not +// The various CMessage subclasses are "mutable views" to the data held by +// CMessage. +// They provide convenient access to message type speficic attributes, but are +// not // allowed to hold extra data of their own. class CTargetMessage : public CMessage { -public: + public: CString GetTarget() const { return GetParam(0); } void SetTarget(const CString& sTarget) { SetParam(0, sTarget); } }; REGISTER_ZNC_MESSAGE(CTargetMessage); class CActionMessage : public CTargetMessage { -public: - CString GetText() const { return GetParam(1).TrimPrefix_n("\001ACTION ").TrimSuffix_n("\001"); } - void SetText(const CString& sText) { SetParam(1, "\001ACTION " + sText + "\001"); } + public: + CString GetText() const { + return GetParam(1).TrimPrefix_n("\001ACTION ").TrimSuffix_n("\001"); + } + void SetText(const CString& sText) { + SetParam(1, "\001ACTION " + sText + "\001"); + } }; REGISTER_ZNC_MESSAGE(CActionMessage); class CCTCPMessage : public CTargetMessage { -public: + public: bool IsReply() const { return GetCommand().Equals("NOTICE"); } - CString GetText() const { return GetParam(1).TrimPrefix_n("\001").TrimSuffix_n("\001"); } + CString GetText() const { + return GetParam(1).TrimPrefix_n("\001").TrimSuffix_n("\001"); + } void SetText(const CString& sText) { SetParam(1, "\001" + sText + "\001"); } }; REGISTER_ZNC_MESSAGE(CCTCPMessage); class CJoinMessage : public CTargetMessage { -public: + public: CString GetKey() const { return GetParam(1); } void SetKey(const CString& sKey) { SetParam(1, sKey); } }; REGISTER_ZNC_MESSAGE(CJoinMessage); class CModeMessage : public CTargetMessage { -public: + public: CString GetModes() const { return GetParams(1).TrimPrefix_n(":"); } }; REGISTER_ZNC_MESSAGE(CModeMessage); class CNickMessage : public CMessage { -public: + public: CString GetOldNick() const { return GetNick().GetNick(); } CString GetNewNick() const { return GetParam(0); } void SetNewNick(const CString& sNick) { SetParam(0, sNick); } @@ -215,20 +236,20 @@ public: REGISTER_ZNC_MESSAGE(CNickMessage); class CNoticeMessage : public CTargetMessage { -public: + public: CString GetText() const { return GetParam(1); } void SetText(const CString& sText) { SetParam(1, sText); } }; REGISTER_ZNC_MESSAGE(CNoticeMessage); class CNumericMessage : public CMessage { -public: + public: unsigned int GetCode() const { return GetCommand().ToUInt(); } }; REGISTER_ZNC_MESSAGE(CNumericMessage); class CKickMessage : public CTargetMessage { -public: + public: CString GetKickedNick() const { return GetParam(1); } void SetKickedNick(const CString& sNick) { SetParam(1, sNick); } CString GetReason() const { return GetParam(2); } @@ -237,31 +258,31 @@ public: REGISTER_ZNC_MESSAGE(CKickMessage); class CPartMessage : public CTargetMessage { -public: + public: CString GetReason() const { return GetParam(1); } void SetReason(const CString& sReason) { SetParam(1, sReason); } }; REGISTER_ZNC_MESSAGE(CPartMessage); class CQuitMessage : public CMessage { -public: + public: CString GetReason() const { return GetParam(0); } void SetReason(const CString& sReason) { SetParam(0, sReason); } }; REGISTER_ZNC_MESSAGE(CQuitMessage); class CTextMessage : public CTargetMessage { -public: + public: CString GetText() const { return GetParam(1); } void SetText(const CString& sText) { SetParam(1, sText); } }; REGISTER_ZNC_MESSAGE(CTextMessage); class CTopicMessage : public CTargetMessage { -public: + public: CString GetTopic() const { return GetParam(1); } void SetTopic(const CString& sTopic) { SetParam(1, sTopic); } }; REGISTER_ZNC_MESSAGE(CTopicMessage); -#endif // !ZNC_MESSAGE_H +#endif // !ZNC_MESSAGE_H diff --git a/include/znc/Modules.h b/include/znc/Modules.h index e0d2a9bd..fac567da 100644 --- a/include/znc/Modules.h +++ b/include/znc/Modules.h @@ -51,24 +51,23 @@ class CModInfo; #endif #if HAVE_VISIBILITY -# define MODULE_EXPORT __attribute__((__visibility__("default"))) +#define MODULE_EXPORT __attribute__((__visibility__("default"))) #else -# define MODULE_EXPORT +#define MODULE_EXPORT #endif -#define MODCOMMONDEFS(CLASS, DESCRIPTION, TYPE) \ - extern "C" { \ - MODULE_EXPORT bool ZNCModInfo(double dCoreVersion, CModInfo& Info); \ - bool ZNCModInfo(double dCoreVersion, CModInfo& Info) { \ - if (dCoreVersion != VERSION) \ - return false; \ - Info.SetDescription(DESCRIPTION); \ - Info.SetDefaultType(TYPE); \ - Info.AddType(TYPE); \ - Info.SetLoader(TModLoad); \ - TModInfo(Info); \ - return true; \ - } \ +#define MODCOMMONDEFS(CLASS, DESCRIPTION, TYPE) \ + extern "C" { \ + MODULE_EXPORT bool ZNCModInfo(double dCoreVersion, CModInfo& Info); \ + bool ZNCModInfo(double dCoreVersion, CModInfo& Info) { \ + if (dCoreVersion != VERSION) return false; \ + Info.SetDescription(DESCRIPTION); \ + Info.SetDefaultType(TYPE); \ + Info.AddType(TYPE); \ + Info.SetLoader(TModLoad); \ + TModInfo(Info); \ + return true; \ + } \ } /** Instead of writing a constructor, you should call this macro. It accepts all @@ -86,10 +85,11 @@ class CModInfo; * * @param CLASS The name of your module's class. */ -#define MODCONSTRUCTOR(CLASS) \ - CLASS(ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, \ - const CString& sModPath, CModInfo::EModuleType eType) \ - : CModule(pDLL, pUser, pNetwork, sModName, sModPath, eType) +#define MODCONSTRUCTOR(CLASS) \ + CLASS(ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, \ + const CString& sModName, const CString& sModPath, \ + CModInfo::EModuleType eType) \ + : CModule(pDLL, pUser, pNetwork, sModName, sModPath, eType) // User Module Macros /** This works exactly like MODULEDEFS, but for user modules. */ @@ -128,8 +128,9 @@ class CSockManager; // !Forward Declarations class CTimer : public CCron { -public: - CTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription); + public: + CTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription); virtual ~CTimer(); @@ -145,43 +146,43 @@ public: CModule* GetModule() const; const CString& GetDescription() const; // !Getters -private: -protected: - CModule* m_pModule; - CString m_sDescription; + private: + protected: + CModule* m_pModule; + CString m_sDescription; }; -typedef void (*FPTimer_t)(CModule *, CFPTimer *); +typedef void (*FPTimer_t)(CModule*, CFPTimer*); class CFPTimer : public CTimer { -public: - CFPTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), m_pFBCallback(nullptr) { - } + public: + CFPTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), + m_pFBCallback(nullptr) {} virtual ~CFPTimer() {} void SetFPCallback(FPTimer_t p) { m_pFBCallback = p; } -protected: + protected: void RunJob() override { if (m_pFBCallback) { m_pFBCallback(m_pModule, this); } } -private: - FPTimer_t m_pFBCallback; + private: + FPTimer_t m_pFBCallback; }; #ifdef HAVE_PTHREAD /// A CJob version which can be safely used in modules. The job will be /// cancelled when the module is unloaded. class CModuleJob : public CJob { -public: - CModuleJob(CModule *pModule, const CString& sName, const CString& sDesc) - : CJob(), m_pModule(pModule), m_sName(sName), m_sDescription(sDesc) { - } + public: + CModuleJob(CModule* pModule, const CString& sName, const CString& sDesc) + : CJob(), m_pModule(pModule), m_sName(sName), m_sDescription(sDesc) {} virtual ~CModuleJob(); CModuleJob(const CModuleJob&) = delete; @@ -193,41 +194,38 @@ public: const CString& GetDescription() const { return m_sDescription; } // !Getters -protected: + protected: CModule* m_pModule; - const CString m_sName; - const CString m_sDescription; + const CString m_sName; + const CString m_sDescription; }; #endif typedef void* ModHandle; class CModInfo { -public: - typedef enum { - GlobalModule, - UserModule, - NetworkModule - } EModuleType; + public: + typedef enum { GlobalModule, UserModule, NetworkModule } EModuleType; - typedef CModule* (*ModLoader)(ModHandle p, CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, const CString& sModPath, EModuleType eType); + typedef CModule* (*ModLoader)(ModHandle p, CUser* pUser, + CIRCNetwork* pNetwork, + const CString& sModName, + const CString& sModPath, EModuleType eType); - CModInfo() : CModInfo("", "", NetworkModule) { - } + CModInfo() : CModInfo("", "", NetworkModule) {} CModInfo(const CString& sName, const CString& sPath, EModuleType eType) - : m_seType(), - m_eDefaultType(eType), - m_sName(sName), - m_sPath(sPath), - m_sDescription(""), - m_sWikiPage(""), - m_sArgsHelpText(""), - m_bHasArgs(false), - m_fLoader(nullptr) { - } + : m_seType(), + m_eDefaultType(eType), + m_sName(sName), + m_sPath(sPath), + m_sDescription(""), + m_sWikiPage(""), + m_sArgsHelpText(""), + m_bHasArgs(false), + m_fLoader(nullptr) {} ~CModInfo() {} - bool operator < (const CModInfo& Info) const { + bool operator<(const CModInfo& Info) const { return (GetName() < Info.GetName()); } @@ -235,16 +233,18 @@ public: return m_seType.find(eType) != m_seType.end(); } - void AddType(EModuleType eType) { - m_seType.insert(eType); - } + void AddType(EModuleType eType) { m_seType.insert(eType); } static CString ModuleTypeToString(EModuleType eType) { switch (eType) { - case GlobalModule: return "Global"; - case UserModule: return "User"; - case NetworkModule: return "Network"; - default: return "UNKNOWN"; + case GlobalModule: + return "Global"; + case UserModule: + return "User"; + case NetworkModule: + return "Network"; + default: + return "UNKNOWN"; } } @@ -269,30 +269,32 @@ public: void SetLoader(ModLoader fLoader) { m_fLoader = fLoader; } void SetDefaultType(EModuleType eType) { m_eDefaultType = eType; } // !Setters -private: -protected: + private: + protected: std::set m_seType; - EModuleType m_eDefaultType; - CString m_sName; - CString m_sPath; - CString m_sDescription; - CString m_sWikiPage; - CString m_sArgsHelpText; - bool m_bHasArgs; - ModLoader m_fLoader; + EModuleType m_eDefaultType; + CString m_sName; + CString m_sPath; + CString m_sDescription; + CString m_sWikiPage; + CString m_sArgsHelpText; + bool m_bHasArgs; + ModLoader m_fLoader; }; -template void TModInfo(CModInfo& Info) {} +template +void TModInfo(CModInfo& Info) {} -template CModule* TModLoad(ModHandle p, CUser* pUser, - CIRCNetwork* pNetwork, const CString& sModName, - const CString& sModPath, CModInfo::EModuleType eType) { +template +CModule* TModLoad(ModHandle p, CUser* pUser, CIRCNetwork* pNetwork, + const CString& sModName, const CString& sModPath, + CModInfo::EModuleType eType) { return new M(p, pUser, pNetwork, sModName, sModPath, eType); } /** A helper class for handling commands in modules. */ class CModCommand { -public: + public: /// Type for the callback function that handles the actual command. typedef void (CModule::*ModCmdFunc)(const CString& sLine); typedef std::function CmdFunc; @@ -306,8 +308,10 @@ public: * @param sArgs Help text describing the arguments to this command. * @param sDesc Help text describing what this command does. */ - CModCommand(const CString& sCmd, CModule* pMod, ModCmdFunc func, const CString& sArgs, const CString& sDesc); - CModCommand(const CString& sCmd, CmdFunc func, const CString& sArgs, const CString& sDesc); + CModCommand(const CString& sCmd, CModule* pMod, ModCmdFunc func, + const CString& sArgs, const CString& sDesc); + CModCommand(const CString& sCmd, CmdFunc func, const CString& sArgs, + const CString& sDesc); /** Copy constructor, needed so that this can be saved in a std::map. * @param other Object to copy from. @@ -337,7 +341,7 @@ public: void Call(const CString& sLine) const { m_pFunc(sLine); } -private: + private: CString m_sCmd; CmdFunc m_pFunc; CString m_sArgs; @@ -358,9 +362,12 @@ private: * @see MODCONSTRUCTOR and MODULEDEFS */ class CModule { -public: - CModule(ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, - const CString& sDataDir, CModInfo::EModuleType eType = CModInfo::NetworkModule); // TODO: remove default value in ZNC 2.x + public: + CModule( + ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, + const CString& sModName, const CString& sDataDir, + CModInfo::EModuleType eType = + CModInfo::NetworkModule); // TODO: remove default value in ZNC 2.x virtual ~CModule(); CModule(const CModule&) = delete; @@ -378,7 +385,7 @@ public: /** This is the same as both CModule::HALTMODS and * CModule::HALTCORE together. */ - HALT = 2, + HALT = 2, /** Stop sending this even to other modules which were not * called yet. Internally, the event is handled normally. */ @@ -418,7 +425,6 @@ public: */ virtual bool OnBoot(); - /** Modules which can only be used with an active user session have to return true here. * @return false for modules that can do stuff for non-logged in web users as well. */ @@ -451,11 +457,14 @@ public: * @return You MUST return true if you want the template to be evaluated and sent to the browser. * Return false if you called Redirect() or PrintErrorPage(). If you didn't, a 404 page will be sent. */ - virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl); + virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl); /** Registers a sub page for the sidebar. * @param spSubPage The SubPage instance. */ - virtual void AddSubPage(TWebSubPage spSubPage) { m_vSubPages.push_back(spSubPage); } + virtual void AddSubPage(TWebSubPage spSubPage) { + m_vSubPages.push_back(spSubPage); + } /** Removes all registered (AddSubPage'd) SubPages. */ virtual void ClearSubPages() { m_vSubPages.clear(); } @@ -472,8 +481,9 @@ public: * @return If you don't need to embed web stuff to the specified place, just return false. * Exact meaning of return value is up to caller, and depends on context. */ - virtual bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl); - + virtual bool OnEmbeddedWebRequest(CWebSock& WebSock, + const CString& sPageName, + CTemplate& Tmpl); /** Called just before znc.conf is rehashed */ virtual void OnPreRehash(); @@ -488,12 +498,12 @@ public: * @param pIRCSock The socket that will be used for the connection. * @return See CModule::EModRet. */ - virtual EModRet OnIRCConnecting(CIRCSock *pIRCSock); + virtual EModRet OnIRCConnecting(CIRCSock* pIRCSock); /** This module hook is called when a CIRCSock fails to connect or * a module returned HALTCORE from OnIRCConnecting. * @param pIRCSock The socket that failed to connect. */ - virtual void OnIRCConnectionError(CIRCSock *pIRCSock); + virtual void OnIRCConnectionError(CIRCSock* pIRCSock); /** This module hook is called before loging in to the IRC server. The * low-level connection is established at this point, but SSL * handshakes didn't necessarily finish yet. @@ -504,7 +514,8 @@ public: * @param sRealName The real name that will be used. * @return See CModule::EModRet. */ - virtual EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName); + virtual EModRet OnIRCRegistration(CString& sPass, CString& sNick, + CString& sIdent, CString& sRealName); /** This module hook is called when a message is broadcasted to all users. * @param sMessage The message that is broadcasted. * @return see CModule::EModRet @@ -522,20 +533,32 @@ public: * @see CIRCSock::GetModeType() for converting uMode into a mode (e.g. * 'o' for op). */ - virtual void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange); - virtual void OnChanPermission(const CNick& OpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange); + virtual void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, + bool bAdded, bool bNoChange); + virtual void OnChanPermission(const CNick& OpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, + bool bAdded, bool bNoChange); /** Called when a nick is opped on a channel */ - virtual void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - virtual void OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); + virtual void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + virtual void OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); /** Called when a nick is deopped on a channel */ - virtual void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - virtual void OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); + virtual void OnDeop2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, bool bNoChange); + virtual void OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); /** Called when a nick is voiced on a channel */ - virtual void OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - virtual void OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); + virtual void OnVoice2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, bool bNoChange); + virtual void OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); /** Called when a nick is devoiced on a channel */ - virtual void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - virtual void OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); + virtual void OnDevoice2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, bool bNoChange); + virtual void OnDevoice(const CNick& OpNick, const CNick& Nick, + CChan& Channel, bool bNoChange); /** Called on an individual channel mode change. * @param pOpNick The nick who changes the channel mode, or nullptr if set by server. * @param Channel The channel whose mode is changed. @@ -544,8 +567,10 @@ public: * @param bAdded True if this mode is added ("+"), else false. * @param bNoChange True if this mode was already effective before. */ - virtual void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange); - virtual void OnMode(const CNick& OpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange); + virtual void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange); + virtual void OnMode(const CNick& OpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange); /** Called on any channel mode change. This is called before the more * detailed mode hooks like e.g. OnOp() and OnMode(). * @param pOpNick The nick who changes the channel mode, or nullptr if set by server. @@ -553,8 +578,10 @@ public: * @param sModes The raw mode change, e.g. "+s-io". * @param sArgs All arguments to the mode change from sModes. */ - virtual void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs); - virtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs); + virtual void OnRawMode2(const CNick* pOpNick, CChan& Channel, + const CString& sModes, const CString& sArgs); + virtual void OnRawMode(const CNick& OpNick, CChan& Channel, + const CString& sModes, const CString& sArgs); /** Called on any raw IRC line received from the IRC server. * @param sLine The line read from the server. @@ -607,18 +634,22 @@ public: * @param Message The quit message. * @param vChans List of channels which you and nick share. */ - virtual void OnQuitMessage(CQuitMessage& Message, const std::vector& vChans); + virtual void OnQuitMessage(CQuitMessage& Message, + const std::vector& vChans); /// @deprecated Use OnQuitMessage() instead. - virtual void OnQuit(const CNick& Nick, const CString& sMessage, const std::vector& vChans); + virtual void OnQuit(const CNick& Nick, const CString& sMessage, + const std::vector& vChans); /** Called when a nickname change occurs. * @since 1.7.0 * @param Message The nick message. * @param vChans Channels which we and nick share. */ - virtual void OnNickMessage(CNickMessage& Message, const std::vector& vChans); + virtual void OnNickMessage(CNickMessage& Message, + const std::vector& vChans); /// @deprecated Use OnNickMessage() instead. - virtual void OnNick(const CNick& Nick, const CString& sNewNick, const std::vector& vChans); + virtual void OnNick(const CNick& Nick, const CString& sNewNick, + const std::vector& vChans); /** Called when a nick is kicked from a channel. * @since 1.7.0 @@ -626,7 +657,8 @@ public: */ virtual void OnKickMessage(CKickMessage& Message); /// @deprecated Use OnKickMessage() instead. - virtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage); + virtual void OnKick(const CNick& OpNick, const CString& sKickedNick, + CChan& Channel, const CString& sMessage); /** This module hook is called just before ZNC tries to join an IRC channel. * @param Chan The channel which is about to get joined. @@ -648,7 +680,8 @@ public: */ virtual void OnPartMessage(CPartMessage& Message); /// @deprecated Use OnPartMessage() instead. - virtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage); + virtual void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage); /** Called when user is invited into a channel * @param Nick The nick who invited you. @@ -678,9 +711,11 @@ public: */ virtual EModRet OnChanBufferPlayMessage(CMessage& Message); /// @deprecated Use OnChanBufferPlayMessage() instead. - virtual EModRet OnChanBufferPlayLine2(CChan& Chan, CClient& Client, CString& sLine, const timeval& tv); + virtual EModRet OnChanBufferPlayLine2(CChan& Chan, CClient& Client, + CString& sLine, const timeval& tv); /// @deprecated Use OnChanBufferPlayMessage() instead. - virtual EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine); + virtual EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, + CString& sLine); /** Called for each message during a query's buffer play back. * @since 1.7.0 @@ -689,7 +724,8 @@ public: */ virtual EModRet OnPrivBufferPlayMessage(CMessage& Message); /// @deprecated Use OnPrivBufferPlayMessage() instead. - virtual EModRet OnPrivBufferPlayLine2(CClient& Client, CString& sLine, const timeval& tv); + virtual EModRet OnPrivBufferPlayLine2(CClient& Client, CString& sLine, + const timeval& tv); /// @deprecated Use OnPrivBufferPlayMessage() instead. virtual EModRet OnPrivBufferPlayLine(CClient& Client, CString& sLine); @@ -844,7 +880,8 @@ public: */ virtual EModRet OnChanActionMessage(CActionMessage& Message); /// @deprecated Use OnChanActionMessage() instead. - virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage); + virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage); /** Called when we receive a private message from IRC. * @since 1.7.0 @@ -880,7 +917,8 @@ public: */ virtual EModRet OnChanNoticeMessage(CNoticeMessage& Message); /// @deprecated Use OnChanNoticeMessage() instead. - virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage); + virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage); /** Called when we receive a channel topic change from IRC. * @since 1.7.0 @@ -999,13 +1037,18 @@ public: // Timer stuff bool AddTimer(CTimer* pTimer); - bool AddTimer(FPTimer_t pFBCallback, const CString& sLabel, u_int uInterval, u_int uCycles = 0, const CString& sDescription = ""); + bool AddTimer(FPTimer_t pFBCallback, const CString& sLabel, u_int uInterval, + u_int uCycles = 0, const CString& sDescription = ""); bool RemTimer(CTimer* pTimer); bool RemTimer(const CString& sLabel); bool UnlinkTimer(CTimer* pTimer); CTimer* FindTimer(const CString& sLabel); - std::set::const_iterator BeginTimers() const { return m_sTimers.begin(); } - std::set::const_iterator EndTimers() const { return m_sTimers.end(); } + std::set::const_iterator BeginTimers() const { + return m_sTimers.begin(); + } + std::set::const_iterator EndTimers() const { + return m_sTimers.end(); + } virtual void ListTimers(); // !Timer stuff @@ -1015,19 +1058,23 @@ public: bool RemSocket(const CString& sSockName); bool UnlinkSocket(CSocket* pSocket); CSocket* FindSocket(const CString& sSockName); - std::set::const_iterator BeginSockets() const { return m_sSockets.begin(); } - std::set::const_iterator EndSockets() const { return m_sSockets.end(); } + std::set::const_iterator BeginSockets() const { + return m_sSockets.begin(); + } + std::set::const_iterator EndSockets() const { + return m_sSockets.end(); + } virtual void ListSockets(); - // !Socket stuff +// !Socket stuff #ifdef HAVE_PTHREAD // Job stuff - void AddJob(CModuleJob *pJob); - void CancelJob(CModuleJob *pJob); + void AddJob(CModuleJob* pJob); + void CancelJob(CModuleJob* pJob); bool CancelJob(const CString& sJobName); void CancelJobs(const std::set& sJobs); - bool UnlinkJob(CModuleJob *pJob); - // !Job stuff + bool UnlinkJob(CModuleJob* pJob); +// !Job stuff #endif // Command stuff @@ -1036,9 +1083,12 @@ public: /// @return True if the command was successfully added. bool AddCommand(const CModCommand& Command); /// @return True if the command was successfully added. - bool AddCommand(const CString& sCmd, CModCommand::ModCmdFunc func, const CString& sArgs = "", const CString& sDesc = ""); + bool AddCommand(const CString& sCmd, CModCommand::ModCmdFunc func, + const CString& sArgs = "", const CString& sDesc = ""); /// @return True if the command was successfully added. - bool AddCommand(const CString& sCmd, const CString& sArgs, const CString& sDesc, std::function func); + bool AddCommand(const CString& sCmd, const CString& sArgs, + const CString& sDesc, + std::function func); /// @return True if the command was successfully removed. bool RemCommand(const CString& sCmd); /// @return The CModCommand instance or nullptr if none was found. @@ -1060,11 +1110,16 @@ public: bool LoadRegistry(); bool SaveRegistry() const; bool MoveRegistry(const CString& sPath); - bool SetNV(const CString & sName, const CString & sValue, bool bWriteToDisk = true); - CString GetNV(const CString & sName) const; - bool HasNV(const CString & sName) const { return m_mssRegistry.find(sName) != m_mssRegistry.end(); } - bool DelNV(const CString & sName, bool bWriteToDisk = true); - MCString::iterator FindNV(const CString & sName) { return m_mssRegistry.find(sName); } + bool SetNV(const CString& sName, const CString& sValue, + bool bWriteToDisk = true); + CString GetNV(const CString& sName) const; + bool HasNV(const CString& sName) const { + return m_mssRegistry.find(sName) != m_mssRegistry.end(); + } + bool DelNV(const CString& sName, bool bWriteToDisk = true); + MCString::iterator FindNV(const CString& sName) { + return m_mssRegistry.find(sName); + } MCString::iterator EndNV() { return m_mssRegistry.end(); } MCString::iterator BeginNV() { return m_mssRegistry.begin(); } void DelNV(MCString::iterator it) { m_mssRegistry.erase(it); } @@ -1123,7 +1178,8 @@ public: * @param sHost The IP the client is connecting from. * @param uPort The port the client is connecting from. */ - virtual void OnClientConnect(CZNCSock* pSock, const CString& sHost, unsigned short uPort); + virtual void OnClientConnect(CZNCSock* pSock, const CString& sHost, + unsigned short uPort); /** This module hook is called when a client tries to login. If your * module wants to handle the login attempt, it must return * CModule::EModRet::HALT; @@ -1135,7 +1191,8 @@ public: * @param sUsername The username that tried to log in. * @param sRemoteIP The IP address from which the client tried to login. */ - virtual void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP); + virtual void OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP); /** This function behaves like CModule::OnUserRaw(), but is also called * before the client successfully logged in to ZNC. You should always * prefer to use CModule::OnUserRaw() if possible. @@ -1157,13 +1214,15 @@ public: * @param bState On or off, depending on which case is interesting for client. * @return true if your module supports this capability in the specified state. */ - virtual bool IsClientCapSupported(CClient* pClient, const CString& sCap, bool bState); + virtual bool IsClientCapSupported(CClient* pClient, const CString& sCap, + bool bState); /** Called when we actually need to turn a capability on or off for a client. * @param pClient The client which requested the capability. * @param sCap name of wanted capability. * @param bState On or off, depending on which case client needs. */ - virtual void OnClientCapRequest(CClient* pClient, const CString& sCap, bool bState); + virtual void OnClientCapRequest(CClient* pClient, const CString& sCap, + bool bState); /** Called when a module is going to be loaded. * @param sModName name of the module. @@ -1174,8 +1233,10 @@ public: * @param[out] sRetMsg text about loading of the module. * @return See CModule::EModRet. */ - virtual EModRet OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg); + virtual EModRet OnModuleLoading(const CString& sModName, + const CString& sArgs, + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg); /** Called when a module is going to be unloaded. * @param pModule the module. * @param[out] bSuccess the module was unloaded successfully @@ -1183,7 +1244,8 @@ public: * @param[out] sRetMsg text about unloading of the module. * @return See CModule::EModRet. */ - virtual EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg); + virtual EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg); /** Called when info about a module is needed. * @param[out] ModInfo put result here, if your module knows it. * @param sModule name of the module. @@ -1192,40 +1254,43 @@ public: * @return See CModule::EModRet. */ virtual EModRet OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg); + bool& bSuccess, CString& sRetMsg); /** Called when list of available mods is requested. * @param ssMods put new modules here. * @param bGlobal true if global modules are needed. */ - virtual void OnGetAvailableMods(std::set& ssMods, CModInfo::EModuleType eType); + virtual void OnGetAvailableMods(std::set& ssMods, + CModInfo::EModuleType eType); // !Global Modules -protected: + protected: CModInfo::EModuleType m_eType; - CString m_sDescription; - std::set m_sTimers; + CString m_sDescription; + std::set m_sTimers; std::set m_sSockets; #ifdef HAVE_PTHREAD std::set m_sJobs; #endif - ModHandle m_pDLL; - CSockManager* m_pManager; - CUser* m_pUser; - CIRCNetwork* m_pNetwork; - CClient* m_pClient; - CString m_sModName; - CString m_sDataDir; - CString m_sSavePath; - CString m_sArgs; - CString m_sModPath; -private: - MCString m_mssRegistry; //!< way to save name/value pairs. Note there is no encryption involved in this - VWebSubPages m_vSubPages; + ModHandle m_pDLL; + CSockManager* m_pManager; + CUser* m_pUser; + CIRCNetwork* m_pNetwork; + CClient* m_pClient; + CString m_sModName; + CString m_sDataDir; + CString m_sSavePath; + CString m_sArgs; + CString m_sModPath; + + private: + MCString + m_mssRegistry; //!< way to save name/value pairs. Note there is no encryption involved in this + VWebSubPages m_vSubPages; std::map m_mCommands; }; class CModules : public std::vector { -public: + public: CModules(); ~CModules(); @@ -1246,25 +1311,42 @@ public: bool OnPostRehash(); bool OnIRCDisconnected(); bool OnIRCConnected(); - bool OnIRCConnecting(CIRCSock *pIRCSock); - bool OnIRCConnectionError(CIRCSock *pIRCSock); - bool OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName); + bool OnIRCConnecting(CIRCSock* pIRCSock); + bool OnIRCConnectionError(CIRCSock* pIRCSock); + bool OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, + CString& sRealName); bool OnBroadcast(CString& sMessage); - bool OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange); - bool OnChanPermission(const CNick& OpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange); - bool OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange); - bool OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs); - bool OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs); - bool OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange); - bool OnMode(const CNick& OpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange); + bool OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange); + bool OnChanPermission(const CNick& OpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange); + bool OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange); + bool OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, + const CString& sArgs); + bool OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, + const CString& sArgs); + bool OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange); + bool OnMode(const CNick& OpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange); bool OnRaw(CString& sLine); bool OnRawMessage(CMessage& Message); @@ -1275,11 +1357,16 @@ public: bool OnModNotice(const CString& sMessage); bool OnModCTCP(const CString& sMessage); - bool OnQuit(const CNick& Nick, const CString& sMessage, const std::vector& vChans); - bool OnQuitMessage(CQuitMessage& Message, const std::vector& vChans); - bool OnNick(const CNick& Nick, const CString& sNewNick, const std::vector& vChans); - bool OnNickMessage(CNickMessage& Message, const std::vector& vChans); - bool OnKick(const CNick& Nick, const CString& sOpNick, CChan& Channel, const CString& sMessage); + bool OnQuit(const CNick& Nick, const CString& sMessage, + const std::vector& vChans); + bool OnQuitMessage(CQuitMessage& Message, + const std::vector& vChans); + bool OnNick(const CNick& Nick, const CString& sNewNick, + const std::vector& vChans); + bool OnNickMessage(CNickMessage& Message, + const std::vector& vChans); + bool OnKick(const CNick& Nick, const CString& sOpNick, CChan& Channel, + const CString& sMessage); bool OnKickMessage(CKickMessage& Message); bool OnJoining(CChan& Channel); bool OnJoin(const CNick& Nick, CChan& Channel); @@ -1290,9 +1377,11 @@ public: bool OnChanBufferStarting(CChan& Chan, CClient& Client); bool OnChanBufferEnding(CChan& Chan, CClient& Client); - bool OnChanBufferPlayLine2(CChan& Chan, CClient& Client, CString& sLine, const timeval& tv); + bool OnChanBufferPlayLine2(CChan& Chan, CClient& Client, CString& sLine, + const timeval& tv); bool OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine); - bool OnPrivBufferPlayLine2(CClient& Client, CString& sLine, const timeval& tv); + bool OnPrivBufferPlayLine2(CClient& Client, CString& sLine, + const timeval& tv); bool OnPrivBufferPlayLine(CClient& Client, CString& sLine); bool OnChanBufferPlayMessage(CMessage& Message); bool OnPrivBufferPlayMessage(CMessage& Message); @@ -1353,52 +1442,66 @@ public: bool OnServerCapResult(const CString& sCap, bool bSuccess); CModule* FindModule(const CString& sModule) const; - bool LoadModule(const CString& sModule, const CString& sArgs, CModInfo::EModuleType eType, CUser* pUser, CIRCNetwork* pNetwork, CString& sRetMsg); + bool LoadModule(const CString& sModule, const CString& sArgs, + CModInfo::EModuleType eType, CUser* pUser, + CIRCNetwork* pNetwork, CString& sRetMsg); bool UnloadModule(const CString& sModule); bool UnloadModule(const CString& sModule, CString& sRetMsg); - bool ReloadModule(const CString& sModule, const CString& sArgs, CUser* pUser, CIRCNetwork* pNetwork, CString& sRetMsg); + bool ReloadModule(const CString& sModule, const CString& sArgs, + CUser* pUser, CIRCNetwork* pNetwork, CString& sRetMsg); - static bool GetModInfo(CModInfo& ModInfo, const CString& sModule, CString &sRetMsg); - static bool GetModPathInfo(CModInfo& ModInfo, const CString& sModule, const CString& sModPath, CString &sRetMsg); - static void GetAvailableMods(std::set& ssMods, CModInfo::EModuleType eType = CModInfo::UserModule); - static void GetDefaultMods(std::set& ssMods, CModInfo::EModuleType eType = CModInfo::UserModule); + static bool GetModInfo(CModInfo& ModInfo, const CString& sModule, + CString& sRetMsg); + static bool GetModPathInfo(CModInfo& ModInfo, const CString& sModule, + const CString& sModPath, CString& sRetMsg); + static void GetAvailableMods( + std::set& ssMods, + CModInfo::EModuleType eType = CModInfo::UserModule); + static void GetDefaultMods( + std::set& ssMods, + CModInfo::EModuleType eType = CModInfo::UserModule); // This returns the path to the .so and to the data dir // which is where static data (webadmin skins) are saved static bool FindModPath(const CString& sModule, CString& sModPath, - CString& sDataPath); + CString& sDataPath); // Return a list of pairs for directories in // which modules can be found. - typedef std::queue > ModDirList; + typedef std::queue> ModDirList; static ModDirList GetModDirs(); // Global Modules bool OnAddUser(CUser& User, CString& sErrorRet); bool OnDeleteUser(CUser& User); - bool OnClientConnect(CZNCSock* pSock, const CString& sHost, unsigned short uPort); + bool OnClientConnect(CZNCSock* pSock, const CString& sHost, + unsigned short uPort); bool OnLoginAttempt(std::shared_ptr Auth); bool OnFailedLogin(const CString& sUsername, const CString& sRemoteIP); bool OnUnknownUserRaw(CClient* pClient, CString& sLine); bool OnUnknownUserRawMessage(CMessage& Message); bool OnClientCapLs(CClient* pClient, SCString& ssCaps); - bool IsClientCapSupported(CClient* pClient, const CString& sCap, bool bState); + bool IsClientCapSupported(CClient* pClient, const CString& sCap, + bool bState); bool OnClientCapRequest(CClient* pClient, const CString& sCap, bool bState); bool OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg); + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg); bool OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg); - bool OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg); - bool OnGetAvailableMods(std::set& ssMods, CModInfo::EModuleType eType); + bool OnGetModInfo(CModInfo& ModInfo, const CString& sModule, bool& bSuccess, + CString& sRetMsg); + bool OnGetAvailableMods(std::set& ssMods, + CModInfo::EModuleType eType); // !Global Modules -private: + private: static ModHandle OpenModule(const CString& sModule, const CString& sModPath, - bool &bVersionMismatch, CModInfo& Info, CString& sRetMsg); + bool& bVersionMismatch, CModInfo& Info, + CString& sRetMsg); -protected: - CUser* m_pUser; - CIRCNetwork* m_pNetwork; - CClient* m_pClient; + protected: + CUser* m_pUser; + CIRCNetwork* m_pNetwork; + CClient* m_pClient; }; -#endif // !ZNC_MODULES_H +#endif // !ZNC_MODULES_H diff --git a/include/znc/Nick.h b/include/znc/Nick.h index e4358cd5..d5b31e1d 100644 --- a/include/znc/Nick.h +++ b/include/znc/Nick.h @@ -26,9 +26,8 @@ class CIRCNetwork; class CChan; // !Forward Decl -class CNick -{ -public: +class CNick { + public: CNick(); CNick(const CString& sNick); ~CNick(); @@ -39,7 +38,8 @@ public: void Reset(); void Parse(const CString& sNickMask); CString GetHostMask() const; - size_t GetCommonChans(std::vector& vChans, CIRCNetwork* pNetwork) const; + size_t GetCommonChans(std::vector& vChans, + CIRCNetwork* pNetwork) const; bool NickEquals(const CString& nickname) const; // Setters @@ -62,13 +62,14 @@ public: // !Getters void Clone(const CNick& SourceNick); -private: -protected: - CString m_sChanPerms; + + private: + protected: + CString m_sChanPerms; CIRCNetwork* m_pNetwork; - CString m_sNick; - CString m_sIdent; - CString m_sHost; + CString m_sNick; + CString m_sIdent; + CString m_sHost; }; -#endif // !ZNC_NICK_H +#endif // !ZNC_NICK_H diff --git a/include/znc/Query.h b/include/znc/Query.h index ae63e332..19e8e5ae 100644 --- a/include/znc/Query.h +++ b/include/znc/Query.h @@ -27,7 +27,7 @@ class CIRCNetwork; // !Forward Declarations class CQuery { -public: + public: CQuery(const CString& sName, CIRCNetwork* pNetwork); ~CQuery(); @@ -37,10 +37,18 @@ public: // Buffer const CBuffer& GetBuffer() const { return m_Buffer; } unsigned int GetBufferCount() const { return m_Buffer.GetLineCount(); } - bool SetBufferCount(unsigned int u, bool bForce = false) { return m_Buffer.SetLineCount(u, bForce); } - size_t AddBuffer(const CMessage& Format, const CString& sText = "") { return m_Buffer.AddLine(Format, sText); } + bool SetBufferCount(unsigned int u, bool bForce = false) { + return m_Buffer.SetLineCount(u, bForce); + } + size_t AddBuffer(const CMessage& Format, const CString& sText = "") { + return m_Buffer.AddLine(Format, sText); + } /// @deprecated - size_t AddBuffer(const CString& sFormat, const CString& sText = "", const timeval* ts = nullptr, const MCString& mssTags = MCString::EmptyMap) { return m_Buffer.AddLine(sFormat, sText, ts, mssTags); } + size_t AddBuffer(const CString& sFormat, const CString& sText = "", + const timeval* ts = nullptr, + const MCString& mssTags = MCString::EmptyMap) { + return m_Buffer.AddLine(sFormat, sText, ts, mssTags); + } void ClearBuffer() { m_Buffer.Clear(); } void SendBuffer(CClient* pClient); void SendBuffer(CClient* pClient, const CBuffer& Buffer); @@ -50,10 +58,10 @@ public: const CString& GetName() const { return m_sName; } // !Getters -private: - CString m_sName; - CIRCNetwork* m_pNetwork; - CBuffer m_Buffer; + private: + CString m_sName; + CIRCNetwork* m_pNetwork; + CBuffer m_Buffer; }; -#endif // !ZNC_QUERY_H +#endif // !ZNC_QUERY_H diff --git a/include/znc/SHA256.h b/include/znc/SHA256.h index 6184ed69..7d68e8d4 100644 --- a/include/znc/SHA256.h +++ b/include/znc/SHA256.h @@ -34,8 +34,8 @@ #ifndef ZNC_SHA2_H #define ZNC_SHA2_H -#define SHA256_DIGEST_SIZE ( 256 / 8) -#define SHA256_BLOCK_SIZE ( 512 / 8) +#define SHA256_DIGEST_SIZE (256 / 8) +#define SHA256_BLOCK_SIZE (512 / 8) #include @@ -47,18 +47,15 @@ #include typedef struct { - size_t tot_len; - size_t len; - unsigned char block[2 * SHA256_BLOCK_SIZE]; - uint32_t h[8]; + size_t tot_len; + size_t len; + unsigned char block[2 * SHA256_BLOCK_SIZE]; + uint32_t h[8]; } sha256_ctx; -void sha256_init(sha256_ctx * ctx); -void sha256_update(sha256_ctx *ctx, const unsigned char *message, - size_t len); -void sha256_final(sha256_ctx *ctx, unsigned char *digest); -void sha256(const unsigned char *message, size_t len, - unsigned char *digest); +void sha256_init(sha256_ctx* ctx); +void sha256_update(sha256_ctx* ctx, const unsigned char* message, size_t len); +void sha256_final(sha256_ctx* ctx, unsigned char* digest); +void sha256(const unsigned char* message, size_t len, unsigned char* digest); #endif /* !ZNC_SHA2_H */ - diff --git a/include/znc/SSLVerifyHost.h b/include/znc/SSLVerifyHost.h index fe0b5952..a3120db3 100644 --- a/include/znc/SSLVerifyHost.h +++ b/include/znc/SSLVerifyHost.h @@ -22,7 +22,8 @@ #include #include -bool ZNC_SSLVerifyHost(const CString& sHost, const X509* pCert, CString& sError); +bool ZNC_SSLVerifyHost(const CString& sHost, const X509* pCert, + CString& sError); #endif /* HAVE_LIBSSL */ diff --git a/include/znc/Server.h b/include/znc/Server.h index 4dc28520..7b7130e3 100644 --- a/include/znc/Server.h +++ b/include/znc/Server.h @@ -21,8 +21,9 @@ #include class CServer { -public: - CServer(const CString& sName, unsigned short uPort = 6667, const CString& sPass = "", bool bSSL = false); + public: + CServer(const CString& sName, unsigned short uPort = 6667, + const CString& sPass = "", bool bSSL = false); ~CServer(); const CString& GetName() const; @@ -31,12 +32,13 @@ public: bool IsSSL() const; CString GetString(bool bIncludePassword = true) const; static bool IsValidHostName(const CString& sHostName); -private: -protected: - CString m_sName; - unsigned short m_uPort; - CString m_sPass; - bool m_bSSL; + + private: + protected: + CString m_sName; + unsigned short m_uPort; + CString m_sPass; + bool m_bSSL; }; -#endif // !ZNC_SERVER_H +#endif // !ZNC_SERVER_H diff --git a/include/znc/Socket.h b/include/znc/Socket.h index 1c82b3a7..871c1570 100644 --- a/include/znc/Socket.h +++ b/include/znc/Socket.h @@ -24,20 +24,26 @@ class CModule; class CZNCSock : public Csock { -public: + public: CZNCSock(int timeout = 60); CZNCSock(const CString& sHost, u_short port, int timeout = 60); ~CZNCSock() {} - int ConvertAddress(const struct sockaddr_storage* pAddr, socklen_t iAddrLen, CString& sIP, u_short* piPort) const override; + int ConvertAddress(const struct sockaddr_storage* pAddr, socklen_t iAddrLen, + CString& sIP, u_short* piPort) const override; #ifdef HAVE_LIBSSL - int VerifyPeerCertificate(int iPreVerify, X509_STORE_CTX * pStoreCTX) override; + int VerifyPeerCertificate(int iPreVerify, + X509_STORE_CTX* pStoreCTX) override; void SSLHandShakeFinished() override; bool SNIConfigureClient(CString& sHostname) override; #endif - void SetHostToVerifySSL(const CString& sHost) { m_sHostToVerifySSL = sHost; } + void SetHostToVerifySSL(const CString& sHost) { + m_sHostToVerifySSL = sHost; + } CString GetSSLPeerFingerprint() const; - void SetSSLTrustedPeerFingerprints(const SCString& ssFPs) { m_ssTrustedFingerprints = ssFPs; } + void SetSSLTrustedPeerFingerprints(const SCString& ssFPs) { + m_ssTrustedFingerprints = ssFPs; + } #ifndef HAVE_ICU // Don't fail to compile when ICU is not enabled @@ -45,30 +51,29 @@ public: #endif virtual CString GetRemoteIP() const { return Csock::GetRemoteIP(); } -protected: + protected: // All existing errno codes seem to be in range 1-300 enum { errnoBadSSLCert = 12569, }; -private: + private: CString m_sHostToVerifySSL; SCString m_ssTrustedFingerprints; SCString m_ssCertVerificationErrors; }; -enum EAddrType { - ADDR_IPV4ONLY, - ADDR_IPV6ONLY, - ADDR_ALL -}; +enum EAddrType { ADDR_IPV4ONLY, ADDR_IPV6ONLY, ADDR_ALL }; class CSockManager : public TSocketManager { -public: + public: CSockManager(); virtual ~CSockManager(); - bool ListenHost(u_short iPort, const CString& sSockName, const CString& sBindHost, bool bSSL = false, int iMaxConns = SOMAXCONN, CZNCSock *pcSock = nullptr, u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { + bool ListenHost(u_short iPort, const CString& sSockName, + const CString& sBindHost, bool bSSL = false, + int iMaxConns = SOMAXCONN, CZNCSock* pcSock = nullptr, + u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { CSListener L(iPort, sBindHost); L.SetSockName(sSockName); @@ -93,11 +98,17 @@ public: return Listen(L, pcSock); } - bool ListenAll(u_short iPort, const CString& sSockName, bool bSSL = false, int iMaxConns = SOMAXCONN, CZNCSock *pcSock = nullptr, u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { - return ListenHost(iPort, sSockName, "", bSSL, iMaxConns, pcSock, iTimeout, eAddr); + bool ListenAll(u_short iPort, const CString& sSockName, bool bSSL = false, + int iMaxConns = SOMAXCONN, CZNCSock* pcSock = nullptr, + u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { + return ListenHost(iPort, sSockName, "", bSSL, iMaxConns, pcSock, + iTimeout, eAddr); } - u_short ListenRand(const CString& sSockName, const CString& sBindHost, bool bSSL = false, int iMaxConns = SOMAXCONN, CZNCSock *pcSock = nullptr, u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { + u_short ListenRand(const CString& sSockName, const CString& sBindHost, + bool bSSL = false, int iMaxConns = SOMAXCONN, + CZNCSock* pcSock = nullptr, u_int iTimeout = 0, + EAddrType eAddr = ADDR_ALL) { unsigned short uPort = 0; CSListener L(0, sBindHost); @@ -125,15 +136,23 @@ public: return uPort; } - u_short ListenAllRand(const CString& sSockName, bool bSSL = false, int iMaxConns = SOMAXCONN, CZNCSock *pcSock = nullptr, u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { - return(ListenRand(sSockName, "", bSSL, iMaxConns, pcSock, iTimeout, eAddr)); + u_short ListenAllRand(const CString& sSockName, bool bSSL = false, + int iMaxConns = SOMAXCONN, CZNCSock* pcSock = nullptr, + u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { + return (ListenRand(sSockName, "", bSSL, iMaxConns, pcSock, iTimeout, + eAddr)); } - void Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout = 60, bool bSSL = false, const CString& sBindHost = "", CZNCSock *pcSock = nullptr); + void Connect(const CString& sHostname, u_short iPort, + const CString& sSockName, int iTimeout = 60, bool bSSL = false, + const CString& sBindHost = "", CZNCSock* pcSock = nullptr); - unsigned int GetAnonConnectionCount(const CString &sIP) const; -private: - void FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock); + unsigned int GetAnonConnectionCount(const CString& sIP) const; + + private: + void FinishConnect(const CString& sHostname, u_short iPort, + const CString& sSockName, int iTimeout, bool bSSL, + const CString& sBindHost, CZNCSock* pcSock); #ifdef HAVE_PTHREAD class CThreadMonitorFD; @@ -141,38 +160,55 @@ private: #endif #ifdef HAVE_THREADED_DNS struct TDNSTask { - TDNSTask() : sHostname(""), iPort(0), sSockName(""), iTimeout(0), bSSL(false), sBindhost(""), pcSock(nullptr), bDoneTarget(false), bDoneBind(false), aiTarget(nullptr), aiBind(nullptr) {} + TDNSTask() + : sHostname(""), + iPort(0), + sSockName(""), + iTimeout(0), + bSSL(false), + sBindhost(""), + pcSock(nullptr), + bDoneTarget(false), + bDoneBind(false), + aiTarget(nullptr), + aiBind(nullptr) {} TDNSTask(const TDNSTask&) = delete; TDNSTask& operator=(const TDNSTask&) = delete; - CString sHostname; - u_short iPort; - CString sSockName; - int iTimeout; - bool bSSL; - CString sBindhost; + CString sHostname; + u_short iPort; + CString sSockName; + int iTimeout; + bool bSSL; + CString sBindhost; CZNCSock* pcSock; - bool bDoneTarget; - bool bDoneBind; + bool bDoneTarget; + bool bDoneBind; addrinfo* aiTarget; addrinfo* aiBind; }; class CDNSJob : public CJob { - public: - CDNSJob() : sHostname(""), task(nullptr), pManager(nullptr), bBind(false), iRes(0), aiResult(nullptr) {} + public: + CDNSJob() + : sHostname(""), + task(nullptr), + pManager(nullptr), + bBind(false), + iRes(0), + aiResult(nullptr) {} CDNSJob(const CDNSJob&) = delete; CDNSJob& operator=(const CDNSJob&) = delete; - CString sHostname; - TDNSTask* task; + CString sHostname; + TDNSTask* task; CSockManager* pManager; - bool bBind; + bool bBind; - int iRes; - addrinfo* aiResult; + int iRes; + addrinfo* aiResult; void runThread() override; void runMain() override; @@ -181,7 +217,7 @@ private: void SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult); static void* TDNSThread(void* argument); #endif -protected: + protected: }; /** @@ -194,7 +230,7 @@ protected: * - MaxBuffer for readline is set to 10240, in the event this is reached the socket is closed (@see ReachedMaxBuffer) */ class CSocket : public CZNCSock { -public: + public: /** * @brief ctor * @param pModule the module this sock instance is associated to @@ -207,7 +243,8 @@ public: * @param uPort the port being connected to * @param iTimeout the timeout period for this specific sock */ - CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout = 60); + CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, + int iTimeout = 60); virtual ~CSocket(); CSocket(const CSocket&) = delete; @@ -224,16 +261,18 @@ public: bool ConnectionFrom(const CString& sHost, unsigned short uPort) override; //! Ease of use Connect, assigns to the manager and is subsequently tracked - bool Connect(const CString& sHostname, unsigned short uPort, bool bSSL = false, unsigned int uTimeout = 60); + bool Connect(const CString& sHostname, unsigned short uPort, + bool bSSL = false, unsigned int uTimeout = 60); //! Ease of use Listen, assigned to the manager and is subsequently tracked bool Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout = 0); // Getters CModule* GetModule() const; // !Getters -private: -protected: - CModule* m_pModule; //!< pointer to the module that this sock instance belongs to + private: + protected: + CModule* + m_pModule; //!< pointer to the module that this sock instance belongs to }; /** @@ -241,7 +280,7 @@ protected: * @brief Base IRC socket for client<->ZNC, and ZNC<->server */ class CIRCSocket : public CZNCSock { -public: + public: #ifdef HAVE_ICU /** * @brief Allow IRC control characters to appear even if protocol encoding explicitly disallows them. @@ -253,19 +292,14 @@ public: * In case if protocol encoding uses these code points for something else, the encoding takes preference, * and they are not IRC control characters anymore. */ - void IcuExtToUCallback( - UConverterToUnicodeArgs* toArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode* err) override; - void IcuExtFromUCallback( - UConverterFromUnicodeArgs* fromArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode* err) override; + void IcuExtToUCallback(UConverterToUnicodeArgs* toArgs, + const char* codeUnits, int32_t length, + UConverterCallbackReason reason, + UErrorCode* err) override; + void IcuExtFromUCallback(UConverterFromUnicodeArgs* fromArgs, + const UChar* codeUnits, int32_t length, + UChar32 codePoint, UConverterCallbackReason reason, + UErrorCode* err) override; #endif }; diff --git a/include/znc/Template.h b/include/znc/Template.h index 2fb10287..8325e011 100644 --- a/include/znc/Template.h +++ b/include/znc/Template.h @@ -26,33 +26,38 @@ class CTemplate; class CTemplateTagHandler { -public: + public: CTemplateTagHandler() {} virtual ~CTemplateTagHandler() {} - virtual bool HandleVar(CTemplate& Tmpl, const CString& sName, const CString& sArgs, CString& sOutput) { + virtual bool HandleVar(CTemplate& Tmpl, const CString& sName, + const CString& sArgs, CString& sOutput) { return false; } - virtual bool HandleTag(CTemplate& Tmpl, const CString& sName, const CString& sArgs, CString& sOutput) { + virtual bool HandleTag(CTemplate& Tmpl, const CString& sName, + const CString& sArgs, CString& sOutput) { return false; } - virtual bool HandleIf(CTemplate& Tmpl, const CString& sName, const CString& sArgs, CString& sOutput) { + virtual bool HandleIf(CTemplate& Tmpl, const CString& sName, + const CString& sArgs, CString& sOutput) { return HandleVar(Tmpl, sName, sArgs, sOutput); } - virtual bool HandleValue(CTemplate& Tmpl, CString& sValue, const MCString& msOptions) { + virtual bool HandleValue(CTemplate& Tmpl, CString& sValue, + const MCString& msOptions) { return false; } -private: + + private: }; class CTemplate; class CTemplateOptions { -public: - CTemplateOptions() : m_eEscapeFrom(CString::EASCII), m_eEscapeTo(CString::EASCII) { - } + public: + CTemplateOptions() + : m_eEscapeFrom(CString::EASCII), m_eEscapeTo(CString::EASCII) {} virtual ~CTemplateOptions() {} @@ -62,17 +67,21 @@ public: CString::EEscape GetEscapeFrom() const { return m_eEscapeFrom; } CString::EEscape GetEscapeTo() const { return m_eEscapeTo; } // !Getters -private: - CString::EEscape m_eEscapeFrom; - CString::EEscape m_eEscapeTo; + private: + CString::EEscape m_eEscapeFrom; + CString::EEscape m_eEscapeTo; }; - class CTemplateLoopContext { -public: - CTemplateLoopContext(unsigned long uFilePos, const CString& sLoopName, bool bReverse, std::vector* pRows) - : m_bReverse(bReverse), m_bHasData(false), m_sName(sLoopName), m_uRowIndex(0), m_uFilePosition(uFilePos), m_pvRows(pRows) { - } + public: + CTemplateLoopContext(unsigned long uFilePos, const CString& sLoopName, + bool bReverse, std::vector* pRows) + : m_bReverse(bReverse), + m_bHasData(false), + m_sName(sLoopName), + m_uRowIndex(0), + m_uFilePosition(uFilePos), + m_pvRows(pRows) {} virtual ~CTemplateLoopContext() {} @@ -84,7 +93,12 @@ public: void SetName(const CString& s) { m_sName = s; } void SetRowIndex(unsigned int u) { m_uRowIndex = u; } unsigned int IncRowIndex() { return ++m_uRowIndex; } - unsigned int DecRowIndex() { if (m_uRowIndex == 0) { return 0; } return --m_uRowIndex; } + unsigned int DecRowIndex() { + if (m_uRowIndex == 0) { + return 0; + } + return --m_uRowIndex; + } void SetFilePosition(unsigned int u) { m_uFilePosition = u; } // !Setters @@ -101,26 +115,41 @@ public: CTemplate* GetRow(unsigned int uIndex); CString GetValue(const CString& sName, bool bFromIf = false); // !Getters -private: - bool m_bReverse; //!< Iterate through this loop in reverse order - bool m_bHasData; //!< Tells whether this loop has real data or not - CString m_sName; //!< The name portion of the tag - unsigned int m_uRowIndex; //!< The index of the current row we're on - unsigned long m_uFilePosition; //!< The file position of the opening tag - std::vector* m_pvRows; //!< This holds pointers to the templates associated with this loop + private: + bool m_bReverse; //!< Iterate through this loop in reverse order + bool m_bHasData; //!< Tells whether this loop has real data or not + CString m_sName; //!< The name portion of the tag + unsigned int m_uRowIndex; //!< The index of the current row we're on + unsigned long + m_uFilePosition; //!< The file position of the opening tag + std::vector* + m_pvRows; //!< This holds pointers to the templates associated with this loop }; - class CTemplate : public MCString { -public: - CTemplate() : CTemplate("") { - } + public: + CTemplate() : CTemplate("") {} - CTemplate(const CString& sFileName) : MCString(), m_pParent(nullptr), m_sFileName(sFileName), m_lsbPaths(), m_mvLoops(), m_vLoopContexts(), m_spOptions(new CTemplateOptions), m_vspTagHandlers() { - } + CTemplate(const CString& sFileName) + : MCString(), + m_pParent(nullptr), + m_sFileName(sFileName), + m_lsbPaths(), + m_mvLoops(), + m_vLoopContexts(), + m_spOptions(new CTemplateOptions), + m_vspTagHandlers() {} - CTemplate(const std::shared_ptr& Options, CTemplate* pParent = nullptr) : MCString(), m_pParent(pParent), m_sFileName(""), m_lsbPaths(), m_mvLoops(), m_vLoopContexts(), m_spOptions(Options), m_vspTagHandlers() { - } + CTemplate(const std::shared_ptr& Options, + CTemplate* pParent = nullptr) + : MCString(), + m_pParent(pParent), + m_sFileName(""), + m_lsbPaths(), + m_mvLoops(), + m_vLoopContexts(), + m_spOptions(Options), + m_vspTagHandlers() {} virtual ~CTemplate(); @@ -132,7 +161,7 @@ public: m_vspTagHandlers.push_back(spTagHandler); } - std::vector >& GetTagHandlers() { + std::vector>& GetTagHandlers() { if (m_pParent) { return m_pParent->GetTagHandlers(); } @@ -148,7 +177,9 @@ public: CString ExpandFile(const CString& sFilename, bool bFromInc = false); bool SetFile(const CString& sFileName); - void SetPath(const CString& sPath); // Sets the dir:dir:dir type path to look at for templates, as of right now no ../../.. protection + void SetPath(const CString& sPath); // Sets the dir:dir:dir type path to + // look at for templates, as of right + // now no ../../.. protection CString MakePath(const CString& sPath) const; void PrependPath(const CString& sPath, bool bIncludesOnly = false); void AppendPath(const CString& sPath, bool bIncludesOnly = false); @@ -172,14 +203,14 @@ public: // Getters const CString& GetFileName() const { return m_sFileName; } // !Getters -private: - CTemplate* m_pParent; - CString m_sFileName; - std::list > m_lsbPaths; - std::map > m_mvLoops; - std::vector m_vLoopContexts; - std::shared_ptr m_spOptions; - std::vector > m_vspTagHandlers; + private: + CTemplate* m_pParent; + CString m_sFileName; + std::list> m_lsbPaths; + std::map> m_mvLoops; + std::vector m_vLoopContexts; + std::shared_ptr m_spOptions; + std::vector> m_vspTagHandlers; }; -#endif // !ZNC_TEMPLATE_H +#endif // !ZNC_TEMPLATE_H diff --git a/include/znc/Threads.h b/include/znc/Threads.h index 1bd3a53a..6fcdae1b 100644 --- a/include/znc/Threads.h +++ b/include/znc/Threads.h @@ -65,15 +65,10 @@ using CConditionVariable = std::condition_variable_any; * For modules you should use CModuleJob instead. */ class CJob { -public: + public: friend class CThreadPool; - enum EJobState { - READY, - RUNNING, - DONE, - CANCELLED - }; + enum EJobState { READY, RUNNING, DONE, CANCELLED }; CJob() : m_eState(READY) {} @@ -92,52 +87,52 @@ public: /// runThread() can return early if this returns true. bool wasCancelled() const; -private: + private: // Undefined copy constructor and assignment operator CJob(const CJob&); CJob& operator=(const CJob&); - // Synchronized via the thread pool's mutex! Do not access without that mutex! + // Synchronized via the thread pool's mutex! Do not access without that + // mutex! EJobState m_eState; }; class CThreadPool { -private: + private: friend class CJob; CThreadPool(); ~CThreadPool(); -public: + public: static CThreadPool& Get(); /// Add a job to the thread pool and run it. The job will be deleted when done. - void addJob(CJob *job); + void addJob(CJob* job); /// Cancel a job that was previously passed to addJob(). This *might* /// mean that runThread() and/or runMain() will not be called on the job. /// This function BLOCKS until the job finishes! - void cancelJob(CJob *job); + void cancelJob(CJob* job); /// Cancel some jobs that were previously passed to addJob(). This *might* /// mean that runThread() and/or runMain() will not be called on some of /// the jobs. This function BLOCKS until all jobs finish! - void cancelJobs(const std::set &jobs); + void cancelJobs(const std::set& jobs); - int getReadFD() const { - return m_iJobPipe[0]; - } + int getReadFD() const { return m_iJobPipe[0]; } void handlePipeReadable() const; -private: + private: void jobDone(CJob* pJob); - // Check if the calling thread is still needed, must be called with m_mutex held + // Check if the calling thread is still needed, must be called with m_mutex + // held bool threadNeeded() const; - CJob *getJobFromPipe() const; - void finishJob(CJob *) const; + CJob* getJobFromPipe() const; + void finishJob(CJob*) const; void threadFunc(); @@ -166,8 +161,8 @@ private: int m_iJobPipe[2]; // list of pending jobs - std::list m_jobs; + std::list m_jobs; }; -#endif // HAVE_PTHREAD -#endif // !ZNC_THREADS_H +#endif // HAVE_PTHREAD +#endif // !ZNC_THREADS_H diff --git a/include/znc/User.h b/include/znc/User.h index d32a3a01..389e2398 100644 --- a/include/znc/User.h +++ b/include/znc/User.h @@ -35,7 +35,7 @@ class CUserTimer; class CServer; class CUser { -public: + public: CUser(const CString& sUserName); ~CUser(); @@ -76,21 +76,28 @@ public: // !Modules // Networks - CIRCNetwork* AddNetwork(const CString &sNetwork, CString& sErrorRet); + CIRCNetwork* AddNetwork(const CString& sNetwork, CString& sErrorRet); bool DeleteNetwork(const CString& sNetwork); - bool AddNetwork(CIRCNetwork *pNetwork); - void RemoveNetwork(CIRCNetwork *pNetwork); + bool AddNetwork(CIRCNetwork* pNetwork); + void RemoveNetwork(CIRCNetwork* pNetwork); CIRCNetwork* FindNetwork(const CString& sNetwork) const; const std::vector& GetNetworks() const; bool HasSpaceForNewNetwork() const; // !Networks - bool PutUser(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutAllUser(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutStatus(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutStatusNotice(const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutModule(const CString& sModule, const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); - bool PutModNotice(const CString& sModule, const CString& sLine, CClient* pClient = nullptr, CClient* pSkipClient = nullptr); + bool PutUser(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutAllUser(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutStatus(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutStatusNotice(const CString& sLine, CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); + bool PutModule(const CString& sModule, const CString& sLine, + CClient* pClient = nullptr, CClient* pSkipClient = nullptr); + bool PutModNotice(const CString& sModule, const CString& sLine, + CClient* pClient = nullptr, + CClient* pSkipClient = nullptr); bool IsUserAttached() const; void UserConnected(CClient* pClient); @@ -105,7 +112,8 @@ public: CString AddTimestamp(time_t tm, const CString& sStr) const; void CloneNetworks(const CUser& User); - bool Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks = true); + bool Clone(const CUser& User, CString& sErrorRet, + bool bCloneNetworks = true); void BounceAllClients(); void AddBytesRead(unsigned long long u) { m_uBytesRead += u; } @@ -196,61 +204,64 @@ public: unsigned int MaxQueryBuffers() const { return m_uMaxQueryBuffers; } // !Getters -protected: - const CString m_sUserName; - const CString m_sCleanUserName; - CString m_sNick; - CString m_sAltNick; - CString m_sIdent; - CString m_sRealName; - CString m_sBindHost; - CString m_sDCCBindHost; - CString m_sPass; - CString m_sPassSalt; - CString m_sStatusPrefix; - CString m_sDefaultChanModes; - CString m_sClientEncoding; + protected: + const CString m_sUserName; + const CString m_sCleanUserName; + CString m_sNick; + CString m_sAltNick; + CString m_sIdent; + CString m_sRealName; + CString m_sBindHost; + CString m_sDCCBindHost; + CString m_sPass; + CString m_sPassSalt; + CString m_sStatusPrefix; + CString m_sDefaultChanModes; + CString m_sClientEncoding; - CString m_sQuitMsg; - MCString m_mssCTCPReplies; - CString m_sTimestampFormat; - CString m_sTimezone; - eHashType m_eHashType; + CString m_sQuitMsg; + MCString m_mssCTCPReplies; + CString m_sTimestampFormat; + CString m_sTimezone; + eHashType m_eHashType; // Paths - CString m_sUserPath; + CString m_sUserPath; // !Paths - bool m_bMultiClients; - bool m_bDenyLoadMod; - bool m_bAdmin; - bool m_bDenySetBindHost; - bool m_bAutoClearChanBuffer; - bool m_bAutoClearQueryBuffer; - bool m_bBeingDeleted; - bool m_bAppendTimestamp; - bool m_bPrependTimestamp; + bool m_bMultiClients; + bool m_bDenyLoadMod; + bool m_bAdmin; + bool m_bDenySetBindHost; + bool m_bAutoClearChanBuffer; + bool m_bAutoClearQueryBuffer; + bool m_bBeingDeleted; + bool m_bAppendTimestamp; + bool m_bPrependTimestamp; - CUserTimer* m_pUserTimer; + CUserTimer* m_pUserTimer; - std::vector m_vIRCNetworks; - std::vector m_vClients; - std::set m_ssAllowedHosts; - unsigned int m_uChanBufferSize; - unsigned int m_uQueryBufferSize; - unsigned long long m_uBytesRead; - unsigned long long m_uBytesWritten; - unsigned int m_uMaxJoinTries; - unsigned int m_uMaxNetworks; - unsigned int m_uMaxQueryBuffers; - unsigned int m_uMaxJoins; - CString m_sSkinName; + std::vector m_vIRCNetworks; + std::vector m_vClients; + std::set m_ssAllowedHosts; + unsigned int m_uChanBufferSize; + unsigned int m_uQueryBufferSize; + unsigned long long m_uBytesRead; + unsigned long long m_uBytesWritten; + unsigned int m_uMaxJoinTries; + unsigned int m_uMaxNetworks; + unsigned int m_uMaxQueryBuffers; + unsigned int m_uMaxJoins; + CString m_sSkinName; - CModules* m_pModules; + CModules* m_pModules; -private: - void SetKeepBuffer(bool b) { SetAutoClearChanBuffer(!b); } // XXX compatibility crap, added in 0.207 - bool LoadModule(const CString& sModName, const CString& sArgs, const CString& sNotice, CString& sError); + private: + void SetKeepBuffer(bool b) { + SetAutoClearChanBuffer(!b); + } // XXX compatibility crap, added in 0.207 + bool LoadModule(const CString& sModName, const CString& sArgs, + const CString& sNotice, CString& sError); }; -#endif // !ZNC_USER_H +#endif // !ZNC_USER_H diff --git a/include/znc/Utils.h b/include/znc/Utils.h index 9a3b4062..0bca31af 100644 --- a/include/znc/Utils.h +++ b/include/znc/Utils.h @@ -28,11 +28,9 @@ #include #include -static inline void SetFdCloseOnExec(int fd) -{ +static inline void SetFdCloseOnExec(int fd) { int flags = fcntl(fd, F_GETFD, 0); - if (flags < 0) - return; // Ignore errors + if (flags < 0) return; // Ignore errors // When we execve() a new process this fd is now automatically closed. fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } @@ -40,7 +38,7 @@ static inline void SetFdCloseOnExec(int fd) static const char g_HexDigits[] = "0123456789abcdef"; class CUtils { -public: + public: CUtils(); ~CUtils(); @@ -63,25 +61,30 @@ public: static CString SaltedMD5Hash(const CString& sPass, const CString& sSalt); static CString SaltedSHA256Hash(const CString& sPass, const CString& sSalt); static CString GetPass(const CString& sPrompt); - static bool GetInput(const CString& sPrompt, CString& sRet, const CString& sDefault = "", const CString& sHint = ""); + static bool GetInput(const CString& sPrompt, CString& sRet, + const CString& sDefault = "", + const CString& sHint = ""); static bool GetBoolInput(const CString& sPrompt, bool bDefault); - static bool GetBoolInput(const CString& sPrompt, bool *pbDefault = nullptr); - static bool GetNumInput(const CString& sPrompt, unsigned int& uRet, unsigned int uMin = 0, unsigned int uMax = ~0, unsigned int uDefault = ~0); + static bool GetBoolInput(const CString& sPrompt, bool* pbDefault = nullptr); + static bool GetNumInput(const CString& sPrompt, unsigned int& uRet, + unsigned int uMin = 0, unsigned int uMax = ~0, + unsigned int uDefault = ~0); static unsigned long long GetMillTime() { struct timeval tv; unsigned long long iTime = 0; gettimeofday(&tv, nullptr); - iTime = (unsigned long long) tv.tv_sec * 1000; - iTime += ((unsigned long long) tv.tv_usec / 1000); + iTime = (unsigned long long)tv.tv_sec * 1000; + iTime += ((unsigned long long)tv.tv_usec / 1000); return iTime; } #ifdef HAVE_LIBSSL - static void GenerateCert(FILE *pOut, const CString& sHost = ""); + static void GenerateCert(FILE* pOut, const CString& sHost = ""); #endif /* HAVE_LIBSSL */ static CString CTime(time_t t, const CString& sTZ); - static CString FormatTime(time_t t, const CString& sFormat, const CString& sTZ); + static CString FormatTime(time_t t, const CString& sFormat, + const CString& sTZ); static CString FormatServerTime(const timeval& tv); static timeval ParseServerTime(const CString& sTime); static SCString GetTimezones(); @@ -92,27 +95,23 @@ public: /// @deprecated Use CMessage instead static void SetMessageTags(CString& sLine, const MCString& mssTags); -private: -protected: + private: + protected: }; class CException { -public: - typedef enum { - EX_Shutdown, - EX_Restart - } EType; + public: + typedef enum { EX_Shutdown, EX_Restart } EType; - CException(EType e) : m_eType(e) { - } + CException(EType e) : m_eType(e) {} virtual ~CException() {} EType GetType() const { return m_eType; } -private: -protected: - EType m_eType; -}; + private: + protected: + EType m_eType; +}; /** Previously this generated a grid-like output from a given input. * @@ -133,8 +132,8 @@ protected: * * But tables look awful in IRC. So now it puts every cell on separate line. */ -class CTable : protected std::vector > { -public: +class CTable : protected std::vector> { + public: /** Constructor * * @param uPreferredWidth If width of table is bigger than this, text in cells will be wrapped to several lines, if possible @@ -163,7 +162,8 @@ public: * If this is not given, the last row will be used. * @return True if setting the cell was successful. */ - bool SetCell(const CString& sColumn, const CString& sValue, size_type uRowIdx = ~0); + bool SetCell(const CString& sColumn, const CString& sValue, + size_type uRowIdx = ~0); /** Get a line of the table's output * @param uIdx The index of the line you want. @@ -176,56 +176,57 @@ public: void Clear(); /// @return The number of rows in this table, not counting the header. - using std::vector >::size; + using std::vector>::size; /// @return True if this table doesn't contain any rows. - using std::vector >::empty; -private: + using std::vector>::empty; + + private: unsigned int GetColumnIndex(const CString& sName) const; VCString Render() const; -protected: + protected: // TODO: cleanup these fields before 1.7.0 (I don't want to break ABI) VCString m_vsHeaders; mutable VCString m_vsOutput; // Rendered table }; - #ifdef HAVE_LIBSSL #include #include #include //! does Blowfish w/64 bit feedback, no padding class CBlowfish { -public: + public: /** * @param sPassword key to encrypt with * @param iEncrypt encrypt method (BF_DECRYPT or BF_ENCRYPT) * @param sIvec what to set the ivector to start with, default sets it all 0's */ - CBlowfish(const CString & sPassword, int iEncrypt, const CString & sIvec = ""); + CBlowfish(const CString& sPassword, int iEncrypt, + const CString& sIvec = ""); ~CBlowfish(); CBlowfish(const CBlowfish&) = default; CBlowfish& operator=(const CBlowfish&) = default; //! output must be freed - static unsigned char *MD5(const unsigned char *input, u_int ilen); + static unsigned char* MD5(const unsigned char* input, u_int ilen); //! returns an md5 of the CString (not hex encoded) - static CString MD5(const CString & sInput, bool bHexEncode = false); + static CString MD5(const CString& sInput, bool bHexEncode = false); //! output must be the same size as input - void Crypt(unsigned char *input, unsigned char *output, u_int ibytes); + void Crypt(unsigned char* input, unsigned char* output, u_int ibytes); //! must free result - unsigned char * Crypt(unsigned char *input, u_int ibytes); - CString Crypt(const CString & sData); + unsigned char* Crypt(unsigned char* input, u_int ibytes); + CString Crypt(const CString& sData); -private: - unsigned char *m_ivec; - BF_KEY m_bkey; - int m_iEncrypt, m_num; + private: + unsigned char* m_ivec; + BF_KEY m_bkey; + int m_iEncrypt, m_num; }; #endif /* HAVE_LIBSSL */ @@ -235,9 +236,9 @@ private: * @author prozac * @brief Insert an object with a time-to-live and check later if it still exists */ -template +template class TCacheMap { -public: + public: TCacheMap(unsigned int uTTL = 5000) : m_mItems(), m_uTTL(uTTL) {} virtual ~TCacheMap() {} @@ -246,27 +247,21 @@ public: * @brief This function adds an item to the cache using the default time-to-live value * @param Item the item to add to the cache */ - void AddItem(const K& Item) { - AddItem(Item, m_uTTL); - } + void AddItem(const K& Item) { AddItem(Item, m_uTTL); } /** * @brief This function adds an item to the cache using a custom time-to-live value * @param Item the item to add to the cache * @param uTTL the time-to-live for this specific item */ - void AddItem(const K& Item, unsigned int uTTL) { - AddItem(Item, V(), uTTL); - } + void AddItem(const K& Item, unsigned int uTTL) { AddItem(Item, V(), uTTL); } /** * @brief This function adds an item to the cache using the default time-to-live value * @param Item the item to add to the cache * @param Val The value associated with the key Item */ - void AddItem(const K& Item, const V& Val) { - AddItem(Item, Val, m_uTTL); - } + void AddItem(const K& Item, const V& Val) { AddItem(Item, Val, m_uTTL); } /** * @brief This function adds an item to the cache using a custom time-to-live value @@ -275,8 +270,9 @@ public: * @param uTTL the time-to-live for this specific item */ void AddItem(const K& Item, const V& Val, unsigned int uTTL) { - if (!uTTL) { // If time-to-live is zero we don't want to waste our time adding it - RemItem(Item); // Remove the item incase it already exists + if (!uTTL) { // If time-to-live is zero we don't want to waste our time + // adding it + RemItem(Item); // Remove the item incase it already exists return; } @@ -301,8 +297,7 @@ public: V* GetItem(const K& Item) { Cleanup(); iterator it = m_mItems.find(Item); - if (it == m_mItems.end()) - return nullptr; + if (it == m_mItems.end()) return nullptr; return &it->second.second; } @@ -311,9 +306,7 @@ public: * @param Item The item to be removed * @return true if item existed and was removed, false if it never existed */ - bool RemItem(const K& Item) { - return (m_mItems.erase(Item) != 0); - } + bool RemItem(const K& Item) { return (m_mItems.erase(Item) != 0); } /** * @brief Cycles through the queue removing all of the stale entries @@ -333,16 +326,14 @@ public: /** * @brief Clear all entries */ - void Clear() { - m_mItems.clear(); - } + void Clear() { m_mItems.clear(); } /** * @brief Returns all entries */ - std::map GetItems() { + std::map GetItems() { Cleanup(); - std::map mItems; + std::map mItems; for (const auto& it : m_mItems) { mItems[it.first] = it.second.second; } @@ -355,11 +346,12 @@ public: // Getters unsigned int GetTTL() const { return m_uTTL; } // !Getters -protected: + protected: typedef std::pair value; typedef typename std::map::iterator iterator; - std::map m_mItems; //!< Map of cached items. The value portion of the map is for the expire time - unsigned int m_uTTL; //!< Default time-to-live duration + std::map + m_mItems; //!< Map of cached items. The value portion of the map is for the expire time + unsigned int m_uTTL; //!< Default time-to-live duration }; -#endif // !ZNC_UTILS_H +#endif // !ZNC_UTILS_H diff --git a/include/znc/WebModules.h b/include/znc/WebModules.h index 6c2c601b..a3544099 100644 --- a/include/znc/WebModules.h +++ b/include/znc/WebModules.h @@ -32,18 +32,19 @@ typedef std::shared_ptr TWebSubPage; typedef std::vector VWebSubPages; class CZNCTagHandler : public CTemplateTagHandler { -public: + public: CZNCTagHandler(CWebSock& pWebSock); virtual ~CZNCTagHandler() {} - bool HandleTag(CTemplate& Tmpl, const CString& sName, const CString& sArgs, CString& sOutput) override; -private: + bool HandleTag(CTemplate& Tmpl, const CString& sName, const CString& sArgs, + CString& sOutput) override; + + private: CWebSock& m_WebSock; }; - class CWebSession { -public: + public: CWebSession(const CString& sId, const CString& sIP); ~CWebSession(); @@ -58,76 +59,90 @@ public: bool IsAdmin() const; void UpdateLastActive(); - CUser* SetUser(CUser* p) { m_pUser = p; return m_pUser; } + CUser* SetUser(CUser* p) { + m_pUser = p; + return m_pUser; + } void ClearMessageLoops(); void FillMessageLoops(CTemplate& Tmpl); size_t AddError(const CString& sMessage); size_t AddSuccess(const CString& sMessage); -private: - CString m_sId; - CString m_sIP; - CUser* m_pUser; - VCString m_vsErrorMsgs; - VCString m_vsSuccessMsgs; - time_t m_tmLastActive; + + private: + CString m_sId; + CString m_sIP; + CUser* m_pUser; + VCString m_vsErrorMsgs; + VCString m_vsSuccessMsgs; + time_t m_tmLastActive; }; - class CWebSubPage { -public: - CWebSubPage(const CString& sName, const CString& sTitle = "", unsigned int uFlags = 0) : m_uFlags(uFlags), m_sName(sName), m_sTitle(sTitle), m_vParams() { - } + public: + CWebSubPage(const CString& sName, const CString& sTitle = "", + unsigned int uFlags = 0) + : m_uFlags(uFlags), m_sName(sName), m_sTitle(sTitle), m_vParams() {} - CWebSubPage(const CString& sName, const CString& sTitle, const VPair& vParams, unsigned int uFlags = 0) : m_uFlags(uFlags), m_sName(sName), m_sTitle(sTitle), m_vParams(vParams) { - } + CWebSubPage(const CString& sName, const CString& sTitle, + const VPair& vParams, unsigned int uFlags = 0) + : m_uFlags(uFlags), + m_sName(sName), + m_sTitle(sTitle), + m_vParams(vParams) {} virtual ~CWebSubPage() {} - enum { - F_ADMIN = 1 - }; + enum { F_ADMIN = 1 }; void SetName(const CString& s) { m_sName = s; } void SetTitle(const CString& s) { m_sTitle = s; } - void AddParam(const CString& sName, const CString& sValue) { m_vParams.push_back(make_pair(sName, sValue)); } + void AddParam(const CString& sName, const CString& sValue) { + m_vParams.push_back(make_pair(sName, sValue)); + } bool RequiresAdmin() const { return m_uFlags & F_ADMIN; } const CString& GetName() const { return m_sName; } const CString& GetTitle() const { return m_sTitle; } const VPair& GetParams() const { return m_vParams; } -private: - unsigned int m_uFlags; - CString m_sName; - CString m_sTitle; - VPair m_vParams; + + private: + unsigned int m_uFlags; + CString m_sName; + CString m_sTitle; + VPair m_vParams; }; -class CWebSessionMap : public TCacheMap > { - public: - CWebSessionMap(unsigned int uTTL = 5000) : TCacheMap >(uTTL) {} - void FinishUserSessions(const CUser& User); +class CWebSessionMap : public TCacheMap> { + public: + CWebSessionMap(unsigned int uTTL = 5000) + : TCacheMap>(uTTL) {} + void FinishUserSessions(const CUser& User); }; class CWebSock : public CHTTPSock { -public: + public: enum EPageReqResult { - PAGE_NOTFOUND, // print 404 and Close() - PAGE_PRINT, // print page contents and Close() - PAGE_DEFERRED, // async processing, Close() will be called from a different place - PAGE_DONE // all stuff has been done + PAGE_NOTFOUND, // print 404 and Close() + PAGE_PRINT, // print page contents and Close() + PAGE_DEFERRED, // async processing, Close() will be called from a + // different place + PAGE_DONE // all stuff has been done }; CWebSock(const CString& sURIPrefix); virtual ~CWebSock(); bool ForceLogin() override; - bool OnLogin(const CString& sUser, const CString& sPass, bool bBasic) override; + bool OnLogin(const CString& sUser, const CString& sPass, + bool bBasic) override; void OnPageRequest(const CString& sURI) override; - EPageReqResult PrintTemplate(const CString& sPageName, CString& sPageRet, CModule* pModule = nullptr); - EPageReqResult PrintStaticFile(const CString& sPath, CString& sPageRet, CModule* pModule = nullptr); + EPageReqResult PrintTemplate(const CString& sPageName, CString& sPageRet, + CModule* pModule = nullptr); + EPageReqResult PrintStaticFile(const CString& sPath, CString& sPageRet, + CModule* pModule = nullptr); CString FindTmpl(CModule* pModule, const CString& sName); @@ -145,27 +160,29 @@ public: static void FinishUserSessions(const CUser& User); -protected: + protected: using CHTTPSock::PrintErrorPage; - bool AddModLoop(const CString& sLoopName, CModule& Module, CTemplate *pTemplate = nullptr); + bool AddModLoop(const CString& sLoopName, CModule& Module, + CTemplate* pTemplate = nullptr); VCString GetDirs(CModule* pModule, bool bIsTemplate); void SetPaths(CModule* pModule, bool bIsTemplate = false); void SetVars(); CString GetCSRFCheck(); -private: - EPageReqResult OnPageRequestInternal(const CString& sURI, CString& sPageRet); + private: + EPageReqResult OnPageRequestInternal(const CString& sURI, + CString& sPageRet); - bool m_bPathsSet; - CTemplate m_Template; + bool m_bPathsSet; + CTemplate m_Template; std::shared_ptr m_spAuth; - CString m_sModName; - CString m_sPath; - CString m_sPage; + CString m_sModName; + CString m_sPath; + CString m_sPage; std::shared_ptr m_spSession; static const unsigned int m_uiMaxSessions; }; -#endif // !ZNC_WEBMODULES_H +#endif // !ZNC_WEBMODULES_H diff --git a/include/znc/ZNCDebug.h b/include/znc/ZNCDebug.h index 4269c1d8..8c858356 100644 --- a/include/znc/ZNCDebug.h +++ b/include/znc/ZNCDebug.h @@ -32,28 +32,29 @@ * * @param f The expression you want to display. */ -#define DEBUG(f) do { \ - if (CDebug::Debug()) { \ - CDebugStream sDebug;\ - sDebug << f;\ - } \ -} while (0) +#define DEBUG(f) \ + do { \ + if (CDebug::Debug()) { \ + CDebugStream sDebug; \ + sDebug << f; \ + } \ + } while (0) class CDebug { -public: + public: static void SetStdoutIsTTY(bool b) { stdoutIsTTY = b; } static bool StdoutIsTTY() { return stdoutIsTTY; } static void SetDebug(bool b) { debug = b; } static bool Debug() { return debug; } -protected: + protected: static bool stdoutIsTTY; static bool debug; }; class CDebugStream : public std::ostringstream { -public: + public: ~CDebugStream(); }; -#endif // !ZNCDEBUG_H +#endif // !ZNCDEBUG_H diff --git a/include/znc/ZNCString.h b/include/znc/ZNCString.h index 749489b7..96e2ec31 100644 --- a/include/znc/ZNCString.h +++ b/include/znc/ZNCString.h @@ -35,33 +35,28 @@ class CString; class MCString; typedef std::set SCString; -typedef std::vector VCString; -typedef std::vector > VPair; +typedef std::vector VCString; +typedef std::vector> VPair; static const unsigned char XX = 0xff; static const unsigned char base64_table[256] = { - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,62, XX,XX,XX,63, - 52,53,54,55, 56,57,58,59, 60,61,XX,XX, XX,XX,XX,XX, - XX, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,XX, XX,XX,XX,XX, - XX,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, - XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, XX,XX,XX,XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, 62, XX, XX, XX, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, XX, XX, XX, XX, XX, XX, XX, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, XX, XX, XX, XX, + XX, XX, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, + XX, XX, XX, XX, XX, XX, XX, XX, XX, }; -enum class CaseSensitivity { - CaseInsensitive, - CaseSensitive -}; +enum class CaseSensitivity { CaseInsensitive, CaseSensitive }; /** * @brief String class that is used inside ZNC. @@ -71,7 +66,7 @@ enum class CaseSensitivity { * Split(). */ class CString : public std::string { -public: + public: typedef enum { EASCII, EURL, @@ -84,7 +79,8 @@ public: } EEscape; static const CaseSensitivity CaseSensitive = CaseSensitivity::CaseSensitive; - static const CaseSensitivity CaseInsensitive = CaseSensitivity::CaseInsensitive; + static const CaseSensitivity CaseInsensitive = + CaseSensitivity::CaseInsensitive; explicit CString(bool b) : std::string(b ? "true" : "false") {} explicit CString(char c); @@ -107,20 +103,20 @@ public: CString(size_t n, char c) : std::string(n, c) {} CString(std::initializer_list list) : std::string(list) {} ~CString() {} - + /** * Casts a CString to another type. Implemented via std::stringstream, you use this * for any class that has an operator<<(std::ostream, YourClass). * @param target The object to cast into. If the cast fails, its state is unspecified. * @return True if the cast succeeds, and false if it fails. */ - template bool Convert(T *target) const - { + template + bool Convert(T* target) const { std::stringstream ss(*this); ss >> *target; - return (bool) ss; // we don't care why it failed, only whether it failed + return (bool)ss; // we don't care why it failed, only whether it failed } - + /** * Joins a collection of objects together, using 'this' as a delimiter. * You can pass either pointers to arrays, or iterators to collections. @@ -128,20 +124,19 @@ public: * @param i_end An iterator pointing past the end of a group of objects. * @return The joined string */ - template CString Join(Iterator i_start, const Iterator &i_end) const - { + template + CString Join(Iterator i_start, const Iterator& i_end) const { if (i_start == i_end) return CString(""); std::ostringstream output; output << *i_start; - while (true) - { + while (true) { ++i_start; if (i_start == i_end) return CString(output.str()); output << *this; output << *i_start; } } - + /** * Compare this string caselessly to some other string. * @param s The string to compare to. @@ -149,7 +144,8 @@ public: * @return An integer less than, equal to, or greater than zero if this * string smaller, equal.... to the given string. */ - int CaseCmp(const CString& s, CString::size_type uLen = CString::npos) const; + int CaseCmp(const CString& s, + CString::size_type uLen = CString::npos) const; /** * Compare this string case sensitively to some other string. * @param s The string to compare to. @@ -169,7 +165,8 @@ public: /** * @deprecated */ - bool Equals(const CString& s, bool bCaseSensitive, CString::size_type uLen = CString::npos) const; + bool Equals(const CString& s, bool bCaseSensitive, + CString::size_type uLen = CString::npos) const; /** * Do a wildcard comparison between two strings. * For example, the following returns true: @@ -181,7 +178,8 @@ public: * @todo Make cs CaseInsensitive by default. * @return true if the wildcard matches. */ - static bool WildCmp(const CString& sWild, const CString& sString, CaseSensitivity cs = CaseSensitive); + static bool WildCmp(const CString& sWild, const CString& sString, + CaseSensitivity cs = CaseSensitive); /** * Do a wild compare on this string. * @param sWild The wildcards used to for the comparison. @@ -190,7 +188,8 @@ public: * @todo Make cs CaseInsensitive by default. * @return The result of this->WildCmp(sWild, *this);. */ - bool WildCmp(const CString& sWild, CaseSensitivity cs = CaseSensitive) const; + bool WildCmp(const CString& sWild, + CaseSensitivity cs = CaseSensitive) const; /** * Turn all characters in this string into their upper-case equivalent. @@ -241,7 +240,10 @@ public: * sRight are removed. * @returns The number of replacements done. */ - static unsigned int Replace(CString& sStr, const CString& sReplace, const CString& sWith, const CString& sLeft = "", const CString& sRight = "", bool bRemoveDelims = false); + static unsigned int Replace(CString& sStr, const CString& sReplace, + const CString& sWith, const CString& sLeft = "", + const CString& sRight = "", + bool bRemoveDelims = false); /** Replace all occurrences in the current string. * @see CString::Replace @@ -253,7 +255,9 @@ public: * @return The result of the replacing. The current string is left * unchanged. */ - CString Replace_n(const CString& sReplace, const CString& sWith, const CString& sLeft = "", const CString& sRight = "", bool bRemoveDelims = false) const; + CString Replace_n(const CString& sReplace, const CString& sWith, + const CString& sLeft = "", const CString& sRight = "", + bool bRemoveDelims = false) const; /** Replace all occurrences in the current string. * @see CString::Replace * @param sReplace The string to look for. @@ -263,7 +267,9 @@ public: * @param bRemoveDelims If true, all matching delimiters are removed. * @returns The number of replacements done. */ - unsigned int Replace(const CString& sReplace, const CString& sWith, const CString& sLeft = "", const CString& sRight = "", bool bRemoveDelims = false); + unsigned int Replace(const CString& sReplace, const CString& sWith, + const CString& sLeft = "", const CString& sRight = "", + bool bRemoveDelims = false); /** Ellipsize the current string. * For example, ellipsizing "Hello, I'm Bob" to the length 9 would * result in "Hello,...". @@ -302,13 +308,16 @@ public: * after it. * @see Split() if you need a string split into all of its tokens. */ - CString Token(size_t uPos, bool bRest = false, const CString& sSep = " ", bool bAllowEmpty = false) const; + CString Token(size_t uPos, bool bRest = false, const CString& sSep = " ", + bool bAllowEmpty = false) const; /** Get a token out of this string. This function behaves much like the * other Token() function in this class. The extra arguments are * handled similarly to Split(). */ - CString Token(size_t uPos, bool bRest, const CString& sSep, bool bAllowEmpty, const CString& sLeft, const CString& sRight, bool bTrimQuotes = true) const; + CString Token(size_t uPos, bool bRest, const CString& sSep, + bool bAllowEmpty, const CString& sLeft, const CString& sRight, + bool bTrimQuotes = true) const; size_type URLSplit(MCString& msRet) const; size_type OptionSplit(MCString& msRet, bool bUpperKeys = false) const; @@ -329,17 +338,19 @@ public: * each token. * @return The number of tokens found. */ - size_type Split(const CString& sDelim, VCString& vsRet, bool bAllowEmpty = true, - const CString& sLeft = "", const CString& sRight = "", bool bTrimQuotes = true, - bool bTrimWhiteSpace = false) const; + size_type Split(const CString& sDelim, VCString& vsRet, + bool bAllowEmpty = true, const CString& sLeft = "", + const CString& sRight = "", bool bTrimQuotes = true, + bool bTrimWhiteSpace = false) const; /** Split up this string into tokens. * This function is identical to the other CString::Split(), except that * the result is returned as a SCString instead of a VCString. */ - size_type Split(const CString& sDelim, SCString& ssRet, bool bAllowEmpty = true, - const CString& sLeft = "", const CString& sRight = "", bool bTrimQuotes = true, - bool bTrimWhiteSpace = false) const; + size_type Split(const CString& sDelim, SCString& ssRet, + bool bAllowEmpty = true, const CString& sLeft = "", + const CString& sRight = "", bool bTrimQuotes = true, + bool bTrimWhiteSpace = false) const; /** Build a string from a format string, replacing values from a map. * The format specification can contain simple named parameters that match @@ -349,7 +360,8 @@ public: * @param msValues A map of named parameters to their values. * @return The string with named parameters replaced. */ - static CString NamedFormat(const CString& sFormat, const MCString& msValues); + static CString NamedFormat(const CString& sFormat, + const MCString& msValues); /** Produces a random string. * @param uLength The length of the resulting string. @@ -512,14 +524,16 @@ public: * sensitive, CaseInsensitive (default) otherwise. * @return True if the string starts with prefix, false otherwise. */ - bool StartsWith(const CString& sPrefix, CaseSensitivity cs = CaseInsensitive) const; + bool StartsWith(const CString& sPrefix, + CaseSensitivity cs = CaseInsensitive) const; /** Check whether the string ends with a given suffix. * @param sSuffix The suffix. * @param cs CaseSensitive if you want the comparison to be case * sensitive, CaseInsensitive (default) otherwise. * @return True if the string ends with suffix, false otherwise. */ - bool EndsWith(const CString& sSuffix, CaseSensitivity cs = CaseInsensitive) const; + bool EndsWith(const CString& sSuffix, + CaseSensitivity cs = CaseInsensitive) const; /** * Check whether the string contains a given string. * @param s The string to search. @@ -564,9 +578,12 @@ public: */ CString StripControls_n() const; -private: -protected: - unsigned char* strnchr(const unsigned char* src, unsigned char c, unsigned int iMaxBytes, unsigned char* pFill = nullptr, unsigned int* piCount = nullptr) const; + private: + protected: + unsigned char* strnchr(const unsigned char* src, unsigned char c, + unsigned int iMaxBytes, + unsigned char* pFill = nullptr, + unsigned int* piCount = nullptr) const; }; /** @@ -576,11 +593,12 @@ protected: * This class maps strings to other strings. */ class MCString : public std::map { -public: + public: /** Construct an empty MCString. */ MCString() : std::map() {} /** Construct a MCString using an initializer list eg. MCString m = { {"key1", "val1"}, {"key2", "val2"} }; */ - MCString(std::initializer_list> list) : std::map(list) {} + MCString(std::initializer_list> list) + : std::map(list) {} /** Destruct this MCString. */ virtual ~MCString() { clear(); } @@ -589,18 +607,17 @@ public: /** Status codes that can be returned by WriteToDisk() and * ReadFromDisk(). */ - enum status_t - { + enum status_t { /// No errors. - MCS_SUCCESS = 0, + MCS_SUCCESS = 0, /// Opening the file failed. - MCS_EOPEN = 1, + MCS_EOPEN = 1, /// Writing to the file failed. - MCS_EWRITE = 2, + MCS_EWRITE = 2, /// WriteFilter() failed. MCS_EWRITEFIL = 3, /// ReadFilter() failed. - MCS_EREADFIL = 4 + MCS_EREADFIL = 4 }; /** Write this map to a file. @@ -624,7 +641,9 @@ public: * @param sValue The value that will be written. Can be modified. * @return true unless WriteToDisk() should fail with MCS_EWRITEFIL. */ - virtual bool WriteFilter(CString& sKey, CString& sValue) const { return true; } + virtual bool WriteFilter(CString& sKey, CString& sValue) const { + return true; + } /** Filter used while reading this map. This function is called by * ReadFromDisk() for each pair that is beging read. This function has * the chance to modify the data that is being read. @@ -632,7 +651,9 @@ public: * @param sValue The value that was read. Can be modified. * @return true unless ReadFromDisk() should fail with MCS_EWRITEFIL. */ - virtual bool ReadFilter(CString& sKey, CString& sValue) const { return true; } + virtual bool ReadFilter(CString& sKey, CString& sValue) const { + return true; + } /** Encode a value so that it can safely be parsed by ReadFromDisk(). * This is an internal function. @@ -642,4 +663,4 @@ public: virtual CString& Decode(CString& sValue) const; }; -#endif // !ZNCSTRING_H +#endif // !ZNCSTRING_H diff --git a/include/znc/defines.h b/include/znc/defines.h index ebe6b92f..b63d6cca 100644 --- a/include/znc/defines.h +++ b/include/znc/defines.h @@ -32,8 +32,9 @@ #endif // Redefine some Csocket debugging mechanisms to use ZNC's -#define CS_DEBUG(f) DEBUG(__FILE__ << ":" << __LINE__ << " " << f) -#define PERROR(f) DEBUG(__FILE__ << ":" << __LINE__ << " " << f << ": " << strerror(GetSockError())) +#define CS_DEBUG(f) DEBUG(__FILE__ << ":" << __LINE__ << " " << f) +#define PERROR(f) \ + DEBUG(__FILE__ << ":" << __LINE__ << " " << f << ": " \ + << strerror(GetSockError())) - -#endif // !ZNC_DEFINES_H +#endif // !ZNC_DEFINES_H diff --git a/include/znc/main.h b/include/znc/main.h index 3dccdbb9..04a001c4 100644 --- a/include/znc/main.h +++ b/include/znc/main.h @@ -23,100 +23,100 @@ extern bool ZNC_NO_NEED_TO_DO_ANYTHING_ON_MODULE_CALL_EXITER; #define NOTHING &ZNC_NO_NEED_TO_DO_ANYTHING_ON_MODULE_CALL_EXITER -#define ALLMODULECALL(macFUNC, macEXITER) \ - do { \ - CModules& GMods = CZNC::Get().GetModules(); \ - bool bAllExit = false; \ - if (GMods.macFUNC) { \ - bAllExit = true; \ - } else { \ - const map& mUsers = \ - CZNC::Get().GetUserMap(); \ - map::const_iterator it; \ - for (it = mUsers.begin(); it != mUsers.end(); ++it) { \ - CModules& UMods = it->second->GetModules(); \ - if (UMods.macFUNC) { \ - bAllExit = true; \ - break; \ - } \ - const vector& mNets = \ - it->second->GetNetworks(); \ - vector::const_iterator it2; \ - for (it2 = mNets.begin(); it2 != mNets.end(); ++it2) { \ - CModules& NMods = (*it2)->GetModules(); \ - if (NMods.macFUNC) { \ - bAllExit = true; \ - break; \ - } \ - } \ - if (bAllExit) break; \ - } \ - } \ - if (bAllExit) *macEXITER = true; \ +#define ALLMODULECALL(macFUNC, macEXITER) \ + do { \ + CModules& GMods = CZNC::Get().GetModules(); \ + bool bAllExit = false; \ + if (GMods.macFUNC) { \ + bAllExit = true; \ + } else { \ + const map& mUsers = CZNC::Get().GetUserMap(); \ + map::const_iterator it; \ + for (it = mUsers.begin(); it != mUsers.end(); ++it) { \ + CModules& UMods = it->second->GetModules(); \ + if (UMods.macFUNC) { \ + bAllExit = true; \ + break; \ + } \ + const vector& mNets = it->second->GetNetworks(); \ + vector::const_iterator it2; \ + for (it2 = mNets.begin(); it2 != mNets.end(); ++it2) { \ + CModules& NMods = (*it2)->GetModules(); \ + if (NMods.macFUNC) { \ + bAllExit = true; \ + break; \ + } \ + } \ + if (bAllExit) break; \ + } \ + } \ + if (bAllExit) *macEXITER = true; \ } while (false) -#define _GLOBALMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ - do { \ - CModules& GMods = CZNC::Get().GetModules(); \ - CUser* pOldGUser = GMods.GetUser(); \ - CIRCNetwork* pOldGNetwork = GMods.GetNetwork(); \ - CClient* pOldGClient = GMods.GetClient(); \ - GMods.SetUser(macUSER); \ - GMods.SetNetwork(macNETWORK); \ - GMods.SetClient(macCLIENT); \ - if (GMods.macFUNC) { \ - GMods.SetUser(pOldGUser); \ - GMods.SetNetwork(pOldGNetwork); \ - GMods.SetClient(pOldGClient); \ - *macEXITER = true; \ - } \ - GMods.SetUser(pOldGUser); \ - GMods.SetNetwork(pOldGNetwork); \ - GMods.SetClient(pOldGClient); \ +#define _GLOBALMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ + do { \ + CModules& GMods = CZNC::Get().GetModules(); \ + CUser* pOldGUser = GMods.GetUser(); \ + CIRCNetwork* pOldGNetwork = GMods.GetNetwork(); \ + CClient* pOldGClient = GMods.GetClient(); \ + GMods.SetUser(macUSER); \ + GMods.SetNetwork(macNETWORK); \ + GMods.SetClient(macCLIENT); \ + if (GMods.macFUNC) { \ + GMods.SetUser(pOldGUser); \ + GMods.SetNetwork(pOldGNetwork); \ + GMods.SetClient(pOldGClient); \ + *macEXITER = true; \ + } \ + GMods.SetUser(pOldGUser); \ + GMods.SetNetwork(pOldGNetwork); \ + GMods.SetClient(pOldGClient); \ } while (false) -#define _USERMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ - do { \ - bool bGlobalExited = false; \ - _GLOBALMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, &bGlobalExited); \ - if (bGlobalExited) { \ - *macEXITER = true; \ - break; \ - } \ - if (macUSER != nullptr) { \ - CModules& UMods = macUSER->GetModules(); \ - CIRCNetwork* pOldUNetwork = UMods.GetNetwork(); \ - CClient* pOldUClient = UMods.GetClient(); \ - UMods.SetNetwork(macNETWORK); \ - UMods.SetClient(macCLIENT); \ - if (UMods.macFUNC) { \ - UMods.SetNetwork(pOldUNetwork); \ - UMods.SetClient(pOldUClient); \ - *macEXITER = true; \ - } \ - UMods.SetNetwork(pOldUNetwork); \ - UMods.SetClient(pOldUClient); \ - } \ +#define _USERMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ + do { \ + bool bGlobalExited = false; \ + _GLOBALMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, \ + &bGlobalExited); \ + if (bGlobalExited) { \ + *macEXITER = true; \ + break; \ + } \ + if (macUSER != nullptr) { \ + CModules& UMods = macUSER->GetModules(); \ + CIRCNetwork* pOldUNetwork = UMods.GetNetwork(); \ + CClient* pOldUClient = UMods.GetClient(); \ + UMods.SetNetwork(macNETWORK); \ + UMods.SetClient(macCLIENT); \ + if (UMods.macFUNC) { \ + UMods.SetNetwork(pOldUNetwork); \ + UMods.SetClient(pOldUClient); \ + *macEXITER = true; \ + } \ + UMods.SetNetwork(pOldUNetwork); \ + UMods.SetClient(pOldUClient); \ + } \ } while (false) -#define NETWORKMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ - do { \ - bool bUserExited = false; \ - _USERMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, &bUserExited); \ - if (bUserExited) { \ - *macEXITER = true; \ - break; \ - } \ - if (macNETWORK != nullptr) { \ - CModules& NMods = macNETWORK->GetModules(); \ - CClient* pOldNClient = NMods.GetClient(); \ - NMods.SetClient(macCLIENT); \ - if (NMods.macFUNC) { \ - NMods.SetClient(pOldNClient); \ - *macEXITER = true; \ - } \ - NMods.SetClient(pOldNClient); \ - } \ +#define NETWORKMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, macEXITER) \ + do { \ + bool bUserExited = false; \ + _USERMODULECALL(macFUNC, macUSER, macNETWORK, macCLIENT, \ + &bUserExited); \ + if (bUserExited) { \ + *macEXITER = true; \ + break; \ + } \ + if (macNETWORK != nullptr) { \ + CModules& NMods = macNETWORK->GetModules(); \ + CClient* pOldNClient = NMods.GetClient(); \ + NMods.SetClient(macCLIENT); \ + if (NMods.macFUNC) { \ + NMods.SetClient(pOldNClient); \ + *macEXITER = true; \ + } \ + NMods.SetClient(pOldNClient); \ + } \ } while (false) #define GLOBALMODULECALL(macFUNC, macEXITER) \ @@ -142,4 +142,4 @@ extern bool ZNC_NO_NEED_TO_DO_ANYTHING_ON_MODULE_CALL_EXITER; * Feel free to also look at existing modules. */ -#endif // !ZNC_MAIN_H +#endif // !ZNC_MAIN_H diff --git a/include/znc/version.h b/include/znc/version.h index 3f8b6391..468134e7 100644 --- a/include/znc/version.h +++ b/include/znc/version.h @@ -2,18 +2,18 @@ #define ZNC_VERSION_H // The following defines are for #if comparison (preprocessor only likes ints) -#define VERSION_MAJOR 1 -#define VERSION_MINOR 7 -#define VERSION_PATCH -1 +#define VERSION_MAJOR 1 +#define VERSION_MINOR 7 +#define VERSION_PATCH -1 // This one is for display purpose -#define VERSION_STR "1.7.x" +#define VERSION_STR "1.7.x" // This one is for ZNCModInfo -#define VERSION (VERSION_MAJOR + VERSION_MINOR / 10.0) +#define VERSION (VERSION_MAJOR + VERSION_MINOR / 10.0) // You can add -DVERSION_EXTRA="stuff" to your CXXFLAGS! #ifndef VERSION_EXTRA -# define VERSION_EXTRA "" +#define VERSION_EXTRA "" #endif extern const char* ZNC_VERSION_EXTRA; -#endif // !ZNC_VERSION_H +#endif // !ZNC_VERSION_H diff --git a/include/znc/znc.h b/include/znc/znc.h index bb9a354c..25c114c5 100644 --- a/include/znc/znc.h +++ b/include/znc/znc.h @@ -34,7 +34,7 @@ class CConfig; class CFile; class CZNC { -public: + public: CZNC(); ~CZNC(); @@ -55,11 +55,13 @@ public: bool DeletePidFile(); bool WaitForChildLock(); bool IsHostAllowed(const CString& sHostMask) const; - // This returns false if there are too many anonymous connections from this ip + // This returns false if there are too many anonymous connections from this + // ip bool AllowConnectionFrom(const CString& sIP) const; void InitDirs(const CString& sArgvPath, const CString& sDataDir); bool OnBoot(); - CString ExpandConfigPath(const CString& sConfigFile, bool bAllowMkDir = true); + CString ExpandConfigPath(const CString& sConfigFile, + bool bAllowMkDir = true); bool WriteNewConfig(const CString& sConfigFile); bool WriteConfig(); bool ParseConfig(const CString& sConfig, CString& sError); @@ -70,7 +72,7 @@ public: static CString GetCompileOptionsString(); CString GetUptime() const; /** @deprecated Since 1.7.0. List of allowed bind hosts was a flawed design. */ - void ClearBindHosts() { } + void ClearBindHosts() {} /** @deprecated Since 1.7.0. List of allowed bind hosts was a flawed design. */ bool AddBindHost(const CString& sHost) { return false; } /** @deprecated Since 1.7.0. List of allowed bind hosts was a flawed design. */ @@ -79,7 +81,7 @@ public: bool AddTrustedProxy(const CString& sHost); bool RemTrustedProxy(const CString& sHost); void Broadcast(const CString& sMessage, bool bAdminOnly = false, - CUser* pSkipUser = nullptr, CClient* pSkipClient = nullptr); + CUser* pSkipUser = nullptr, CClient* pSkipClient = nullptr); void AddBytesRead(unsigned long long u) { m_uBytesRead += u; } void AddBytesWritten(unsigned long long u) { m_uBytesWritten += u; } unsigned long long BytesRead() const { return m_uBytesRead; } @@ -92,21 +94,30 @@ public: // while also providing the traffic of all users together, traffic which // couldn't be accounted to any particular user and the total traffic // generated through ZNC. - TrafficStatsMap GetTrafficStats(TrafficStatsPair &Users, - TrafficStatsPair &ZNC, TrafficStatsPair &Total); - TrafficStatsMap GetNetworkTrafficStats(const CString& sUsername, TrafficStatsPair& Total); + TrafficStatsMap GetTrafficStats(TrafficStatsPair& Users, + TrafficStatsPair& ZNC, + TrafficStatsPair& Total); + TrafficStatsMap GetNetworkTrafficStats(const CString& sUsername, + TrafficStatsPair& Total); // Authenticate a user. // The result is passed back via callbacks to CAuthBase. void AuthUser(std::shared_ptr AuthClass); // Setters - void SetConfigState(enum ConfigState e) { std::lock_guard guard(m_mutexConfigState); m_eConfigState = e; } + void SetConfigState(enum ConfigState e) { + std::lock_guard guard(m_mutexConfigState); + m_eConfigState = e; + } void SetSkinName(const CString& s) { m_sSkinName = s; } - void SetStatusPrefix(const CString& s) { m_sStatusPrefix = (s.empty()) ? "*" : s; } + void SetStatusPrefix(const CString& s) { + m_sStatusPrefix = (s.empty()) ? "*" : s; + } void SetMaxBufferSize(unsigned int i) { m_uiMaxBufferSize = i; } void SetAnonIPLimit(unsigned int i) { m_uiAnonIPLimit = i; } - void SetServerThrottle(unsigned int i) { m_sConnectThrottle.SetTTL(i*1000); } + void SetServerThrottle(unsigned int i) { + m_sConnectThrottle.SetTTL(i * 1000); + } void SetProtectWebSessions(bool b) { m_bProtectWebSessions = b; } void SetHideVersion(bool b) { m_bHideVersion = b; } void SetConnectDelay(unsigned int i); @@ -116,7 +127,10 @@ public: // !Setters // Getters - enum ConfigState GetConfigState() { std::lock_guard guard(m_mutexConfigState); return m_eConfigState; } + enum ConfigState GetConfigState() { + std::lock_guard guard(m_mutexConfigState); + return m_eConfigState; + } CSockManager& GetManager() { return m_Manager; } const CSockManager& GetManager() const { return m_Manager; } CModules& GetModules() { return *m_pModules; } @@ -136,17 +150,23 @@ public: /** @deprecated Since 1.7.0. List of allowed bind hosts was a flawed design. */ const VCString& GetBindHosts() const { return m_vsBindHosts; } const VCString& GetTrustedProxies() const { return m_vsTrustedProxies; } - const std::vector& GetListeners() const { return m_vpListeners; } + const std::vector& GetListeners() const { + return m_vpListeners; + } time_t TimeStarted() const { return m_TimeStarted; } unsigned int GetMaxBufferSize() const { return m_uiMaxBufferSize; } unsigned int GetAnonIPLimit() const { return m_uiAnonIPLimit; } - unsigned int GetServerThrottle() const { return m_sConnectThrottle.GetTTL() / 1000; } + unsigned int GetServerThrottle() const { + return m_sConnectThrottle.GetTTL() / 1000; + } unsigned int GetConnectDelay() const { return m_uiConnectDelay; } bool GetProtectWebSessions() const { return m_bProtectWebSessions; } bool GetHideVersion() const { return m_bHideVersion; } CString GetSSLCiphers() const { return m_sSSLCiphers; } CString GetSSLProtocols() const { return m_sSSLProtocols; } - Csock::EDisableProtocol GetDisabledSSLProtocols() const { return static_cast(m_uDisabledSSLProtocols); } + Csock::EDisableProtocol GetDisabledSSLProtocols() const { + return static_cast(m_uDisabledSSLProtocols); + } CString GetSSLCertFile() const { return m_sSSLCertFile; } static VCString GetAvailableSSLProtocols(); // !Getters @@ -166,31 +186,44 @@ public: * * @param sModule The name of the module to reload */ - bool UpdateModule(const CString &sModule); + bool UpdateModule(const CString& sModule); bool DeleteUser(const CString& sUsername); bool AddUser(CUser* pUser, CString& sErrorRet, bool bStartup = false); - const std::map & GetUserMap() const { return(m_msUsers); } + const std::map& GetUserMap() const { return (m_msUsers); } // Listener yummy - CListener* FindListener(u_short uPort, const CString& BindHost, EAddrType eAddr); + CListener* FindListener(u_short uPort, const CString& BindHost, + EAddrType eAddr); bool AddListener(CListener*); bool AddListener(unsigned short uPort, const CString& sBindHost, - const CString& sURIPrefix, bool bSSL, - EAddrType eAddr, CListener::EAcceptType eAccept, CString& sError); + const CString& sURIPrefix, bool bSSL, EAddrType eAddr, + CListener::EAcceptType eAccept, CString& sError); bool DelListener(CListener*); // Message of the Day - void SetMotd(const CString& sMessage) { ClearMotd(); AddMotd(sMessage); } - void AddMotd(const CString& sMessage) { if (!sMessage.empty()) { m_vsMotd.push_back(sMessage); } } + void SetMotd(const CString& sMessage) { + ClearMotd(); + AddMotd(sMessage); + } + void AddMotd(const CString& sMessage) { + if (!sMessage.empty()) { + m_vsMotd.push_back(sMessage); + } + } void ClearMotd() { m_vsMotd.clear(); } const VCString& GetMotd() const { return m_vsMotd; } // !MOTD - void AddServerThrottle(CString sName) { m_sConnectThrottle.AddItem(sName, true); } - bool GetServerThrottle(CString sName) { bool *b = m_sConnectThrottle.GetItem(sName); return (b && *b); } + void AddServerThrottle(CString sName) { + m_sConnectThrottle.AddItem(sName, true); + } + bool GetServerThrottle(CString sName) { + bool* b = m_sConnectThrottle.GetItem(sName); + return (b && *b); + } - void AddNetworkToQueue(CIRCNetwork *pNetwork); + void AddNetworkToQueue(CIRCNetwork* pNetwork); std::list& GetConnectionQueue() { return m_lpConnectQueue; } // This creates a CConnectQueueTimer if we haven't got one yet @@ -201,11 +234,11 @@ public: void ResumeConnectQueue(); // Never call this unless you are CConnectQueueTimer::~CConnectQueueTimer() - void LeakConnectQueueTimer(CConnectQueueTimer *pTimer); + void LeakConnectQueueTimer(CConnectQueueTimer* pTimer); static void DumpConfig(const CConfig* Config); -private: + private: CFile* InitPidFile(); bool ReadConfig(CConfig& config, CString& sError); @@ -219,46 +252,46 @@ private: bool AddListener(const CString& sLine, CString& sError); bool AddListener(CConfig* pConfig, CString& sError); -protected: - time_t m_TimeStarted; + protected: + time_t m_TimeStarted; - enum ConfigState m_eConfigState; - std::mutex m_mutexConfigState; + enum ConfigState m_eConfigState; + std::mutex m_mutexConfigState; - std::vector m_vpListeners; - std::map m_msUsers; - std::map m_msDelUsers; - CSockManager m_Manager; + std::vector m_vpListeners; + std::map m_msUsers; + std::map m_msDelUsers; + CSockManager m_Manager; - CString m_sCurPath; - CString m_sZNCPath; + CString m_sCurPath; + CString m_sZNCPath; - CString m_sConfigFile; - CString m_sSkinName; - CString m_sStatusPrefix; - CString m_sPidFile; - CString m_sSSLCertFile; - CString m_sSSLKeyFile; - CString m_sSSLDHParamFile; - CString m_sSSLCiphers; - CString m_sSSLProtocols; - VCString m_vsBindHosts; // TODO: remove (deprecated in 1.7.0) - VCString m_vsTrustedProxies; - VCString m_vsMotd; - CFile* m_pLockFile; - unsigned int m_uiConnectDelay; - unsigned int m_uiAnonIPLimit; - unsigned int m_uiMaxBufferSize; - unsigned int m_uDisabledSSLProtocols; - CModules* m_pModules; - unsigned long long m_uBytesRead; - unsigned long long m_uBytesWritten; - std::list m_lpConnectQueue; - CConnectQueueTimer *m_pConnectQueueTimer; - unsigned int m_uiConnectPaused; - TCacheMap m_sConnectThrottle; - bool m_bProtectWebSessions; - bool m_bHideVersion; + CString m_sConfigFile; + CString m_sSkinName; + CString m_sStatusPrefix; + CString m_sPidFile; + CString m_sSSLCertFile; + CString m_sSSLKeyFile; + CString m_sSSLDHParamFile; + CString m_sSSLCiphers; + CString m_sSSLProtocols; + VCString m_vsBindHosts; // TODO: remove (deprecated in 1.7.0) + VCString m_vsTrustedProxies; + VCString m_vsMotd; + CFile* m_pLockFile; + unsigned int m_uiConnectDelay; + unsigned int m_uiAnonIPLimit; + unsigned int m_uiMaxBufferSize; + unsigned int m_uDisabledSSLProtocols; + CModules* m_pModules; + unsigned long long m_uBytesRead; + unsigned long long m_uBytesWritten; + std::list m_lpConnectQueue; + CConnectQueueTimer* m_pConnectQueueTimer; + unsigned int m_uiConnectPaused; + TCacheMap m_sConnectThrottle; + bool m_bProtectWebSessions; + bool m_bHideVersion; }; -#endif // !ZNC_H +#endif // !ZNC_H diff --git a/modules/adminlog.cpp b/modules/adminlog.cpp index cd2c9a8d..06bcb5cf 100644 --- a/modules/adminlog.cpp +++ b/modules/adminlog.cpp @@ -23,11 +23,15 @@ #include class CAdminLogMod : public CModule { -public: + public: MODCONSTRUCTOR(CAdminLogMod) { AddHelpCommand(); - AddCommand("Show", static_cast(&CAdminLogMod::OnShowCommand), "", "Show the logging target"); - AddCommand("Target", static_cast(&CAdminLogMod::OnTargetCommand), " [path]", "Set the logging target"); + AddCommand("Show", static_cast( + &CAdminLogMod::OnShowCommand), + "", "Show the logging target"); + AddCommand("Target", static_cast( + &CAdminLogMod::OnTargetCommand), + " [path]", "Set the logging target"); openlog("znc", LOG_PID, LOG_DAEMON); } @@ -36,7 +40,7 @@ public: closelog(); } - bool OnLoad(const CString & sArgs, CString & sMessage) override { + bool OnLoad(const CString& sArgs, CString& sMessage) override { CString sTarget = GetNV("target"); if (sTarget.Equals("syslog")) m_eLogMode = LOG_TO_SYSLOG; @@ -49,41 +53,52 @@ public: SetLogFilePath(GetNV("path")); - Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]"); + Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + + CString(getuid()) + ":" + CString(getgid()) + "]"); return true; } void OnIRCConnected() override { - Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] connected to IRC: " + GetNetwork()->GetCurrentServer()->GetName()); + Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + + "] connected to IRC: " + + GetNetwork()->GetCurrentServer()->GetName()); } void OnIRCDisconnected() override { - Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC"); + Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + + "] disconnected from IRC"); } EModRet OnRaw(CString& sLine) override { if (sLine.StartsWith("ERROR ")) { - //ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) - //ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason)) + // ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) + // ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by + // Killer (reason)) CString sError(sLine.substr(6)); - if (sError.Left(1) == ":") - sError.LeftChomp(); - Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC: " + - GetNetwork()->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE); + if (sError.Left(1) == ":") sError.LeftChomp(); + Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + + "] disconnected from IRC: " + + GetNetwork()->GetCurrentServer()->GetName() + " [" + + sError + "]", + LOG_NOTICE); } return CONTINUE; - } + } void OnClientLogin() override { - Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + GetClient()->GetRemoteIP()); + Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + + GetClient()->GetRemoteIP()); } void OnClientDisconnect() override { - Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + GetClient()->GetRemoteIP()); + Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + + GetClient()->GetRemoteIP()); } - void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override { - Log("[" + sUsername + "] failed to login from " + sRemoteIP, LOG_WARNING); + void OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP) override { + Log("[" + sUsername + "] failed to login from " + sRemoteIP, + LOG_WARNING); } void SetLogFilePath(CString sPath) { @@ -104,8 +119,7 @@ public: } void Log(CString sLine, int iPrio = LOG_INFO) { - if (m_eLogMode & LOG_TO_SYSLOG) - syslog(iPrio, "%s", sLine.c_str()); + if (m_eLogMode & LOG_TO_SYSLOG) syslog(iPrio, "%s", sLine.c_str()); if (m_eLogMode & LOG_TO_FILE) { time_t curtime; @@ -114,14 +128,15 @@ public: time(&curtime); timeinfo = localtime(&curtime); - strftime(buf,sizeof(buf),"[%Y-%m-%d %H:%M:%S] ",timeinfo); + strftime(buf, sizeof(buf), "[%Y-%m-%d %H:%M:%S] ", timeinfo); CFile LogFile(m_sLogFile); if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT)) LogFile.Write(buf + sLine + "\n"); else - DEBUG("Failed to write to [" << m_sLogFile << "]: " << strerror(errno)); + DEBUG("Failed to write to [" << m_sLogFile + << "]: " << strerror(errno)); } } @@ -175,34 +190,35 @@ public: void OnShowCommand(const CString& sCommand) { CString sTarget; - switch (m_eLogMode) - { - case LOG_TO_FILE: - sTarget = "file"; - break; - case LOG_TO_SYSLOG: - sTarget = "syslog"; - break; - case LOG_TO_BOTH: - sTarget = "both, file and syslog"; - break; + switch (m_eLogMode) { + case LOG_TO_FILE: + sTarget = "file"; + break; + case LOG_TO_SYSLOG: + sTarget = "syslog"; + break; + case LOG_TO_BOTH: + sTarget = "both, file and syslog"; + break; } PutModule("Logging is enabled for " + sTarget); if (m_eLogMode != LOG_TO_SYSLOG) PutModule("Log file will be written to [" + m_sLogFile + "]"); } -private: + + private: enum LogMode { - LOG_TO_FILE = 1 << 0, + LOG_TO_FILE = 1 << 0, LOG_TO_SYSLOG = 1 << 1, - LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG + LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG }; LogMode m_eLogMode = LOG_TO_FILE; CString m_sLogFile; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("adminlog"); } diff --git a/modules/alias.cpp b/modules/alias.cpp index 0d777cb1..7ca8ef85 100644 --- a/modules/alias.cpp +++ b/modules/alias.cpp @@ -25,43 +25,34 @@ using std::vector; using std::stringstream; -class CAlias -{ -private: - CModule *parent; +class CAlias { + private: + CModule* parent; CString name; VCString alias_cmds; -public: + public: // getters/setters - const CString &GetName() const - { - return name; - } + const CString& GetName() const { return name; } // name should be a single, all uppercase word - void SetName(const CString &newname) - { + void SetName(const CString& newname) { name = newname.Token(0, false, " "); name.MakeUpper(); } // combined getter/setter for command list - VCString &AliasCmds() - { - return alias_cmds; - } + VCString& AliasCmds() { return alias_cmds; } // check registry if alias exists - static bool AliasExists(CModule *module, CString alias_name) - { + static bool AliasExists(CModule* module, CString alias_name) { alias_name = alias_name.Token(0, false, " ").MakeUpper(); return (module->FindNV(alias_name) != module->EndNV()); } - // populate alias from stored settings in registry, or return false if none exists - static bool AliasGet(CAlias &alias, CModule *module, CString line) - { + // populate alias from stored settings in registry, or return false if none + // exists + static bool AliasGet(CAlias& alias, CModule* module, CString line) { line = line.Token(0, false, " ").MakeUpper(); MCString::iterator i = module->FindNV(line); if (i == module->EndNV()) return false; @@ -73,34 +64,36 @@ public: // constructors CAlias() : parent(nullptr) {} - CAlias(CModule *new_parent, const CString &new_name) : parent(new_parent) { SetName(new_name); } + CAlias(CModule* new_parent, const CString& new_name) : parent(new_parent) { + SetName(new_name); + } // produce a command string from this alias' command list - CString GetCommands() const - { + CString GetCommands() const { return CString("\n").Join(alias_cmds.begin(), alias_cmds.end()); } // write this alias to registry - void Commit() const - { + void Commit() const { if (!parent) return; parent->SetNV(name, GetCommands()); } // delete this alias from regisrty - void Delete() const - { + void Delete() const { if (!parent) return; parent->DelNV(name); } -private: - // this function helps imprint out. it checks if there is a substitution token at 'caret' in 'alias_data' - // and if it finds one, pulls the appropriate token out of 'line' and appends it to 'output', and updates 'caret'. - // 'skip' is updated based on the logic that we should skip the % at the caret if we fail to parse the token. - static void ParseToken(const CString &alias_data, const CString &line, CString &output, size_t &caret, size_t &skip) - { + private: + // this function helps imprint out. it checks if there is a substitution + // token at 'caret' in 'alias_data' + // and if it finds one, pulls the appropriate token out of 'line' and + // appends it to 'output', and updates 'caret'. + // 'skip' is updated based on the logic that we should skip the % at the + // caret if we fail to parse the token. + static void ParseToken(const CString& alias_data, const CString& line, + CString& output, size_t& caret, size_t& skip) { bool optional = false; bool subsequent = false; size_t index = caret + 1; @@ -108,244 +101,271 @@ private: skip = 1; - if (alias_data.length() > index && alias_data[index] == '?') { optional = true; ++index; } // try to read optional flag - if (alias_data.length() > index && CString(alias_data.substr(index)).Convert(&token)) // try to read integer + if (alias_data.length() > index && alias_data[index] == '?') { + optional = true; + ++index; + } // try to read optional flag + if (alias_data.length() > index && + CString(alias_data.substr(index)) + .Convert(&token)) // try to read integer { - while(alias_data.length() > index && alias_data[index] >= '0' && alias_data[index] <= '9') ++index; // skip any numeric digits in string - } // (supposed to fail if whitespace precedes integer) - else return; // token was malformed. leave caret unchanged, and flag first character for skipping - if (alias_data.length() > index && alias_data[index] == '+') { subsequent = true; ++index; } // try to read subsequent flag - if (alias_data.length() > index && alias_data[index] == '%') { ++index; } // try to read end-of-substitution marker - else return; + while (alias_data.length() > index && alias_data[index] >= '0' && + alias_data[index] <= '9') + ++index; // skip any numeric digits in string + } // (supposed to fail if whitespace precedes integer) + else + return; // token was malformed. leave caret unchanged, and flag + // first character for skipping + if (alias_data.length() > index && alias_data[index] == '+') { + subsequent = true; + ++index; + } // try to read subsequent flag + if (alias_data.length() > index && alias_data[index] == '%') { + ++index; + } // try to read end-of-substitution marker + else + return; - CString stok = line.Token(token, subsequent, " "); // if we get here, we're definitely dealing with a token, so get the token's value + CString stok = line.Token(token, subsequent, " "); // if we get here, + // we're definitely + // dealing with a + // token, so get the + // token's value if (stok.empty() && !optional) - throw std::invalid_argument(CString("missing required parameter: ") + CString(token)); // blow up if token is required and also empty - output.append(stok); // write token value to output + throw std::invalid_argument( + CString("missing required parameter: ") + + CString(token)); // blow up if token is required and also empty + output.append(stok); // write token value to output - skip = 0; // since we're moving the cursor after the end of the token, skip no characters - caret = index; // advance the cursor forward by the size of the token + skip = 0; // since we're moving the cursor after the end of the token, + // skip no characters + caret = index; // advance the cursor forward by the size of the token } -public: + public: // read an IRC line and do token substitution - // throws an exception if a required parameter is missing, and might also throw if you manage to make it bork - CString Imprint(CString line) const - { + // throws an exception if a required parameter is missing, and might also + // throw if you manage to make it bork + CString Imprint(CString line) const { CString output; CString alias_data = GetCommands(); alias_data = parent->ExpandString(alias_data); size_t lastfound = 0, skip = 0; - // it would be very inefficient to attempt to blindly replace every possible token + // it would be very inefficient to attempt to blindly replace every + // possible token // so let's just parse the line and replace when we find them // token syntax: // %[?]n[+]% - // adding ? makes the substitution optional (you'll get "" if there are insufficient tokens, otherwise the alias will fail) - // adding + makes the substitution contain all tokens from the nth to the end of the line - while (true) - { - // if (found >= (int) alias_data.length()) break; // shouldn't be possible. + // adding ? makes the substitution optional (you'll get "" if there are + // insufficient tokens, otherwise the alias will fail) + // adding + makes the substitution contain all tokens from the nth to + // the end of the line + while (true) { + // if (found >= (int) alias_data.length()) break; // shouldn't be + // possible. size_t found = alias_data.find("%", lastfound + skip); - if (found == CString::npos) break; // if we found nothing, break - output.append(alias_data.substr(lastfound, found - lastfound)); // capture everything between the last stopping point and here - ParseToken(alias_data, line, output, found, skip); // attempt to read a token, updates indices based on success/failure + if (found == CString::npos) break; // if we found nothing, break + output.append(alias_data.substr( + lastfound, found - lastfound)); // capture everything between + // the last stopping point and + // here + ParseToken(alias_data, line, output, found, + skip); // attempt to read a token, updates indices based + // on success/failure lastfound = found; } - output += alias_data.substr(lastfound); // append from the final + output += alias_data.substr(lastfound); // append from the final return output; } }; class CAliasMod : public CModule { -private: + private: bool sending_lines; -public: - void CreateCommand(const CString& sLine) - { + public: + void CreateCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); - if (!CAlias::AliasExists(this, name)) - { + if (!CAlias::AliasExists(this, name)) { CAlias na(this, name); na.Commit(); PutModule("Created alias: " + na.GetName()); - } - else PutModule("Alias already exists."); + } else + PutModule("Alias already exists."); } - void DeleteCommand(const CString& sLine) - { + void DeleteCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias delete_alias; - if (CAlias::AliasGet(delete_alias, this, name)) - { + if (CAlias::AliasGet(delete_alias, this, name)) { PutModule("Deleted alias: " + delete_alias.GetName()); delete_alias.Delete(); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - void AddCmd(const CString& sLine) - { + void AddCmd(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias add_alias; - if (CAlias::AliasGet(add_alias, this, name)) - { + if (CAlias::AliasGet(add_alias, this, name)) { add_alias.AliasCmds().push_back(sLine.Token(2, true, " ")); add_alias.Commit(); PutModule("Modified alias."); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - void InsertCommand(const CString& sLine) - { + void InsertCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias insert_alias; int index; - if (CAlias::AliasGet(insert_alias, this, name)) - { - // if Convert succeeds, then i has been successfully read from user input - if (!sLine.Token(2, false, " ").Convert(&index) || index < 0 || index > (int) insert_alias.AliasCmds().size()) - { + if (CAlias::AliasGet(insert_alias, this, name)) { + // if Convert succeeds, then i has been successfully read from user + // input + if (!sLine.Token(2, false, " ").Convert(&index) || index < 0 || + index > (int)insert_alias.AliasCmds().size()) { PutModule("Invalid index."); return; } - insert_alias.AliasCmds().insert(insert_alias.AliasCmds().begin() + index, sLine.Token(3, true, " ")); + insert_alias.AliasCmds().insert( + insert_alias.AliasCmds().begin() + index, + sLine.Token(3, true, " ")); insert_alias.Commit(); PutModule("Modified alias."); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - void RemoveCommand(const CString& sLine) - { + void RemoveCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias remove_alias; int index; - if (CAlias::AliasGet(remove_alias, this, name)) - { - if (!sLine.Token(2, false, " ").Convert(&index) || index < 0 || index > (int) remove_alias.AliasCmds().size() - 1) - { + if (CAlias::AliasGet(remove_alias, this, name)) { + if (!sLine.Token(2, false, " ").Convert(&index) || index < 0 || + index > (int)remove_alias.AliasCmds().size() - 1) { PutModule("Invalid index."); return; } - remove_alias.AliasCmds().erase(remove_alias.AliasCmds().begin() + index); + remove_alias.AliasCmds().erase(remove_alias.AliasCmds().begin() + + index); remove_alias.Commit(); PutModule("Modified alias."); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - void ClearCommand(const CString& sLine) - { + void ClearCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias clear_alias; - if (CAlias::AliasGet(clear_alias, this, name)) - { + if (CAlias::AliasGet(clear_alias, this, name)) { clear_alias.AliasCmds().clear(); clear_alias.Commit(); PutModule("Modified alias."); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - void ListCommand(const CString& sLine) - { + void ListCommand(const CString& sLine) { CString output = "The following aliases exist:"; MCString::iterator i = BeginNV(); if (i == EndNV()) output += " [none]"; - for (; i != EndNV(); ++i) - { + for (; i != EndNV(); ++i) { output.append(" "); output.append(i->first); } PutModule(output); } - void DumpCommand(const CString& sLine) - { + void DumpCommand(const CString& sLine) { MCString::iterator i = BeginNV(); - - if (i == EndNV()) { + + if (i == EndNV()) { PutModule("There are no aliases."); return; } - + PutModule("-----------------------"); - PutModule("/ZNC-CLEAR-ALL-ALIASES!"); - for (; i != EndNV(); ++i) - { + PutModule("/ZNC-CLEAR-ALL-ALIASES!"); + for (; i != EndNV(); ++i) { PutModule("/msg " + GetModNick() + " Create " + i->first); if (!i->second.empty()) { VCString it; uint idx; i->second.Split("\n", it); - - for (idx = 0; idx < it.size(); ++idx) - { - PutModule("/msg " + GetModNick() + " Add " + i->first + " " + it[idx]); - } + + for (idx = 0; idx < it.size(); ++idx) { + PutModule("/msg " + GetModNick() + " Add " + i->first + + " " + it[idx]); + } } } PutModule("-----------------------"); } - void InfoCommand(const CString& sLine) - { + void InfoCommand(const CString& sLine) { CString name = sLine.Token(1, false, " "); CAlias info_alias; - if (CAlias::AliasGet(info_alias, this, name)) - { + if (CAlias::AliasGet(info_alias, this, name)) { PutModule("Actions for alias " + info_alias.GetName() + ":"); - for (size_t i = 0; i < info_alias.AliasCmds().size(); ++i) - { + for (size_t i = 0; i < info_alias.AliasCmds().size(); ++i) { CString num(i); CString padding(4 - (num.length() > 3 ? 3 : num.length()), ' '); PutModule(num + padding + info_alias.AliasCmds()[i]); } PutModule("End of actions for alias " + info_alias.GetName() + "."); - } - else PutModule("Alias does not exist."); + } else + PutModule("Alias does not exist."); } - MODCONSTRUCTOR(CAliasMod), - sending_lines(false) - { + MODCONSTRUCTOR(CAliasMod), sending_lines(false) { AddHelpCommand(); - AddCommand("Create", static_cast(&CAliasMod::CreateCommand), "", "Creates a new, blank alias called name."); - AddCommand("Delete", static_cast(&CAliasMod::DeleteCommand), "", "Deletes an existing alias."); - AddCommand("Add", static_cast(&CAliasMod::AddCmd), " ", "Adds a line to an existing alias."); - AddCommand("Insert", static_cast(&CAliasMod::InsertCommand), " ", "Inserts a line into an existing alias."); - AddCommand("Remove", static_cast(&CAliasMod::RemoveCommand), " ", "Removes a line from an existing alias."); - AddCommand("Clear", static_cast(&CAliasMod::ClearCommand), "", "Removes all line from an existing alias."); - AddCommand("List", static_cast(&CAliasMod::ListCommand), "", "Lists all aliases by name."); - AddCommand("Info", static_cast(&CAliasMod::InfoCommand), "", "Reports the actions performed by an alias."); - AddCommand("Dump", static_cast(&CAliasMod::DumpCommand), "", "Generate a list of commands to copy your alias config."); - + AddCommand("Create", static_cast( + &CAliasMod::CreateCommand), + "", "Creates a new, blank alias called name."); + AddCommand("Delete", static_cast( + &CAliasMod::DeleteCommand), + "", "Deletes an existing alias."); + AddCommand("Add", + static_cast(&CAliasMod::AddCmd), + " ", "Adds a line to an existing alias."); + AddCommand("Insert", static_cast( + &CAliasMod::InsertCommand), + " ", + "Inserts a line into an existing alias."); + AddCommand("Remove", static_cast( + &CAliasMod::RemoveCommand), + " ", "Removes a line from an existing alias."); + AddCommand("Clear", static_cast( + &CAliasMod::ClearCommand), + "", "Removes all line from an existing alias."); + AddCommand("List", static_cast( + &CAliasMod::ListCommand), + "", "Lists all aliases by name."); + AddCommand("Info", static_cast( + &CAliasMod::InfoCommand), + "", "Reports the actions performed by an alias."); + AddCommand( + "Dump", + static_cast(&CAliasMod::DumpCommand), "", + "Generate a list of commands to copy your alias config."); } - EModRet OnUserRaw(CString& sLine) override - { + EModRet OnUserRaw(CString& sLine) override { CAlias current_alias; if (sending_lines) return CONTINUE; - try - { - if (sLine.Equals("ZNC-CLEAR-ALL-ALIASES!")) - { + try { + if (sLine.Equals("ZNC-CLEAR-ALL-ALIASES!")) { ListCommand(""); PutModule("Clearing all of them!"); ClearNV(); return HALT; - } - else if (CAlias::AliasGet(current_alias, this, sLine)) - { + } else if (CAlias::AliasGet(current_alias, this, sLine)) { VCString rawLines; current_alias.Imprint(sLine).Split("\n", rawLines, false); sending_lines = true; @@ -357,12 +377,13 @@ public: sending_lines = false; return HALT; } - } - catch (std::exception &e) - { - CString my_nick = (GetNetwork() == nullptr ? "" : GetNetwork()->GetCurNick()); + } catch (std::exception& e) { + CString my_nick = + (GetNetwork() == nullptr ? "" : GetNetwork()->GetCurNick()); if (my_nick.empty()) my_nick = "*"; - PutUser(CString(":znc.in 461 " + my_nick + " " + current_alias.GetName() + " :ZNC alias error: ") + e.what()); + PutUser(CString(":znc.in 461 " + my_nick + " " + + current_alias.GetName() + " :ZNC alias error: ") + + e.what()); return HALTCORE; } @@ -370,10 +391,10 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("alias"); Info.AddType(CModInfo::NetworkModule); } USERMODULEDEFS(CAliasMod, "Provides bouncer-side command alias support.") - diff --git a/modules/autoattach.cpp b/modules/autoattach.cpp index fd6f055d..871f4003 100644 --- a/modules/autoattach.cpp +++ b/modules/autoattach.cpp @@ -20,53 +20,44 @@ using std::vector; class CAttachMatch { -public: - CAttachMatch(CModule *pModule, const CString& sChannels, const CString& sSearch, const CString& sHostmasks, bool bNegated) - { + public: + CAttachMatch(CModule* pModule, const CString& sChannels, + const CString& sSearch, const CString& sHostmasks, + bool bNegated) { m_pModule = pModule; m_sChannelWildcard = sChannels; m_sSearchWildcard = sSearch; m_sHostmaskWildcard = sHostmasks; m_bNegated = bNegated; - if (m_sChannelWildcard.empty()) - m_sChannelWildcard = "*"; - if (m_sSearchWildcard.empty()) - m_sSearchWildcard = "*"; - if (m_sHostmaskWildcard.empty()) - m_sHostmaskWildcard = "*!*@*"; + if (m_sChannelWildcard.empty()) m_sChannelWildcard = "*"; + if (m_sSearchWildcard.empty()) m_sSearchWildcard = "*"; + if (m_sHostmaskWildcard.empty()) m_sHostmaskWildcard = "*!*@*"; } - bool IsMatch(const CString& sChan, const CString& sHost, const CString& sMessage) const { + bool IsMatch(const CString& sChan, const CString& sHost, + const CString& sMessage) const { if (!sHost.WildCmp(m_sHostmaskWildcard, CString::CaseInsensitive)) return false; if (!sChan.WildCmp(m_sChannelWildcard, CString::CaseInsensitive)) return false; - if (!sMessage.WildCmp(m_pModule->ExpandString(m_sSearchWildcard), CString::CaseInsensitive)) + if (!sMessage.WildCmp(m_pModule->ExpandString(m_sSearchWildcard), + CString::CaseInsensitive)) return false; return true; } - bool IsNegated() const { - return m_bNegated; - } + bool IsNegated() const { return m_bNegated; } - const CString& GetHostMask() const { - return m_sHostmaskWildcard; - } + const CString& GetHostMask() const { return m_sHostmaskWildcard; } - const CString& GetSearch() const { - return m_sSearchWildcard; - } + const CString& GetSearch() const { return m_sSearchWildcard; } - const CString& GetChans() const { - return m_sChannelWildcard; - } + const CString& GetChans() const { return m_sChannelWildcard; } CString ToString() { CString sRes; - if (m_bNegated) - sRes += "!"; + if (m_bNegated) sRes += "!"; sRes += m_sChannelWildcard; sRes += " "; sRes += m_sSearchWildcard; @@ -75,20 +66,20 @@ public: return sRes; } -private: + private: bool m_bNegated; - CModule *m_pModule; + CModule* m_pModule; CString m_sChannelWildcard; CString m_sSearchWildcard; CString m_sHostmaskWildcard; }; class CChanAttach : public CModule { -public: + public: typedef vector VAttachMatch; typedef VAttachMatch::iterator VAttachIter; -private: + private: void HandleAdd(const CString& sLine) { CString sMsg = sLine.Token(1, true); bool bHelp = false; @@ -112,7 +103,7 @@ private: } void HandleDel(const CString& sLine) { - CString sMsg = sLine.Token(1, true); + CString sMsg = sLine.Token(1, true); bool bNegated = sMsg.TrimPrefix("!"); CString sChan = sMsg.Token(0); CString sSearch = sMsg.Token(1); @@ -148,25 +139,30 @@ private: } } -public: + public: MODCONSTRUCTOR(CChanAttach) { AddHelpCommand(); - AddCommand("Add", static_cast(&CChanAttach::HandleAdd), - "[!]<#chan> ", "Add an entry, use !#chan to negate and * for wildcards"); - AddCommand("Del", static_cast(&CChanAttach::HandleDel), - "[!]<#chan> ", "Remove an entry, needs to be an exact match"); - AddCommand("List", static_cast(&CChanAttach::HandleList), - "", "List all entries"); + AddCommand("Add", static_cast( + &CChanAttach::HandleAdd), + "[!]<#chan> ", + "Add an entry, use !#chan to negate and * for wildcards"); + AddCommand("Del", static_cast( + &CChanAttach::HandleDel), + "[!]<#chan> ", + "Remove an entry, needs to be an exact match"); + AddCommand("List", static_cast( + &CChanAttach::HandleList), + "", "List all entries"); } - virtual ~CChanAttach() { - } + virtual ~CChanAttach() {} bool OnLoad(const CString& sArgs, CString& sMessage) override { VCString vsChans; sArgs.Split(" ", vsChans, false); - for (VCString::const_iterator it = vsChans.begin(); it != vsChans.end(); ++it) { + for (VCString::const_iterator it = vsChans.begin(); it != vsChans.end(); + ++it) { CString sAdd = *it; bool bNegated = sAdd.TrimPrefix("!"); CString sChan = sAdd.Token(0); @@ -199,13 +195,11 @@ public: const CString& sMessage = Message; VAttachIter it; - if (!Channel.IsDetached()) - return; + if (!Channel.IsDetached()) return; // Any negated match? for (it = m_vMatches.begin(); it != m_vMatches.end(); ++it) { - if (it->IsNegated() && it->IsMatch(sChan, sHost, sMessage)) - return; + if (it->IsNegated() && it->IsMatch(sChan, sHost, sMessage)) return; } // Now check for a positive match @@ -217,7 +211,8 @@ public: } } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { TryAttach(Nick, Channel, sMessage); return CONTINUE; } @@ -227,34 +222,34 @@ public: return CONTINUE; } - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override { TryAttach(Nick, Channel, sMessage); return CONTINUE; } - VAttachIter FindEntry(const CString& sChan, const CString& sSearch, const CString& sHost) { + VAttachIter FindEntry(const CString& sChan, const CString& sSearch, + const CString& sHost) { VAttachIter it = m_vMatches.begin(); for (; it != m_vMatches.end(); ++it) { - if (sHost.empty() || it->GetHostMask() != sHost) - continue; - if (sSearch.empty() || it->GetSearch() != sSearch) - continue; - if (sChan.empty() || it->GetChans() != sChan) - continue; + if (sHost.empty() || it->GetHostMask() != sHost) continue; + if (sSearch.empty() || it->GetSearch() != sSearch) continue; + if (sChan.empty() || it->GetChans() != sChan) continue; return it; } return m_vMatches.end(); } - bool Add(bool bNegated, const CString& sChan, const CString& sSearch, const CString& sHost) { + bool Add(bool bNegated, const CString& sChan, const CString& sSearch, + const CString& sHost) { CAttachMatch attach(this, sChan, sSearch, sHost, bNegated); // Check for duplicates VAttachIter it = m_vMatches.begin(); for (; it != m_vMatches.end(); ++it) { - if (it->GetHostMask() == attach.GetHostMask() - && it->GetChans() == attach.GetChans() - && it->GetSearch() == attach.GetSearch()) + if (it->GetHostMask() == attach.GetHostMask() && + it->GetChans() == attach.GetChans() && + it->GetSearch() == attach.GetSearch()) return false; } @@ -266,25 +261,28 @@ public: return true; } - bool Del(bool bNegated, const CString& sChan, const CString& sSearch, const CString& sHost) { + bool Del(bool bNegated, const CString& sChan, const CString& sSearch, + const CString& sHost) { VAttachIter it = FindEntry(sChan, sSearch, sHost); - if (it == m_vMatches.end() || it->IsNegated() != bNegated) - return false; + if (it == m_vMatches.end() || it->IsNegated() != bNegated) return false; DelNV(it->ToString()); m_vMatches.erase(it); return true; } -private: + + private: VAttachMatch m_vMatches; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("autoattach"); Info.SetHasArgs(true); - Info.SetArgsHelpText("List of channel masks and channel masks with ! before them."); + Info.SetArgsHelpText( + "List of channel masks and channel masks with ! before them."); } NETWORKMODULEDEFS(CChanAttach, "Reattaches you to channels on activity.") diff --git a/modules/autocycle.cpp b/modules/autocycle.cpp index ae67f09b..e2f88fa1 100644 --- a/modules/autocycle.cpp +++ b/modules/autocycle.cpp @@ -20,12 +20,19 @@ using std::vector; class CAutoCycleMod : public CModule { -public: + public: MODCONSTRUCTOR(CAutoCycleMod) { AddHelpCommand(); - AddCommand("Add", static_cast(&CAutoCycleMod::OnAddCommand), "[!]<#chan>", "Add an entry, use !#chan to negate and * for wildcards"); - AddCommand("Del", static_cast(&CAutoCycleMod::OnDelCommand), "[!]<#chan>", "Remove an entry, needs to be an exact match"); - AddCommand("List", static_cast(&CAutoCycleMod::OnListCommand), "", "List all entries"); + AddCommand("Add", static_cast( + &CAutoCycleMod::OnAddCommand), + "[!]<#chan>", + "Add an entry, use !#chan to negate and * for wildcards"); + AddCommand("Del", static_cast( + &CAutoCycleMod::OnDelCommand), + "[!]<#chan>", "Remove an entry, needs to be an exact match"); + AddCommand("List", static_cast( + &CAutoCycleMod::OnListCommand), + "", "List all entries"); m_recentlyCycled.SetTTL(15 * 1000); } @@ -48,8 +55,7 @@ public: } // Default is auto cycle for all channels - if (m_vsChans.empty()) - Add("*"); + if (m_vsChans.empty()) Add("*"); return true; } @@ -96,35 +102,35 @@ public: } } - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override { + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override { AutoCycle(Channel); } - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override { - for (CChan* pChan : vChans) - AutoCycle(*pChan); + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override { + for (CChan* pChan : vChans) AutoCycle(*pChan); } - void OnKick(const CNick& Nick, const CString& sOpNick, CChan& Channel, const CString& sMessage) override { + void OnKick(const CNick& Nick, const CString& sOpNick, CChan& Channel, + const CString& sMessage) override { AutoCycle(Channel); } -protected: + protected: void AutoCycle(CChan& Channel) { - if (!IsAutoCycle(Channel.GetName())) - return; + if (!IsAutoCycle(Channel.GetName())) return; // Did we recently annoy opers via cycling of an empty channel? - if (m_recentlyCycled.HasItem(Channel.GetName())) - return; + if (m_recentlyCycled.HasItem(Channel.GetName())) return; // Is there only one person left in the channel? - if (Channel.GetNickCount() != 1) - return; + if (Channel.GetNickCount() != 1) return; // Is that person us and we don't have op? const CNick& pNick = Channel.GetNicks().begin()->second; - if (!pNick.HasPerm(CChan::Op) && pNick.NickEquals(GetNetwork()->GetCurNick())) { + if (!pNick.HasPerm(CChan::Op) && + pNick.NickEquals(GetNetwork()->GetCurNick())) { Channel.Cycle(); m_recentlyCycled.AddItem(Channel.GetName()); } @@ -134,13 +140,11 @@ protected: CString sChan = sInput; if (sChan.TrimPrefix("!")) { for (const CString& s : m_vsNegChans) { - if (s.Equals(sChan)) - return true; + if (s.Equals(sChan)) return true; } } else { for (const CString& s : m_vsChans) { - if (s.Equals(sChan)) - return true; + if (s.Equals(sChan)) return true; } } return false; @@ -166,8 +170,7 @@ protected: bool Del(const CString& sChan) { vector::iterator it, end; - if (sChan.empty() || sChan == "!") - return false; + if (sChan.empty() || sChan == "!") return false; if (sChan.Left(1) == "!") { CString sTmp = sChan.substr(1); @@ -175,11 +178,9 @@ protected: end = m_vsNegChans.end(); for (; it != end; ++it) - if (*it == sTmp) - break; + if (*it == sTmp) break; - if (it == end) - return false; + if (it == end) return false; m_vsNegChans.erase(it); } else { @@ -187,11 +188,9 @@ protected: end = m_vsChans.end(); for (; it != end; ++it) - if (*it == sChan) - break; + if (*it == sChan) break; - if (it == end) - return false; + if (it == end) return false; m_vsChans.erase(it); } @@ -217,16 +216,19 @@ protected: return false; } -private: + private: vector m_vsChans; vector m_vsNegChans; TCacheMap m_recentlyCycled; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("autocycle"); Info.SetHasArgs(true); - Info.SetArgsHelpText("List of channel masks and channel masks with ! before them."); + Info.SetArgsHelpText( + "List of channel masks and channel masks with ! before them."); } -NETWORKMODULEDEFS(CAutoCycleMod, "Rejoins channels to gain Op if you're the only user left") +NETWORKMODULEDEFS(CAutoCycleMod, + "Rejoins channels to gain Op if you're the only user left") diff --git a/modules/autoop.cpp b/modules/autoop.cpp index 88c978f2..61611465 100644 --- a/modules/autoop.cpp +++ b/modules/autoop.cpp @@ -26,33 +26,31 @@ class CAutoOpMod; #define AUTOOP_CHALLENGE_LENGTH 32 class CAutoOpTimer : public CTimer { -public: - + public: CAutoOpTimer(CAutoOpMod* pModule) - : CTimer((CModule*) pModule, 20, 0, "AutoOpChecker", "Check channels for auto op candidates") { + : CTimer((CModule*)pModule, 20, 0, "AutoOpChecker", + "Check channels for auto op candidates") { m_pParent = pModule; } virtual ~CAutoOpTimer() {} -private: -protected: + private: + protected: void RunJob() override; CAutoOpMod* m_pParent; }; class CAutoOpUser { -public: + public: CAutoOpUser() {} - CAutoOpUser(const CString& sLine) { - FromString(sLine); - } + CAutoOpUser(const CString& sLine) { FromString(sLine); } - CAutoOpUser(const CString& sUsername, const CString& sUserKey, const CString& sHostmasks, const CString& sChannels) : - m_sUsername(sUsername), - m_sUserKey(sUserKey) { + CAutoOpUser(const CString& sUsername, const CString& sUserKey, + const CString& sHostmasks, const CString& sChannels) + : m_sUsername(sUsername), m_sUserKey(sUserKey) { AddHostmasks(sHostmasks); AddChans(sChannels); } @@ -128,7 +126,8 @@ public: } CString ToString() const { - return m_sUsername + "\t" + GetHostmasks() + "\t" + m_sUserKey + "\t" + GetChannels(); + return m_sUsername + "\t" + GetHostmasks() + "\t" + m_sUserKey + "\t" + + GetChannels(); } bool FromString(const CString& sLine) { @@ -139,25 +138,42 @@ public: return !m_sUserKey.empty(); } -private: -protected: - CString m_sUsername; - CString m_sUserKey; + + private: + protected: + CString m_sUsername; + CString m_sUserKey; set m_ssHostmasks; set m_ssChans; }; class CAutoOpMod : public CModule { -public: + public: MODCONSTRUCTOR(CAutoOpMod) { AddHelpCommand(); - AddCommand("ListUsers", static_cast(&CAutoOpMod::OnListUsersCommand), "", "List all users"); - AddCommand("AddChans", static_cast(&CAutoOpMod::OnAddChansCommand), " [channel] ...", "Adds channels to a user"); - AddCommand("DelChans", static_cast(&CAutoOpMod::OnDelChansCommand), " [channel] ...", "Removes channels from a user"); - AddCommand("AddMasks", static_cast(&CAutoOpMod::OnAddMasksCommand), " ,[mask] ...", "Adds masks to a user"); - AddCommand("DelMasks", static_cast(&CAutoOpMod::OnDelMasksCommand), " ,[mask] ...", "Removes masks from a user"); - AddCommand("AddUser", static_cast(&CAutoOpMod::OnAddUserCommand), " [,...] [channels]", "Adds a user"); - AddCommand("DelUser", static_cast(&CAutoOpMod::OnDelUserCommand), "", "Removes a user"); + AddCommand("ListUsers", static_cast( + &CAutoOpMod::OnListUsersCommand), + "", "List all users"); + AddCommand("AddChans", static_cast( + &CAutoOpMod::OnAddChansCommand), + " [channel] ...", "Adds channels to a user"); + AddCommand("DelChans", static_cast( + &CAutoOpMod::OnDelChansCommand), + " [channel] ...", + "Removes channels from a user"); + AddCommand("AddMasks", static_cast( + &CAutoOpMod::OnAddMasksCommand), + " ,[mask] ...", "Adds masks to a user"); + AddCommand("DelMasks", static_cast( + &CAutoOpMod::OnDelMasksCommand), + " ,[mask] ...", "Removes masks from a user"); + AddCommand("AddUser", static_cast( + &CAutoOpMod::OnAddUserCommand), + " [,...] [channels]", + "Adds a user"); + AddCommand("DelUser", static_cast( + &CAutoOpMod::OnDelUserCommand), + "", "Removes a user"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { @@ -168,7 +184,8 @@ public: const CString& sLine = it->second; CAutoOpUser* pUser = new CAutoOpUser; - if (!pUser->FromString(sLine) || FindUser(pUser->GetUsername().AsLower())) { + if (!pUser->FromString(sLine) || + FindUser(pUser->GetUsername().AsLower())) { delete pUser; } else { m_msUsers[pUser->GetUsername().AsLower()] = pUser; @@ -192,7 +209,8 @@ public: } } - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override { + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override { MCString::iterator it = m_msQueue.find(Nick.GetNick().AsLower()); if (it != m_msQueue.end()) { @@ -200,7 +218,8 @@ public: } } - void OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) override { + void OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) override { // Update the queue with nick changes MCString::iterator it = m_msQueue.find(OldNick.GetNick().AsLower()); @@ -226,9 +245,10 @@ public: return HALTCORE; } - void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { + void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { if (Nick.GetNick() == GetNetwork()->GetIRCNick().GetNick()) { - const map& msNicks = Channel.GetNicks(); + const map& msNicks = Channel.GetNicks(); for (const auto& it : msNicks) { if (!it.second.HasPerm(CChan::Op)) { @@ -254,9 +274,12 @@ public: CString sKey = sLine.Token(3); if (sHost.empty()) { - PutModule("Usage: AddUser [,...] [channels]"); + PutModule( + "Usage: AddUser [,...] " + "[channels]"); } else { - CAutoOpUser* pUser = AddUser(sUser, sKey, sHost, sLine.Token(4, true)); + CAutoOpUser* pUser = + AddUser(sUser, sKey, sHost, sLine.Token(4, true)); if (pUser) { SetNV(sUser, pUser->ToString()); @@ -297,7 +320,7 @@ public: Table.SetCell("User", it.second->GetUsername()); Table.SetCell("Key", it.second->GetUserKey()); Table.SetCell("Channels", it.second->GetChannels()); - } else if (a == vsHostmasks.size()-1) { + } else if (a == vsHostmasks.size() - 1) { Table.SetCell("User", "`-"); } else { Table.SetCell("User", "|-"); @@ -347,7 +370,8 @@ public: } pUser->DelChans(sChans); - PutModule("Channel(s) Removed from user [" + pUser->GetUsername() + "]"); + PutModule("Channel(s) Removed from user [" + pUser->GetUsername() + + "]"); SetNV(pUser->GetUsername(), pUser->ToString()); } @@ -389,26 +413,32 @@ public: } if (pUser->DelHostmasks(sHostmasks)) { - PutModule("Removed user [" + pUser->GetUsername() + "] with key [" + pUser->GetUserKey() + "] and channels [" + pUser->GetChannels() + "]"); + PutModule("Removed user [" + pUser->GetUsername() + "] with key [" + + pUser->GetUserKey() + "] and channels [" + + pUser->GetChannels() + "]"); DelUser(sUser); DelNV(sUser); } else { - PutModule("Hostmasks(s) Removed from user [" + pUser->GetUsername() + "]"); + PutModule("Hostmasks(s) Removed from user [" + + pUser->GetUsername() + "]"); SetNV(pUser->GetUsername(), pUser->ToString()); } } CAutoOpUser* FindUser(const CString& sUser) { - map::iterator it = m_msUsers.find(sUser.AsLower()); + map::iterator it = + m_msUsers.find(sUser.AsLower()); return (it != m_msUsers.end()) ? it->second : nullptr; } - CAutoOpUser* FindUserByHost(const CString& sHostmask, const CString& sChannel = "") { + CAutoOpUser* FindUserByHost(const CString& sHostmask, + const CString& sChannel = "") { for (const auto& it : m_msUsers) { CAutoOpUser* pUser = it.second; - if (pUser->HostMatches(sHostmask) && (sChannel.empty() || pUser->ChannelMatches(sChannel))) { + if (pUser->HostMatches(sHostmask) && + (sChannel.empty() || pUser->ChannelMatches(sChannel))) { return pUser; } } @@ -417,7 +447,8 @@ public: } bool CheckAutoOp(const CNick& Nick, CChan& Channel) { - CAutoOpUser *pUser = FindUserByHost(Nick.GetHostMask(), Channel.GetName()); + CAutoOpUser* pUser = + FindUserByHost(Nick.GetHostMask(), Channel.GetName()); if (!pUser) { return false; @@ -437,7 +468,8 @@ public: } void DelUser(const CString& sUser) { - map::iterator it = m_msUsers.find(sUser.AsLower()); + map::iterator it = + m_msUsers.find(sUser.AsLower()); if (it == m_msUsers.end()) { PutModule("That user does not exist"); @@ -449,7 +481,8 @@ public: PutModule("User [" + sUser + "] removed"); } - CAutoOpUser* AddUser(const CString& sUser, const CString& sKey, const CString& sHosts, const CString& sChans) { + CAutoOpUser* AddUser(const CString& sUser, const CString& sKey, + const CString& sHosts, const CString& sChans) { if (m_msUsers.find(sUser) != m_msUsers.end()) { PutModule("That user already exists"); return nullptr; @@ -457,7 +490,8 @@ public: CAutoOpUser* pUser = new CAutoOpUser(sUser, sKey, sHosts, sChans); m_msUsers[sUser.AsLower()] = pUser; - PutModule("User [" + sUser + "] added with hostmask(s) [" + sHosts + "]"); + PutModule("User [" + sUser + "] added with hostmask(s) [" + sHosts + + "]"); return pUser; } @@ -470,17 +504,20 @@ public: for (const auto& it : m_msUsers) { pUser = it.second; - // First verify that the person who challenged us matches a user's host + // First verify that the person who challenged us matches a user's + // host if (pUser->HostMatches(Nick.GetHostMask())) { const vector& Chans = GetNetwork()->GetChans(); bMatchedHost = true; - // Also verify that they are opped in at least one of the user's chans + // Also verify that they are opped in at least one of the user's + // chans for (CChan* pChan : Chans) { const CNick* pNick = pChan->FindNick(Nick.GetNick()); if (pNick) { - if (pNick->HasPerm(CChan::Op) && pUser->ChannelMatches(pChan->GetName())) { + if (pNick->HasPerm(CChan::Op) && + pUser->ChannelMatches(pChan->GetName())) { bValid = true; break; } @@ -495,21 +532,27 @@ public: if (!bValid) { if (bMatchedHost) { - PutModule("[" + Nick.GetHostMask() + "] sent us a challenge but they are not opped in any defined channels."); + PutModule("[" + Nick.GetHostMask() + + "] sent us a challenge but they are not opped in any " + "defined channels."); } else { - PutModule("[" + Nick.GetHostMask() + "] sent us a challenge but they do not match a defined user."); + PutModule("[" + Nick.GetHostMask() + + "] sent us a challenge but they do not match a " + "defined user."); } return false; } if (sChallenge.length() != AUTOOP_CHALLENGE_LENGTH) { - PutModule("WARNING! [" + Nick.GetHostMask() + "] sent an invalid challenge."); + PutModule("WARNING! [" + Nick.GetHostMask() + + "] sent an invalid challenge."); return false; } CString sResponse = pUser->GetUserKey() + "::" + sChallenge; - PutIRC("NOTICE " + Nick.GetNick() + " :!ZNCAO RESPONSE " + sResponse.MD5()); + PutIRC("NOTICE " + Nick.GetNick() + " :!ZNCAO RESPONSE " + + sResponse.MD5()); return false; } @@ -517,7 +560,9 @@ public: MCString::iterator itQueue = m_msQueue.find(Nick.GetNick().AsLower()); if (itQueue == m_msQueue.end()) { - PutModule("[" + Nick.GetHostMask() + "] sent an unchallenged response. This could be due to lag."); + PutModule( + "[" + Nick.GetHostMask() + + "] sent an unchallenged response. This could be due to lag."); return false; } @@ -526,17 +571,22 @@ public: for (const auto& it : m_msUsers) { if (it.second->HostMatches(Nick.GetHostMask())) { - if (sResponse == CString(it.second->GetUserKey() + "::" + sChallenge).MD5()) { + if (sResponse == + CString(it.second->GetUserKey() + "::" + sChallenge) + .MD5()) { OpUser(Nick, *it.second); return true; } else { - PutModule("WARNING! [" + Nick.GetHostMask() + "] sent a bad response. Please verify that you have their correct password."); + PutModule("WARNING! [" + Nick.GetHostMask() + + "] sent a bad response. Please verify that you " + "have their correct password."); return false; } } } - PutModule("WARNING! [" + Nick.GetHostMask() + "] sent a response but did not match any defined users."); + PutModule("WARNING! [" + Nick.GetHostMask() + + "] sent a response but did not match any defined users."); return false; } @@ -548,7 +598,8 @@ public: while (bRemoved) { bRemoved = false; - for (MCString::iterator it = m_msQueue.begin(); it != m_msQueue.end(); ++it) { + for (MCString::iterator it = m_msQueue.begin(); + it != m_msQueue.end(); ++it) { if (!it->second.empty()) { m_msQueue.erase(it); bRemoved = true; @@ -568,25 +619,27 @@ public: const vector& Chans = GetNetwork()->GetChans(); for (CChan* pChan : Chans) { - if (pChan->HasPerm(CChan::Op) && User.ChannelMatches(pChan->GetName())) { + if (pChan->HasPerm(CChan::Op) && + User.ChannelMatches(pChan->GetName())) { const CNick* pNick = pChan->FindNick(Nick.GetNick()); if (pNick && !pNick->HasPerm(CChan::Op)) { - PutIRC("MODE " + pChan->GetName() + " +o " + Nick.GetNick()); + PutIRC("MODE " + pChan->GetName() + " +o " + + Nick.GetNick()); } } } } -private: + + private: map m_msUsers; - MCString m_msQueue; + MCString m_msQueue; }; -void CAutoOpTimer::RunJob() { - m_pParent->ProcessQueue(); -} +void CAutoOpTimer::RunJob() { m_pParent->ProcessQueue(); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("autoop"); } diff --git a/modules/autoreply.cpp b/modules/autoreply.cpp index e869ceae..33fcaa8e 100644 --- a/modules/autoreply.cpp +++ b/modules/autoreply.cpp @@ -19,11 +19,15 @@ #include class CAutoReplyMod : public CModule { -public: + public: MODCONSTRUCTOR(CAutoReplyMod) { AddHelpCommand(); - AddCommand("Set", static_cast(&CAutoReplyMod::OnSetCommand), "", "Sets a new reply"); - AddCommand("Show", static_cast(&CAutoReplyMod::OnShowCommand), "", "Displays the current query reply"); + AddCommand("Set", static_cast( + &CAutoReplyMod::OnSetCommand), + "", "Sets a new reply"); + AddCommand("Show", static_cast( + &CAutoReplyMod::OnShowCommand), + "", "Displays the current query reply"); m_Messaged.SetTTL(1000 * 120); } @@ -37,9 +41,7 @@ public: return true; } - void SetReply(const CString& sReply) { - SetNV("Reply", sReply); - } + void SetReply(const CString& sReply) { SetNV("Reply", sReply); } CString GetReply() { CString sReply = GetNV("Reply"); @@ -52,17 +54,14 @@ public: } void Handle(const CString& sNick) { - CIRCSock *pIRCSock = GetNetwork()->GetIRCSock(); + CIRCSock* pIRCSock = GetNetwork()->GetIRCSock(); if (!pIRCSock) // WTF? return; - if (sNick == pIRCSock->GetNick()) - return; - if (m_Messaged.HasItem(sNick)) - return; + if (sNick == pIRCSock->GetNick()) return; + if (m_Messaged.HasItem(sNick)) return; - if (GetNetwork()->IsUserAttached()) - return; + if (GetNetwork()->IsUserAttached()) return; m_Messaged.AddItem(sNick); PutIRC("NOTICE " + sNick + " :" + GetReply()); @@ -74,8 +73,8 @@ public: } void OnShowCommand(const CString& sCommand) { - PutModule("Current reply is: " + GetNV("Reply") - + " (" + GetReply() + ")"); + PutModule("Current reply is: " + GetNV("Reply") + " (" + GetReply() + + ")"); } void OnSetCommand(const CString& sCommand) { @@ -83,16 +82,18 @@ public: PutModule("New reply set"); } -private: + private: TCacheMap m_Messaged; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("autoreply"); Info.AddType(CModInfo::NetworkModule); Info.SetHasArgs(true); - Info.SetArgsHelpText("You might specify a reply text. It is used when automatically answering queries, if you are not connected to ZNC."); + Info.SetArgsHelpText( + "You might specify a reply text. It is used when automatically " + "answering queries, if you are not connected to ZNC."); } USERMODULEDEFS(CAutoReplyMod, "Reply to queries when you are away") - diff --git a/modules/autovoice.cpp b/modules/autovoice.cpp index a7dc1576..32025ae2 100644 --- a/modules/autovoice.cpp +++ b/modules/autovoice.cpp @@ -22,16 +22,14 @@ using std::map; using std::set; class CAutoVoiceUser { -public: + public: CAutoVoiceUser() {} - CAutoVoiceUser(const CString& sLine) { - FromString(sLine); - } + CAutoVoiceUser(const CString& sLine) { FromString(sLine); } - CAutoVoiceUser(const CString& sUsername, const CString& sHostmask, const CString& sChannels) : - m_sUsername(sUsername), - m_sHostmask(sHostmask) { + CAutoVoiceUser(const CString& sUsername, const CString& sHostmask, + const CString& sChannels) + : m_sUsername(sUsername), m_sHostmask(sHostmask) { AddChans(sChannels); } @@ -107,22 +105,34 @@ public: return !m_sHostmask.empty(); } -private: -protected: - CString m_sUsername; - CString m_sHostmask; + + private: + protected: + CString m_sUsername; + CString m_sHostmask; set m_ssChans; }; class CAutoVoiceMod : public CModule { -public: + public: MODCONSTRUCTOR(CAutoVoiceMod) { AddHelpCommand(); - AddCommand("ListUsers", static_cast(&CAutoVoiceMod::OnListUsersCommand), "", "List all users"); - AddCommand("AddChans", static_cast(&CAutoVoiceMod::OnAddChansCommand), " [channel] ...", "Adds channels to a user"); - AddCommand("DelChans", static_cast(&CAutoVoiceMod::OnDelChansCommand), " [channel] ...", "Removes channels from a user"); - AddCommand("AddUser", static_cast(&CAutoVoiceMod::OnAddUserCommand), " [channels]", "Adds a user"); - AddCommand("DelUser", static_cast(&CAutoVoiceMod::OnDelUserCommand), "", "Removes a user"); + AddCommand("ListUsers", static_cast( + &CAutoVoiceMod::OnListUsersCommand), + "", "List all users"); + AddCommand("AddChans", static_cast( + &CAutoVoiceMod::OnAddChansCommand), + " [channel] ...", "Adds channels to a user"); + AddCommand("DelChans", static_cast( + &CAutoVoiceMod::OnDelChansCommand), + " [channel] ...", + "Removes channels from a user"); + AddCommand("AddUser", static_cast( + &CAutoVoiceMod::OnAddUserCommand), + " [channels]", "Adds a user"); + AddCommand("DelUser", static_cast( + &CAutoVoiceMod::OnDelUserCommand), + "", "Removes a user"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { @@ -142,7 +152,8 @@ public: const CString& sLine = it->second; CAutoVoiceUser* pUser = new CAutoVoiceUser; - if (!pUser->FromString(sLine) || FindUser(pUser->GetUsername().AsLower())) { + if (!pUser->FromString(sLine) || + FindUser(pUser->GetUsername().AsLower())) { delete pUser; } else { m_msUsers[pUser->GetUsername().AsLower()] = pUser; @@ -165,17 +176,20 @@ public: if (Channel.HasPerm(CChan::Op) || Channel.HasPerm(CChan::HalfOp)) { for (const auto& it : m_msUsers) { // and the nick who joined is a valid user - if (it.second->HostMatches(Nick.GetHostMask()) && it.second->ChannelMatches(Channel.GetName())) { - PutIRC("MODE " + Channel.GetName() + " +v " + Nick.GetNick()); + if (it.second->HostMatches(Nick.GetHostMask()) && + it.second->ChannelMatches(Channel.GetName())) { + PutIRC("MODE " + Channel.GetName() + " +v " + + Nick.GetNick()); break; } } } } - void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { + void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { if (Nick.NickEquals(GetNetwork()->GetNick())) { - const map& msNicks = Channel.GetNicks(); + const map& msNicks = Channel.GetNicks(); for (const auto& it : msNicks) { if (!it.second.HasPerm(CChan::Voice)) { @@ -186,7 +200,8 @@ public: } bool CheckAutoVoice(const CNick& Nick, CChan& Channel) { - CAutoVoiceUser *pUser = FindUserByHost(Nick.GetHostMask(), Channel.GetName()); + CAutoVoiceUser* pUser = + FindUserByHost(Nick.GetHostMask(), Channel.GetName()); if (!pUser) { return false; } @@ -282,22 +297,26 @@ public: } pUser->DelChans(sChans); - PutModule("Channel(s) Removed from user [" + pUser->GetUsername() + "]"); + PutModule("Channel(s) Removed from user [" + pUser->GetUsername() + + "]"); SetNV(pUser->GetUsername(), pUser->ToString()); } CAutoVoiceUser* FindUser(const CString& sUser) { - map::iterator it = m_msUsers.find(sUser.AsLower()); + map::iterator it = + m_msUsers.find(sUser.AsLower()); return (it != m_msUsers.end()) ? it->second : nullptr; } - CAutoVoiceUser* FindUserByHost(const CString& sHostmask, const CString& sChannel = "") { + CAutoVoiceUser* FindUserByHost(const CString& sHostmask, + const CString& sChannel = "") { for (const auto& it : m_msUsers) { CAutoVoiceUser* pUser = it.second; - if (pUser->HostMatches(sHostmask) && (sChannel.empty() || pUser->ChannelMatches(sChannel))) { + if (pUser->HostMatches(sHostmask) && + (sChannel.empty() || pUser->ChannelMatches(sChannel))) { return pUser; } } @@ -306,7 +325,8 @@ public: } void DelUser(const CString& sUser) { - map::iterator it = m_msUsers.find(sUser.AsLower()); + map::iterator it = + m_msUsers.find(sUser.AsLower()); if (it == m_msUsers.end()) { PutModule("That user does not exist"); @@ -318,7 +338,8 @@ public: PutModule("User [" + sUser + "] removed"); } - CAutoVoiceUser* AddUser(const CString& sUser, const CString& sHost, const CString& sChans) { + CAutoVoiceUser* AddUser(const CString& sUser, const CString& sHost, + const CString& sChans) { if (m_msUsers.find(sUser) != m_msUsers.end()) { PutModule("That user already exists"); return nullptr; @@ -330,14 +351,18 @@ public: return pUser; } -private: + private: map m_msUsers; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("autovoice"); Info.SetHasArgs(true); - Info.SetArgsHelpText("Each argument is either a channel you want autovoice for (which can include wildcards) or, if it starts with !, it is an exception for autovoice."); + Info.SetArgsHelpText( + "Each argument is either a channel you want autovoice for (which can " + "include wildcards) or, if it starts with !, it is an exception for " + "autovoice."); } NETWORKMODULEDEFS(CAutoVoiceMod, "Auto voice the good people") diff --git a/modules/awaynick.cpp b/modules/awaynick.cpp index 5eba2d91..e74331ae 100644 --- a/modules/awaynick.cpp +++ b/modules/awaynick.cpp @@ -17,7 +17,7 @@ #include class CAwayNickMod : public CModule { -public: + public: MODCONSTRUCTOR(CAwayNickMod) {} bool OnLoad(const CString&, CString& sMessage) override { @@ -26,8 +26,10 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("awaynick"); } -NETWORKMODULEDEFS(CAwayNickMod, "retired module - see http://wiki.znc.in/awaynick") +NETWORKMODULEDEFS(CAwayNickMod, + "retired module - see http://wiki.znc.in/awaynick") diff --git a/modules/awaystore.cpp b/modules/awaystore.cpp index a26cea1b..0cc1f5d7 100644 --- a/modules/awaystore.cpp +++ b/modules/awaystore.cpp @@ -18,9 +18,12 @@ /* * Quiet Away and message logger * - * I originally wrote this module for when I had multiple clients connected to ZNC. I would leave work and forget to close my client, arriving at home - * and re-attaching there someone may have messaged me in commute and I wouldn't know it until I would arrive back at work the next day. I wrote it such that - * my xchat client would monitor desktop activity and ping the module to let it know I was active. Within a few minutes of inactivity the pinging stops and + * I originally wrote this module for when I had multiple clients connected to + *ZNC. I would leave work and forget to close my client, arriving at home + * and re-attaching there someone may have messaged me in commute and I wouldn't + *know it until I would arrive back at work the next day. I wrote it such that + * my xchat client would monitor desktop activity and ping the module to let it + *know I was active. Within a few minutes of inactivity the pinging stops and * the away module sets the user as away and logging commences. */ @@ -40,30 +43,31 @@ using std::map; class CAway; -class CAwayJob : public CTimer -{ -public: - CAwayJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} +class CAwayJob : public CTimer { + public: + CAwayJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CAwayJob() {} -protected: + protected: void RunJob() override; }; -class CAway : public CModule -{ +class CAway : public CModule { void AwayCommand(const CString& sCommand) { CString sReason; time_t curtime; time(&curtime); if (sCommand.Token(1) != "-quiet") { - sReason = CUtils::FormatTime(curtime, sCommand.Token(1, true), GetUser()->GetTimezone()); + sReason = CUtils::FormatTime(curtime, sCommand.Token(1, true), + GetUser()->GetTimezone()); PutModNotice("You have been marked as away"); } else { - sReason = CUtils::FormatTime(curtime, sCommand.Token(2, true), GetUser()->GetTimezone()); + sReason = CUtils::FormatTime(curtime, sCommand.Token(2, true), + GetUser()->GetTimezone()); } Away(false, sReason); @@ -93,7 +97,8 @@ class CAway : public CModule void DeleteCommand(const CString& sCommand) { CString sWhich = sCommand.Token(1); if (sWhich == "all") { - PutModNotice("Deleted " + CString(m_vMessages.size()) + " Messages."); + PutModNotice("Deleted " + CString(m_vMessages.size()) + + " Messages."); for (u_int a = 0; a < m_vMessages.size(); a++) m_vMessages.erase(m_vMessages.begin() + a--); } else if (sWhich.empty()) { @@ -123,8 +128,7 @@ class CAway : public CModule void PingCommand(const CString& sCommand) { Ping(); - if (m_bIsAway) - Back(); + if (m_bIsAway) Back(); } void PassCommand(const CString& sCommand) { @@ -133,7 +137,7 @@ class CAway : public CModule } void ShowCommand(const CString& sCommand) { - map< CString, vector< CString> > msvOutput; + map> msvOutput; for (u_int a = 0; a < m_vMessages.size(); a++) { CString sTime = m_vMessages[a].Token(0, false); CString sWhom = m_vMessages[a].Token(1, false); @@ -165,7 +169,8 @@ class CAway : public CModule msvOutput[sWhom].push_back(sTmp); } - for (map< CString, vector< CString> >::iterator it = msvOutput.begin(); it != msvOutput.end(); ++it) { + for (map>::iterator it = msvOutput.begin(); + it != msvOutput.end(); ++it) { PutModule(it->first); for (u_int a = 0; a < it->second.size(); a++) PutModule(it->second[a]); @@ -196,84 +201,92 @@ class CAway : public CModule } void TimerCommand(const CString& sCommand) { - PutModule("Current timer setting: " + CString(GetAwayTime()) + " seconds"); + PutModule("Current timer setting: " + CString(GetAwayTime()) + + " seconds"); } -public: - MODCONSTRUCTOR(CAway) - { + public: + MODCONSTRUCTOR(CAway) { Ping(); m_bIsAway = false; m_bBootError = false; m_saveMessages = true; m_chanMessages = false; SetAwayTime(300); - AddTimer(new CAwayJob(this, 60, 0, "AwayJob", "Checks for idle and saves messages every 1 minute")); + AddTimer( + new CAwayJob(this, 60, 0, "AwayJob", + "Checks for idle and saves messages every 1 minute")); AddHelpCommand(); - AddCommand("Away", static_cast(&CAway::AwayCommand), - "[-quiet]"); - AddCommand("Back", static_cast(&CAway::BackCommand), - "[-quiet]"); - AddCommand("Messages", static_cast(&CAway::BackCommand)); - AddCommand("Delete", static_cast(&CAway::DeleteCommand), - "delete "); - AddCommand("Save", static_cast(&CAway::SaveCommand)); - AddCommand("Ping", static_cast(&CAway::PingCommand)); - AddCommand("Pass", static_cast(&CAway::PassCommand)); - AddCommand("Show", static_cast(&CAway::ShowCommand)); - AddCommand("Replay", static_cast(&CAway::ReplayCommand)); - AddCommand("EnableTimer", static_cast(&CAway::EnableTimerCommand)); - AddCommand("DisableTimer", static_cast(&CAway::DisableTimerCommand)); - AddCommand("SetTimer", static_cast(&CAway::SetTimerCommand), - ""); - AddCommand("Timer", static_cast(&CAway::TimerCommand)); - + AddCommand("Away", + static_cast(&CAway::AwayCommand), + "[-quiet]"); + AddCommand("Back", + static_cast(&CAway::BackCommand), + "[-quiet]"); + AddCommand("Messages", + static_cast(&CAway::BackCommand)); + AddCommand("Delete", + static_cast(&CAway::DeleteCommand), + "delete "); + AddCommand("Save", + static_cast(&CAway::SaveCommand)); + AddCommand("Ping", + static_cast(&CAway::PingCommand)); + AddCommand("Pass", + static_cast(&CAway::PassCommand)); + AddCommand("Show", + static_cast(&CAway::ShowCommand)); + AddCommand("Replay", + static_cast(&CAway::ReplayCommand)); + AddCommand("EnableTimer", static_cast( + &CAway::EnableTimerCommand)); + AddCommand("DisableTimer", static_cast( + &CAway::DisableTimerCommand)); + AddCommand("SetTimer", static_cast( + &CAway::SetTimerCommand), + ""); + AddCommand("Timer", + static_cast(&CAway::TimerCommand)); } - virtual ~CAway() - { - if (!m_bBootError) - SaveBufferToDisk(); + virtual ~CAway() { + if (!m_bBootError) SaveBufferToDisk(); } - bool OnLoad(const CString& sArgs, CString& sMessage) override - { + bool OnLoad(const CString& sArgs, CString& sMessage) override { CString sMyArgs = sArgs; size_t uIndex = 0; - if (sMyArgs.Token(0) == "-nostore") - { + if (sMyArgs.Token(0) == "-nostore") { uIndex++; m_saveMessages = false; } - if (sMyArgs.Token(uIndex) == "-chans") - { + if (sMyArgs.Token(uIndex) == "-chans") { uIndex++; m_chanMessages = true; } - if (sMyArgs.Token(uIndex) == "-notimer") - { + if (sMyArgs.Token(uIndex) == "-notimer") { SetAwayTime(0); sMyArgs = sMyArgs.Token(uIndex + 1, true); - } else if (sMyArgs.Token(uIndex) == "-timer") - { + } else if (sMyArgs.Token(uIndex) == "-timer") { SetAwayTime(sMyArgs.Token(uIndex + 1).ToInt()); sMyArgs = sMyArgs.Token(uIndex + 2, true); } - if (m_saveMessages) - { - if (!sMyArgs.empty()) - { + if (m_saveMessages) { + if (!sMyArgs.empty()) { m_sPassword = CBlowfish::MD5(sMyArgs); } else { - sMessage = "This module needs as an argument a keyphrase used for encryption"; + sMessage = + "This module needs as an argument a keyphrase used for " + "encryption"; return false; } - if (!BootStrap()) - { - sMessage = "Failed to decrypt your saved messages - " - "Did you give the right encryption key as an argument to this module?"; + if (!BootStrap()) { + sMessage = + "Failed to decrypt your saved messages - " + "Did you give the right encryption key as an argument to " + "this module?"; m_bBootError = true; return false; } @@ -282,19 +295,17 @@ public: return true; } - void OnIRCConnected() override - { + void OnIRCConnected() override { if (m_bIsAway) - Away(true); // reset away if we are reconnected + Away(true); // reset away if we are reconnected else - Back(); // ircd seems to remember your away if you killed the client and came back + Back(); // ircd seems to remember your away if you killed the + // client and came back } - bool BootStrap() - { + bool BootStrap() { CString sFile; - if (DecryptMessages(sFile)) - { + if (DecryptMessages(sFile)) { VCString vsLines; VCString::iterator it; @@ -307,17 +318,16 @@ public: } } else { m_sPassword = ""; - CUtils::PrintError("[" + GetModName() + ".so] Failed to Decrypt Messages"); - return(false); + CUtils::PrintError("[" + GetModName() + + ".so] Failed to Decrypt Messages"); + return (false); } - return(true); + return (true); } - void SaveBufferToDisk() - { - if (!m_sPassword.empty()) - { + void SaveBufferToDisk() { + if (!m_sPassword.empty()) { CString sFile = CRYPT_VERIFICATION_TOKEN; for (u_int b = 0; b < m_vMessages.size(); b++) @@ -326,8 +336,7 @@ public: CBlowfish c(m_sPassword, BF_ENCRYPT); sFile = c.Crypt(sFile); CString sPath = GetPath(); - if (!sPath.empty()) - { + if (!sPath.empty()) { CFile File(sPath); if (File.Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) { File.Chmod(0600); @@ -338,204 +347,178 @@ public: } } - void OnClientLogin() override - { - Back(true); - } - void OnClientDisconnect() override - { - Away(); - } + void OnClientLogin() override { Back(true); } + void OnClientDisconnect() override { Away(); } - CString GetPath() - { + CString GetPath() { CString sBuffer = GetUser()->GetUserName(); CString sRet = GetSavePath(); sRet += "/.znc-away-" + CBlowfish::MD5(sBuffer, true); - return(sRet); + return (sRet); } - void Away(bool bForce = false, const CString & sReason = "") - { - if ((!m_bIsAway) || (bForce)) - { + void Away(bool bForce = false, const CString& sReason = "") { + if ((!m_bIsAway) || (bForce)) { if (!bForce) m_sReason = sReason; else if (!sReason.empty()) m_sReason = sReason; time_t iTime = time(nullptr); - char *pTime = ctime(&iTime); + char* pTime = ctime(&iTime); CString sTime; - if (pTime) - { + if (pTime) { sTime = pTime; sTime.Trim(); } - if (m_sReason.empty()) - m_sReason = "Auto Away at " + sTime; + if (m_sReason.empty()) m_sReason = "Auto Away at " + sTime; PutIRC("AWAY :" + m_sReason); m_bIsAway = true; } } - void Back(bool bUsePrivMessage = false) - { + void Back(bool bUsePrivMessage = false) { PutIRC("away"); m_bIsAway = false; - if (!m_vMessages.empty()) - { - if (bUsePrivMessage) - { + if (!m_vMessages.empty()) { + if (bUsePrivMessage) { PutModule("Welcome Back!"); - PutModule("You have " + CString(m_vMessages.size()) + " messages!"); - } - else - { + PutModule("You have " + CString(m_vMessages.size()) + + " messages!"); + } else { PutModNotice("Welcome Back!"); - PutModNotice("You have " + CString(m_vMessages.size()) + " messages!"); + PutModNotice("You have " + CString(m_vMessages.size()) + + " messages!"); } } m_sReason = ""; } - EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override - { - if (m_bIsAway) - AddMessage(time(nullptr), Nick, sMessage); - return(CONTINUE); + EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override { + if (m_bIsAway) AddMessage(time(nullptr), Nick, sMessage); + return (CONTINUE); } - EModRet OnChanMsg(CNick& nick, CChan& channel, CString& sMessage) override - { - if(m_bIsAway && m_chanMessages && sMessage.AsLower().find(m_pNetwork->GetCurNick().AsLower()) != CString::npos) { + EModRet OnChanMsg(CNick& nick, CChan& channel, CString& sMessage) override { + if (m_bIsAway && m_chanMessages && + sMessage.AsLower().find(m_pNetwork->GetCurNick().AsLower()) != + CString::npos) { AddMessage(time(nullptr), nick, channel.GetName() + " " + sMessage); } - - return(CONTINUE); + + return (CONTINUE); } - EModRet OnPrivAction(CNick& Nick, CString& sMessage) override - { + EModRet OnPrivAction(CNick& Nick, CString& sMessage) override { if (m_bIsAway) { AddMessage(time(nullptr), Nick, "* " + sMessage); } - return(CONTINUE); + return (CONTINUE); } - EModRet OnUserNotice(CString& sTarget, CString& sMessage) override - { + EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { Ping(); - if (m_bIsAway) - Back(); + if (m_bIsAway) Back(); - return(CONTINUE); + return (CONTINUE); } - EModRet OnUserMsg(CString& sTarget, CString& sMessage) override - { + EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { Ping(); - if (m_bIsAway) - Back(); + if (m_bIsAway) Back(); - return(CONTINUE); + return (CONTINUE); } - EModRet OnUserAction(CString& sTarget, CString& sMessage) override - { + EModRet OnUserAction(CString& sTarget, CString& sMessage) override { Ping(); - if (m_bIsAway) - Back(); + if (m_bIsAway) Back(); - return(CONTINUE); + return (CONTINUE); } - time_t GetTimeStamp() const { return(m_iLastSentData); } + time_t GetTimeStamp() const { return (m_iLastSentData); } void Ping() { m_iLastSentData = time(nullptr); } time_t GetAwayTime() { return m_iAutoAway; } void SetAwayTime(time_t u) { m_iAutoAway = u; } - bool IsAway() { return(m_bIsAway); } + bool IsAway() { return (m_bIsAway); } -private: + private: CString m_sPassword; - bool m_bBootError; - bool DecryptMessages(CString & sBuffer) - { + bool m_bBootError; + bool DecryptMessages(CString& sBuffer) { CString sMessages = GetPath(); CString sFile; sBuffer = ""; CFile File(sMessages); - if (sMessages.empty() || !File.Open() || !File.ReadFile(sFile)) - { - PutModule("Unable to find buffer"); - return(true); // gonna be successful here + if (sMessages.empty() || !File.Open() || !File.ReadFile(sFile)) { + PutModule("Unable to find buffer"); + return (true); // gonna be successful here } File.Close(); - if (!sFile.empty()) - { + if (!sFile.empty()) { CBlowfish c(m_sPassword, BF_DECRYPT); sBuffer = c.Crypt(sFile); - if (sBuffer.Left(strlen(CRYPT_VERIFICATION_TOKEN)) != CRYPT_VERIFICATION_TOKEN) - { + if (sBuffer.Left(strlen(CRYPT_VERIFICATION_TOKEN)) != + CRYPT_VERIFICATION_TOKEN) { // failed to decode :( PutModule("Unable to decode Encrypted messages"); - return(false); + return (false); } sBuffer.erase(0, strlen(CRYPT_VERIFICATION_TOKEN)); } - return(true); + return (true); } - void AddMessage(time_t iTime, const CNick & Nick, const CString & sMessage) - { + void AddMessage(time_t iTime, const CNick& Nick, const CString& sMessage) { if (Nick.GetNick() == GetNetwork()->GetIRCNick().GetNick()) - return; // ignore messages from self + return; // ignore messages from self AddMessage(CString(iTime) + " " + Nick.GetNickMask() + " " + sMessage); } - void AddMessage(const CString & sText) - { - if (m_saveMessages) - { + void AddMessage(const CString& sText) { + if (m_saveMessages) { m_vMessages.push_back(sText); } } - time_t m_iLastSentData; - bool m_bIsAway; - time_t m_iAutoAway; + time_t m_iLastSentData; + bool m_bIsAway; + time_t m_iAutoAway; vector m_vMessages; - CString m_sReason; - bool m_saveMessages; - bool m_chanMessages; + CString m_sReason; + bool m_saveMessages; + bool m_chanMessages; }; - -void CAwayJob::RunJob() -{ - CAway *p = (CAway *)GetModule(); +void CAwayJob::RunJob() { + CAway* p = (CAway*)GetModule(); p->SaveBufferToDisk(); - if (!p->IsAway()) - { + if (!p->IsAway()) { time_t iNow = time(nullptr); - if ((iNow - p->GetTimeStamp()) > p->GetAwayTime() && p->GetAwayTime() != 0) + if ((iNow - p->GetTimeStamp()) > p->GetAwayTime() && + p->GetAwayTime() != 0) p->Away(); } } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("awaystore"); Info.SetHasArgs(true); - Info.SetArgsHelpText("[ -notimer | -timer N ] [-chans] passw0rd . N is number of seconds, 600 by default."); + Info.SetArgsHelpText( + "[ -notimer | -timer N ] [-chans] passw0rd . N is number of seconds, " + "600 by default."); } -NETWORKMODULEDEFS(CAway, "Adds auto-away with logging, useful when you use ZNC from different locations") - +NETWORKMODULEDEFS(CAway, + "Adds auto-away with logging, useful when you use ZNC from " + "different locations") diff --git a/modules/block_motd.cpp b/modules/block_motd.cpp index ec8d4b68..fdb1c981 100644 --- a/modules/block_motd.cpp +++ b/modules/block_motd.cpp @@ -17,14 +17,17 @@ #include class CBlockMotd : public CModule { -public: + public: MODCONSTRUCTOR(CBlockMotd) { AddHelpCommand(); - AddCommand("GetMotd", static_cast(&CBlockMotd::OverrideCommand), "[]", "Override the block with this command. Can optionally specify which server to query."); + AddCommand("GetMotd", static_cast( + &CBlockMotd::OverrideCommand), + "[]", + "Override the block with this command. Can optionally " + "specify which server to query."); } - virtual ~CBlockMotd() { - } + virtual ~CBlockMotd() {} void OverrideCommand(const CString& sLine) { m_bTemporaryAcceptMotd = true; @@ -37,31 +40,33 @@ public: } } - EModRet OnRaw(CString &sLine) override { + EModRet OnRaw(CString& sLine) override { const CString sCmd = sLine.Token(1); - if ((sCmd == "375" /* begin of MOTD */ || sCmd == "372" /* MOTD */) - && !m_bTemporaryAcceptMotd) + if ((sCmd == "375" /* begin of MOTD */ || sCmd == "372" /* MOTD */) && + !m_bTemporaryAcceptMotd) return HALT; - + if (sCmd == "376" /* End of MOTD */) { if (!m_bTemporaryAcceptMotd) { - sLine = sLine.Token(0) + " 422 " + - sLine.Token(2) + " :MOTD blocked by ZNC"; + sLine = sLine.Token(0) + " 422 " + sLine.Token(2) + + " :MOTD blocked by ZNC"; } m_bTemporaryAcceptMotd = false; } return CONTINUE; } -private: + private: bool m_bTemporaryAcceptMotd = false; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("block_motd"); } -USERMODULEDEFS(CBlockMotd, "Block the MOTD from IRC so it's not sent to your client(s).") +USERMODULEDEFS(CBlockMotd, + "Block the MOTD from IRC so it's not sent to your client(s).") diff --git a/modules/blockuser.cpp b/modules/blockuser.cpp index 8e991de3..8534cf09 100644 --- a/modules/blockuser.cpp +++ b/modules/blockuser.cpp @@ -22,12 +22,18 @@ using std::vector; #define MESSAGE "Your account has been disabled. Contact your administrator." class CBlockUser : public CModule { -public: + public: MODCONSTRUCTOR(CBlockUser) { AddHelpCommand(); - AddCommand("List", static_cast(&CBlockUser::OnListCommand), "", "List blocked users"); - AddCommand("Block", static_cast(&CBlockUser::OnBlockCommand), "", "Block a user"); - AddCommand("Unblock", static_cast(&CBlockUser::OnUnblockCommand), "", "Unblock a user"); + AddCommand("List", static_cast( + &CBlockUser::OnListCommand), + "", "List blocked users"); + AddCommand("Block", static_cast( + &CBlockUser::OnBlockCommand), + "", "Block a user"); + AddCommand("Unblock", static_cast( + &CBlockUser::OnUnblockCommand), + "", "Unblock a user"); } virtual ~CBlockUser() {} @@ -84,8 +90,7 @@ public: Table.SetCell("Blocked user", it->first); } - if (PutModule(Table) == 0) - PutModule("No users blocked"); + if (PutModule(Table) == 0) PutModule("No users blocked"); } void OnBlockCommand(const CString& sCommand) { @@ -121,31 +126,39 @@ public: PutModule("This user is not blocked"); } - bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) { CString sAction = Tmpl["WebadminAction"]; if (sAction == "display") { Tmpl["Blocked"] = CString(IsBlocked(Tmpl["Username"])); - Tmpl["Self"] = CString(Tmpl["Username"].Equals(WebSock.GetSession()->GetUser()->GetUserName())); + Tmpl["Self"] = CString(Tmpl["Username"].Equals( + WebSock.GetSession()->GetUser()->GetUserName())); return true; } - if (sAction == "change" && WebSock.GetParam("embed_blockuser_presented").ToBool()) { - if (Tmpl["Username"].Equals(WebSock.GetSession()->GetUser()->GetUserName()) && - WebSock.GetParam("embed_blockuser_block").ToBool()) { + if (sAction == "change" && + WebSock.GetParam("embed_blockuser_presented").ToBool()) { + if (Tmpl["Username"].Equals( + WebSock.GetSession()->GetUser()->GetUserName()) && + WebSock.GetParam("embed_blockuser_block").ToBool()) { WebSock.GetSession()->AddError("You can't block yourself"); } else if (WebSock.GetParam("embed_blockuser_block").ToBool()) { if (!WebSock.GetParam("embed_blockuser_old").ToBool()) { if (Block(Tmpl["Username"])) { - WebSock.GetSession()->AddSuccess("Blocked [" + Tmpl["Username"] + "]"); + WebSock.GetSession()->AddSuccess( + "Blocked [" + Tmpl["Username"] + "]"); } else { - WebSock.GetSession()->AddError("Couldn't block [" + Tmpl["Username"] + "]"); + WebSock.GetSession()->AddError( + "Couldn't block [" + Tmpl["Username"] + "]"); } } - } else if (WebSock.GetParam("embed_blockuser_old").ToBool()){ + } else if (WebSock.GetParam("embed_blockuser_old").ToBool()) { if (DelNV(Tmpl["Username"])) { - WebSock.GetSession()->AddSuccess("Unblocked [" + Tmpl["Username"] + "]"); + WebSock.GetSession()->AddSuccess( + "Unblocked [" + Tmpl["Username"] + "]"); } else { - WebSock.GetSession()->AddError("User [" + Tmpl["Username"] + "is not blocked"); + WebSock.GetSession()->AddError( + "User [" + Tmpl["Username"] + "is not blocked"); } } return true; @@ -154,7 +167,7 @@ public: return false; } -private: + private: bool IsBlocked(const CString& sUser) { MCString::iterator it; for (it = BeginNV(); it != EndNV(); ++it) { @@ -166,10 +179,9 @@ private: } bool Block(const CString& sUser) { - CUser *pUser = CZNC::Get().FindUser(sUser); + CUser* pUser = CZNC::Get().FindUser(sUser); - if (!pUser) - return false; + if (!pUser) return false; // Disconnect all clients vector vpClients = pUser->GetAllClients(); @@ -181,7 +193,8 @@ private: // Disconnect all networks from irc vector vNetworks = pUser->GetNetworks(); - for (vector::iterator it2 = vNetworks.begin(); it2 != vNetworks.end(); ++it2) { + for (vector::iterator it2 = vNetworks.begin(); + it2 != vNetworks.end(); ++it2) { (*it2)->SetIRCConnectEnabled(false); } @@ -190,10 +203,12 @@ private: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("blockuser"); Info.SetHasArgs(true); - Info.SetArgsHelpText("Enter one or more user names. Separate them by spaces."); + Info.SetArgsHelpText( + "Enter one or more user names. Separate them by spaces."); } GLOBALMODULEDEFS(CBlockUser, "Block certain users from logging in.") diff --git a/modules/bouncedcc.cpp b/modules/bouncedcc.cpp index 5f76401c..749616b6 100644 --- a/modules/bouncedcc.cpp +++ b/modules/bouncedcc.cpp @@ -22,16 +22,22 @@ using std::set; class CBounceDCCMod; class CDCCBounce : public CSocket { -public: + public: CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, - const CString& sFileName, const CString& sRemoteNick, - const CString& sRemoteIP, bool bIsChat = false); - CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, - const CString& sRemoteNick, const CString& sRemoteIP, - const CString& sFileName, int iTimeout = 60, bool bIsChat = false); + const CString& sFileName, const CString& sRemoteNick, + const CString& sRemoteIP, bool bIsChat = false); + CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, + unsigned short uPort, const CString& sRemoteNick, + const CString& sRemoteIP, const CString& sFileName, + int iTimeout = 60, bool bIsChat = false); virtual ~CDCCBounce(); - static unsigned short DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP); + static unsigned short DCCRequest(const CString& sNick, + unsigned long uLongIP, + unsigned short uPort, + const CString& sFileName, bool bIsChat, + CBounceDCCMod* pMod, + const CString& sRemoteIP); void ReadLine(const CString& sData) override; void ReadData(const char* data, size_t len) override; @@ -46,7 +52,9 @@ public: void Shutdown(); void PutServ(const CString& sLine); void PutPeer(const CString& sLine); - bool IsPeerConnected() { return (m_pPeer) ? m_pPeer->IsConnected() : false; } + bool IsPeerConnected() { + return (m_pPeer) ? m_pPeer->IsConnected() : false; + } // Setters void SetPeer(CDCCBounce* p) { m_pPeer = p; } @@ -64,21 +72,21 @@ public: bool IsRemote() { return m_bIsRemote; } bool IsChat() { return m_bIsChat; } // !Getters -private: -protected: - CString m_sRemoteNick; - CString m_sRemoteIP; - CString m_sConnectIP; - CString m_sLocalIP; - CString m_sFileName; - CBounceDCCMod* m_pModule; - CDCCBounce* m_pPeer; - unsigned short m_uRemotePort; - bool m_bIsChat; - bool m_bIsRemote; + private: + protected: + CString m_sRemoteNick; + CString m_sRemoteIP; + CString m_sConnectIP; + CString m_sLocalIP; + CString m_sFileName; + CBounceDCCMod* m_pModule; + CDCCBounce* m_pPeer; + unsigned short m_uRemotePort; + bool m_bIsChat; + bool m_bIsRemote; - static const unsigned int m_uiMaxDCCBuffer; - static const unsigned int m_uiMinDCCBuffer; + static const unsigned int m_uiMaxDCCBuffer; + static const unsigned int m_uiMinDCCBuffer; }; // If we buffer more than this in memory, we will throttle the receiving side @@ -87,7 +95,7 @@ const unsigned int CDCCBounce::m_uiMaxDCCBuffer = 10 * 1024; const unsigned int CDCCBounce::m_uiMinDCCBuffer = 2 * 1024; class CBounceDCCMod : public CModule { -public: + public: void ListDCCsCommand(const CString& sLine) { CTable Table; Table.AddColumn("Type"); @@ -99,7 +107,7 @@ public: set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCBounce* pSock = (CDCCBounce*) *it; + CDCCBounce* pSock = (CDCCBounce*)*it; CString sSockName = pSock->GetSockName(); if (!(pSock->IsRemote())) { @@ -142,29 +150,32 @@ public: MODCONSTRUCTOR(CBounceDCCMod) { AddHelpCommand(); - AddCommand("ListDCCs", static_cast(&CBounceDCCMod::ListDCCsCommand), - "", "List all active DCCs"); - AddCommand("UseClientIP", static_cast(&CBounceDCCMod::UseClientIPCommand), - ""); + AddCommand("ListDCCs", static_cast( + &CBounceDCCMod::ListDCCsCommand), + "", "List all active DCCs"); + AddCommand("UseClientIP", static_cast( + &CBounceDCCMod::UseClientIPCommand), + ""); } virtual ~CBounceDCCMod() {} - CString GetLocalDCCIP() { - return GetUser()->GetLocalDCCIP(); - } + CString GetLocalDCCIP() { return GetUser()->GetLocalDCCIP(); } - bool UseClientIP() { - return GetNV("UseClientIP").ToBool(); - } + bool UseClientIP() { return GetNV("UseClientIP").ToBool(); } EModRet OnUserCTCP(CString& sTarget, CString& sMessage) override { if (sMessage.StartsWith("DCC ")) { - CString sType = sMessage.Token(1, false, " ", false, "\"", "\"", true); - CString sFile = sMessage.Token(2, false, " ", false, "\"", "\"", false); - unsigned long uLongIP = sMessage.Token(3, false, " ", false, "\"", "\"", true).ToULong(); - unsigned short uPort = sMessage.Token(4, false, " ", false, "\"", "\"", true).ToUShort(); - unsigned long uFileSize = sMessage.Token(5, false, " ", false, "\"", "\"", true).ToULong(); + CString sType = + sMessage.Token(1, false, " ", false, "\"", "\"", true); + CString sFile = + sMessage.Token(2, false, " ", false, "\"", "\"", false); + unsigned long uLongIP = sMessage.Token(3, false, " ", false, "\"", + "\"", true).ToULong(); + unsigned short uPort = sMessage.Token(4, false, " ", false, "\"", + "\"", true).ToUShort(); + unsigned long uFileSize = sMessage.Token(5, false, " ", false, "\"", + "\"", true).ToULong(); CString sIP = GetLocalDCCIP(); if (!UseClientIP()) { @@ -172,15 +183,22 @@ public: } if (sType.Equals("CHAT")) { - unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, "", true, this, ""); + unsigned short uBNCPort = CDCCBounce::DCCRequest( + sTarget, uLongIP, uPort, "", true, this, ""); if (uBNCPort) { - PutIRC("PRIVMSG " + sTarget + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); + PutIRC("PRIVMSG " + sTarget + " :\001DCC CHAT chat " + + CString(CUtils::GetLongIP(sIP)) + " " + + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 - unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, sFile, false, this, ""); + unsigned short uBNCPort = CDCCBounce::DCCRequest( + sTarget, uLongIP, uPort, sFile, false, this, ""); if (uBNCPort) { - PutIRC("PRIVMSG " + sTarget + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); + PutIRC("PRIVMSG " + sTarget + " :\001DCC SEND " + sFile + + " " + CString(CUtils::GetLongIP(sIP)) + " " + + CString(uBNCPort) + " " + CString(uFileSize) + + "\001"); } } else if (sType.Equals("RESUME")) { // PRIVMSG user :DCC RESUME "znc.o" 58810 151552 @@ -188,20 +206,27 @@ public: set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCBounce* pSock = (CDCCBounce*) *it; + CDCCBounce* pSock = (CDCCBounce*)*it; if (pSock->GetLocalPort() == uResumePort) { - PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); + PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + + " " + sFile + " " + + CString(pSock->GetUserPort()) + " " + + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { - // Need to lookup the connection by port, filter the port, and forward to the user + // Need to lookup the connection by port, filter the port, and + // forward to the user set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCBounce* pSock = (CDCCBounce*) *it; + CDCCBounce* pSock = (CDCCBounce*)*it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { - PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); + PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + + " " + sFile + " " + + CString(pSock->GetLocalPort()) + " " + + sMessage.Token(4) + "\001"); } } } @@ -216,46 +241,72 @@ public: CIRCNetwork* pNetwork = GetNetwork(); if (sMessage.StartsWith("DCC ") && pNetwork->IsUserAttached()) { // DCC CHAT chat 2453612361 44592 - CString sType = sMessage.Token(1, false, " ", false, "\"", "\"", true); - CString sFile = sMessage.Token(2, false, " ", false, "\"", "\"", false); - unsigned long uLongIP = sMessage.Token(3, false, " ", false, "\"", "\"", true).ToULong(); - unsigned short uPort = sMessage.Token(4, false, " ", false, "\"", "\"", true).ToUShort(); - unsigned long uFileSize = sMessage.Token(5, false, " ", false, "\"", "\"", true).ToULong(); + CString sType = + sMessage.Token(1, false, " ", false, "\"", "\"", true); + CString sFile = + sMessage.Token(2, false, " ", false, "\"", "\"", false); + unsigned long uLongIP = sMessage.Token(3, false, " ", false, "\"", + "\"", true).ToULong(); + unsigned short uPort = sMessage.Token(4, false, " ", false, "\"", + "\"", true).ToUShort(); + unsigned long uFileSize = sMessage.Token(5, false, " ", false, "\"", + "\"", true).ToULong(); if (sType.Equals("CHAT")) { CNick FromNick(Nick.GetNickMask()); - unsigned short uBNCPort = CDCCBounce::DCCRequest(FromNick.GetNick(), uLongIP, uPort, "", true, this, CUtils::GetIP(uLongIP)); + unsigned short uBNCPort = CDCCBounce::DCCRequest( + FromNick.GetNick(), uLongIP, uPort, "", true, this, + CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); - PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + pNetwork->GetCurNick() + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); + PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + + pNetwork->GetCurNick() + " :\001DCC CHAT chat " + + CString(CUtils::GetLongIP(sIP)) + " " + + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 - unsigned short uBNCPort = CDCCBounce::DCCRequest(Nick.GetNick(), uLongIP, uPort, sFile, false, this, CUtils::GetIP(uLongIP)); + unsigned short uBNCPort = CDCCBounce::DCCRequest( + Nick.GetNick(), uLongIP, uPort, sFile, false, this, + CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); - PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + pNetwork->GetCurNick() + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); + PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + + pNetwork->GetCurNick() + " :\001DCC SEND " + sFile + + " " + CString(CUtils::GetLongIP(sIP)) + " " + + CString(uBNCPort) + " " + CString(uFileSize) + + "\001"); } } else if (sType.Equals("RESUME")) { - // Need to lookup the connection by port, filter the port, and forward to the user + // Need to lookup the connection by port, filter the port, and + // forward to the user unsigned short uResumePort = sMessage.Token(3).ToUShort(); set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCBounce* pSock = (CDCCBounce*) *it; + CDCCBounce* pSock = (CDCCBounce*)*it; if (pSock->GetLocalPort() == uResumePort) { - PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + pNetwork->GetCurNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); + PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + + pNetwork->GetCurNick() + " :\001DCC " + sType + + " " + sFile + " " + + CString(pSock->GetUserPort()) + " " + + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { - // Need to lookup the connection by port, filter the port, and forward to the user + // Need to lookup the connection by port, filter the port, and + // forward to the user set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCBounce* pSock = (CDCCBounce*) *it; + CDCCBounce* pSock = (CDCCBounce*)*it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { - PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + pNetwork->GetCurNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); + PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + + pNetwork->GetCurNick() + " :\001DCC " + sType + + " " + sFile + " " + + CString(pSock->GetLocalPort()) + " " + + sMessage.Token(4) + "\001"); } } } @@ -267,9 +318,11 @@ public: } }; -CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, - const CString& sFileName, const CString& sRemoteNick, - const CString& sRemoteIP, bool bIsChat) : CSocket(pMod) { +CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, + unsigned short uPort, const CString& sFileName, + const CString& sRemoteNick, const CString& sRemoteIP, + bool bIsChat) + : CSocket(pMod) { m_uRemotePort = uPort; m_sConnectIP = CUtils::GetIP(uLongIP); m_sRemoteIP = sRemoteIP; @@ -288,9 +341,11 @@ CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned shor } } -CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, - const CString& sRemoteNick, const CString& sRemoteIP, const CString& sFileName, - int iTimeout, bool bIsChat) : CSocket(pMod, sHostname, uPort, iTimeout) { +CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, + unsigned short uPort, const CString& sRemoteNick, + const CString& sRemoteIP, const CString& sFileName, + int iTimeout, bool bIsChat) + : CSocket(pMod, sHostname, uPort, iTimeout) { m_uRemotePort = 0; m_bIsChat = bIsChat; m_pModule = pMod; @@ -328,7 +383,8 @@ void CDCCBounce::ReachedMaxBuffer() { CString sType = (m_bIsChat) ? "Chat" : "Xfer"; - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Too long line received"); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Too long line received"); Close(); } @@ -340,14 +396,15 @@ void CDCCBounce::ReadData(const char* data, size_t len) { if (BufLen >= m_uiMaxDCCBuffer) { DEBUG(GetSockName() << " The send buffer is over the " - "limit (" << BufLen <<"), throttling"); + "limit (" << BufLen << "), throttling"); PauseRead(); } } } void CDCCBounce::ReadPaused() { - if (!m_pPeer || m_pPeer->GetInternalWriteBuffer().length() <= m_uiMinDCCBuffer) + if (!m_pPeer || + m_pPeer->GetInternalWriteBuffer().length() <= m_uiMinDCCBuffer) UnPauseRead(); } @@ -363,9 +420,13 @@ void CDCCBounce::Timeout() { sHost = "."; } - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout while connecting" + sHost); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Timeout while connecting" + sHost); } else { - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout waiting for incoming connection [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Timeout waiting for incoming connection [" + + Csock::GetLocalIP() + ":" + + CString(Csock::GetLocalPort()) + "]"); } } @@ -380,7 +441,8 @@ void CDCCBounce::ConnectionRefused() { sHost = "."; } - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Connection Refused while connecting" + sHost); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Connection Refused while connecting" + sHost); } void CDCCBounce::SockError(int iErrno, const CString& sDescription) { @@ -393,9 +455,13 @@ void CDCCBounce::SockError(int iErrno, const CString& sDescription) { sHost = "[" + sHost + " " + CString(Csock::GetPort()) + "]"; } - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + sDescription + "]" + sHost); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Socket error [" + sDescription + "]" + sHost); } else { - m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + sDescription + "] [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); + m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + + "): Socket error [" + sDescription + "] [" + + Csock::GetLocalIP() + ":" + + CString(Csock::GetLocalPort()) + "]"); } } @@ -421,14 +487,21 @@ Csock* CDCCBounce::GetSockObj(const CString& sHost, unsigned short uPort) { m_sRemoteIP = sHost; } - CDCCBounce* pSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); - CDCCBounce* pRemoteSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); + CDCCBounce* pSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, + m_sRemoteIP, m_sFileName, m_bIsChat); + CDCCBounce* pRemoteSock = + new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, + m_sFileName, m_bIsChat); pSock->SetPeer(pRemoteSock); pRemoteSock->SetPeer(pSock); pRemoteSock->SetRemote(true); pSock->SetRemote(false); - CZNC::Get().GetManager().Connect(m_sConnectIP, m_uRemotePort, "DCC::" + CString((m_bIsChat) ? "Chat" : "XFER") + "::Remote::" + m_sRemoteNick, 60, false, m_sLocalIP, pRemoteSock); + CZNC::Get().GetManager().Connect( + m_sConnectIP, m_uRemotePort, + "DCC::" + CString((m_bIsChat) ? "Chat" : "XFER") + "::Remote::" + + m_sRemoteNick, + 60, false, m_sLocalIP, pRemoteSock); pSock->SetSockName(GetSockName()); return pSock; @@ -447,17 +520,26 @@ void CDCCBounce::PutPeer(const CString& sLine) { } } -unsigned short CDCCBounce::DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP) { - CDCCBounce* pDCCBounce = new CDCCBounce(pMod, uLongIP, uPort, sFileName, sNick, sRemoteIP, bIsChat); - unsigned short uListenPort = CZNC::Get().GetManager().ListenRand("DCC::" + CString((bIsChat) ? "Chat" : "Xfer") + "::Local::" + sNick, - pMod->GetLocalDCCIP(), false, SOMAXCONN, pDCCBounce, 120); +unsigned short CDCCBounce::DCCRequest(const CString& sNick, + unsigned long uLongIP, + unsigned short uPort, + const CString& sFileName, bool bIsChat, + CBounceDCCMod* pMod, + const CString& sRemoteIP) { + CDCCBounce* pDCCBounce = new CDCCBounce(pMod, uLongIP, uPort, sFileName, + sNick, sRemoteIP, bIsChat); + unsigned short uListenPort = CZNC::Get().GetManager().ListenRand( + "DCC::" + CString((bIsChat) ? "Chat" : "Xfer") + "::Local::" + sNick, + pMod->GetLocalDCCIP(), false, SOMAXCONN, pDCCBounce, 120); return uListenPort; } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("bouncedcc"); } -USERMODULEDEFS(CBounceDCCMod, "Bounces DCC transfers through ZNC instead of sending them directly to the user. ") - +USERMODULEDEFS(CBounceDCCMod, + "Bounces DCC transfers through ZNC instead of sending them " + "directly to the user. ") diff --git a/modules/buffextras.cpp b/modules/buffextras.cpp index 9c6ec5b3..cb500ffe 100644 --- a/modules/buffextras.cpp +++ b/modules/buffextras.cpp @@ -20,20 +20,27 @@ using std::vector; class CBuffExtras : public CModule { -public: + public: MODCONSTRUCTOR(CBuffExtras) {} virtual ~CBuffExtras() {} - void AddBuffer(CChan& Channel, const CString& sMessage, const timeval* tv = nullptr, const MCString& mssTags = MCString::EmptyMap) { - // If they have AutoClearChanBuffer enabled, only add messages if no client is connected + void AddBuffer(CChan& Channel, const CString& sMessage, + const timeval* tv = nullptr, + const MCString& mssTags = MCString::EmptyMap) { + // If they have AutoClearChanBuffer enabled, only add messages if no + // client is connected if (Channel.AutoClearChanBuffer() && GetNetwork()->IsUserOnline()) return; - Channel.AddBuffer(":" + GetModNick() + "!" + GetModName() + "@znc.in PRIVMSG " + _NAMEDFMT(Channel.GetName()) + " :{text}", sMessage, tv, mssTags); + Channel.AddBuffer(":" + GetModNick() + "!" + GetModName() + + "@znc.in PRIVMSG " + + _NAMEDFMT(Channel.GetName()) + " :{text}", + sMessage, tv, mssTags); } - void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override { + void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override { const CString sNickMask = pOpNick ? pOpNick->GetNickMask() : "Server"; AddBuffer(Channel, sNickMask + " set mode: " + sModes + " " + sArgs); } @@ -43,13 +50,17 @@ public: const CString sKickedNick = Message.GetKickedNick(); CChan& Channel = *Message.GetChan(); const CString sMessage = Message.GetReason(); - AddBuffer(Channel, OpNick.GetNickMask() + " kicked " + sKickedNick + " Reason: [" + sMessage + "]", &Message.GetTime(), Message.GetTags()); + AddBuffer(Channel, OpNick.GetNickMask() + " kicked " + sKickedNick + + " Reason: [" + sMessage + "]", + &Message.GetTime(), Message.GetTags()); } - void OnQuitMessage(CQuitMessage& Message, const vector& vChans) override { + void OnQuitMessage(CQuitMessage& Message, + const vector& vChans) override { const CNick& Nick = Message.GetNick(); const CString sMessage = Message.GetReason(); - CString sMsg = Nick.GetNickMask() + " quit with message: [" + sMessage + "]"; + CString sMsg = + Nick.GetNickMask() + " quit with message: [" + sMessage + "]"; for (CChan* pChan : vChans) { AddBuffer(*pChan, sMsg, &Message.GetTime(), Message.GetTags()); } @@ -58,17 +69,21 @@ public: void OnJoinMessage(CJoinMessage& Message) override { const CNick& Nick = Message.GetNick(); CChan& Channel = *Message.GetChan(); - AddBuffer(Channel, Nick.GetNickMask() + " joined", &Message.GetTime(), Message.GetTags()); + AddBuffer(Channel, Nick.GetNickMask() + " joined", &Message.GetTime(), + Message.GetTags()); } void OnPartMessage(CPartMessage& Message) override { const CNick& Nick = Message.GetNick(); CChan& Channel = *Message.GetChan(); const CString sMessage = Message.GetReason(); - AddBuffer(Channel, Nick.GetNickMask() + " parted with message: [" + sMessage + "]", &Message.GetTime(), Message.GetTags()); + AddBuffer(Channel, Nick.GetNickMask() + " parted with message: [" + + sMessage + "]", + &Message.GetTime(), Message.GetTags()); } - void OnNickMessage(CNickMessage& Message, const vector& vChans) override { + void OnNickMessage(CNickMessage& Message, + const vector& vChans) override { const CNick& OldNick = Message.GetNick(); const CString sNewNick = Message.GetNewNick(); CString sMsg = OldNick.GetNickMask() + " is now known as " + sNewNick; @@ -81,16 +96,18 @@ public: const CNick& Nick = Message.GetNick(); CChan& Channel = *Message.GetChan(); const CString sTopic = Message.GetTopic(); - AddBuffer(Channel, Nick.GetNickMask() + " changed the topic to: " + sTopic, &Message.GetTime(), Message.GetTags()); + AddBuffer(Channel, + Nick.GetNickMask() + " changed the topic to: " + sTopic, + &Message.GetTime(), Message.GetTags()); return CONTINUE; } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("buffextras"); Info.AddType(CModInfo::NetworkModule); } USERMODULEDEFS(CBuffExtras, "Add joins, parts etc. to the playback buffer") - diff --git a/modules/cert.cpp b/modules/cert.cpp index d5a7beef..90755668 100644 --- a/modules/cert.cpp +++ b/modules/cert.cpp @@ -22,44 +22,48 @@ #include class CCertMod : public CModule { -public: - void Delete(const CString &line) { + public: + void Delete(const CString& line) { if (CFile::Delete(PemFile())) { PutModule("Pem file deleted"); } else { - PutModule("The pem file doesn't exist or there was a error deleting the pem file."); + PutModule( + "The pem file doesn't exist or there was a error deleting the " + "pem file."); } } - void Info(const CString &line) { + void Info(const CString& line) { if (HasPemFile()) { PutModule("You have a certificate in: " + PemFile()); } else { - PutModule("You do not have a certificate. Please use the web interface to add a certificate"); + PutModule( + "You do not have a certificate. Please use the web interface " + "to add a certificate"); if (GetUser()->IsAdmin()) { - PutModule("Alternatively you can either place one at " + PemFile()); + PutModule("Alternatively you can either place one at " + + PemFile()); } } } MODCONSTRUCTOR(CCertMod) { AddHelpCommand(); - AddCommand("delete", static_cast(&CCertMod::Delete), - "", "Delete the current certificate"); - AddCommand("info", static_cast(&CCertMod::Info), "", "Show the current certificate"); + AddCommand("delete", + static_cast(&CCertMod::Delete), "", + "Delete the current certificate"); + AddCommand("info", + static_cast(&CCertMod::Info), "", + "Show the current certificate"); } virtual ~CCertMod() {} - CString PemFile() const { - return GetSavePath() + "/user.pem"; - } + CString PemFile() const { return GetSavePath() + "/user.pem"; } - bool HasPemFile() const { - return (CFile::Exists(PemFile())); - } + bool HasPemFile() const { return (CFile::Exists(PemFile())); } - EModRet OnIRCConnecting(CIRCSock *pIRCSock) override { + EModRet OnIRCConnecting(CIRCSock* pIRCSock) override { if (HasPemFile()) { pIRCSock->SetPemLocation(PemFile()); } @@ -69,7 +73,8 @@ public: CString GetWebMenuTitle() override { return "Certificate"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { Tmpl["Cert"] = CString(HasPemFile()); return true; @@ -93,7 +98,8 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("cert"); } diff --git a/modules/certauth.cpp b/modules/certauth.cpp index 8b420873..2e726bdf 100644 --- a/modules/certauth.cpp +++ b/modules/certauth.cpp @@ -25,16 +25,22 @@ using std::set; using std::pair; class CSSLClientCertMod : public CModule { -public: + public: MODCONSTRUCTOR(CSSLClientCertMod) { AddHelpCommand(); - AddCommand("Add", static_cast(&CSSLClientCertMod::HandleAddCommand), - "[pubkey]", "If pubkey is not provided will use the current key"); - AddCommand("Del", static_cast(&CSSLClientCertMod::HandleDelCommand), - "id"); - AddCommand("List", static_cast(&CSSLClientCertMod::HandleListCommand),"", "List your public keys"); - AddCommand("Show", static_cast(&CSSLClientCertMod::HandleShowCommand), - "", "Print your current key"); + AddCommand("Add", static_cast( + &CSSLClientCertMod::HandleAddCommand), + "[pubkey]", + "If pubkey is not provided will use the current key"); + AddCommand("Del", static_cast( + &CSSLClientCertMod::HandleDelCommand), + "id"); + AddCommand("List", static_cast( + &CSSLClientCertMod::HandleListCommand), + "", "List your public keys"); + AddCommand("Show", static_cast( + &CSSLClientCertMod::HandleShowCommand), + "", "Print your current key"); } virtual ~CSSLClientCertMod() {} @@ -45,7 +51,8 @@ public: // We need the SSL_VERIFY_PEER flag on all listeners, or else // the client doesn't send a ssl cert for (CListener* pListener : vListeners) - pListener->GetRealListener()->SetRequireClientCertFlags(SSL_VERIFY_PEER); + pListener->GetRealListener()->SetRequireClientCertFlags( + SSL_VERIFY_PEER); for (MCString::const_iterator it = BeginNV(); it != EndNV(); ++it) { VCString vsKeys; @@ -64,9 +71,7 @@ public: return true; } - void OnPostRehash() override { - OnBoot(); - } + void OnPostRehash() override { OnBoot(); } bool OnLoad(const CString& sArgs, CString& sMessage) override { OnBoot(); @@ -82,16 +87,15 @@ public: sVal += sKey + " "; } - if (!sVal.empty()) - SetNV(it.first, sVal, false); + if (!sVal.empty()) SetNV(it.first, sVal, false); } return SaveRegistry(); } - bool AddKey(CUser *pUser, const CString& sKey) { - const pair pair - = m_PubKeys[pUser->GetUserName()].insert(sKey.AsLower()); + bool AddKey(CUser* pUser, const CString& sKey) { + const pair pair = + m_PubKeys[pUser->GetUserName()].insert(sKey.AsLower()); if (pair.second) { Save(); @@ -102,11 +106,10 @@ public: EModRet OnLoginAttempt(std::shared_ptr Auth) override { const CString sUser = Auth->GetUsername(); - Csock *pSock = Auth->GetSocket(); - CUser *pUser = CZNC::Get().FindUser(sUser); + Csock* pSock = Auth->GetSocket(); + CUser* pUser = CZNC::Get().FindUser(sUser); - if (pSock == nullptr || pUser == nullptr) - return CONTINUE; + if (pSock == nullptr || pUser == nullptr) return CONTINUE; const CString sPubKey = GetKey(pSock); DEBUG("User: " << sUser << " Key: " << sPubKey); @@ -210,14 +213,13 @@ public: } it->second.erase(it2); - if (it->second.size() == 0) - m_PubKeys.erase(it); + if (it->second.size() == 0) m_PubKeys.erase(it); PutModule("Removed"); Save(); } - CString GetKey(Csock *pSock) { + CString GetKey(Csock* pSock) { CString sRes; long int res = pSock->GetPeerFingerprint(sRes); @@ -225,20 +227,21 @@ public: // This is 'inspired' by charybdis' libratbox switch (res) { - case X509_V_OK: - case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: - case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: - case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: - return sRes.AsLower(); - default: - return ""; + case X509_V_OK: + case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: + case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: + case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: + return sRes.AsLower(); + default: + return ""; } } CString GetWebMenuTitle() override { return "certauth"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { - CUser *pUser = WebSock.GetSession()->GetUser(); + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { + CUser* pUser = WebSock.GetSession()->GetUser(); if (sPageName == "index") { MSCString::const_iterator it = m_PubKeys.find(pUser->GetUserName()); @@ -273,14 +276,16 @@ public: return false; } -private: + private: // Maps user names to a list of allowed pubkeys - typedef map > MSCString; - MSCString m_PubKeys; + typedef map> MSCString; + MSCString m_PubKeys; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("certauth"); } -GLOBALMODULEDEFS(CSSLClientCertMod, "Allow users to authenticate via SSL client certificates.") +GLOBALMODULEDEFS(CSSLClientCertMod, + "Allow users to authenticate via SSL client certificates.") diff --git a/modules/chansaver.cpp b/modules/chansaver.cpp index 94c4fa71..f603bb5c 100644 --- a/modules/chansaver.cpp +++ b/modules/chansaver.cpp @@ -19,12 +19,10 @@ #include class CChanSaverMod : public CModule { -public: - MODCONSTRUCTOR(CChanSaverMod) { - } + public: + MODCONSTRUCTOR(CChanSaverMod) {} - virtual ~CChanSaverMod() { - } + virtual ~CChanSaverMod() {} bool OnLoad(const CString& sArgsi, CString& sMessage) override { switch (GetType()) { @@ -67,19 +65,23 @@ public: } void OnJoin(const CNick& Nick, CChan& Channel) override { - if (!Channel.InConfig() && GetNetwork()->GetIRCNick().NickEquals(Nick.GetNick())) { + if (!Channel.InConfig() && + GetNetwork()->GetIRCNick().NickEquals(Nick.GetNick())) { Channel.SetInConfig(true); } } - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override { - if (Channel.InConfig() && GetNetwork()->GetIRCNick().NickEquals(Nick.GetNick())) { + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override { + if (Channel.InConfig() && + GetNetwork()->GetIRCNick().NickEquals(Nick.GetNick())) { Channel.SetInConfig(false); } } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("chansaver"); Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); diff --git a/modules/clearbufferonmsg.cpp b/modules/clearbufferonmsg.cpp index 9aa69326..f55885a9 100644 --- a/modules/clearbufferonmsg.cpp +++ b/modules/clearbufferonmsg.cpp @@ -33,7 +33,7 @@ enum { }; class CClearBufferOnMsgMod : public CModule { -public: + public: MODCONSTRUCTOR(CClearBufferOnMsgMod) { SetAllRules(true); // false for backward compatibility @@ -48,8 +48,7 @@ public: for (CChan* pChan : vChans) { // Skip detached channels, they weren't read yet - if (pChan->IsDetached()) - continue; + if (pChan->IsDetached()) continue; pChan->ClearBuffer(); // We deny AutoClearChanBuffer on all channels since this module @@ -70,50 +69,42 @@ public: } EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { - if (m_bRules[RULE_MSG]) - ClearAllBuffers(); + if (m_bRules[RULE_MSG]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserCTCP(CString& sTarget, CString& sMessage) override { - if (m_bRules[RULE_CTCP]) - ClearAllBuffers(); + if (m_bRules[RULE_CTCP]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserAction(CString& sTarget, CString& sMessage) override { - if (m_bRules[RULE_ACTION]) - ClearAllBuffers(); + if (m_bRules[RULE_ACTION]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { - if (m_bRules[RULE_NOTICE]) - ClearAllBuffers(); + if (m_bRules[RULE_NOTICE]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserPart(CString& sChannel, CString& sMessage) override { - if (m_bRules[RULE_PART]) - ClearAllBuffers(); + if (m_bRules[RULE_PART]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserTopic(CString& sChannel, CString& sTopic) override { - if (m_bRules[RULE_TOPIC]) - ClearAllBuffers(); + if (m_bRules[RULE_TOPIC]) ClearAllBuffers(); return CONTINUE; } EModRet OnUserQuit(CString& sMessage) override { - if (m_bRules[RULE_QUIT]) - ClearAllBuffers(); + if (m_bRules[RULE_QUIT]) ClearAllBuffers(); return CONTINUE; } void SetAllRules(bool bVal) { - for (int i = 0; i < RULE_MAX; i++) - m_bRules[i] = bVal; + for (int i = 0; i < RULE_MAX; i++) m_bRules[i] = bVal; } void SetRule(const CString& sOpt, bool bVal) { @@ -121,14 +112,14 @@ public: CString sName; int Index; } Names[RULE_MAX] = { - { "msg", RULE_MSG }, - { "ctcp", RULE_CTCP }, - { "action", RULE_ACTION }, - { "notice", RULE_NOTICE }, - { "part", RULE_PART }, - { "topic", RULE_TOPIC }, - { "quit", RULE_QUIT }, - }; + {"msg", RULE_MSG}, + {"ctcp", RULE_CTCP}, + {"action", RULE_ACTION}, + {"notice", RULE_NOTICE}, + {"part", RULE_PART}, + {"topic", RULE_TOPIC}, + {"quit", RULE_QUIT}, + }; if (sOpt.Equals("all")) { SetAllRules(bVal); @@ -155,14 +146,17 @@ public: return true; } -private: - bool m_bRules[RULE_MAX]; + private: + bool m_bRules[RULE_MAX]; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("clearbufferonmsg"); Info.SetHasArgs(true); Info.SetArgsHelpText("[ [!] ]"); } -USERMODULEDEFS(CClearBufferOnMsgMod, "Clear all channel and query buffers whenever the user does something") +USERMODULEDEFS( + CClearBufferOnMsgMod, + "Clear all channel and query buffers whenever the user does something") diff --git a/modules/clientnotify.cpp b/modules/clientnotify.cpp index 0198b896..d07eaa25 100644 --- a/modules/clientnotify.cpp +++ b/modules/clientnotify.cpp @@ -20,7 +20,7 @@ using std::set; class CClientNotifyMod : public CModule { -protected: + protected: CString m_sMethod; bool m_bNewOnly{}; bool m_bOnDisconnect{}; @@ -34,27 +34,37 @@ protected: } void SendNotification(const CString& sMessage) { - if(m_sMethod == "message") { + if (m_sMethod == "message") { GetUser()->PutStatus(sMessage, nullptr, GetClient()); - } - else if(m_sMethod == "notice") { + } else if (m_sMethod == "notice") { GetUser()->PutStatusNotice(sMessage, nullptr, GetClient()); } } -public: + public: MODCONSTRUCTOR(CClientNotifyMod) { AddHelpCommand(); - AddCommand("Method", static_cast(&CClientNotifyMod::OnMethodCommand), "", "Sets the notify method"); - AddCommand("NewOnly", static_cast(&CClientNotifyMod::OnNewOnlyCommand), "", "Turns notifications for unseen IP addresses on or off"); - AddCommand("OnDisconnect", static_cast(&CClientNotifyMod::OnDisconnectCommand), "", "Turns notifications for clients disconnecting on or off"); - AddCommand("Show", static_cast(&CClientNotifyMod::OnShowCommand), "", "Show the current settings"); + AddCommand("Method", static_cast( + &CClientNotifyMod::OnMethodCommand), + "", "Sets the notify method"); + AddCommand("NewOnly", static_cast( + &CClientNotifyMod::OnNewOnlyCommand), + "", + "Turns notifications for unseen IP addresses on or off"); + AddCommand("OnDisconnect", static_cast( + &CClientNotifyMod::OnDisconnectCommand), + "", + "Turns notifications for clients disconnecting on or off"); + AddCommand("Show", static_cast( + &CClientNotifyMod::OnShowCommand), + "", "Show the current settings"); } bool OnLoad(const CString& sArgs, CString& sMessage) override { m_sMethod = GetNV("method"); - if(m_sMethod != "notice" && m_sMethod != "message" && m_sMethod != "off") { + if (m_sMethod != "notice" && m_sMethod != "message" && + m_sMethod != "off") { m_sMethod = "message"; } @@ -68,10 +78,12 @@ public: void OnClientLogin() override { CString sRemoteIP = GetClient()->GetRemoteIP(); - if(!m_bNewOnly || m_sClientsSeen.find(sRemoteIP) == m_sClientsSeen.end()) { - SendNotification("Another client authenticated as your user. " - "Use the 'ListClients' command to see all " + - CString(GetUser()->GetAllClients().size()) + " clients."); + if (!m_bNewOnly || + m_sClientsSeen.find(sRemoteIP) == m_sClientsSeen.end()) { + SendNotification( + "Another client authenticated as your user. " + "Use the 'ListClients' command to see all " + + CString(GetUser()->GetAllClients().size()) + " clients."); // the set<> will automatically disregard duplicates: m_sClientsSeen.insert(sRemoteIP); @@ -79,10 +91,12 @@ public: } void OnClientDisconnect() override { - if(m_bOnDisconnect) { - SendNotification("A client disconnected from your user. " - "Use the 'ListClients' command to see the " + - CString(GetUser()->GetAllClients().size()) + " remaining client(s)."); + if (m_bOnDisconnect) { + SendNotification( + "A client disconnected from your user. " + "Use the 'ListClients' command to see the " + + CString(GetUser()->GetAllClients().size()) + + " remaining client(s)."); } } @@ -126,14 +140,18 @@ public: } void OnShowCommand(const CString& sLine) { - PutModule("Current settings: Method: " + m_sMethod + ", for unseen IP addresses only: " + CString(m_bNewOnly) + - ", notify on disconnecting clients: " + CString(m_bOnDisconnect)); + PutModule("Current settings: Method: " + m_sMethod + + ", for unseen IP addresses only: " + CString(m_bNewOnly) + + ", notify on disconnecting clients: " + + CString(m_bOnDisconnect)); } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("clientnotify"); } -USERMODULEDEFS(CClientNotifyMod, "Notifies you when another IRC client logs into or out of your account. Configurable.") - +USERMODULEDEFS(CClientNotifyMod, + "Notifies you when another IRC client logs into or out of your " + "account. Configurable.") diff --git a/modules/controlpanel.cpp b/modules/controlpanel.cpp index abb89c53..cadfa2e3 100644 --- a/modules/controlpanel.cpp +++ b/modules/controlpanel.cpp @@ -25,12 +25,12 @@ using std::map; using std::vector; -template +template struct array_size_helper { char __place_holder[N]; }; -template +template static array_size_helper array_size(T (&)[N]) { return array_size_helper(); } @@ -40,21 +40,24 @@ static array_size_helper array_size(T (&)[N]) { class CAdminMod : public CModule { using CModule::PutModule; - void PrintVarsHelp(const CString& sFilter, const char* vars[][2], unsigned int uSize, const CString& sDescription) { + void PrintVarsHelp(const CString& sFilter, const char* vars[][2], + unsigned int uSize, const CString& sDescription) { CTable VarTable; VarTable.AddColumn("Type"); VarTable.AddColumn("Variables"); std::map mvsTypedVariables; for (unsigned int i = 0; i != uSize; ++i) { CString sVar = CString(vars[i][0]).AsLower(); - if (sFilter.empty() || sVar.StartsWith(sFilter) || sVar.WildCmp(sFilter)) { + if (sFilter.empty() || sVar.StartsWith(sFilter) || + sVar.WildCmp(sFilter)) { mvsTypedVariables[vars[i][1]].emplace_back(vars[i][0]); } } for (const auto& i : mvsTypedVariables) { VarTable.AddRow(); VarTable.SetCell("Type", i.first); - VarTable.SetCell("Variables", CString(", ").Join(i.second.cbegin(), i.second.cend())); + VarTable.SetCell("Variables", CString(", ").Join(i.second.cbegin(), + i.second.cend())); } if (!VarTable.empty()) { PutModule(sDescription); @@ -73,85 +76,95 @@ class CAdminMod : public CModule { const CString sCmdFilter = sLine.Token(1, false); const CString sVarFilter = sLine.Token(2, true).AsLower(); - if (sCmdFilter.empty() || sCmdFilter.StartsWith("Set") || sCmdFilter.StartsWith("Get")) { + if (sCmdFilter.empty() || sCmdFilter.StartsWith("Set") || + sCmdFilter.StartsWith("Get")) { static const char* vars[][2] = { - {"Nick", str}, - {"Altnick", str}, - {"Ident", str}, - {"RealName", str}, - {"BindHost", str}, - {"MultiClients", boolean}, - {"DenyLoadMod", boolean}, - {"DenySetBindHost", boolean}, - {"DefaultChanModes", str}, - {"QuitMsg", str}, - {"ChanBufferSize", integer}, - {"QueryBufferSize", integer}, - {"AutoClearChanBuffer", boolean}, - {"AutoClearQueryBuffer",boolean}, - {"Password", str}, - {"JoinTries", integer}, - {"MaxJoins", integer}, - {"MaxNetworks", integer}, - {"MaxQueryBuffers", integer}, - {"Timezone", str}, - {"Admin", boolean}, - {"AppendTimestamp", boolean}, - {"PrependTimestamp", boolean}, - {"TimestampFormat", str}, - {"DCCBindHost", str}, - {"StatusPrefix", str}, + {"Nick", str}, + {"Altnick", str}, + {"Ident", str}, + {"RealName", str}, + {"BindHost", str}, + {"MultiClients", boolean}, + {"DenyLoadMod", boolean}, + {"DenySetBindHost", boolean}, + {"DefaultChanModes", str}, + {"QuitMsg", str}, + {"ChanBufferSize", integer}, + {"QueryBufferSize", integer}, + {"AutoClearChanBuffer", boolean}, + {"AutoClearQueryBuffer", boolean}, + {"Password", str}, + {"JoinTries", integer}, + {"MaxJoins", integer}, + {"MaxNetworks", integer}, + {"MaxQueryBuffers", integer}, + {"Timezone", str}, + {"Admin", boolean}, + {"AppendTimestamp", boolean}, + {"PrependTimestamp", boolean}, + {"TimestampFormat", str}, + {"DCCBindHost", str}, + {"StatusPrefix", str}, #ifdef HAVE_ICU - {"ClientEncoding", str}, + {"ClientEncoding", str}, #endif }; - PrintVarsHelp(sVarFilter, vars, ARRAY_SIZE(vars), "The following variables are available when using the Set/Get commands:"); + PrintVarsHelp(sVarFilter, vars, ARRAY_SIZE(vars), + "The following variables are available when using " + "the Set/Get commands:"); } - if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetNetwork") || sCmdFilter.StartsWith("GetNetwork")) { + if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetNetwork") || + sCmdFilter.StartsWith("GetNetwork")) { static const char* nvars[][2] = { - {"Nick", str}, - {"Altnick", str}, - {"Ident", str}, - {"RealName", str}, - {"BindHost", str}, - {"FloodRate", doublenum}, - {"FloodBurst", integer}, - {"JoinDelay", integer}, + {"Nick", str}, + {"Altnick", str}, + {"Ident", str}, + {"RealName", str}, + {"BindHost", str}, + {"FloodRate", doublenum}, + {"FloodBurst", integer}, + {"JoinDelay", integer}, #ifdef HAVE_ICU - {"Encoding", str}, + {"Encoding", str}, #endif - {"QuitMsg", str}, + {"QuitMsg", str}, }; - PrintVarsHelp(sVarFilter, nvars, ARRAY_SIZE(nvars), "The following variables are available when using the SetNetwork/GetNetwork commands:"); + PrintVarsHelp(sVarFilter, nvars, ARRAY_SIZE(nvars), + "The following variables are available when using " + "the SetNetwork/GetNetwork commands:"); } - if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetChan") || sCmdFilter.StartsWith("GetChan")) { - static const char* cvars[][2] = { - {"DefModes", str}, - {"Key", str}, - {"BufferSize", integer}, - {"InConfig", boolean}, - {"AutoClearChanBuffer", boolean}, - {"Detached", boolean} - }; - PrintVarsHelp(sVarFilter, cvars, ARRAY_SIZE(cvars), "The following variables are available when using the SetChan/GetChan commands:"); + if (sCmdFilter.empty() || sCmdFilter.StartsWith("SetChan") || + sCmdFilter.StartsWith("GetChan")) { + static const char* cvars[][2] = {{"DefModes", str}, + {"Key", str}, + {"BufferSize", integer}, + {"InConfig", boolean}, + {"AutoClearChanBuffer", boolean}, + {"Detached", boolean}}; + PrintVarsHelp(sVarFilter, cvars, ARRAY_SIZE(cvars), + "The following variables are available when using " + "the SetChan/GetChan commands:"); } if (sCmdFilter.empty()) - PutModule("You can use $user as the user name and $network as the network name for modifying your own user and network."); + PutModule( + "You can use $user as the user name and $network as the " + "network name for modifying your own user and network."); } CUser* FindUser(const CString& sUsername) { if (sUsername.Equals("$me") || sUsername.Equals("$user")) return GetUser(); - CUser *pUser = CZNC::Get().FindUser(sUsername); + CUser* pUser = CZNC::Get().FindUser(sUsername); if (!pUser) { PutModule("Error: User [" + sUsername + "] not found."); return nullptr; } if (pUser != GetUser() && !GetUser()->IsAdmin()) { - PutModule("Error: You need to have admin rights to modify other users!"); + PutModule( + "Error: You need to have admin rights to modify other users!"); return nullptr; } return pUser; @@ -160,26 +173,28 @@ class CAdminMod : public CModule { CIRCNetwork* FindNetwork(CUser* pUser, const CString& sNetwork) { if (sNetwork.Equals("$net") || sNetwork.Equals("$network")) { if (pUser != GetUser()) { - PutModule("Error: You cannot use " + sNetwork + " to modify other users!"); + PutModule("Error: You cannot use " + sNetwork + + " to modify other users!"); return nullptr; } return CModule::GetNetwork(); } CIRCNetwork* pNetwork = pUser->FindNetwork(sNetwork); if (!pNetwork) { - PutModule("Error: [" + pUser->GetUserName() + "] does not have a network named [" + sNetwork + "]."); + PutModule("Error: [" + pUser->GetUserName() + + "] does not have a network named [" + sNetwork + "]."); } return pNetwork; } void Get(const CString& sLine) { const CString sVar = sLine.Token(1).AsLower(); - CString sUsername = sLine.Token(2, true); + CString sUsername = sLine.Token(2, true); CUser* pUser; if (sVar.empty()) { - PutModule("Usage: Get [username]"); - return; + PutModule("Usage: Get [username]"); + return; } if (sUsername.empty()) { @@ -188,8 +203,7 @@ class CAdminMod : public CModule { pUser = FindUser(sUsername); } - if (!pUser) - return; + if (!pUser) return; if (sVar == "nick") PutModule("Nick = " + pUser->GetNick()); @@ -214,15 +228,23 @@ class CAdminMod : public CModule { else if (sVar == "buffercount") PutModule("BufferCount = " + CString(pUser->GetBufferCount())); else if (sVar == "chanbuffersize") - PutModule("ChanBufferSize = " + CString(pUser->GetChanBufferSize())); + PutModule("ChanBufferSize = " + + CString(pUser->GetChanBufferSize())); else if (sVar == "querybuffersize") - PutModule("QueryBufferSize = " + CString(pUser->GetQueryBufferSize())); + PutModule("QueryBufferSize = " + + CString(pUser->GetQueryBufferSize())); else if (sVar == "keepbuffer") - PutModule("KeepBuffer = " + CString(!pUser->AutoClearChanBuffer())); // XXX compatibility crap, added in 0.207 + PutModule("KeepBuffer = " + + CString(!pUser->AutoClearChanBuffer())); // XXX + // compatibility + // crap, added + // in 0.207 else if (sVar == "autoclearchanbuffer") - PutModule("AutoClearChanBuffer = " + CString(pUser->AutoClearChanBuffer())); + PutModule("AutoClearChanBuffer = " + + CString(pUser->AutoClearChanBuffer())); else if (sVar == "autoclearquerybuffer") - PutModule("AutoClearQueryBuffer = " + CString(pUser->AutoClearQueryBuffer())); + PutModule("AutoClearQueryBuffer = " + + CString(pUser->AutoClearQueryBuffer())); else if (sVar == "maxjoins") PutModule("MaxJoins = " + CString(pUser->MaxJoins())); else if (sVar == "maxnetworks") @@ -234,9 +256,11 @@ class CAdminMod : public CModule { else if (sVar == "timezone") PutModule("Timezone = " + pUser->GetTimezone()); else if (sVar == "appendtimestamp") - PutModule("AppendTimestamp = " + CString(pUser->GetTimestampAppend())); + PutModule("AppendTimestamp = " + + CString(pUser->GetTimestampAppend())); else if (sVar == "prependtimestamp") - PutModule("PrependTimestamp = " + CString(pUser->GetTimestampPrepend())); + PutModule("PrependTimestamp = " + + CString(pUser->GetTimestampPrepend())); else if (sVar == "timestampformat") PutModule("TimestampFormat = " + pUser->GetTimestampFormat()); else if (sVar == "dccbindhost") @@ -254,9 +278,9 @@ class CAdminMod : public CModule { } void Set(const CString& sLine) { - const CString sVar = sLine.Token(1).AsLower(); - CString sUserName = sLine.Token(2); - CString sValue = sLine.Token(3, true); + const CString sVar = sLine.Token(1).AsLower(); + CString sUserName = sLine.Token(2); + CString sValue = sLine.Token(3, true); if (sValue.empty()) { PutModule("Usage: Set "); @@ -264,27 +288,22 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUserName); - if (!pUser) - return; + if (!pUser) return; if (sVar == "nick") { pUser->SetNick(sValue); PutModule("Nick = " + sValue); - } - else if (sVar == "altnick") { + } else if (sVar == "altnick") { pUser->SetAltNick(sValue); PutModule("AltNick = " + sValue); - } - else if (sVar == "ident") { + } else if (sVar == "ident") { pUser->SetIdent(sValue); PutModule("Ident = " + sValue); - } - else if (sVar == "realname") { + } else if (sVar == "realname") { pUser->SetRealName(sValue); PutModule("RealName = " + sValue); - } - else if (sVar == "bindhost") { - if(!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { + } else if (sVar == "bindhost") { + if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { if (sValue.Equals(GetUser()->GetBindHost())) { PutModule("This bind host is already set!"); return; @@ -295,139 +314,118 @@ class CAdminMod : public CModule { } else { PutModule("Access denied!"); } - } - else if (sVar == "multiclients") { + } else if (sVar == "multiclients") { bool b = sValue.ToBool(); pUser->SetMultiClients(b); PutModule("MultiClients = " + CString(b)); - } - else if (sVar == "denyloadmod") { - if(GetUser()->IsAdmin()) { + } else if (sVar == "denyloadmod") { + if (GetUser()->IsAdmin()) { bool b = sValue.ToBool(); pUser->SetDenyLoadMod(b); PutModule("DenyLoadMod = " + CString(b)); } else { PutModule("Access denied!"); } - } - else if (sVar == "denysetbindhost") { - if(GetUser()->IsAdmin()) { + } else if (sVar == "denysetbindhost") { + if (GetUser()->IsAdmin()) { bool b = sValue.ToBool(); pUser->SetDenySetBindHost(b); PutModule("DenySetBindHost = " + CString(b)); } else { PutModule("Access denied!"); } - } - else if (sVar == "defaultchanmodes") { + } else if (sVar == "defaultchanmodes") { pUser->SetDefaultChanModes(sValue); PutModule("DefaultChanModes = " + sValue); - } - else if (sVar == "quitmsg") { + } else if (sVar == "quitmsg") { pUser->SetQuitMsg(sValue); PutModule("QuitMsg = " + sValue); - } - else if (sVar == "chanbuffersize" || sVar == "buffercount") { + } else if (sVar == "chanbuffersize" || sVar == "buffercount") { unsigned int i = sValue.ToUInt(); // Admins don't have to honour the buffer limit if (pUser->SetChanBufferSize(i, GetUser()->IsAdmin())) { PutModule("ChanBufferSize = " + sValue); } else { PutModule("Setting failed, limit is " + - CString(CZNC::Get().GetMaxBufferSize())); + CString(CZNC::Get().GetMaxBufferSize())); } - } - else if (sVar == "querybuffersize") { + } else if (sVar == "querybuffersize") { unsigned int i = sValue.ToUInt(); // Admins don't have to honour the buffer limit if (pUser->SetQueryBufferSize(i, GetUser()->IsAdmin())) { PutModule("QueryBufferSize = " + sValue); } else { PutModule("Setting failed, limit is " + - CString(CZNC::Get().GetMaxBufferSize())); + CString(CZNC::Get().GetMaxBufferSize())); } - } - else if (sVar == "keepbuffer") { // XXX compatibility crap, added in 0.207 + } else if (sVar == + "keepbuffer") { // XXX compatibility crap, added in 0.207 bool b = !sValue.ToBool(); pUser->SetAutoClearChanBuffer(b); PutModule("AutoClearChanBuffer = " + CString(b)); - } - else if (sVar == "autoclearchanbuffer") { + } else if (sVar == "autoclearchanbuffer") { bool b = sValue.ToBool(); pUser->SetAutoClearChanBuffer(b); PutModule("AutoClearChanBuffer = " + CString(b)); - } - else if (sVar == "autoclearquerybuffer") { + } else if (sVar == "autoclearquerybuffer") { bool b = sValue.ToBool(); pUser->SetAutoClearQueryBuffer(b); PutModule("AutoClearQueryBuffer = " + CString(b)); - } - else if (sVar == "password") { + } else if (sVar == "password") { const CString sSalt = CUtils::GetSalt(); const CString sHash = CUser::SaltedHash(sValue, sSalt); pUser->SetPass(sHash, CUser::HASH_DEFAULT, sSalt); PutModule("Password has been changed!"); - } - else if (sVar == "maxjoins") { + } else if (sVar == "maxjoins") { unsigned int i = sValue.ToUInt(); pUser->SetMaxJoins(i); PutModule("MaxJoins = " + CString(pUser->MaxJoins())); - } - else if (sVar == "maxnetworks") { - if(GetUser()->IsAdmin()) { + } else if (sVar == "maxnetworks") { + if (GetUser()->IsAdmin()) { unsigned int i = sValue.ToUInt(); pUser->SetMaxNetworks(i); PutModule("MaxNetworks = " + sValue); } else { PutModule("Access denied!"); } - } - else if (sVar == "maxquerybuffers") { + } else if (sVar == "maxquerybuffers") { unsigned int i = sValue.ToUInt(); pUser->SetMaxQueryBuffers(i); PutModule("MaxQueryBuffers = " + sValue); - } - else if (sVar == "jointries") { + } else if (sVar == "jointries") { unsigned int i = sValue.ToUInt(); pUser->SetJoinTries(i); PutModule("JoinTries = " + CString(pUser->JoinTries())); - } - else if (sVar == "timezone") { + } else if (sVar == "timezone") { pUser->SetTimezone(sValue); PutModule("Timezone = " + pUser->GetTimezone()); - } - else if (sVar == "admin") { - if(GetUser()->IsAdmin() && pUser != GetUser()) { + } else if (sVar == "admin") { + if (GetUser()->IsAdmin() && pUser != GetUser()) { bool b = sValue.ToBool(); pUser->SetAdmin(b); PutModule("Admin = " + CString(pUser->IsAdmin())); } else { PutModule("Access denied!"); } - } - else if (sVar == "prependtimestamp") { + } else if (sVar == "prependtimestamp") { bool b = sValue.ToBool(); pUser->SetTimestampPrepend(b); PutModule("PrependTimestamp = " + CString(b)); - } - else if (sVar == "appendtimestamp") { + } else if (sVar == "appendtimestamp") { bool b = sValue.ToBool(); pUser->SetTimestampAppend(b); PutModule("AppendTimestamp = " + CString(b)); - } - else if (sVar == "timestampformat") { + } else if (sVar == "timestampformat") { pUser->SetTimestampFormat(sValue); PutModule("TimestampFormat = " + sValue); - } - else if (sVar == "dccbindhost") { - if(!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { + } else if (sVar == "dccbindhost") { + if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { pUser->SetDCCBindHost(sValue); PutModule("DCCBindHost = " + sValue); } else { PutModule("Access denied!"); } - } - else if (sVar == "statusprefix") { + } else if (sVar == "statusprefix") { if (sVar.find_first_of(" \t\n") == CString::npos) { pUser->SetStatusPrefix(sValue); PutModule("StatusPrefix = " + sValue); @@ -450,7 +448,7 @@ class CAdminMod : public CModule { const CString sUsername = sLine.Token(2); const CString sNetwork = sLine.Token(3); - CIRCNetwork *pNetwork = nullptr; + CIRCNetwork* pNetwork = nullptr; CUser* pUser; if (sVar.empty()) { @@ -472,7 +470,9 @@ class CAdminMod : public CModule { if (pUser == GetUser()) { pNetwork = CModule::GetNetwork(); } else { - PutModule("Error: A network must be specified to get another users settings."); + PutModule( + "Error: A network must be specified to get another users " + "settings."); return; } @@ -521,11 +521,12 @@ class CAdminMod : public CModule { const CString sNetwork = sLine.Token(3); const CString sValue = sLine.Token(4, true); - CUser *pUser = nullptr; - CIRCNetwork *pNetwork = nullptr; + CUser* pUser = nullptr; + CIRCNetwork* pNetwork = nullptr; if (sValue.empty()) { - PutModule("Usage: SetNetwork "); + PutModule( + "Usage: SetNetwork "); return; } @@ -557,7 +558,7 @@ class CAdminMod : public CModule { pNetwork->SetRealName(sValue); PutModule("RealName = " + pNetwork->GetRealName()); } else if (sVar.Equals("bindhost")) { - if(!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { + if (!pUser->DenySetBindHost() || GetUser()->IsAdmin()) { if (sValue.Equals(pNetwork->GetBindHost())) { PutModule("This bind host is already set!"); return; @@ -589,63 +590,65 @@ class CAdminMod : public CModule { PutModule("Error: Unknown variable"); } } - + void AddChan(const CString& sLine) { - const CString sUsername = sLine.Token(1); - const CString sNetwork = sLine.Token(2); - const CString sChan = sLine.Token(3); - + const CString sUsername = sLine.Token(1); + const CString sNetwork = sLine.Token(2); + const CString sChan = sLine.Token(3); + if (sChan.empty()) { PutModule("Usage: AddChan "); return; } - + CUser* pUser = FindUser(sUsername); - if (!pUser) - return; - + if (!pUser) return; + CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { return; } - + if (pNetwork->FindChan(sChan)) { - PutModule("Error: [" + sUsername + "] already has a channel named [" + sChan + "]."); + PutModule("Error: [" + sUsername + + "] already has a channel named [" + sChan + "]."); return; } - + CChan* pChan = new CChan(sChan, pNetwork, true); if (pNetwork->AddChan(pChan)) - PutModule("Channel [" + pChan->GetName() + "] for user [" + sUsername + "] added."); + PutModule("Channel [" + pChan->GetName() + "] for user [" + + sUsername + "] added."); else - PutModule("Could not add channel [" + sChan + "] for user [" + sUsername + "], does it already exist?"); + PutModule("Could not add channel [" + sChan + "] for user [" + + sUsername + "], does it already exist?"); } - + void DelChan(const CString& sLine) { - const CString sUsername = sLine.Token(1); - const CString sNetwork = sLine.Token(2); - const CString sChan = sLine.Token(3); - + const CString sUsername = sLine.Token(1); + const CString sNetwork = sLine.Token(2); + const CString sChan = sLine.Token(3); + if (sChan.empty()) { PutModule("Usage: DelChan "); return; } - + CUser* pUser = FindUser(sUsername); - if (!pUser) - return; - + if (!pUser) return; + CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { return; } - + std::vector vChans = pNetwork->FindChans(sChan); if (vChans.empty()) { - PutModule("Error: User [" + sUsername + "] does not have any channel matching [" + sChan + "]."); + PutModule("Error: User [" + sUsername + + "] does not have any channel matching [" + sChan + "]."); return; } - + VCString vsNames; for (const CChan* pChan : vChans) { const CString& sName = pChan->GetName(); @@ -653,14 +656,16 @@ class CAdminMod : public CModule { pNetwork->PutIRC("PART " + sName); pNetwork->DelChan(sName); } - - PutModule("Channel(s) [" + CString(",").Join(vsNames.begin(), vsNames.end()) + "] for user [" + sUsername + "] deleted."); + + PutModule("Channel(s) [" + + CString(",").Join(vsNames.begin(), vsNames.end()) + + "] for user [" + sUsername + "] deleted."); } void GetChan(const CString& sLine) { - const CString sVar = sLine.Token(1).AsLower(); - CString sUsername = sLine.Token(2); - CString sNetwork = sLine.Token(3); + const CString sVar = sLine.Token(1).AsLower(); + CString sUsername = sLine.Token(2); + CString sNetwork = sLine.Token(3); CString sChan = sLine.Token(4, true); if (sChan.empty()) { @@ -669,8 +674,7 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { @@ -685,7 +689,8 @@ class CAdminMod : public CModule { for (CChan* pChan : vChans) { if (sVar == "defmodes") { - PutModule(pChan->GetName() + ": DefModes = " + pChan->GetDefaultModes()); + PutModule(pChan->GetName() + ": DefModes = " + + pChan->GetDefaultModes()); } else if (sVar == "buffersize" || sVar == "buffer") { CString sValue(pChan->GetBufferCount()); if (!pChan->HasBufferCountSet()) { @@ -693,17 +698,25 @@ class CAdminMod : public CModule { } PutModule(pChan->GetName() + ": BufferSize = " + sValue); } else if (sVar == "inconfig") { - PutModule(pChan->GetName() + ": InConfig = " + CString(pChan->InConfig())); + PutModule(pChan->GetName() + ": InConfig = " + + CString(pChan->InConfig())); } else if (sVar == "keepbuffer") { - PutModule(pChan->GetName() + ": KeepBuffer = " + CString(!pChan->AutoClearChanBuffer()));// XXX compatibility crap, added in 0.207 + PutModule( + pChan->GetName() + ": KeepBuffer = " + + CString(!pChan->AutoClearChanBuffer())); // XXX + // compatibility + // crap, added in + // 0.207 } else if (sVar == "autoclearchanbuffer") { CString sValue(pChan->AutoClearChanBuffer()); if (!pChan->HasAutoClearChanBufferSet()) { sValue += " (default)"; } - PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + sValue); + PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + + sValue); } else if (sVar == "detached") { - PutModule(pChan->GetName() + ": Detached = " + CString(pChan->IsDetached())); + PutModule(pChan->GetName() + ": Detached = " + + CString(pChan->IsDetached())); } else if (sVar == "key") { PutModule(pChan->GetName() + ": Key = " + pChan->GetKey()); } else { @@ -715,19 +728,20 @@ class CAdminMod : public CModule { void SetChan(const CString& sLine) { const CString sVar = sLine.Token(1).AsLower(); - CString sUsername = sLine.Token(2); - CString sNetwork = sLine.Token(3); - CString sChan = sLine.Token(4); - CString sValue = sLine.Token(5, true); + CString sUsername = sLine.Token(2); + CString sNetwork = sLine.Token(3); + CString sChan = sLine.Token(4); + CString sValue = sLine.Token(5, true); if (sValue.empty()) { - PutModule("Usage: SetChan "); + PutModule( + "Usage: SetChan " + ""); return; } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { @@ -748,23 +762,26 @@ class CAdminMod : public CModule { unsigned int i = sValue.ToUInt(); if (sValue.Equals("-")) { pChan->ResetBufferCount(); - PutModule(pChan->GetName() + ": BufferSize = " + CString(pChan->GetBufferCount())); - // Admins don't have to honour the buffer limit + PutModule(pChan->GetName() + ": BufferSize = " + + CString(pChan->GetBufferCount())); + // Admins don't have to honour the buffer limit } else if (pChan->SetBufferCount(i, GetUser()->IsAdmin())) { PutModule(pChan->GetName() + ": BufferSize = " + sValue); } else { PutModule("Setting failed, limit is " + - CString(CZNC::Get().GetMaxBufferSize())); + CString(CZNC::Get().GetMaxBufferSize())); return; } } else if (sVar == "inconfig") { bool b = sValue.ToBool(); pChan->SetInConfig(b); PutModule(pChan->GetName() + ": InConfig = " + CString(b)); - } else if (sVar == "keepbuffer") { // XXX compatibility crap, added in 0.207 + } else if (sVar == "keepbuffer") { // XXX compatibility crap, added + // in 0.207 bool b = !sValue.ToBool(); pChan->SetAutoClearChanBuffer(b); - PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + CString(b)); + PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + + CString(b)); } else if (sVar == "autoclearchanbuffer") { if (sValue.Equals("-")) { pChan->ResetAutoClearChanBuffer(); @@ -772,7 +789,8 @@ class CAdminMod : public CModule { bool b = sValue.ToBool(); pChan->SetAutoClearChanBuffer(b); } - PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + CString(pChan->AutoClearChanBuffer())); + PutModule(pChan->GetName() + ": AutoClearChanBuffer = " + + CString(pChan->AutoClearChanBuffer())); } else if (sVar == "detached") { bool b = sValue.ToBool(); if (pChan->IsDetached() != b) { @@ -793,8 +811,7 @@ class CAdminMod : public CModule { } void ListUsers(const CString&) { - if (!GetUser()->IsAdmin()) - return; + if (!GetUser()->IsAdmin()) return; const map& msUsers = CZNC::Get().GetUserMap(); CTable Table; @@ -829,9 +846,7 @@ class CAdminMod : public CModule { return; } - const CString - sUsername = sLine.Token(1), - sPassword = sLine.Token(2); + const CString sUsername = sLine.Token(1), sPassword = sLine.Token(2); if (sPassword.empty()) { PutModule("Usage: AddUser "); return; @@ -844,7 +859,8 @@ class CAdminMod : public CModule { CUser* pNewUser = new CUser(sUsername); CString sSalt = CUtils::GetSalt(); - pNewUser->SetPass(CUser::SaltedHash(sPassword, sSalt), CUser::HASH_DEFAULT, sSalt); + pNewUser->SetPass(CUser::SaltedHash(sPassword, sSalt), + CUser::HASH_DEFAULT, sSalt); CString sErr; if (!CZNC::Get().AddUser(pNewUser, sErr)) { @@ -863,13 +879,13 @@ class CAdminMod : public CModule { return; } - const CString sUsername = sLine.Token(1, true); + const CString sUsername = sLine.Token(1, true); if (sUsername.empty()) { PutModule("Usage: DelUser "); return; } - CUser *pUser = CZNC::Get().FindUser(sUsername); + CUser* pUser = CZNC::Get().FindUser(sUsername); if (!pUser) { PutModule("Error: User [" + sUsername + "] does not exist!"); @@ -897,16 +913,15 @@ class CAdminMod : public CModule { return; } - const CString - sOldUsername = sLine.Token(1), - sNewUsername = sLine.Token(2, true); + const CString sOldUsername = sLine.Token(1), + sNewUsername = sLine.Token(2, true); if (sOldUsername.empty() || sNewUsername.empty()) { PutModule("Usage: CloneUser "); return; } - CUser *pOldUser = CZNC::Get().FindUser(sOldUsername); + CUser* pOldUser = CZNC::Get().FindUser(sOldUsername); if (!pOldUser) { PutModule("Error: User [" + sOldUsername + "] not found!"); @@ -934,7 +949,7 @@ class CAdminMod : public CModule { void AddNetwork(const CString& sLine) { CString sUser = sLine.Token(1); CString sNetwork = sLine.Token(2); - CUser *pUser = GetUser(); + CUser* pUser = GetUser(); if (sNetwork.empty()) { sNetwork = sUser; @@ -952,27 +967,35 @@ class CAdminMod : public CModule { } if (!GetUser()->IsAdmin() && !pUser->HasSpaceForNewNetwork()) { - PutStatus("Network number limit reached. Ask an admin to increase the limit for you, or delete unneeded networks using /znc DelNetwork "); + PutStatus( + "Network number limit reached. Ask an admin to increase the " + "limit for you, or delete unneeded networks using /znc " + "DelNetwork "); return; } if (pUser->FindNetwork(sNetwork)) { - PutModule("[" + pUser->GetUserName() + "] already has a network with the name [" + sNetwork + "]"); + PutModule("[" + pUser->GetUserName() + + "] already has a network with the name [" + sNetwork + + "]"); return; } CString sNetworkAddError; if (pUser->AddNetwork(sNetwork, sNetworkAddError)) { - PutModule("Network [" + sNetwork + "] added for user [" + pUser->GetUserName() + "]."); + PutModule("Network [" + sNetwork + "] added for user [" + + pUser->GetUserName() + "]."); } else { - PutModule("Network [" + sNetwork + "] could not be added for user [" + pUser->GetUserName() + "]: " + sNetworkAddError); + PutModule("Network [" + sNetwork + + "] could not be added for user [" + pUser->GetUserName() + + "]: " + sNetworkAddError); } } void DelNetwork(const CString& sLine) { CString sUser = sLine.Token(1); CString sNetwork = sLine.Token(2); - CUser *pUser = GetUser(); + CUser* pUser = GetUser(); if (sNetwork.empty()) { sNetwork = sUser; @@ -994,20 +1017,24 @@ class CAdminMod : public CModule { } if (pNetwork == CModule::GetNetwork()) { - PutModule("The currently active network can be deleted via " + GetUser()->GetStatusPrefix() + "status"); + PutModule("The currently active network can be deleted via " + + GetUser()->GetStatusPrefix() + "status"); return; } if (pUser->DeleteNetwork(sNetwork)) { - PutModule("Network [" + sNetwork + "] deleted on user [" + pUser->GetUserName() + "]."); + PutModule("Network [" + sNetwork + "] deleted on user [" + + pUser->GetUserName() + "]."); } else { - PutModule("Network [" + sNetwork + "] could not be deleted for user [" + pUser->GetUserName() + "]."); + PutModule("Network [" + sNetwork + + "] could not be deleted for user [" + + pUser->GetUserName() + "]."); } } void ListNetworks(const CString& sLine) { CString sUser = sLine.Token(1); - CUser *pUser = GetUser(); + CUser* pUser = GetUser(); if (!sUser.empty()) { pUser = FindUser(sUser); @@ -1054,8 +1081,7 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { @@ -1063,9 +1089,12 @@ class CAdminMod : public CModule { } if (pNetwork->AddServer(sServer)) - PutModule("Added IRC Server [" + sServer + "] for network [" + sNetwork + "] for user [" + pUser->GetUserName() + "]."); + PutModule("Added IRC Server [" + sServer + "] for network [" + + sNetwork + "] for user [" + pUser->GetUserName() + "]."); else - PutModule("Could not add IRC server [" + sServer + "] for network [" + sNetwork + "] for user [" + pUser->GetUserName() + "]."); + PutModule("Could not add IRC server [" + sServer + + "] for network [" + sNetwork + "] for user [" + + pUser->GetUserName() + "]."); } void DelServer(const CString& sLine) { @@ -1081,8 +1110,7 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { @@ -1090,9 +1118,12 @@ class CAdminMod : public CModule { } if (pNetwork->DelServer(sServer, uPort, sPass)) - PutModule("Deleted IRC Server [" + sServer + "] for network [" + sNetwork + "] for user [" + pUser->GetUserName() + "]."); + PutModule("Deleted IRC Server [" + sServer + "] for network [" + + sNetwork + "] for user [" + pUser->GetUserName() + "]."); else - PutModule("Could not delete IRC server [" + sServer + "] for network [" + sNetwork + "] for user [" + pUser->GetUserName() + "]."); + PutModule("Could not delete IRC server [" + sServer + + "] for network [" + sNetwork + "] for user [" + + pUser->GetUserName() + "]."); } void ReconnectUser(const CString& sLine) { @@ -1115,20 +1146,21 @@ class CAdminMod : public CModule { return; } - CIRCSock *pIRCSock = pNetwork->GetIRCSock(); + CIRCSock* pIRCSock = pNetwork->GetIRCSock(); // cancel connection attempt: if (pIRCSock && !pIRCSock->IsConnected()) { pIRCSock->Close(); } // or close existing connection: - else if(pIRCSock) { + else if (pIRCSock) { pIRCSock->Quit(); } // then reconnect pNetwork->SetIRCConnectEnabled(true); - PutModule("Queued network [" + sNetwork + "] for user [" + pUser->GetUserName() + "] for a reconnect."); + PutModule("Queued network [" + sNetwork + "] for user [" + + pUser->GetUserName() + "] for a reconnect."); } void DisconnectUser(const CString& sLine) { @@ -1152,7 +1184,8 @@ class CAdminMod : public CModule { } pNetwork->SetIRCConnectEnabled(false); - PutModule("Closed IRC connection for network [" + sNetwork + "] on user [" + sUserName + "]."); + PutModule("Closed IRC connection for network [" + sNetwork + + "] on user [" + sUserName + "]."); } void ListCTCP(const CString& sLine) { @@ -1162,8 +1195,7 @@ class CAdminMod : public CModule { sUserName = GetUser()->GetUserName(); } CUser* pUser = FindUser(sUserName); - if (!pUser) - return; + if (!pUser) return; const MCString& msCTCPReplies = pUser->GetCTCPReplies(); CTable Table; @@ -1176,7 +1208,8 @@ class CAdminMod : public CModule { } if (Table.empty()) { - PutModule("No CTCP replies for user [" + pUser->GetUserName() + "] configured!"); + PutModule("No CTCP replies for user [" + pUser->GetUserName() + + "] configured!"); } else { PutModule("CTCP replies for user [" + pUser->GetUserName() + "]:"); PutModule(Table); @@ -1184,9 +1217,9 @@ class CAdminMod : public CModule { } void AddCTCP(const CString& sLine) { - CString sUserName = sLine.Token(1); + CString sUserName = sLine.Token(1); CString sCTCPRequest = sLine.Token(2); - CString sCTCPReply = sLine.Token(3, true); + CString sCTCPReply = sLine.Token(3, true); if (sCTCPRequest.empty()) { sCTCPRequest = sUserName; @@ -1195,14 +1228,16 @@ class CAdminMod : public CModule { } if (sCTCPRequest.empty()) { PutModule("Usage: AddCTCP [user] [request] [reply]"); - PutModule("This will cause ZNC to reply to the CTCP instead of forwarding it to clients."); - PutModule("An empty reply will cause the CTCP request to be blocked."); + PutModule( + "This will cause ZNC to reply to the CTCP instead of " + "forwarding it to clients."); + PutModule( + "An empty reply will cause the CTCP request to be blocked."); return; } CUser* pUser = FindUser(sUserName); - if (!pUser) - return; + if (!pUser) return; if (pUser->AddCTCPReply(sCTCPRequest, sCTCPReply)) PutModule("Added!"); @@ -1211,7 +1246,7 @@ class CAdminMod : public CModule { } void DelCTCP(const CString& sLine) { - CString sUserName = sLine.Token(1); + CString sUserName = sLine.Token(1); CString sCTCPRequest = sLine.Token(2, true); if (sCTCPRequest.empty()) { @@ -1219,8 +1254,7 @@ class CAdminMod : public CModule { sUserName = GetUser()->GetUserName(); } CUser* pUser = FindUser(sUserName); - if (!pUser) - return; + if (!pUser) return; if (sCTCPRequest.empty()) { PutModule("Usage: DelCTCP [user] [request]"); @@ -1228,40 +1262,49 @@ class CAdminMod : public CModule { } if (pUser->DelCTCPReply(sCTCPRequest)) - PutModule("Successfully removed [" + sCTCPRequest + "] for user [" + pUser->GetUserName() + "]."); + PutModule("Successfully removed [" + sCTCPRequest + "] for user [" + + pUser->GetUserName() + "]."); else - PutModule("Error: [" + sCTCPRequest + "] not found for user [" + pUser->GetUserName() + "]!"); + PutModule("Error: [" + sCTCPRequest + "] not found for user [" + + pUser->GetUserName() + "]!"); } - void LoadModuleFor(CModules& Modules, const CString& sModName, const CString& sArgs, CModInfo::EModuleType eType, CUser* pUser, CIRCNetwork* pNetwork) { + void LoadModuleFor(CModules& Modules, const CString& sModName, + const CString& sArgs, CModInfo::EModuleType eType, + CUser* pUser, CIRCNetwork* pNetwork) { if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) { PutModule("Loading modules has been disabled."); return; } CString sModRet; - CModule *pMod = Modules.FindModule(sModName); + CModule* pMod = Modules.FindModule(sModName); if (!pMod) { - if (!Modules.LoadModule(sModName, sArgs, eType, pUser, pNetwork, sModRet)) { - PutModule("Unable to load module [" + sModName + "] [" + sModRet + "]"); + if (!Modules.LoadModule(sModName, sArgs, eType, pUser, pNetwork, + sModRet)) { + PutModule("Unable to load module [" + sModName + "] [" + + sModRet + "]"); } else { PutModule("Loaded module [" + sModName + "]"); } } else if (pMod->GetArgs() != sArgs) { - if (!Modules.ReloadModule(sModName, sArgs, pUser, pNetwork, sModRet)) { - PutModule("Unable to reload module [" + sModName + "] [" + sModRet + "]"); + if (!Modules.ReloadModule(sModName, sArgs, pUser, pNetwork, + sModRet)) { + PutModule("Unable to reload module [" + sModName + "] [" + + sModRet + "]"); } else { PutModule("Reloaded module [" + sModName + "]"); } } else { - PutModule("Unable to load module [" + sModName + "] because it is already loaded"); + PutModule("Unable to load module [" + sModName + + "] because it is already loaded"); } } void LoadModuleForUser(const CString& sLine) { CString sUsername = sLine.Token(1); - CString sModName = sLine.Token(2); - CString sArgs = sLine.Token(3, true); + CString sModName = sLine.Token(2); + CString sArgs = sLine.Token(3, true); if (sModName.empty()) { PutModule("Usage: LoadModule [args]"); @@ -1269,36 +1312,39 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; - LoadModuleFor(pUser->GetModules(), sModName, sArgs, CModInfo::UserModule, pUser, nullptr); + LoadModuleFor(pUser->GetModules(), sModName, sArgs, + CModInfo::UserModule, pUser, nullptr); } void LoadModuleForNetwork(const CString& sLine) { CString sUsername = sLine.Token(1); - CString sNetwork = sLine.Token(2); - CString sModName = sLine.Token(3); - CString sArgs = sLine.Token(4, true); + CString sNetwork = sLine.Token(2); + CString sModName = sLine.Token(3); + CString sArgs = sLine.Token(4, true); if (sModName.empty()) { - PutModule("Usage: LoadNetModule [args]"); + PutModule( + "Usage: LoadNetModule " + "[args]"); return; } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { return; } - LoadModuleFor(pNetwork->GetModules(), sModName, sArgs, CModInfo::NetworkModule, pUser, pNetwork); + LoadModuleFor(pNetwork->GetModules(), sModName, sArgs, + CModInfo::NetworkModule, pUser, pNetwork); } - void UnLoadModuleFor(CModules& Modules, const CString& sModName, CUser* pUser) { + void UnLoadModuleFor(CModules& Modules, const CString& sModName, + CUser* pUser) { if (pUser->DenyLoadMod() && !GetUser()->IsAdmin()) { PutModule("Loading modules has been disabled."); return; @@ -1311,7 +1357,8 @@ class CAdminMod : public CModule { CString sModRet; if (!Modules.UnloadModule(sModName, sModRet)) { - PutModule("Unable to unload module [" + sModName + "] [" + sModRet + "]"); + PutModule("Unable to unload module [" + sModName + "] [" + sModRet + + "]"); } else { PutModule("Unloaded module [" + sModName + "]"); } @@ -1319,7 +1366,7 @@ class CAdminMod : public CModule { void UnLoadModuleForUser(const CString& sLine) { CString sUsername = sLine.Token(1); - CString sModName = sLine.Token(2); + CString sModName = sLine.Token(2); if (sModName.empty()) { PutModule("Usage: UnloadModule "); @@ -1327,25 +1374,24 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; UnLoadModuleFor(pUser->GetModules(), sModName, pUser); } void UnLoadModuleForNetwork(const CString& sLine) { CString sUsername = sLine.Token(1); - CString sNetwork = sLine.Token(2); - CString sModName = sLine.Token(3); + CString sNetwork = sLine.Token(2); + CString sModName = sLine.Token(3); if (sModName.empty()) { - PutModule("Usage: UnloadNetModule "); + PutModule( + "Usage: UnloadNetModule "); return; } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { @@ -1383,15 +1429,15 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; - ListModulesFor(pUser->GetModules(), "User [" + pUser->GetUserName() + "]"); + ListModulesFor(pUser->GetModules(), + "User [" + pUser->GetUserName() + "]"); } void ListModulesForNetwork(const CString& sLine) { CString sUsername = sLine.Token(1); - CString sNetwork = sLine.Token(2); + CString sNetwork = sLine.Token(2); if (sNetwork.empty()) { PutModule("Usage: ListNetMods "); @@ -1399,86 +1445,132 @@ class CAdminMod : public CModule { } CUser* pUser = FindUser(sUsername); - if (!pUser) - return; + if (!pUser) return; CIRCNetwork* pNetwork = FindNetwork(pUser, sNetwork); if (!pNetwork) { return; } - ListModulesFor(pNetwork->GetModules(), "Network [" + pNetwork->GetName() + "] of user [" + pUser->GetUserName() + "]"); + ListModulesFor(pNetwork->GetModules(), + "Network [" + pNetwork->GetName() + "] of user [" + + pUser->GetUserName() + "]"); } -public: + public: MODCONSTRUCTOR(CAdminMod) { - AddCommand("Help", static_cast(&CAdminMod::PrintHelp), - "[command] [variable]", "Prints help for matching commands and variables"); - AddCommand("Get", static_cast(&CAdminMod::Get), - " [username]", "Prints the variable's value for the given or current user"); - AddCommand("Set", static_cast(&CAdminMod::Set), - " ", "Sets the variable's value for the given user"); - AddCommand("GetNetwork", static_cast(&CAdminMod::GetNetwork), - " [username] [network]", "Prints the variable's value for the given network"); - AddCommand("SetNetwork", static_cast(&CAdminMod::SetNetwork), - " ", "Sets the variable's value for the given network"); - AddCommand("GetChan", static_cast(&CAdminMod::GetChan), - " [username] ", "Prints the variable's value for the given channel"); - AddCommand("SetChan", static_cast(&CAdminMod::SetChan), - " ", "Sets the variable's value for the given channel"); - AddCommand("AddChan", static_cast(&CAdminMod::AddChan), - " ", "Adds a new channel"); - AddCommand("DelChan", static_cast(&CAdminMod::DelChan), - " ", "Deletes a channel"); - AddCommand("ListUsers", static_cast(&CAdminMod::ListUsers), - "", "Lists users"); - AddCommand("AddUser", static_cast(&CAdminMod::AddUser), - " ", "Adds a new user"); - AddCommand("DelUser", static_cast(&CAdminMod::DelUser), - "", "Deletes a user"); - AddCommand("CloneUser", static_cast(&CAdminMod::CloneUser), - " ", "Clones a user"); - AddCommand("AddServer", static_cast(&CAdminMod::AddServer), - " ", "Adds a new IRC server for the given or current user"); - AddCommand("DelServer", static_cast(&CAdminMod::DelServer), - " ", "Deletes an IRC server from the given or current user"); - AddCommand("Reconnect", static_cast(&CAdminMod::ReconnectUser), - " ", "Cycles the user's IRC server connection"); - AddCommand("Disconnect", static_cast(&CAdminMod::DisconnectUser), - " ", "Disconnects the user from their IRC server"); - AddCommand("LoadModule", static_cast(&CAdminMod::LoadModuleForUser), - " [args]", "Loads a Module for a user"); - AddCommand("UnLoadModule", static_cast(&CAdminMod::UnLoadModuleForUser), - " ", "Removes a Module of a user"); - AddCommand("ListMods", static_cast(&CAdminMod::ListModulesForUser), - "", "Get the list of modules for a user"); - AddCommand("LoadNetModule",static_cast(&CAdminMod::LoadModuleForNetwork), - " [args]", "Loads a Module for a network"); - AddCommand("UnLoadNetModule",static_cast(&CAdminMod::UnLoadModuleForNetwork), - " ", "Removes a Module of a network"); - AddCommand("ListNetMods", static_cast(&CAdminMod::ListModulesForNetwork), - " ", "Get the list of modules for a network"); - AddCommand("ListCTCPs", static_cast(&CAdminMod::ListCTCP), - "", "List the configured CTCP replies"); - AddCommand("AddCTCP", static_cast(&CAdminMod::AddCTCP), - " [reply]", "Configure a new CTCP reply"); - AddCommand("DelCTCP", static_cast(&CAdminMod::DelCTCP), - " ", "Remove a CTCP reply"); + AddCommand("Help", + static_cast(&CAdminMod::PrintHelp), + "[command] [variable]", + "Prints help for matching commands and variables"); + AddCommand("Get", static_cast(&CAdminMod::Get), + " [username]", + "Prints the variable's value for the given or current user"); + AddCommand("Set", static_cast(&CAdminMod::Set), + " ", + "Sets the variable's value for the given user"); + AddCommand("GetNetwork", + static_cast(&CAdminMod::GetNetwork), + " [username] [network]", + "Prints the variable's value for the given network"); + AddCommand("SetNetwork", + static_cast(&CAdminMod::SetNetwork), + " ", + "Sets the variable's value for the given network"); + AddCommand("GetChan", + static_cast(&CAdminMod::GetChan), + " [username] ", + "Prints the variable's value for the given channel"); + AddCommand("SetChan", + static_cast(&CAdminMod::SetChan), + " ", + "Sets the variable's value for the given channel"); + AddCommand("AddChan", + static_cast(&CAdminMod::AddChan), + " ", "Adds a new channel"); + AddCommand("DelChan", + static_cast(&CAdminMod::DelChan), + " ", "Deletes a channel"); + AddCommand("ListUsers", + static_cast(&CAdminMod::ListUsers), + "", "Lists users"); + AddCommand("AddUser", + static_cast(&CAdminMod::AddUser), + " ", "Adds a new user"); + AddCommand("DelUser", + static_cast(&CAdminMod::DelUser), + "", "Deletes a user"); + AddCommand("CloneUser", + static_cast(&CAdminMod::CloneUser), + " ", "Clones a user"); + AddCommand("AddServer", + static_cast(&CAdminMod::AddServer), + " ", + "Adds a new IRC server for the given or current user"); + AddCommand("DelServer", + static_cast(&CAdminMod::DelServer), + " ", + "Deletes an IRC server from the given or current user"); + AddCommand( + "Reconnect", + static_cast(&CAdminMod::ReconnectUser), + " ", "Cycles the user's IRC server connection"); + AddCommand("Disconnect", static_cast( + &CAdminMod::DisconnectUser), + " ", + "Disconnects the user from their IRC server"); + AddCommand( + "LoadModule", + static_cast(&CAdminMod::LoadModuleForUser), + " [args]", "Loads a Module for a user"); + AddCommand("UnLoadModule", static_cast( + &CAdminMod::UnLoadModuleForUser), + " ", "Removes a Module of a user"); + AddCommand("ListMods", static_cast( + &CAdminMod::ListModulesForUser), + "", "Get the list of modules for a user"); + AddCommand("LoadNetModule", static_cast( + &CAdminMod::LoadModuleForNetwork), + " [args]", + "Loads a Module for a network"); + AddCommand("UnLoadNetModule", static_cast( + &CAdminMod::UnLoadModuleForNetwork), + " ", + "Removes a Module of a network"); + AddCommand("ListNetMods", static_cast( + &CAdminMod::ListModulesForNetwork), + " ", + "Get the list of modules for a network"); + AddCommand("ListCTCPs", + static_cast(&CAdminMod::ListCTCP), + "", "List the configured CTCP replies"); + AddCommand("AddCTCP", + static_cast(&CAdminMod::AddCTCP), + " [reply]", "Configure a new CTCP reply"); + AddCommand("DelCTCP", + static_cast(&CAdminMod::DelCTCP), + " ", "Remove a CTCP reply"); // Network commands - AddCommand("AddNetwork", static_cast(&CAdminMod::AddNetwork), - "[username] ", "Add a network for a user"); - AddCommand("DelNetwork", static_cast(&CAdminMod::DelNetwork), - "[username] ", "Delete a network for a user"); - AddCommand("ListNetworks", static_cast(&CAdminMod::ListNetworks), - "[username]", "List all networks for a user"); + AddCommand("AddNetwork", + static_cast(&CAdminMod::AddNetwork), + "[username] ", "Add a network for a user"); + AddCommand("DelNetwork", + static_cast(&CAdminMod::DelNetwork), + "[username] ", "Delete a network for a user"); + AddCommand("ListNetworks", static_cast( + &CAdminMod::ListNetworks), + "[username]", "List all networks for a user"); } virtual ~CAdminMod() {} }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("controlpanel"); } -USERMODULEDEFS(CAdminMod, "Dynamic configuration through IRC. Allows editing only yourself if you're not ZNC admin.") +USERMODULEDEFS(CAdminMod, + "Dynamic configuration through IRC. Allows editing only " + "yourself if you're not ZNC admin.") diff --git a/modules/crypt.cpp b/modules/crypt.cpp index cafe114e..0fa3e703 100644 --- a/modules/crypt.cpp +++ b/modules/crypt.cpp @@ -16,29 +16,36 @@ //! @author prozac@rottenboy.com // -// The encryption here was designed to be compatible with mircryption's CBC mode. +// The encryption here was designed to be compatible with mircryption's CBC +// mode. // // Latest tested against: -// MircryptionSuite - Mircryption ver 1.19.01 (dll v1.15.01 , mirc v7.32) CBC loaded and ready. +// MircryptionSuite - Mircryption ver 1.19.01 (dll v1.15.01 , mirc v7.32) CBC +// loaded and ready. // // TODO: // // 1) Encrypt key storage file // 2) Secure key exchange using pub/priv keys and the DH algorithm -// 3) Some way of notifying the user that the current channel is in "encryption mode" verses plain text +// 3) Some way of notifying the user that the current channel is in "encryption +// mode" verses plain text // 4) Temporarily disable a target (nick/chan) // -// NOTE: This module is currently NOT intended to secure you from your shell admin. -// The keys are currently stored in plain text, so anyone with access to your account (or root) can obtain them. -// It is strongly suggested that you enable SSL between znc and your client otherwise the encryption stops at znc and gets sent to your client in plain text. +// NOTE: This module is currently NOT intended to secure you from your shell +// admin. +// The keys are currently stored in plain text, so anyone with access to +// your account (or root) can obtain them. +// It is strongly suggested that you enable SSL between znc and your +// client otherwise the encryption stops at znc and gets sent to your +// client in plain text. // #include #include #include -#define REQUIRESSL 1 -#define NICK_PREFIX_KEY "[nick-prefix]" +#define REQUIRESSL 1 +#define NICK_PREFIX_KEY "[nick-prefix]" class CCryptMod : public CModule { CString NickPrefix() { @@ -46,12 +53,18 @@ class CCryptMod : public CModule { return it != EndNV() ? it->second : "*"; } -public: + public: MODCONSTRUCTOR(CCryptMod) { AddHelpCommand(); - AddCommand("DelKey", static_cast(&CCryptMod::OnDelKeyCommand), "<#chan|Nick>", "Remove a key for nick or channel"); - AddCommand("SetKey", static_cast(&CCryptMod::OnSetKeyCommand), "<#chan|Nick> ", "Set a key for nick or channel"); - AddCommand("ListKeys", static_cast(&CCryptMod::OnListKeysCommand), "", "List all keys"); + AddCommand("DelKey", static_cast( + &CCryptMod::OnDelKeyCommand), + "<#chan|Nick>", "Remove a key for nick or channel"); + AddCommand("SetKey", static_cast( + &CCryptMod::OnSetKeyCommand), + "<#chan|Nick> ", "Set a key for nick or channel"); + AddCommand("ListKeys", static_cast( + &CCryptMod::OnListKeysCommand), + "", "List all keys"); } virtual ~CCryptMod() {} @@ -70,8 +83,13 @@ public: CString sNickMask = GetNetwork()->GetIRCNick().GetNickMask(); if (pChan) { if (!pChan->AutoClearChanBuffer()) - pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + " PRIVMSG " + _NAMEDFMT(sTarget) + " :{text}", sMessage); - GetUser()->PutUser(":" + NickPrefix() + sNickMask + " PRIVMSG " + sTarget + " :" + sMessage, nullptr, GetClient()); + pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + + " PRIVMSG " + _NAMEDFMT(sTarget) + + " :{text}", + sMessage); + GetUser()->PutUser(":" + NickPrefix() + sNickMask + + " PRIVMSG " + sTarget + " :" + sMessage, + nullptr, GetClient()); } CString sMsg = MakeIvec() + sMessage; @@ -100,8 +118,13 @@ public: CString sNickMask = GetNetwork()->GetIRCNick().GetNickMask(); if (pChan) { if (!pChan->AutoClearChanBuffer()) - pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + " NOTICE " + _NAMEDFMT(sTarget) + " :{text}", sMessage); - GetUser()->PutUser(":" + NickPrefix() + sNickMask + " NOTICE " + sTarget + " :" + sMessage, NULL, GetClient()); + pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + + " NOTICE " + _NAMEDFMT(sTarget) + + " :{text}", + sMessage); + GetUser()->PutUser(":" + NickPrefix() + sNickMask + " NOTICE " + + sTarget + " :" + sMessage, + NULL, GetClient()); } CString sMsg = MakeIvec() + sMessage; @@ -130,8 +153,14 @@ public: CString sNickMask = GetNetwork()->GetIRCNick().GetNickMask(); if (pChan) { if (!pChan->AutoClearChanBuffer()) - pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + " PRIVMSG " + _NAMEDFMT(sTarget) + " :\001ACTION {text}\001", sMessage); - GetUser()->PutUser(":" + NickPrefix() + sNickMask + " PRIVMSG " + sTarget + " :\001ACTION " + sMessage + "\001", NULL, GetClient()); + pChan->AddBuffer(":" + NickPrefix() + _NAMEDFMT(sNickMask) + + " PRIVMSG " + _NAMEDFMT(sTarget) + + " :\001ACTION {text}\001", + sMessage); + GetUser()->PutUser(":" + NickPrefix() + sNickMask + + " PRIVMSG " + sTarget + " :\001ACTION " + + sMessage + "\001", + NULL, GetClient()); } CString sMsg = MakeIvec() + sMessage; @@ -185,12 +214,14 @@ public: return CONTINUE; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { FilterIncoming(Channel.GetName(), Nick, sMessage); return CONTINUE; } - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override { FilterIncoming(Channel.GetName(), Nick, sMessage); return CONTINUE; } @@ -212,14 +243,15 @@ public: sTopic.TrimPrefix(":"); FilterIncoming(pChan->GetName(), *Nick, sTopic); - sLine = sLine.Token(0) + " " + sLine.Token(1) + " " + sLine.Token(2) + " " + pChan->GetName() + " :" + sTopic; - + sLine = sLine.Token(0) + " " + sLine.Token(1) + " " + + sLine.Token(2) + " " + pChan->GetName() + " :" + sTopic; } return CONTINUE; -} + } - void FilterIncoming(const CString& sTarget, CNick& Nick, CString& sMessage) { + void FilterIncoming(const CString& sTarget, CNick& Nick, + CString& sMessage) { if (sMessage.TrimPrefix("+OK *")) { MCString::iterator it = FindNV(sTarget.AsLower()); @@ -231,7 +263,6 @@ public: Nick.SetNick(NickPrefix() + Nick.GetNick()); } } - } void OnDelKeyCommand(const CString& sCommand) { @@ -252,12 +283,14 @@ public: CString sTarget = sCommand.Token(1); CString sKey = sCommand.Token(2, true); - // Strip "cbc:" from beginning of string incase someone pastes directly from mircryption + // Strip "cbc:" from beginning of string incase someone pastes directly + // from mircryption sKey.TrimPrefix("cbc:"); if (!sKey.empty()) { SetNV(sTarget.AsLower(), sKey); - PutModule("Set encryption key for [" + sTarget + "] to [" + sKey + "]"); + PutModule("Set encryption key for [" + sTarget + "] to [" + sKey + + "]"); } else { PutModule("Usage: SetKey <#chan|Nick> "); } @@ -293,14 +326,15 @@ public: time_t t; time(&t); int r = rand(); - sRet.append((char*) &t, 4); - sRet.append((char*) &r, 4); + sRet.append((char*)&t, 4); + sRet.append((char*)&r, 4); return sRet; } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("crypt"); } diff --git a/modules/ctcpflood.cpp b/modules/ctcpflood.cpp index d64018ef..05e2a4a8 100644 --- a/modules/ctcpflood.cpp +++ b/modules/ctcpflood.cpp @@ -19,16 +19,21 @@ #include class CCtcpFloodMod : public CModule { -public: + public: MODCONSTRUCTOR(CCtcpFloodMod) { AddHelpCommand(); - AddCommand("Secs", static_cast(&CCtcpFloodMod::OnSecsCommand), "", "Set seconds limit"); - AddCommand("Lines", static_cast(&CCtcpFloodMod::OnLinesCommand), "", "Set lines limit"); - AddCommand("Show", static_cast(&CCtcpFloodMod::OnShowCommand), "", "Show the current limits"); + AddCommand("Secs", static_cast( + &CCtcpFloodMod::OnSecsCommand), + "", "Set seconds limit"); + AddCommand("Lines", static_cast( + &CCtcpFloodMod::OnLinesCommand), + "", "Set lines limit"); + AddCommand("Show", static_cast( + &CCtcpFloodMod::OnShowCommand), + "", "Show the current limits"); } - ~CCtcpFloodMod() { - } + ~CCtcpFloodMod() {} void Save() { // We save the settings twice because the module arguments can @@ -49,10 +54,8 @@ public: m_iThresholdSecs = GetNV("secs").ToUInt(); } - if (m_iThresholdSecs == 0) - m_iThresholdSecs = 2; - if (m_iThresholdMsgs == 0) - m_iThresholdMsgs = 4; + if (m_iThresholdSecs == 0) m_iThresholdSecs = 2; + if (m_iThresholdMsgs == 0) m_iThresholdMsgs = 4; Save(); @@ -61,8 +64,7 @@ public: EModRet Message(const CNick& Nick, const CString& sMessage) { // We never block /me, because it doesn't cause a reply - if (sMessage.Token(0).Equals("ACTION")) - return CONTINUE; + if (sMessage.Token(0).Equals("ACTION")) return CONTINUE; if (m_tLastCTCP + m_iThresholdSecs < time(nullptr)) { m_tLastCTCP = time(nullptr); @@ -74,7 +76,8 @@ public: if (m_iNumCTCP < m_iThresholdMsgs) return CONTINUE; else if (m_iNumCTCP == m_iThresholdMsgs) - PutModule("Limit reached by [" + Nick.GetHostMask() + "], blocking all CTCP"); + PutModule("Limit reached by [" + Nick.GetHostMask() + + "], blocking all CTCP"); // Reset the timeout so that we continue blocking messages m_tLastCTCP = time(nullptr); @@ -86,7 +89,8 @@ public: return Message(Nick, sMessage); } - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { return Message(Nick, sMessage); } @@ -99,8 +103,7 @@ public: } m_iThresholdSecs = sArg.ToUInt(); - if (m_iThresholdSecs == 0) - m_iThresholdSecs = 1; + if (m_iThresholdSecs == 0) m_iThresholdSecs = 1; PutModule("Set seconds limit to [" + CString(m_iThresholdSecs) + "]"); Save(); @@ -115,19 +118,20 @@ public: } m_iThresholdMsgs = sArg.ToUInt(); - if (m_iThresholdMsgs == 0) - m_iThresholdMsgs = 2; + if (m_iThresholdMsgs == 0) m_iThresholdMsgs = 2; PutModule("Set lines limit to [" + CString(m_iThresholdMsgs) + "]"); Save(); } void OnShowCommand(const CString& sCommand) { - PutModule("Current limit is " + CString(m_iThresholdMsgs) + " CTCPs " - "in " + CString(m_iThresholdSecs) + " secs"); + PutModule("Current limit is " + CString(m_iThresholdMsgs) + + " CTCPs " + "in " + + CString(m_iThresholdSecs) + " secs"); } -private: + private: time_t m_tLastCTCP = 0; unsigned int m_iNumCTCP = 0; @@ -135,10 +139,15 @@ private: unsigned int m_iThresholdMsgs{}; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("ctcpflood"); Info.SetHasArgs(true); - Info.SetArgsHelpText("This user module takes none to two arguments. The first argument is the number of lines after which the flood-protection is triggered. The second argument is the time (s) to in which the number of lines is reached. The default setting is 4 CTCPs in 2 seconds"); + Info.SetArgsHelpText( + "This user module takes none to two arguments. The first argument is " + "the number of lines after which the flood-protection is triggered. " + "The second argument is the time (s) to in which the number of lines " + "is reached. The default setting is 4 CTCPs in 2 seconds"); } USERMODULEDEFS(CCtcpFloodMod, "Don't forward CTCP floods to clients") diff --git a/modules/cyrusauth.cpp b/modules/cyrusauth.cpp index d94fe756..079c7ea3 100644 --- a/modules/cyrusauth.cpp +++ b/modules/cyrusauth.cpp @@ -27,28 +27,30 @@ #include class CSASLAuthMod : public CModule { -public: + public: MODCONSTRUCTOR(CSASLAuthMod) { - m_Cache.SetTTL(60000/*ms*/); + m_Cache.SetTTL(60000 /*ms*/); m_cbs[0].id = SASL_CB_GETOPT; - m_cbs[0].proc = reinterpret_cast(CSASLAuthMod::getopt); + m_cbs[0].proc = reinterpret_cast(CSASLAuthMod::getopt); m_cbs[0].context = this; m_cbs[1].id = SASL_CB_LIST_END; m_cbs[1].proc = nullptr; m_cbs[1].context = nullptr; AddHelpCommand(); - AddCommand("CreateUser", static_cast(&CSASLAuthMod::CreateUserCommand), - "[yes|no]"); - AddCommand("CloneUser", static_cast(&CSASLAuthMod::CloneUserCommand), - "[username]"); - AddCommand("DisableCloneUser", static_cast(&CSASLAuthMod::DisableCloneUserCommand)); + AddCommand("CreateUser", static_cast( + &CSASLAuthMod::CreateUserCommand), + "[yes|no]"); + AddCommand("CloneUser", static_cast( + &CSASLAuthMod::CloneUserCommand), + "[username]"); + AddCommand("DisableCloneUser", + static_cast( + &CSASLAuthMod::DisableCloneUserCommand)); } - virtual ~CSASLAuthMod() { - sasl_done(); - } + virtual ~CSASLAuthMod() { sasl_done(); } void OnModCommand(const CString& sCommand) override { if (GetUser()->IsAdmin()) { @@ -67,7 +69,8 @@ public: if (it->Equals("saslauthd") || it->Equals("auxprop")) { m_sMethod += *it + " "; } else { - CUtils::PrintError("Ignoring invalid SASL pwcheck method: " + *it); + CUtils::PrintError("Ignoring invalid SASL pwcheck method: " + + *it); sMessage = "Ignored invalid SASL pwcheck method"; } } @@ -90,8 +93,8 @@ public: EModRet OnLoginAttempt(std::shared_ptr Auth) override { const CString& sUsername = Auth->GetUsername(); const CString& sPassword = Auth->GetPassword(); - CUser *pUser(CZNC::Get().FindUser(sUsername)); - sasl_conn_t *sasl_conn(nullptr); + CUser* pUser(CZNC::Get().FindUser(sUsername)); + sasl_conn_t* sasl_conn(nullptr); bool bSuccess = false; if (!pUser && !CreateUser()) { @@ -102,11 +105,15 @@ public: if (m_Cache.HasItem(sCacheKey)) { bSuccess = true; DEBUG("saslauth: Found [" + sUsername + "] in cache"); - } else if (sasl_server_new("znc", nullptr, nullptr, nullptr, nullptr, m_cbs, 0, &sasl_conn) == SASL_OK && - sasl_checkpass(sasl_conn, sUsername.c_str(), sUsername.size(), sPassword.c_str(), sPassword.size()) == SASL_OK) { + } else if (sasl_server_new("znc", nullptr, nullptr, nullptr, nullptr, + m_cbs, 0, &sasl_conn) == SASL_OK && + sasl_checkpass(sasl_conn, sUsername.c_str(), + sUsername.size(), sPassword.c_str(), + sPassword.size()) == SASL_OK) { m_Cache.AddItem(sCacheKey); - DEBUG("saslauth: Successful SASL authentication [" + sUsername + "]"); + DEBUG("saslauth: Successful SASL authentication [" + sUsername + + "]"); bSuccess = true; } @@ -119,28 +126,32 @@ public: pUser = new CUser(sUsername); if (ShouldCloneUser()) { - CUser *pBaseUser = CZNC::Get().FindUser(CloneUser()); + CUser* pBaseUser = CZNC::Get().FindUser(CloneUser()); if (!pBaseUser) { - DEBUG("saslauth: Clone User [" << CloneUser() << "] User not found"); + DEBUG("saslauth: Clone User [" << CloneUser() + << "] User not found"); delete pUser; pUser = nullptr; } if (pUser && !pUser->Clone(*pBaseUser, sErr)) { - DEBUG("saslauth: Clone User [" << CloneUser() << "] failed: " << sErr); + DEBUG("saslauth: Clone User [" << CloneUser() + << "] failed: " << sErr); delete pUser; pUser = nullptr; } } if (pUser) { - // "::" is an invalid MD5 hash, so user won't be able to login by usual method + // "::" is an invalid MD5 hash, so user won't be able to + // login by usual method pUser->SetPass("::", CUser::HASH_MD5, "::"); } if (pUser && !CZNC::Get().AddUser(pUser, sErr)) { - DEBUG("saslauth: Add user [" << sUsername << "] failed: " << sErr); + DEBUG("saslauth: Add user [" << sUsername + << "] failed: " << sErr); delete pUser; pUser = nullptr; } @@ -157,7 +168,7 @@ public: const CString& GetMethod() const { return m_sMethod; } - void CreateUserCommand(const CString &sLine) { + void CreateUserCommand(const CString& sLine) { CString sCreate = sLine.Token(1); if (!sCreate.empty()) { @@ -171,7 +182,7 @@ public: } } - void CloneUserCommand(const CString &sLine) { + void CloneUserCommand(const CString& sLine) { CString sUsername = sLine.Token(1); if (!sUsername.empty()) { @@ -185,31 +196,25 @@ public: } } - void DisableCloneUserCommand(const CString &sLine) { + void DisableCloneUserCommand(const CString& sLine) { DelNV("CloneUser"); PutModule("Clone user disabled"); } - bool CreateUser() const { - return GetNV("CreateUser").ToBool(); - } + bool CreateUser() const { return GetNV("CreateUser").ToBool(); } - CString CloneUser() const { - return GetNV("CloneUser"); - } + CString CloneUser() const { return GetNV("CloneUser"); } - bool ShouldCloneUser() { - return !GetNV("CloneUser").empty(); - } + bool ShouldCloneUser() { return !GetNV("CloneUser").empty(); } -protected: - TCacheMap m_Cache; + protected: + TCacheMap m_Cache; sasl_callback_t m_cbs[2]; CString m_sMethod; - static int getopt(void *context, const char *plugin_name, - const char *option, const char **result, unsigned *len) { + static int getopt(void* context, const char* plugin_name, + const char* option, const char** result, unsigned* len) { if (CString(option).Equals("pwcheck_method")) { *result = ((CSASLAuthMod*)context)->GetMethod().c_str(); return SASL_OK; @@ -219,10 +224,15 @@ protected: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("cyrusauth"); Info.SetHasArgs(true); - Info.SetArgsHelpText("This global module takes up to two arguments - the methods of authentication - auxprop and saslauthd"); + Info.SetArgsHelpText( + "This global module takes up to two arguments - the methods of " + "authentication - auxprop and saslauthd"); } -GLOBALMODULEDEFS(CSASLAuthMod, "Allow users to authenticate via SASL password verification method") +GLOBALMODULEDEFS( + CSASLAuthMod, + "Allow users to authenticate via SASL password verification method") diff --git a/modules/dcc.cpp b/modules/dcc.cpp index 04819316..6a2a45a0 100644 --- a/modules/dcc.cpp +++ b/modules/dcc.cpp @@ -23,9 +23,13 @@ using std::set; class CDCCMod; class CDCCSock : public CSocket { -public: - CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sLocalFile, unsigned long uFileSize = 0, CFile* pFile = nullptr); - CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort, const CString& sLocalFile, unsigned long uFileSize); + public: + CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, + const CString& sLocalFile, unsigned long uFileSize = 0, + CFile* pFile = nullptr); + CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, + const CString& sRemoteIP, unsigned short uRemotePort, + const CString& sLocalFile, unsigned long uFileSize); virtual ~CDCCSock(); void ReadData(const char* data, size_t len) override; @@ -52,35 +56,43 @@ public: const CString& GetFileName() const { return m_sFileName; } const CString& GetLocalFile() const { return m_sLocalFile; } CFile* GetFile() { return m_pFile; } - double GetProgress() const { return ((m_uFileSize) && (m_uBytesSoFar)) ? (double) (((double) m_uBytesSoFar / (double) m_uFileSize) *100.0) : 0; } + double GetProgress() const { + return ((m_uFileSize) && (m_uBytesSoFar)) + ? (double)(((double)m_uBytesSoFar / (double)m_uFileSize) * + 100.0) + : 0; + } bool IsSend() const { return m_bSend; } - //const CString& GetRemoteIP() const { return m_sRemoteIP; } + // const CString& GetRemoteIP() const { return m_sRemoteIP; } // !Getters -private: -protected: - CString m_sRemoteNick; - CString m_sRemoteIP; - CString m_sFileName; - CString m_sLocalFile; - CString m_sSendBuf; - unsigned short m_uRemotePort; - unsigned long long m_uFileSize; - unsigned long long m_uBytesSoFar; - bool m_bSend; - bool m_bNoDelFile; - CFile* m_pFile; - CDCCMod* m_pModule; + private: + protected: + CString m_sRemoteNick; + CString m_sRemoteIP; + CString m_sFileName; + CString m_sLocalFile; + CString m_sSendBuf; + unsigned short m_uRemotePort; + unsigned long long m_uFileSize; + unsigned long long m_uBytesSoFar; + bool m_bSend; + bool m_bNoDelFile; + CFile* m_pFile; + CDCCMod* m_pModule; }; class CDCCMod : public CModule { -public: + public: MODCONSTRUCTOR(CDCCMod) { AddHelpCommand(); - AddCommand("Send", static_cast(&CDCCMod::SendCommand), - " "); - AddCommand("Get", static_cast(&CDCCMod::GetCommand), - ""); - AddCommand("ListTransfers", static_cast(&CDCCMod::ListTransfersCommand)); + AddCommand("Send", + static_cast(&CDCCMod::SendCommand), + " "); + AddCommand("Get", + static_cast(&CDCCMod::GetCommand), + ""); + AddCommand("ListTransfers", static_cast( + &CDCCMod::ListTransfersCommand)); } virtual ~CDCCMod() {} @@ -97,7 +109,8 @@ public: #endif bool SendFile(const CString& sRemoteNick, const CString& sFileName) { - CString sFullPath = CDir::ChangeDir(GetSavePath(), sFileName, CZNC::Get().GetHomePath()); + CString sFullPath = CDir::ChangeDir(GetSavePath(), sFileName, + CZNC::Get().GetHomePath()); CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sFullPath); CFile* pFile = pSock->OpenFile(false); @@ -108,36 +121,50 @@ public: } CString sLocalDCCIP = GetUser()->GetLocalDCCIP(); - unsigned short uPort = CZNC::Get().GetManager().ListenRand("DCC::LISTEN::" + sRemoteNick, sLocalDCCIP, false, SOMAXCONN, pSock, 120); + unsigned short uPort = CZNC::Get().GetManager().ListenRand( + "DCC::LISTEN::" + sRemoteNick, sLocalDCCIP, false, SOMAXCONN, pSock, + 120); if (GetUser()->GetNick().Equals(sRemoteNick)) { - PutUser(":*dcc!znc@znc.in PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(sLocalDCCIP)) + " " - + CString(uPort) + " " + CString(pFile->GetSize()) + "\001"); + PutUser(":*dcc!znc@znc.in PRIVMSG " + sRemoteNick + + " :\001DCC SEND " + pFile->GetShortName() + " " + + CString(CUtils::GetLongIP(sLocalDCCIP)) + " " + + CString(uPort) + " " + CString(pFile->GetSize()) + "\001"); } else { - PutIRC("PRIVMSG " + sRemoteNick + " :\001DCC SEND " + pFile->GetShortName() + " " + CString(CUtils::GetLongIP(sLocalDCCIP)) + " " - + CString(uPort) + " " + CString(pFile->GetSize()) + "\001"); + PutIRC("PRIVMSG " + sRemoteNick + " :\001DCC SEND " + + pFile->GetShortName() + " " + + CString(CUtils::GetLongIP(sLocalDCCIP)) + " " + + CString(uPort) + " " + CString(pFile->GetSize()) + "\001"); } - PutModule("DCC -> [" + sRemoteNick + "][" + pFile->GetShortName() + "] - Attempting Send."); + PutModule("DCC -> [" + sRemoteNick + "][" + pFile->GetShortName() + + "] - Attempting Send."); return true; } - bool GetFile(const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort, const CString& sFileName, unsigned long uFileSize) { + bool GetFile(const CString& sRemoteNick, const CString& sRemoteIP, + unsigned short uRemotePort, const CString& sFileName, + unsigned long uFileSize) { if (CFile::Exists(sFileName)) { - PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + "] - File already exists."); + PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + + "] - File already exists."); return false; } - CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sRemoteIP, uRemotePort, sFileName, uFileSize); + CDCCSock* pSock = new CDCCSock(this, sRemoteNick, sRemoteIP, + uRemotePort, sFileName, uFileSize); if (!pSock->OpenFile()) { delete pSock; return false; } - CZNC::Get().GetManager().Connect(sRemoteIP, uRemotePort, "DCC::GET::" + sRemoteNick, 60, false, GetUser()->GetLocalDCCIP(), pSock); + CZNC::Get().GetManager().Connect(sRemoteIP, uRemotePort, + "DCC::GET::" + sRemoteNick, 60, false, + GetUser()->GetLocalDCCIP(), pSock); - PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + "] - Attempting to connect to [" + sRemoteIP + "]"); + PutModule("DCC <- [" + sRemoteNick + "][" + sFileName + + "] - Attempting to connect to [" + sRemoteIP + "]"); return true; } @@ -193,7 +220,7 @@ public: set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCSock* pSock = (CDCCSock*) *it; + CDCCSock* pSock = (CDCCSock*)*it; Table.AddRow(); Table.SetCell("Nick", pSock->GetRemoteNick()); @@ -209,8 +236,11 @@ public: if (pSock->GetType() == Csock::LISTENER) { Table.SetCell("State", "Waiting"); } else { - Table.SetCell("State", CString::ToPercent(pSock->GetProgress())); - Table.SetCell("Speed", CString((int)(pSock->GetAvgRead() / 1024.0)) + " KiB/s"); + Table.SetCell("State", + CString::ToPercent(pSock->GetProgress())); + Table.SetCell( + "Speed", + CString((int)(pSock->GetAvgRead() / 1024.0)) + " KiB/s"); } } @@ -227,33 +257,45 @@ public: set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CDCCSock* pSock = (CDCCSock*) *it; + CDCCSock* pSock = (CDCCSock*)*it; if (pSock->GetLocalPort() == uResumePort) { if (pSock->Seek(uResumeSize)) { - PutModule("DCC -> [" + pSock->GetRemoteNick() + "][" + pSock->GetFileName() + "] - Attempting to resume from file position [" + CString(uResumeSize) + "]"); - PutUser(":*dcc!znc@znc.in PRIVMSG " + GetUser()->GetNick() + " :\001DCC ACCEPT " + sFile + " " + CString(uResumePort) + " " + CString(uResumeSize) + "\001"); + PutModule( + "DCC -> [" + pSock->GetRemoteNick() + "][" + + pSock->GetFileName() + + "] - Attempting to resume from file position [" + + CString(uResumeSize) + "]"); + PutUser(":*dcc!znc@znc.in PRIVMSG " + + GetUser()->GetNick() + " :\001DCC ACCEPT " + + sFile + " " + CString(uResumePort) + " " + + CString(uResumeSize) + "\001"); } else { - PutModule("DCC -> [" + GetUser()->GetNick() + "][" + sFile + "] Unable to find send to initiate resume."); + PutModule("DCC -> [" + GetUser()->GetNick() + "][" + + sFile + + "] Unable to find send to initiate resume."); } } - } } else if (sMessage.StartsWith("DCC SEND ")) { - CString sLocalFile = CDir::CheckPathPrefix(GetSavePath(), sMessage.Token(2)); + CString sLocalFile = + CDir::CheckPathPrefix(GetSavePath(), sMessage.Token(2)); if (sLocalFile.empty()) { PutModule("Bad DCC file: " + sMessage.Token(2)); } unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); - GetFile(GetClient()->GetNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize); + GetFile(GetClient()->GetNick(), CUtils::GetIP(uLongIP), uPort, + sLocalFile, uFileSize); } } }; -CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sLocalFile, - unsigned long uFileSize, CFile* pFile) : CSocket(pMod) { +CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, + const CString& sLocalFile, unsigned long uFileSize, + CFile* pFile) + : CSocket(pMod) { m_sRemoteNick = sRemoteNick; m_uFileSize = uFileSize; m_uRemotePort = 0; @@ -266,8 +308,10 @@ CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sLo SetMaxBufferThreshold(0); } -CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, const CString& sRemoteIP, unsigned short uRemotePort, - const CString& sLocalFile, unsigned long uFileSize) : CSocket(pMod) { +CDCCSock::CDCCSock(CDCCMod* pMod, const CString& sRemoteNick, + const CString& sRemoteIP, unsigned short uRemotePort, + const CString& sLocalFile, unsigned long uFileSize) + : CSocket(pMod) { m_sRemoteNick = sRemoteNick; m_sRemoteIP = sRemoteIP; m_uRemotePort = uRemotePort; @@ -291,7 +335,9 @@ CDCCSock::~CDCCSock() { void CDCCSock::ReadData(const char* data, size_t len) { if (!m_pFile) { DEBUG("File not open! closing get."); - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!"); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + + m_sRemoteNick + "][" + m_sFileName + + "] - File not open!"); Close(); return; } @@ -318,7 +364,7 @@ void CDCCSock::ReadData(const char* data, size_t len) { m_pFile->Write(data, len); m_uBytesSoFar += len; uint32_t uSoFar = htonl((uint32_t)m_uBytesSoFar); - Write((char*) &uSoFar, sizeof(uSoFar)); + Write((char*)&uSoFar, sizeof(uSoFar)); if (m_uBytesSoFar >= m_uFileSize) { Close(); @@ -328,22 +374,28 @@ void CDCCSock::ReadData(const char* data, size_t len) { void CDCCSock::ConnectionRefused() { DEBUG(GetSockName() << " == ConnectionRefused()"); - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused."); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + + "][" + m_sFileName + "] - Connection Refused."); } void CDCCSock::Timeout() { DEBUG(GetSockName() << " == Timeout()"); - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out."); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + + "][" + m_sFileName + "] - Timed Out."); } void CDCCSock::SockError(int iErrno, const CString& sDescription) { - DEBUG(GetSockName() << " == SockError(" << iErrno << ", " << sDescription << ")"); - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + sDescription + "]"); + DEBUG(GetSockName() << " == SockError(" << iErrno << ", " << sDescription + << ")"); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + + "][" + m_sFileName + "] - Socket Error [" + + sDescription + "]"); } void CDCCSock::Connected() { DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")"); - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started."); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + + "][" + m_sFileName + "] - Transfer Started."); if (m_bSend) { SendPacket(); @@ -353,7 +405,8 @@ void CDCCSock::Connected() { } void CDCCSock::Disconnected() { - const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - "; + const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + + m_sRemoteNick + "][" + m_sFileName + "] - "; DEBUG(GetSockName() << " == Disconnected()"); @@ -361,11 +414,13 @@ void CDCCSock::Disconnected() { m_pModule->PutModule(sStart + "TooMuchData!"); } else if (m_uBytesSoFar == m_uFileSize) { if (m_bSend) { - m_pModule->PutModule(sStart + "Completed! - Sent [" + m_sLocalFile + - "] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]"); + m_pModule->PutModule( + sStart + "Completed! - Sent [" + m_sLocalFile + "] at [" + + CString((int)(GetAvgWrite() / 1024.0)) + " KiB/s ]"); } else { - m_pModule->PutModule(sStart + "Completed! - Saved to [" + m_sLocalFile + - "] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]"); + m_pModule->PutModule( + sStart + "Completed! - Saved to [" + m_sLocalFile + "] at [" + + CString((int)(GetAvgRead() / 1024.0)) + " KiB/s ]"); } } else { m_pModule->PutModule(sStart + "Incomplete!"); @@ -374,7 +429,9 @@ void CDCCSock::Disconnected() { void CDCCSock::SendPacket() { if (!m_pFile) { - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely."); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + + m_sRemoteNick + "][" + m_sFileName + + "] - File closed prematurely."); Close(); return; } @@ -382,8 +439,9 @@ void CDCCSock::SendPacket() { if (GetInternalWriteBuffer().size() > 1024 * 1024) { // There is still enough data to be written, don't add more // stuff to that buffer. - DEBUG("SendPacket(): Skipping send, buffer still full enough [" << GetInternalWriteBuffer().size() << "][" - << m_sRemoteNick << "][" << m_sFileName << "]"); + DEBUG("SendPacket(): Skipping send, buffer still full enough [" + << GetInternalWriteBuffer().size() << "][" << m_sRemoteNick + << "][" << m_sFileName << "]"); return; } @@ -391,7 +449,9 @@ void CDCCSock::SendPacket() { ssize_t iLen = m_pFile->Read(szBuf, 4096); if (iLen < 0) { - m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file."); + m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + + m_sRemoteNick + "][" + m_sFileName + + "] - Error reading from file."); Close(); return; } @@ -405,7 +465,8 @@ void CDCCSock::SendPacket() { Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) { Close(); - CDCCSock* pSock = new CDCCSock(m_pModule, m_sRemoteNick, m_sLocalFile, m_uFileSize, m_pFile); + CDCCSock* pSock = new CDCCSock(m_pModule, m_sRemoteNick, m_sLocalFile, + m_uFileSize, m_pFile); pSock->SetSockName("DCC::SEND::" + m_sRemoteNick); pSock->SetTimeout(120); pSock->SetFileName(m_sFileName); @@ -417,7 +478,9 @@ Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) { CFile* CDCCSock::OpenFile(bool bWrite) { if ((m_pFile) || (m_sLocalFile.empty())) { - m_pModule->PutModule(((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file."); + m_pModule->PutModule(((bWrite) ? "DCC <- [" : "DCC -> [") + + m_sRemoteNick + "][" + m_sLocalFile + + "] - Unable to open file."); return nullptr; } @@ -427,38 +490,47 @@ CFile* CDCCSock::OpenFile(bool bWrite) { if (m_pFile->Exists()) { delete m_pFile; m_pFile = nullptr; - m_pModule->PutModule("DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]"); + m_pModule->PutModule("DCC <- [" + m_sRemoteNick + + "] - File already exists [" + m_sLocalFile + + "]"); return nullptr; } if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) { delete m_pFile; m_pFile = nullptr; - m_pModule->PutModule("DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]"); + m_pModule->PutModule("DCC <- [" + m_sRemoteNick + + "] - Could not open file [" + m_sLocalFile + + "]"); return nullptr; } } else { if (!m_pFile->IsReg()) { delete m_pFile; m_pFile = nullptr; - m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]"); + m_pModule->PutModule("DCC -> [" + m_sRemoteNick + + "] - Not a file [" + m_sLocalFile + "]"); return nullptr; } if (!m_pFile->Open()) { delete m_pFile; m_pFile = nullptr; - m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]"); + m_pModule->PutModule("DCC -> [" + m_sRemoteNick + + "] - Could not open file [" + m_sLocalFile + + "]"); return nullptr; } // The DCC specs only allow file transfers with files smaller // than 4GiB (see ReadData()). unsigned long long uFileSize = m_pFile->GetSize(); - if (uFileSize > (unsigned long long) 0xffffffffULL) { + if (uFileSize > (unsigned long long)0xffffffffULL) { delete m_pFile; m_pFile = nullptr; - m_pModule->PutModule("DCC -> [" + m_sRemoteNick + "] - File too large (>4 GiB) [" + m_sLocalFile + "]"); + m_pModule->PutModule("DCC -> [" + m_sRemoteNick + + "] - File too large (>4 GiB) [" + + m_sLocalFile + "]"); return nullptr; } @@ -481,9 +553,10 @@ bool CDCCSock::Seek(unsigned long int uPos) { return false; } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("dcc"); } -USERMODULEDEFS(CDCCMod, "This module allows you to transfer files to and from ZNC") - +USERMODULEDEFS(CDCCMod, + "This module allows you to transfer files to and from ZNC") diff --git a/modules/fail2ban.cpp b/modules/fail2ban.cpp index ce65b06f..b16f717b 100644 --- a/modules/fail2ban.cpp +++ b/modules/fail2ban.cpp @@ -17,14 +17,26 @@ #include class CFailToBanMod : public CModule { -public: + public: MODCONSTRUCTOR(CFailToBanMod) { AddHelpCommand(); - AddCommand("Timeout", static_cast(&CFailToBanMod::OnTimeoutCommand), "[minutes]", "The number of minutes IPs are blocked after a failed login."); - AddCommand("Attempts", static_cast(&CFailToBanMod::OnAttemptsCommand), "[count]", "The number of allowed failed login attempts."); - AddCommand("Ban", static_cast(&CFailToBanMod::OnBanCommand), "", "Ban the specified hosts."); - AddCommand("Unban", static_cast(&CFailToBanMod::OnUnbanCommand), "", "Unban the specified hosts."); - AddCommand("List", static_cast(&CFailToBanMod::OnListCommand), "", "List banned hosts."); + AddCommand( + "Timeout", static_cast( + &CFailToBanMod::OnTimeoutCommand), + "[minutes]", + "The number of minutes IPs are blocked after a failed login."); + AddCommand("Attempts", static_cast( + &CFailToBanMod::OnAttemptsCommand), + "[count]", "The number of allowed failed login attempts."); + AddCommand("Ban", static_cast( + &CFailToBanMod::OnBanCommand), + "", "Ban the specified hosts."); + AddCommand("Unban", static_cast( + &CFailToBanMod::OnUnbanCommand), + "", "Unban the specified hosts."); + AddCommand("List", static_cast( + &CFailToBanMod::OnListCommand), + "", "List banned hosts."); } virtual ~CFailToBanMod() {} @@ -40,10 +52,12 @@ public: if (sArgs.empty()) { timeout = 1; - } else if (timeout == 0 || m_uiAllowedFailed == 0 || !sArgs.Token(2, true).empty()) { - sMessage = "Invalid argument, must be the number of minutes " - "IPs are blocked after a failed login and can be " - "followed by number of allowed failed login attempts"; + } else if (timeout == 0 || m_uiAllowedFailed == 0 || + !sArgs.Token(2, true).empty()) { + sMessage = + "Invalid argument, must be the number of minutes " + "IPs are blocked after a failed login and can be " + "followed by number of allowed failed login attempts"; return false; } @@ -53,17 +67,13 @@ public: return true; } - void OnPostRehash() override { - m_Cache.Clear(); - } + void OnPostRehash() override { m_Cache.Clear(); } void Add(const CString& sHost, unsigned int count) { m_Cache.AddItem(sHost, count, m_Cache.GetTTL()); } - bool Remove(const CString& sHost) { - return m_Cache.RemItem(sHost); - } + bool Remove(const CString& sHost) { return m_Cache.RemItem(sHost); } void OnTimeoutCommand(const CString& sCommand) { CString sArg = sCommand.Token(1); @@ -74,11 +84,13 @@ public: PutModule("Usage: Timeout [minutes]"); } else { m_Cache.SetTTL(uTimeout * 60 * 1000); - SetArgs(CString(m_Cache.GetTTL() / 60 / 1000) + " " + CString(m_uiAllowedFailed)); + SetArgs(CString(m_Cache.GetTTL() / 60 / 1000) + " " + + CString(m_uiAllowedFailed)); PutModule("Timeout: " + CString(uTimeout) + " min"); } } else { - PutModule("Timeout: " + CString(m_Cache.GetTTL() / 60 / 1000) + " min"); + PutModule("Timeout: " + CString(m_Cache.GetTTL() / 60 / 1000) + + " min"); } } @@ -91,7 +103,8 @@ public: PutModule("Usage: Attempts [count]"); } else { m_uiAllowedFailed = uiAttempts; - SetArgs(CString(m_Cache.GetTTL() / 60 / 1000) + " " + CString(m_uiAllowedFailed)); + SetArgs(CString(m_Cache.GetTTL() / 60 / 1000) + " " + + CString(m_uiAllowedFailed)); PutModule("Attempts: " + CString(uiAttempts)); } } else { @@ -156,8 +169,9 @@ public: } } - void OnClientConnect(CZNCSock* pClient, const CString& sHost, unsigned short uPort) override { - unsigned int *pCount = m_Cache.GetItem(sHost); + void OnClientConnect(CZNCSock* pClient, const CString& sHost, + unsigned short uPort) override { + unsigned int* pCount = m_Cache.GetItem(sHost); if (sHost.empty() || pCount == nullptr || *pCount < m_uiAllowedFailed) { return; } @@ -165,12 +179,15 @@ public: // refresh their ban Add(sHost, *pCount); - pClient->Write("ERROR :Closing link [Please try again later - reconnecting too fast]\r\n"); + pClient->Write( + "ERROR :Closing link [Please try again later - reconnecting too " + "fast]\r\n"); pClient->Close(Csock::CLT_AFTERWRITE); } - void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override { - unsigned int *pCount = m_Cache.GetItem(sRemoteIP); + void OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP) override { + unsigned int* pCount = m_Cache.GetItem(sRemoteIP); if (pCount) Add(sRemoteIP, *pCount + 1); else @@ -181,10 +198,9 @@ public: // e.g. webadmin ends up here const CString& sRemoteIP = Auth->GetRemoteIP(); - if (sRemoteIP.empty()) - return CONTINUE; + if (sRemoteIP.empty()) return CONTINUE; - unsigned int *pCount = m_Cache.GetItem(sRemoteIP); + unsigned int* pCount = m_Cache.GetItem(sRemoteIP); if (pCount && *pCount >= m_uiAllowedFailed) { // OnFailedLogin() will refresh their ban Auth->RefuseLogin("Please try again later - reconnecting too fast"); @@ -194,15 +210,18 @@ public: return CONTINUE; } -private: + private: TCacheMap m_Cache; - unsigned int m_uiAllowedFailed{}; + unsigned int m_uiAllowedFailed{}; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("fail2ban"); Info.SetHasArgs(true); - Info.SetArgsHelpText("You might enter the time in minutes for the IP banning and the number of failed logins before any action is taken."); + Info.SetArgsHelpText( + "You might enter the time in minutes for the IP banning and the number " + "of failed logins before any action is taken."); } GLOBALMODULEDEFS(CFailToBanMod, "Block IPs for some time after a failed login.") diff --git a/modules/flooddetach.cpp b/modules/flooddetach.cpp index cd88bd28..3d402b99 100644 --- a/modules/flooddetach.cpp +++ b/modules/flooddetach.cpp @@ -21,20 +21,27 @@ using std::map; class CFloodDetachMod : public CModule { -public: + public: MODCONSTRUCTOR(CFloodDetachMod) { m_iThresholdSecs = 0; m_iThresholdMsgs = 0; AddHelpCommand(); - AddCommand("Show", static_cast(&CFloodDetachMod::ShowCommand), ""); - AddCommand("Secs", static_cast(&CFloodDetachMod::SecsCommand), "[]"); - AddCommand("Lines", static_cast(&CFloodDetachMod::LinesCommand), "[]"); - AddCommand("Silent", static_cast(&CFloodDetachMod::SilentCommand), "[yes|no]"); + AddCommand("Show", static_cast( + &CFloodDetachMod::ShowCommand), + ""); + AddCommand("Secs", static_cast( + &CFloodDetachMod::SecsCommand), + "[]"); + AddCommand("Lines", static_cast( + &CFloodDetachMod::LinesCommand), + "[]"); + AddCommand("Silent", static_cast( + &CFloodDetachMod::SilentCommand), + "[yes|no]"); } - ~CFloodDetachMod() { - } + ~CFloodDetachMod() {} void Save() { // We save the settings twice because the module arguments can @@ -55,19 +62,15 @@ public: m_iThresholdSecs = GetNV("secs").ToUInt(); } - if (m_iThresholdSecs == 0) - m_iThresholdSecs = 2; - if (m_iThresholdMsgs == 0) - m_iThresholdMsgs = 5; + if (m_iThresholdSecs == 0) m_iThresholdSecs = 2; + if (m_iThresholdMsgs == 0) m_iThresholdMsgs = 5; Save(); return true; } - void OnIRCDisconnected() override { - m_chans.clear(); - } + void OnIRCDisconnected() override { m_chans.clear(); } void Cleanup() { Limits::iterator it; @@ -75,12 +78,11 @@ public: for (it = m_chans.begin(); it != m_chans.end(); ++it) { // The timeout for this channel did not expire yet? - if (it->second.first + (time_t)m_iThresholdSecs >= now) - continue; + if (it->second.first + (time_t)m_iThresholdSecs >= now) continue; - CChan *pChan = GetNetwork()->FindChan(it->first); - if (it->second.second >= m_iThresholdMsgs - && pChan && pChan->IsDetached()) { + CChan* pChan = GetNetwork()->FindChan(it->first); + if (it->second.second >= m_iThresholdMsgs && pChan && + pChan->IsDetached()) { // The channel is detached and it is over the // messages limit. Since we only track those // limits for non-detached channels or for @@ -88,8 +90,9 @@ public: // we detached because of a flood. if (!GetNV("silent").ToBool()) { - PutModule("Flood in [" + pChan->GetName() + "] is over, " - "re-attaching..."); + PutModule("Flood in [" + pChan->GetName() + + "] is over, " + "re-attaching..."); } // No buffer playback, makes sense, doesn't it? pChan->ClearBuffer(); @@ -100,8 +103,7 @@ public: m_chans.erase(it2); // Without this Bad Things (tm) could happen - if (it == m_chans.end()) - break; + if (it == m_chans.end()) break; } } @@ -116,8 +118,7 @@ public: if (it == m_chans.end()) { // We don't track detached channels - if (Channel.IsDetached()) - return; + if (Channel.IsDetached()) return; // This is the first message for this channel, start a // new timeout. @@ -139,8 +140,7 @@ public: it->second.second++; - if (it->second.second < m_iThresholdMsgs) - return; + if (it->second.second < m_iThresholdMsgs) return; // The channel hit the limit, reset the timeout so that we keep // it detached for longer. @@ -148,8 +148,9 @@ public: Channel.DetachUser(); if (!GetNV("silent").ToBool()) { - PutModule("Channel [" + Channel.GetName() + "] was " - "flooded, you've been detached"); + PutModule("Channel [" + Channel.GetName() + + "] was " + "flooded, you've been detached"); } } @@ -159,12 +160,14 @@ public: } // This also catches OnChanAction() - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { Message(Channel); return CONTINUE; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { Message(Channel); return CONTINUE; } @@ -174,15 +177,18 @@ public: return CONTINUE; } - void OnNick(const CNick& Nick, const CString& sNewNick, const std::vector& vChans) override { + void OnNick(const CNick& Nick, const CString& sNewNick, + const std::vector& vChans) override { for (CChan* pChan : vChans) { Message(*pChan); } } void ShowCommand(const CString& sLine) { - PutModule("Current limit is " + CString(m_iThresholdMsgs) + " lines " - "in " + CString(m_iThresholdSecs) + " secs."); + PutModule("Current limit is " + CString(m_iThresholdMsgs) + + " lines " + "in " + + CString(m_iThresholdSecs) + " secs."); } void SecsCommand(const CString& sLine) { @@ -192,10 +198,10 @@ public: PutModule("Seconds limit is [" + CString(m_iThresholdSecs) + "]"); } else { m_iThresholdSecs = sArg.ToUInt(); - if (m_iThresholdSecs == 0) - m_iThresholdSecs = 1; + if (m_iThresholdSecs == 0) m_iThresholdSecs = 1; - PutModule("Set seconds limit to [" + CString(m_iThresholdSecs) + "]"); + PutModule("Set seconds limit to [" + CString(m_iThresholdSecs) + + "]"); Save(); } } @@ -207,8 +213,7 @@ public: PutModule("Lines limit is [" + CString(m_iThresholdMsgs) + "]"); } else { m_iThresholdMsgs = sArg.ToUInt(); - if (m_iThresholdMsgs == 0) - m_iThresholdMsgs = 2; + if (m_iThresholdMsgs == 0) m_iThresholdMsgs = 2; PutModule("Set lines limit to [" + CString(m_iThresholdMsgs) + "]"); Save(); @@ -229,17 +234,20 @@ public: } } -private: - typedef map > Limits; + private: + typedef map> Limits; Limits m_chans; unsigned int m_iThresholdSecs; unsigned int m_iThresholdMsgs; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("flooddetach"); Info.SetHasArgs(true); - Info.SetArgsHelpText("This user module takes up to two arguments. Arguments are msgs and secs numbers."); + Info.SetArgsHelpText( + "This user module takes up to two arguments. Arguments are msgs and " + "secs numbers."); } USERMODULEDEFS(CFloodDetachMod, "Detach channels when flooded") diff --git a/modules/identfile.cpp b/modules/identfile.cpp index b2f7ca55..f7b15016 100644 --- a/modules/identfile.cpp +++ b/modules/identfile.cpp @@ -22,26 +22,29 @@ class CIdentFileModule : public CModule { CString m_sOrigISpoof; CFile* m_pISpoofLockFile; - CIRCSock *m_pIRCSock; + CIRCSock* m_pIRCSock; -public: + public: MODCONSTRUCTOR(CIdentFileModule) { AddHelpCommand(); - AddCommand("GetFile", static_cast(&CIdentFileModule::GetFile)); - AddCommand("SetFile", static_cast(&CIdentFileModule::SetFile), - ""); - AddCommand("GetFormat", static_cast(&CIdentFileModule::GetFormat)); - AddCommand("SetFormat", static_cast(&CIdentFileModule::SetFormat), - ""); - AddCommand("Show", static_cast(&CIdentFileModule::Show)); + AddCommand("GetFile", static_cast( + &CIdentFileModule::GetFile)); + AddCommand("SetFile", static_cast( + &CIdentFileModule::SetFile), + ""); + AddCommand("GetFormat", static_cast( + &CIdentFileModule::GetFormat)); + AddCommand("SetFormat", static_cast( + &CIdentFileModule::SetFormat), + ""); + AddCommand("Show", static_cast( + &CIdentFileModule::Show)); m_pISpoofLockFile = nullptr; m_pIRCSock = nullptr; } - virtual ~CIdentFileModule() { - ReleaseISpoof(); - } + virtual ~CIdentFileModule() { ReleaseISpoof(); } void GetFile(const CString& sLine) { PutModule("File is set to: " + GetNV("File")); @@ -55,19 +58,24 @@ public: void SetFormat(const CString& sLine) { SetNV("Format", sLine.Token(1, true)); PutModule("Format has been set to: " + GetNV("Format")); - PutModule("Format would be expanded to: " + ExpandString(GetNV("Format"))); + PutModule("Format would be expanded to: " + + ExpandString(GetNV("Format"))); } void GetFormat(const CString& sLine) { PutModule("Format is set to: " + GetNV("Format")); - PutModule("Format would be expanded to: " + ExpandString(GetNV("Format"))); + PutModule("Format would be expanded to: " + + ExpandString(GetNV("Format"))); } void Show(const CString& sLine) { - PutModule("m_pISpoofLockFile = " + CString((long long)m_pISpoofLockFile)); + PutModule("m_pISpoofLockFile = " + + CString((long long)m_pISpoofLockFile)); PutModule("m_pIRCSock = " + CString((long long)m_pIRCSock)); if (m_pIRCSock) { - PutModule("user/network - " + m_pIRCSock->GetNetwork()->GetUser()->GetUserName() + "/" + m_pIRCSock->GetNetwork()->GetName()); + PutModule("user/network - " + + m_pIRCSock->GetNetwork()->GetUser()->GetUserName() + "/" + + m_pIRCSock->GetNetwork()->GetName()); } else { PutModule("identfile is free"); } @@ -81,7 +89,7 @@ public: } } - void SetIRCSock(CIRCSock *pIRCSock) { + void SetIRCSock(CIRCSock* pIRCSock) { if (m_pIRCSock) { CZNC::Get().ResumeConnectQueue(); } @@ -106,8 +114,8 @@ public: } char buf[1024]; - memset((char*) buf, 0, 1024); - m_pISpoofLockFile->Read(buf ,1024); + memset((char*)buf, 0, 1024); + m_pISpoofLockFile->Read(buf, 1024); m_sOrigISpoof = buf; if (!m_pISpoofLockFile->Seek(0) || !m_pISpoofLockFile->Truncate()) { @@ -124,7 +132,9 @@ public: sData.Replace("%", GetUser()->GetIdent()); } - DEBUG("Writing [" + sData + "] to ident spoof file [" + m_pISpoofLockFile->GetLongName() + "] for user/network [" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "]"); + DEBUG("Writing [" + sData + "] to ident spoof file [" + + m_pISpoofLockFile->GetLongName() + "] for user/network [" + + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "]"); m_pISpoofLockFile->Write(sData + "\n"); @@ -132,8 +142,12 @@ public: } void ReleaseISpoof() { - DEBUG("Releasing ident spoof for user/network [" + (m_pIRCSock ? m_pIRCSock->GetNetwork()->GetUser()->GetUserName() + "/" + - m_pIRCSock->GetNetwork()->GetName() : "") + "]"); + DEBUG("Releasing ident spoof for user/network [" + + (m_pIRCSock + ? m_pIRCSock->GetNetwork()->GetUser()->GetUserName() + "/" + + m_pIRCSock->GetNetwork()->GetName() + : "") + + "]"); SetIRCSock(nullptr); @@ -162,16 +176,19 @@ public: return true; } - EModRet OnIRCConnecting(CIRCSock *pIRCSock) override { + EModRet OnIRCConnecting(CIRCSock* pIRCSock) override { if (m_pISpoofLockFile != nullptr) { DEBUG("Aborting connection, ident spoof lock file exists"); - PutModule("Aborting connection, another user or network is currently connecting and using the ident spoof file"); + PutModule( + "Aborting connection, another user or network is currently " + "connecting and using the ident spoof file"); return HALTCORE; } if (!WriteISpoof()) { DEBUG("identfile [" + GetNV("File") + "] could not be written"); - PutModule("[" + GetNV("File") + "] could not be written, retrying..."); + PutModule("[" + GetNV("File") + + "] could not be written, retrying..."); return HALTCORE; } @@ -185,7 +202,7 @@ public: } } - void OnIRCConnectionError(CIRCSock *pIRCSock) override { + void OnIRCConnectionError(CIRCSock* pIRCSock) override { if (m_pIRCSock == pIRCSock) { ReleaseISpoof(); } @@ -198,8 +215,11 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("identfile"); } -GLOBALMODULEDEFS(CIdentFileModule, "Write the ident of a user to a file when they are trying to connect.") +GLOBALMODULEDEFS( + CIdentFileModule, + "Write the ident of a user to a file when they are trying to connect.") diff --git a/modules/imapauth.cpp b/modules/imapauth.cpp index 64011acb..5c004415 100644 --- a/modules/imapauth.cpp +++ b/modules/imapauth.cpp @@ -21,33 +21,34 @@ using std::map; class CIMAPAuthMod; class CIMAPSock : public CSocket { -public: + public: CIMAPSock(CIMAPAuthMod* pModule, std::shared_ptr Auth) - : CSocket((CModule*) pModule), m_spAuth(Auth) { - m_pIMAPMod = pModule; - m_bSentReply = false; - m_bSentLogin = false; - EnableReadLine(); + : CSocket((CModule*)pModule), m_spAuth(Auth) { + m_pIMAPMod = pModule; + m_bSentReply = false; + m_bSentLogin = false; + EnableReadLine(); } virtual ~CIMAPSock() { if (!m_bSentReply) { - m_spAuth->RefuseLogin("IMAP server is down, please try again later"); + m_spAuth->RefuseLogin( + "IMAP server is down, please try again later"); } } void ReadLine(const CString& sLine) override; -private: -protected: - CIMAPAuthMod* m_pIMAPMod; - bool m_bSentLogin; - bool m_bSentReply; + + private: + protected: + CIMAPAuthMod* m_pIMAPMod; + bool m_bSentLogin; + bool m_bSentReply; std::shared_ptr m_spAuth; }; - class CIMAPAuthMod : public CModule { -public: + public: MODCONSTRUCTOR(CIMAPAuthMod) { m_Cache.SetTTL(60000); m_sServer = "localhost"; @@ -57,13 +58,11 @@ public: virtual ~CIMAPAuthMod() {} - bool OnBoot() override { - return true; - } + bool OnBoot() override { return true; } bool OnLoad(const CString& sArgs, CString& sMessage) override { if (sArgs.Trim_n().empty()) { - return true; // use defaults + return true; // use defaults } m_sServer = sArgs.Token(0); @@ -87,12 +86,15 @@ public: EModRet OnLoginAttempt(std::shared_ptr Auth) override { CUser* pUser = CZNC::Get().FindUser(Auth->GetUsername()); - if (!pUser) { // @todo Will want to do some sort of && !m_bAllowCreate in the future + if (!pUser) { // @todo Will want to do some sort of && !m_bAllowCreate + // in the future Auth->RefuseLogin("Invalid User - Halting IMAP Lookup"); return HALT; } - if (pUser && m_Cache.HasItem(CString(Auth->GetUsername() + ":" + Auth->GetPassword()).MD5())) { + if (pUser && + m_Cache.HasItem(CString(Auth->GetUsername() + ":" + + Auth->GetPassword()).MD5())) { DEBUG("+++ Found in cache"); Auth->AcceptLogin(*pUser); return HALT; @@ -104,22 +106,19 @@ public: return HALT; } - void OnModCommand(const CString& sLine) override { - } + void OnModCommand(const CString& sLine) override {} - void CacheLogin(const CString& sLogin) { - m_Cache.AddItem(sLogin); - } + void CacheLogin(const CString& sLogin) { m_Cache.AddItem(sLogin); } // Getters const CString& GetUserFormat() const { return m_sUserFormat; } // !Getters -private: + private: // Settings - CString m_sServer; - unsigned short m_uPort; - bool m_bSSL; - CString m_sUserFormat; + CString m_sServer; + unsigned short m_uPort; + bool m_bSSL; + CString m_sUserFormat; // !Settings TCacheMap m_Cache; @@ -140,13 +139,17 @@ void CIMAPSock::ReadLine(const CString& sLine) { } } - Write("AUTH LOGIN " + sUsername + " " + m_spAuth->GetPassword() + "\r\n"); + Write("AUTH LOGIN " + sUsername + " " + m_spAuth->GetPassword() + + "\r\n"); } else if (sLine.Left(5) == "AUTH ") { CUser* pUser = CZNC::Get().FindUser(m_spAuth->GetUsername()); if (pUser && sLine.StartsWith("AUTH OK")) { m_spAuth->AcceptLogin(*pUser); - m_pIMAPMod->CacheLogin(CString(m_spAuth->GetUsername() + ":" + m_spAuth->GetPassword()).MD5()); // Use MD5 so passes don't sit in memory in plain text + m_pIMAPMod->CacheLogin( + CString(m_spAuth->GetUsername() + ":" + m_spAuth->GetPassword()) + .MD5()); // Use MD5 so passes don't sit in memory in plain + // text DEBUG("+++ Successful IMAP lookup"); } else { m_spAuth->RefuseLogin("Invalid Password"); @@ -158,7 +161,8 @@ void CIMAPSock::ReadLine(const CString& sLine) { } } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("imapauth"); Info.SetHasArgs(true); Info.SetArgsHelpText("[ server [+]port [ UserFormatString ] ]"); diff --git a/modules/keepnick.cpp b/modules/keepnick.cpp index b943bb40..e44e8472 100644 --- a/modules/keepnick.cpp +++ b/modules/keepnick.cpp @@ -22,23 +22,29 @@ using std::vector; class CKeepNickMod; class CKeepNickTimer : public CTimer { -public: - CKeepNickTimer(CKeepNickMod *pMod); + public: + CKeepNickTimer(CKeepNickMod* pMod); ~CKeepNickTimer() {} void RunJob() override; -private: + private: CKeepNickMod* m_pMod; }; class CKeepNickMod : public CModule { -public: + public: MODCONSTRUCTOR(CKeepNickMod) { AddHelpCommand(); - AddCommand("Enable", static_cast(&CKeepNickMod::OnEnableCommand), "", "Try to get your primary nick"); - AddCommand("Disable", static_cast(&CKeepNickMod::OnDisableCommand), "", "No longer trying to get your primary nick"); - AddCommand("State", static_cast(&CKeepNickMod::OnStateCommand), "", "Show the current state"); + AddCommand("Enable", static_cast( + &CKeepNickMod::OnEnableCommand), + "", "Try to get your primary nick"); + AddCommand("Disable", static_cast( + &CKeepNickMod::OnDisableCommand), + "", "No longer trying to get your primary nick"); + AddCommand("State", static_cast( + &CKeepNickMod::OnStateCommand), + "", "Show the current state"); } ~CKeepNickMod() {} @@ -47,8 +53,7 @@ public: m_pTimer = nullptr; // Check if we need to start the timer - if (GetNetwork()->IsIRCConnected()) - OnIRCConnected(); + if (GetNetwork()->IsIRCConnected()) OnIRCConnected(); return true; } @@ -60,12 +65,10 @@ public: CIRCSock* pIRCSock = GetNetwork()->GetIRCSock(); - if (!pIRCSock) - return; + if (!pIRCSock) return; // Do we already have the nick we want? - if (pIRCSock->GetNick().Equals(GetNick())) - return; + if (pIRCSock->GetNick().Equals(GetNick())) return; PutIRC("NICK " + GetNick()); } @@ -74,13 +77,13 @@ public: CString sConfNick = GetNetwork()->GetNick(); CIRCSock* pIRCSock = GetNetwork()->GetIRCSock(); - if (pIRCSock) - sConfNick = sConfNick.Left(pIRCSock->GetMaxNickLen()); + if (pIRCSock) sConfNick = sConfNick.Left(pIRCSock->GetMaxNickLen()); return sConfNick; } - void OnNick(const CNick& Nick, const CString& sNewNick, const vector& vChans) override { + void OnNick(const CNick& Nick, const CString& sNewNick, + const vector& vChans) override { if (sNewNick == GetNetwork()->GetIRCSock()->GetNick()) { // We are changing our own nick if (Nick.NickEquals(GetNick())) { @@ -102,7 +105,8 @@ public: } } - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override { + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override { // If someone with the nick we want quits, be fast and get the nick if (Nick.NickEquals(GetNick())) { KeepNick(); @@ -122,16 +126,14 @@ public: } void Enable() { - if (m_pTimer) - return; + if (m_pTimer) return; m_pTimer = new CKeepNickTimer(this); AddTimer(m_pTimer); } void Disable() { - if (!m_pTimer) - return; + if (!m_pTimer) return; m_pTimer->Stop(); RemTimer(m_pTimer); @@ -140,34 +142,32 @@ public: EModRet OnUserRaw(CString& sLine) override { // We dont care if we are not connected to IRC - if (!GetNetwork()->IsIRCConnected()) - return CONTINUE; + if (!GetNetwork()->IsIRCConnected()) return CONTINUE; // We are trying to get the config nick and this is a /nick? - if (!m_pTimer || !sLine.Token(0).Equals("NICK")) - return CONTINUE; + if (!m_pTimer || !sLine.Token(0).Equals("NICK")) return CONTINUE; // Is the nick change for the nick we are trying to get? CString sNick = sLine.Token(1); // Don't even think of using spaces in your nick! - if (sNick.Left(1) == ":") - sNick.LeftChomp(); + if (sNick.Left(1) == ":") sNick.LeftChomp(); - if (!sNick.Equals(GetNick())) - return CONTINUE; + if (!sNick.Equals(GetNick())) return CONTINUE; // Indeed trying to change to this nick, generate a 433 for it. // This way we can *always* block incoming 433s from the server. - PutUser(":" + GetNetwork()->GetIRCServer() + " 433 " + GetNetwork()->GetIRCNick().GetNick() - + " " + sNick + " :ZNC is already trying to get this nickname"); + PutUser(":" + GetNetwork()->GetIRCServer() + " 433 " + + GetNetwork()->GetIRCNick().GetNick() + " " + sNick + + " :ZNC is already trying to get this nickname"); return CONTINUE; } EModRet OnRaw(CString& sLine) override { // Are we trying to get our primary nick and we caused this error? // :irc.server.net 433 mynick badnick :Nickname is already in use. - if (m_pTimer && sLine.Token(1) == "433" && sLine.Token(3).Equals(GetNick())) + if (m_pTimer && sLine.Token(1) == "433" && + sLine.Token(3).Equals(GetNick())) return HALT; return CONTINUE; @@ -190,21 +190,21 @@ public: PutModule("Currently disabled, try 'enable'"); } -private: + private: // If this is nullptr, we are turned off for some reason CKeepNickTimer* m_pTimer = nullptr; }; -CKeepNickTimer::CKeepNickTimer(CKeepNickMod *pMod) : CTimer(pMod, 30, 0, - "KeepNickTimer", "Tries to acquire this user's primary nick") { +CKeepNickTimer::CKeepNickTimer(CKeepNickMod* pMod) + : CTimer(pMod, 30, 0, "KeepNickTimer", + "Tries to acquire this user's primary nick") { m_pMod = pMod; } -void CKeepNickTimer::RunJob() { - m_pMod->KeepNick(); -} +void CKeepNickTimer::RunJob() { m_pMod->KeepNick(); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("keepnick"); } diff --git a/modules/kickrejoin.cpp b/modules/kickrejoin.cpp index 95a210ae..2a074236 100644 --- a/modules/kickrejoin.cpp +++ b/modules/kickrejoin.cpp @@ -25,35 +25,40 @@ #include #include -class CRejoinJob: public CTimer { -public: - CRejoinJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) { - } +class CRejoinJob : public CTimer { + public: + CRejoinJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CRejoinJob() {} -protected: + protected: void RunJob() override { CIRCNetwork* pNetwork = GetModule()->GetNetwork(); CChan* pChan = pNetwork->FindChan(GetName().Token(1, true)); if (pChan) { pChan->Enable(); - GetModule()->PutIRC("JOIN " + pChan->GetName() + " " + pChan->GetKey()); + GetModule()->PutIRC("JOIN " + pChan->GetName() + " " + + pChan->GetKey()); } } }; class CRejoinMod : public CModule { -private: + private: unsigned int delay = 10; -public: + public: MODCONSTRUCTOR(CRejoinMod) { AddHelpCommand(); - AddCommand("SetDelay", static_cast(&CRejoinMod::OnSetDelayCommand), "", "Set the rejoin delay"); - AddCommand("ShowDelay", static_cast(&CRejoinMod::OnShowDelayCommand), "", "Show the rejoin delay"); + AddCommand("SetDelay", static_cast( + &CRejoinMod::OnSetDelayCommand), + "", "Set the rejoin delay"); + AddCommand("ShowDelay", static_cast( + &CRejoinMod::OnShowDelayCommand), + "", "Show the rejoin delay"); } virtual ~CRejoinMod() {} @@ -70,8 +75,9 @@ public: if ((i == 0 && sArgs == "0") || i > 0) delay = i; else { - sErrorMsg = "Illegal argument, " - "must be a positive number or 0"; + sErrorMsg = + "Illegal argument, " + "must be a positive number or 0"; return false; } } @@ -104,7 +110,8 @@ public: PutModule("Rejoin delay disabled"); } - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& pChan, const CString& sMessage) override { + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& pChan, + const CString& sMessage) override { if (GetNetwork()->GetCurNick().Equals(sKickedNick)) { if (!delay) { PutIRC("JOIN " + pChan.GetName() + " " + pChan.GetKey()); @@ -112,15 +119,17 @@ public: return; } AddTimer(new CRejoinJob(this, delay, 1, "Rejoin " + pChan.GetName(), - "Rejoin channel after a delay")); + "Rejoin channel after a delay")); } } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("kickrejoin"); Info.SetHasArgs(true); - Info.SetArgsHelpText("You might enter the number of seconds to wait before rejoining."); + Info.SetArgsHelpText( + "You might enter the number of seconds to wait before rejoining."); } NETWORKMODULEDEFS(CRejoinMod, "Autorejoin on kick") diff --git a/modules/lastseen.cpp b/modules/lastseen.cpp index 43132cef..1e8a429d 100644 --- a/modules/lastseen.cpp +++ b/modules/lastseen.cpp @@ -23,16 +23,17 @@ using std::pair; using std::multimap; class CLastSeenMod : public CModule { -private: - time_t GetTime(const CUser *pUser) { + private: + time_t GetTime(const CUser* pUser) { return GetNV(pUser->GetUserName()).ToULong(); } - void SetTime(const CUser *pUser) { + void SetTime(const CUser* pUser) { SetNV(pUser->GetUserName(), CString(time(nullptr))); } - const CString FormatLastSeen(const CUser *pUser, const char* sDefault = "") { + const CString FormatLastSeen(const CUser* pUser, + const char* sDefault = "") { time_t last = GetTime(pUser); if (last < 1) { return sDefault; @@ -46,7 +47,7 @@ private: typedef multimap MTimeMulti; typedef map MUsers; - void ShowCommand(const CString &sLine) { + void ShowCommand(const CString& sLine) { if (!GetUser()->IsAdmin()) { PutModule("Access denied"); return; @@ -68,23 +69,21 @@ private: PutModule(Table); } -public: + public: MODCONSTRUCTOR(CLastSeenMod) { AddHelpCommand(); - AddCommand("Show", static_cast(&CLastSeenMod::ShowCommand),"", "Shows list of users and when they last logged in"); + AddCommand("Show", static_cast( + &CLastSeenMod::ShowCommand), + "", "Shows list of users and when they last logged in"); } virtual ~CLastSeenMod() {} // Event stuff: - void OnClientLogin() override { - SetTime(GetUser()); - } + void OnClientLogin() override { SetTime(GetUser()); } - void OnClientDisconnect() override { - SetTime(GetUser()); - } + void OnClientDisconnect() override { SetTime(GetUser()); } EModRet OnDeleteUser(CUser& User) override { DelNV(User.GetUserName()); @@ -96,24 +95,30 @@ public: bool WebRequiresAdmin() override { return true; } CString GetWebMenuTitle() override { return "Last Seen"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { CModules& GModules = CZNC::Get().GetModules(); - Tmpl["WebAdminLoaded"] = CString(GModules.FindModule("webadmin") != nullptr); + Tmpl["WebAdminLoaded"] = + CString(GModules.FindModule("webadmin") != nullptr); MTimeMulti mmSorted; const MUsers& mUsers = CZNC::Get().GetUserMap(); - for (MUsers::const_iterator uit = mUsers.begin(); uit != mUsers.end(); ++uit) { - mmSorted.insert(pair(GetTime(uit->second), uit->second)); + for (MUsers::const_iterator uit = mUsers.begin(); + uit != mUsers.end(); ++uit) { + mmSorted.insert( + pair(GetTime(uit->second), uit->second)); } - for (MTimeMulti::const_iterator it = mmSorted.begin(); it != mmSorted.end(); ++it) { - CUser *pUser = it->second; + for (MTimeMulti::const_iterator it = mmSorted.begin(); + it != mmSorted.end(); ++it) { + CUser* pUser = it->second; CTemplate& Row = Tmpl.AddRow("UserLoop"); Row["Username"] = pUser->GetUserName(); - Row["IsSelf"] = CString(pUser == WebSock.GetSession()->GetUser()); + Row["IsSelf"] = + CString(pUser == WebSock.GetSession()->GetUser()); Row["LastSeen"] = FormatLastSeen(pUser, "never"); } @@ -123,7 +128,8 @@ public: return false; } - bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) { CUser* pUser = CZNC::Get().FindUser(Tmpl["Username"]); if (pUser) { @@ -134,11 +140,12 @@ public: return false; } - }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("lastseen"); } -GLOBALMODULEDEFS(CLastSeenMod, "Collects data about when a user last logged in.") +GLOBALMODULEDEFS(CLastSeenMod, + "Collects data about when a user last logged in.") diff --git a/modules/listsockets.cpp b/modules/listsockets.cpp index cab7d2da..5253d759 100644 --- a/modules/listsockets.cpp +++ b/modules/listsockets.cpp @@ -18,10 +18,8 @@ #include class CSocketSorter { -public: - CSocketSorter(Csock* p) { - m_pSock = p; - } + public: + CSocketSorter(Csock* p) { m_pSock = p; } bool operator<(const CSocketSorter& other) const { // The 'biggest' item is displayed first. // return false: this is first @@ -29,10 +27,8 @@ public: // Listeners go to the top if (m_pSock->GetType() != other.m_pSock->GetType()) { - if (m_pSock->GetType() == Csock::LISTENER) - return false; - if (other.m_pSock->GetType() == Csock::LISTENER) - return true; + if (m_pSock->GetType() == Csock::LISTENER) return false; + if (other.m_pSock->GetType() == Csock::LISTENER) return true; } const CString& sMyName = m_pSock->GetSockName(); const CString& sMyName2 = sMyName.Token(1, true, "::"); @@ -42,35 +38,35 @@ public: bool bHisEmpty = sHisName2.empty(); // Then sort by first token after "::" - if (bMyEmpty && !bHisEmpty) - return false; - if (bHisEmpty && !bMyEmpty) - return true; + if (bMyEmpty && !bHisEmpty) return false; + if (bHisEmpty && !bMyEmpty) return true; if (!bMyEmpty && !bHisEmpty) { int c = sMyName2.StrCmp(sHisName2); - if (c < 0) - return false; - if (c > 0) - return true; + if (c < 0) return false; + if (c > 0) return true; } // and finally sort by the whole socket name return sMyName.StrCmp(sHisName) > 0; } Csock* GetSock() const { return m_pSock; } -private: + + private: Csock* m_pSock; }; class CListSockets : public CModule { -public: + public: MODCONSTRUCTOR(CListSockets) { AddHelpCommand(); - AddCommand("List", static_cast(&CListSockets::OnListCommand), "[-n]", "Show the list of active sockets. Pass -n to show IP addresses"); + AddCommand( + "List", + static_cast(&CListSockets::OnListCommand), + "[-n]", + "Show the list of active sockets. Pass -n to show IP addresses"); } - bool OnLoad(const CString& sArgs, CString& sMessage) override - { + bool OnLoad(const CString& sArgs, CString& sMessage) override { #ifndef MOD_LISTSOCKETS_ALLOW_EVERYONE if (!GetUser()->IsAdmin()) { sMessage = "You must be admin to use this module"; @@ -91,8 +87,7 @@ public: // another socket took over the connection from this // socket. So ignore this to avoid listing the // connection twice. - if (pSock->GetCloseType() == Csock::CLT_DEREFERENCE) - continue; + if (pSock->GetCloseType() == Csock::CLT_DEREFERENCE) continue; ret.push(pSock); } @@ -102,7 +97,8 @@ public: bool WebRequiresAdmin() override { return true; } CString GetWebMenuTitle() override { return "List sockets"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { if (CZNC::Get().GetManager().empty()) { return false; @@ -160,7 +156,8 @@ public: CString GetCreatedTime(Csock* pSocket) { unsigned long long iStartTime = pSocket->GetStartTime(); time_t iTime = iStartTime / 1000; - return CUtils::FormatTime(iTime, "%Y-%m-%d %H:%M:%S", GetUser()->GetTimezone()); + return CUtils::FormatTime(iTime, "%Y-%m-%d %H:%M:%S", + GetUser()->GetTimezone()); } CString GetLocalHost(Csock* pSocket, bool bShowHosts) { @@ -240,21 +237,20 @@ public: Table.SetCell("Local", GetLocalHost(pSocket, bShowHosts)); Table.SetCell("Remote", GetRemoteHost(pSocket, bShowHosts)); Table.SetCell("In", CString::ToByteStr(pSocket->GetBytesRead())); - Table.SetCell("Out", CString::ToByteStr(pSocket->GetBytesWritten())); + Table.SetCell("Out", + CString::ToByteStr(pSocket->GetBytesWritten())); } PutModule(Table); return; } - virtual ~CListSockets() { - } - + virtual ~CListSockets() {} }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("listsockets"); } USERMODULEDEFS(CListSockets, "List active sockets") - diff --git a/modules/log.cpp b/modules/log.cpp index 8430fde4..1c67bf4d 100644 --- a/modules/log.cpp +++ b/modules/log.cpp @@ -1,6 +1,7 @@ /* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. - * Copyright (C) 2006-2007, CNU (http://cnu.dieplz.net/znc) + * Copyright (C) 2006-2007, CNU + *(http://cnu.dieplz.net/znc) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +27,9 @@ using std::vector; class CLogRule { -public: - CLogRule(const CString& sRule, bool bEnabled = true) : m_sRule(sRule), m_bEnabled(bEnabled) {} + public: + CLogRule(const CString& sRule, bool bEnabled = true) + : m_sRule(sRule), m_bEnabled(bEnabled) {} const CString& GetRule() const { return m_sRule; } bool IsEnabled() const { return m_bEnabled; } @@ -41,19 +43,17 @@ public: return m_sRule == sOther.GetRule(); } - CString ToString() const { - return (m_bEnabled ? "" : "!") + m_sRule; - } + CString ToString() const { return (m_bEnabled ? "" : "!") + m_sRule; } -private: + private: CString m_sRule; bool m_bEnabled; }; -class CLogMod: public CModule { +class CLogMod : public CModule { void Set(const CString& sLine) { - const CString sVar = sLine.Token(1).AsLower(); - bool b = sLine.Token(2).ToBool(); + const CString sVar = sLine.Token(1).AsLower(); + bool b = sLine.Token(2).ToBool(); if (sVar == "joins" || sVar == "quits" || sVar == "nickchanges") { SetNV(sVar, CString(b)); @@ -61,19 +61,26 @@ class CLogMod: public CModule { } else PutModule(sVar + " is invalid."); } -public: - MODCONSTRUCTOR(CLogMod) - { + + public: + MODCONSTRUCTOR(CLogMod) { m_bSanitize = false; AddHelpCommand(); - AddCommand("SetRules", static_cast(&CLogMod::SetRulesCmd), - "", "Set logging rules, use !#chan or !query to negate and * for wildcards"); - AddCommand("ClearRules", static_cast(&CLogMod::ClearRulesCmd), - "", "Clear all logging rules"); - AddCommand("ListRules", static_cast(&CLogMod::ListRulesCmd), - "", "List all logging rules"); - AddCommand("Set", static_cast(&CLogMod::Set), - "boolean", "Set one of the following booleans, joins, quits, nickchanges"); + AddCommand("SetRules", + static_cast(&CLogMod::SetRulesCmd), + "", + "Set logging rules, use !#chan or !query to negate and * " + "for wildcards"); + AddCommand("ClearRules", static_cast( + &CLogMod::ClearRulesCmd), + "", "Clear all logging rules"); + AddCommand("ListRules", + static_cast(&CLogMod::ListRulesCmd), + "", "List all logging rules"); + AddCommand( + "Set", static_cast(&CLogMod::Set), + "boolean", + "Set one of the following booleans, joins, quits, nickchanges"); } void SetRulesCmd(const CString& sLine); @@ -94,38 +101,44 @@ public: void OnIRCDisconnected() override; EModRet OnBroadcast(CString& sMessage) override; - void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override; - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override; - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override; + void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override; + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override; + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override; void OnJoin(const CNick& Nick, CChan& Channel) override; - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override; - void OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) override; + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override; + void OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) override; EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override; /* notices */ EModRet OnUserNotice(CString& sTarget, CString& sMessage) override; EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override; - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override; /* actions */ EModRet OnUserAction(CString& sTarget, CString& sMessage) override; EModRet OnPrivAction(CNick& Nick, CString& sMessage) override; - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override; /* msgs */ EModRet OnUserMsg(CString& sTarget, CString& sMessage) override; EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override; EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override; -private: - CString m_sLogPath; - CString m_sTimestamp; - bool m_bSanitize; - vector m_vRules; + private: + CString m_sLogPath; + CString m_sTimestamp; + bool m_bSanitize; + vector m_vRules; }; -void CLogMod::SetRulesCmd(const CString& sLine) -{ +void CLogMod::SetRulesCmd(const CString& sLine) { VCString vsRules = SplitRules(sLine.Token(1, true)); if (vsRules.empty()) { @@ -138,8 +151,7 @@ void CLogMod::SetRulesCmd(const CString& sLine) } } -void CLogMod::ClearRulesCmd(const CString& sLine) -{ +void CLogMod::ClearRulesCmd(const CString& sLine) { size_t uCount = m_vRules.size(); if (uCount == 0) { @@ -152,8 +164,7 @@ void CLogMod::ClearRulesCmd(const CString& sLine) } } -void CLogMod::ListRulesCmd(const CString& sLine) -{ +void CLogMod::ListRulesCmd(const CString& sLine) { CTable Table; Table.AddColumn("Rule"); Table.AddColumn("Logging enabled"); @@ -171,8 +182,7 @@ void CLogMod::ListRulesCmd(const CString& sLine) } } -void CLogMod::SetRules(const VCString& vsRules) -{ +void CLogMod::SetRules(const VCString& vsRules) { m_vRules.clear(); for (CString sRule : vsRules) { @@ -181,8 +191,7 @@ void CLogMod::SetRules(const VCString& vsRules) } } -VCString CLogMod::SplitRules(const CString& sRules) const -{ +VCString CLogMod::SplitRules(const CString& sRules) const { CString sCopy = sRules; sCopy.Replace(",", " "); @@ -192,8 +201,7 @@ VCString CLogMod::SplitRules(const CString& sRules) const return vsRules; } -CString CLogMod::JoinRules(const CString& sSeparator) const -{ +CString CLogMod::JoinRules(const CString& sSeparator) const { VCString vsRules; for (const CLogRule& Rule : m_vRules) { vsRules.push_back(Rule.ToString()); @@ -202,8 +210,7 @@ CString CLogMod::JoinRules(const CString& sSeparator) const return sSeparator.Join(vsRules.begin(), vsRules.end()); } -bool CLogMod::TestRules(const CString& sTarget) const -{ +bool CLogMod::TestRules(const CString& sTarget) const { for (const CLogRule& Rule : m_vRules) { if (Rule.Compare(sTarget)) { return Rule.IsEnabled(); @@ -213,8 +220,8 @@ bool CLogMod::TestRules(const CString& sTarget) const return true; } -void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/) -{ +void CLogMod::PutLog(const CString& sLine, + const CString& sWindow /*= "Status"*/) { if (!TestRules(sWindow)) { return; } @@ -225,23 +232,24 @@ void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/ time(&curtime); // Generate file name sPath = CUtils::FormatTime(curtime, m_sLogPath, GetUser()->GetTimezone()); - if (sPath.empty()) - { + if (sPath.empty()) { DEBUG("Could not format log path [" << sPath << "]"); return; } // TODO: Properly handle IRC case mapping // $WINDOW has to be handled last, since it can contain % - sPath.Replace("$USER", CString((GetUser() ? GetUser()->GetUserName() : "UNKNOWN"))); - sPath.Replace("$NETWORK", CString((GetNetwork() ? GetNetwork()->GetName() : "znc"))); - sPath.Replace("$WINDOW", CString(sWindow.Replace_n("/", "-").Replace_n("\\", "-")).AsLower()); + sPath.Replace("$USER", + CString((GetUser() ? GetUser()->GetUserName() : "UNKNOWN"))); + sPath.Replace("$NETWORK", + CString((GetNetwork() ? GetNetwork()->GetName() : "znc"))); + sPath.Replace("$WINDOW", CString(sWindow.Replace_n("/", "-") + .Replace_n("\\", "-")).AsLower()); // Check if it's allowed to write in this specific path sPath = CDir::CheckPathPrefix(GetSavePath(), sPath); - if (sPath.empty()) - { - DEBUG("Invalid log path ["<GetTimezone()) + " " + (m_bSanitize ? sLine.StripControls_n() : sLine) + "\n"); + if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT)) { + LogFile.Write(CUtils::FormatTime(curtime, m_sTimestamp, + GetUser()->GetTimezone()) + + " " + (m_bSanitize ? sLine.StripControls_n() : sLine) + + "\n"); } else DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno)); } -void CLogMod::PutLog(const CString& sLine, const CChan& Channel) -{ +void CLogMod::PutLog(const CString& sLine, const CChan& Channel) { PutLog(sLine, Channel.GetName()); } -void CLogMod::PutLog(const CString& sLine, const CNick& Nick) -{ +void CLogMod::PutLog(const CString& sLine, const CNick& Nick) { PutLog(sLine, Nick.GetNick()); } -CString CLogMod::GetServer() -{ +CString CLogMod::GetServer() { CServer* pServer = GetNetwork()->GetCurrentServer(); CString sSSL; - if (!pServer) - return "(no server)"; + if (!pServer) return "(no server)"; - if (pServer->IsSSL()) - sSSL = "+"; + if (pServer->IsSSL()) sSSL = "+"; return pServer->GetName() + " " + sSSL + CString(pServer->GetPort()); } -bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) -{ +bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) { VCString vsArgs; sArgs.QuoteSplit(vsArgs); @@ -299,7 +303,9 @@ bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) } else { // Only one arg may be LogPath if (bHaveLogPath) { - sMessage = "Invalid args [" + sArgs + "]. Only one log path allowed. Check that there are no spaces in the path."; + sMessage = "Invalid args [" + sArgs + + "]. Only one log path allowed. Check that there " + "are no spaces in the path."; return false; } m_sLogPath = sArg; @@ -313,21 +319,27 @@ bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) // Add default filename to path if it's a folder if (GetType() == CModInfo::UserModule) { - if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { + if (m_sLogPath.Right(1) == "/" || + m_sLogPath.find("$WINDOW") == CString::npos || + m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$NETWORK/$WINDOW/%Y-%m-%d.log"; } } else if (GetType() == CModInfo::NetworkModule) { - if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos) { + if (m_sLogPath.Right(1) == "/" || + m_sLogPath.find("$WINDOW") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } m_sLogPath += "$WINDOW/%Y-%m-%d.log"; } } else { - if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$USER") == CString::npos || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) { + if (m_sLogPath.Right(1) == "/" || + m_sLogPath.find("$USER") == CString::npos || + m_sLogPath.find("$WINDOW") == CString::npos || + m_sLogPath.find("$NETWORK") == CString::npos) { if (!m_sLogPath.empty()) { m_sLogPath += "/"; } @@ -342,78 +354,83 @@ bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage) // Check if it's allowed to write in this path in general m_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath); if (m_sLogPath.empty()) { - sMessage = "Invalid log path ["+m_sLogPath+"]."; + sMessage = "Invalid log path [" + m_sLogPath + "]."; return false; } else { - sMessage = "Logging to ["+m_sLogPath+"]. Using timestamp format '"+m_sTimestamp+"'"; + sMessage = "Logging to [" + m_sLogPath + "]. Using timestamp format '" + + m_sTimestamp + "'"; return true; } } - -void CLogMod::OnIRCConnected() -{ +void CLogMod::OnIRCConnected() { PutLog("Connected to IRC (" + GetServer() + ")"); } -void CLogMod::OnIRCDisconnected() -{ +void CLogMod::OnIRCDisconnected() { PutLog("Disconnected from IRC (" + GetServer() + ")"); } -CModule::EModRet CLogMod::OnBroadcast(CString& sMessage) -{ +CModule::EModRet CLogMod::OnBroadcast(CString& sMessage) { PutLog("Broadcast: " + sMessage); return CONTINUE; } -void CLogMod::OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) -{ +void CLogMod::OnRawMode2(const CNick* pOpNick, CChan& Channel, + const CString& sModes, const CString& sArgs) { const CString sNick = pOpNick ? pOpNick->GetNick() : "Server"; PutLog("*** " + sNick + " sets mode: " + sModes + " " + sArgs, Channel); } -void CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) -{ - PutLog("*** " + sKickedNick + " was kicked by " + OpNick.GetNick() + " (" + sMessage + ")", Channel); +void CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, + CChan& Channel, const CString& sMessage) { + PutLog("*** " + sKickedNick + " was kicked by " + OpNick.GetNick() + " (" + + sMessage + ")", + Channel); } -void CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) -{ +void CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) { if (!HasNV("quits") || GetNV("quits").ToBool()) { for (CChan* pChan : vChans) - PutLog("*** Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", *pChan); + PutLog("*** Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + + "@" + Nick.GetHost() + ") (" + sMessage + ")", + *pChan); } } -void CLogMod::OnJoin(const CNick& Nick, CChan& Channel) -{ +void CLogMod::OnJoin(const CNick& Nick, CChan& Channel) { if (!HasNV("joins") || GetNV("joins").ToBool()) - PutLog("*** Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ")", Channel); + PutLog("*** Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + + Nick.GetHost() + ")", + Channel); } -void CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) -{ - PutLog("*** Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", Channel); +void CLogMod::OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) { + PutLog("*** Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + + Nick.GetHost() + ") (" + sMessage + ")", + Channel); } -void CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) -{ +void CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) { if (!HasNV("nickchanges") || GetNV("nickchanges").ToBool()) { for (CChan* pChan : vChans) - PutLog("*** " + OldNick.GetNick() + " is now known as " + sNewNick, *pChan); + PutLog("*** " + OldNick.GetNick() + " is now known as " + sNewNick, + *pChan); } } -CModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) -{ - PutLog("*** " + Nick.GetNick() + " changes topic to '" + sTopic + "'", Channel); +CModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, + CString& sTopic) { + PutLog("*** " + Nick.GetNick() + " changes topic to '" + sTopic + "'", + Channel); return CONTINUE; } /* notices */ -CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage) -{ +CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage) { CIRCNetwork* pNetwork = GetNetwork(); if (pNetwork) { PutLog("-" + pNetwork->GetCurNick() + "- " + sMessage, sTarget); @@ -422,21 +439,19 @@ CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage) return CONTINUE; } -CModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage) -{ +CModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Nick); return CONTINUE; } -CModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) -{ +CModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) { PutLog("-" + Nick.GetNick() + "- " + sMessage, Channel); return CONTINUE; } /* actions */ -CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage) -{ +CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage) { CIRCNetwork* pNetwork = GetNetwork(); if (pNetwork) { PutLog("* " + pNetwork->GetCurNick() + " " + sMessage, sTarget); @@ -445,21 +460,19 @@ CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage) return CONTINUE; } -CModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage) -{ +CModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Nick); return CONTINUE; } -CModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) -{ +CModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) { PutLog("* " + Nick.GetNick() + " " + sMessage, Channel); return CONTINUE; } /* msgs */ -CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage) -{ +CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage) { CIRCNetwork* pNetwork = GetNetwork(); if (pNetwork) { PutLog("<" + pNetwork->GetCurNick() + "> " + sMessage, sTarget); @@ -468,19 +481,19 @@ CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage) return CONTINUE; } -CModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage) -{ +CModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Nick); return CONTINUE; } -CModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) -{ +CModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, + CString& sMessage) { PutLog("<" + Nick.GetNick() + "> " + sMessage, Channel); return CONTINUE; } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetHasArgs(true); diff --git a/modules/missingmotd.cpp b/modules/missingmotd.cpp index e7e0fe33..8857e9cb 100644 --- a/modules/missingmotd.cpp +++ b/modules/missingmotd.cpp @@ -17,7 +17,7 @@ #include class CMissingMotd : public CModule { -public: + public: MODCONSTRUCTOR(CMissingMotd) {} void OnClientLogin() override { @@ -25,11 +25,10 @@ public: } }; -template<> void TModInfo(CModInfo& Info) -{ - Info.SetWikiPage("missingmotd"); - Info.SetHasArgs(false); +template <> +void TModInfo(CModInfo& Info) { + Info.SetWikiPage("missingmotd"); + Info.SetHasArgs(false); } USERMODULEDEFS(CMissingMotd, "Sends 422 to clients when they login") - diff --git a/modules/modperl.cpp b/modules/modperl.cpp index d585125a..8f313570 100644 --- a/modules/modperl.cpp +++ b/modules/modperl.cpp @@ -29,7 +29,7 @@ #include #if defined(__APPLE__) && defined(__MACH__) -#include // for _NSGetEnviron +#include // for _NSGetEnviron #endif #include "modperl/pstring.h" @@ -40,24 +40,40 @@ using std::vector; // Allows perl to load .so files when needed by .pm // For example, it needs to load ZNC.so extern "C" { - void boot_DynaLoader (pTHX_ CV* cv); - static void xs_init(pTHX) { - newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, __FILE__); - } +void boot_DynaLoader(pTHX_ CV* cv); +static void xs_init(pTHX) { + newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, __FILE__); +} } -class CModPerl: public CModule { - PerlInterpreter *m_pPerl; -public: - MODCONSTRUCTOR(CModPerl) { - m_pPerl = nullptr; - } +class CModPerl : public CModule { + PerlInterpreter* m_pPerl; -#define PSTART dSP; I32 ax; int ret = 0; ENTER; SAVETMPS; PUSHMARK(SP) -#define PCALL(name) PUTBACK; ret = call_pv(name, G_EVAL|G_ARRAY); SPAGAIN; SP -= ret; ax = (SP - PL_stack_base) + 1 -#define PEND ax += 0; PUTBACK; FREETMPS; LEAVE + public: + MODCONSTRUCTOR(CModPerl) { m_pPerl = nullptr; } + +#define PSTART \ + dSP; \ + I32 ax; \ + int ret = 0; \ + ENTER; \ + SAVETMPS; \ + PUSHMARK(SP) +#define PCALL(name) \ + PUTBACK; \ + ret = call_pv(name, G_EVAL | G_ARRAY); \ + SPAGAIN; \ + SP -= ret; \ + ax = (SP - PL_stack_base) + 1 +#define PEND \ + ax += 0; \ + PUTBACK; \ + FREETMPS; \ + LEAVE #define PUSH_STR(s) XPUSHs(PString(s).GetSV()) -#define PUSH_PTR(type, p) XPUSHs(SWIG_NewInstanceObj(const_cast(p), SWIG_TypeQuery(#type), SWIG_SHADOW)) +#define PUSH_PTR(type, p) \ + XPUSHs(SWIG_NewInstanceObj(const_cast(p), SWIG_TypeQuery(#type), \ + SWIG_SHADOW)) bool OnLoad(const CString& sArgsi, CString& sMessage) override { CString sModPath, sTmp; @@ -67,15 +83,19 @@ public: } sTmp = CDir::ChangeDir(sModPath, ".."); int argc = 6; - char *pArgv[] = {"", "-T", "-w", - "-I", const_cast(sTmp.c_str()), - const_cast(sModPath.c_str()), nullptr}; - char **argv = pArgv; - char *** const pEnviron = + char* pArgv[] = {"", + "-T", + "-w", + "-I", + const_cast(sTmp.c_str()), + const_cast(sModPath.c_str()), + nullptr}; + char** argv = pArgv; + char*** const pEnviron = #if defined(__APPLE__) && defined(__MACH__) - _NSGetEnviron(); + _NSGetEnviron(); #else - &environ; + &environ; #endif PERL_SYS_INIT3(&argc, &argv, pEnviron); m_pPerl = perl_alloc(); @@ -98,8 +118,10 @@ public: return true; } - virtual EModRet OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg) override { + virtual EModRet OnModuleLoading(const CString& sModName, + const CString& sArgs, + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg) override { EModRet result = HALT; PSTART; PUSH_STR(sModName); @@ -115,13 +137,14 @@ public: result = HALT; DEBUG("Perl ZNC::Core::LoadModule died: " << sRetMsg); } else if (ret < 1 || 2 < ret) { - sRetMsg = "Error: Perl ZNC::Core::LoadModule returned " + CString(ret) + " values."; + sRetMsg = "Error: Perl ZNC::Core::LoadModule returned " + + CString(ret) + " values."; bSuccess = false; result = HALT; } else { ELoadPerlMod eLPM = static_cast(SvUV(ST(0))); if (Perl_NotFound == eLPM) { - result = CONTINUE; // Not a Perl module + result = CONTINUE; // Not a Perl module } else { sRetMsg = PString(ST(1)); result = HALT; @@ -133,7 +156,8 @@ public: return result; } - EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg) override { + EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg) override { CPerlModule* pMod = AsPerlModule(pModule); if (pMod) { EModRet result = HALT; @@ -145,7 +169,8 @@ public: bSuccess = false; sRetMsg = PString(ERRSV); } else if (ret < 1 || 2 < ret) { - sRetMsg = "Error: Perl ZNC::Core::UnloadModule returned " + CString(ret) + " values."; + sRetMsg = "Error: Perl ZNC::Core::UnloadModule returned " + + CString(ret) + " values."; bSuccess = false; result = HALT; } else { @@ -155,7 +180,9 @@ public: sRetMsg = "Module [" + sModName + "] unloaded"; result = HALT; } else { - result = CONTINUE; // module wasn't loaded by modperl. Perhaps a module-provider written in perl did that. + result = CONTINUE; // module wasn't loaded by modperl. + // Perhaps a module-provider written in + // perl did that. } } PEND; @@ -166,7 +193,7 @@ public: } virtual EModRet OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg) override { + bool& bSuccess, CString& sRetMsg) override { PSTART; PUSH_STR(sModule); PUSH_PTR(CModInfo*, &ModInfo); @@ -177,7 +204,7 @@ public: sRetMsg = PString(ERRSV); DEBUG("Perl ZNC::Core::GetModInfo died: " << sRetMsg); } else if (0 < ret) { - switch(static_cast(SvUV(ST(0)))) { + switch (static_cast(SvUV(ST(0)))) { case Perl_NotFound: result = CONTINUE; break; @@ -208,8 +235,8 @@ public: return result; } - void OnGetAvailableMods(set& ssMods, CModInfo::EModuleType eType) override { - + void OnGetAvailableMods(set& ssMods, + CModInfo::EModuleType eType) override { unsigned int a = 0; CDir Dir; @@ -231,7 +258,8 @@ public: PUSH_PTR(CModInfo*, &ModInfo); PCALL("ZNC::Core::ModInfoByPath"); if (SvTRUE(ERRSV)) { - DEBUG(__PRETTY_FUNCTION__ << ": " << sPath << ": " << PString(ERRSV)); + DEBUG(__PRETTY_FUNCTION__ << ": " << sPath << ": " + << PString(ERRSV)); } else if (ModInfo.SupportsType(eType)) { ssMods.insert(ModInfo); } @@ -250,7 +278,6 @@ public: PERL_SYS_TERM(); } } - }; #include "modperl/functions.cpp" @@ -283,22 +310,33 @@ CPerlTimer::~CPerlTimer() { } } -#define SOCKSTART PSTART; XPUSHs(GetPerlObj()) -#define SOCKCBCHECK(OnSuccess) PCALL("ZNC::Core::CallSocket"); if (SvTRUE(ERRSV)) { Close(); DEBUG("Perl socket hook died with: " + PString(ERRSV)); } else { OnSuccess; } PEND -#define CBSOCK(Func) void CPerlSocket::Func() {\ - CPerlModule* pMod = AsPerlModule(GetModule());\ - if (pMod) {\ - SOCKSTART;\ - PUSH_STR("On" #Func);\ - SOCKCBCHECK();\ - }\ -} +#define SOCKSTART \ + PSTART; \ + XPUSHs(GetPerlObj()) +#define SOCKCBCHECK(OnSuccess) \ + PCALL("ZNC::Core::CallSocket"); \ + if (SvTRUE(ERRSV)) { \ + Close(); \ + DEBUG("Perl socket hook died with: " + PString(ERRSV)); \ + } else { \ + OnSuccess; \ + } \ + PEND +#define CBSOCK(Func) \ + void CPerlSocket::Func() { \ + CPerlModule* pMod = AsPerlModule(GetModule()); \ + if (pMod) { \ + SOCKSTART; \ + PUSH_STR("On" #Func); \ + SOCKCBCHECK(); \ + } \ + } CBSOCK(Connected); CBSOCK(Disconnected); CBSOCK(Timeout); CBSOCK(ConnectionRefused); -void CPerlSocket::ReadData(const char *data, size_t len) { +void CPerlSocket::ReadData(const char* data, size_t len) { CPerlModule* pMod = AsPerlModule(GetModule()); if (pMod) { SOCKSTART; @@ -325,9 +363,7 @@ Csock* CPerlSocket::GetSockObj(const CString& sHost, unsigned short uPort) { PUSH_STR("_Accepted"); PUSH_STR(sHost); mXPUSHi(uPort); - SOCKCBCHECK( - result = SvToPtr("CPerlSocket*")(ST(0)); - ); + SOCKCBCHECK(result = SvToPtr("CPerlSocket*")(ST(0));); } return result; } @@ -342,7 +378,8 @@ CPerlSocket::~CPerlSocket() { } } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("modperl"); } diff --git a/modules/modperl/module.h b/modules/modperl/module.h index 5206465d..7905322d 100644 --- a/modules/modperl/module.h +++ b/modules/modperl/module.h @@ -28,52 +28,67 @@ class CPerlModule : public CModule { SV* m_perlObj; VWebSubPages* _GetSubPages(); -public: - CPerlModule(CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, const CString& sDataPath, - CModInfo::EModuleType eType, SV* perlObj) - : CModule(nullptr, pUser, pNetwork, sModName, sDataPath, eType) { + + public: + CPerlModule(CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, + const CString& sDataPath, CModInfo::EModuleType eType, + SV* perlObj) + : CModule(nullptr, pUser, pNetwork, sModName, sDataPath, eType) { m_perlObj = newSVsv(perlObj); } - SV* GetPerlObj() { - return sv_2mortal(newSVsv(m_perlObj)); - } + SV* GetPerlObj() { return sv_2mortal(newSVsv(m_perlObj)); } bool OnBoot() override; bool WebRequiresLogin() override; bool WebRequiresAdmin() override; CString GetWebMenuTitle() override; bool OnWebPreRequest(CWebSock& WebSock, const CString& sPageName) override; - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override; + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override; VWebSubPages& GetSubPages() override; void OnPreRehash() override; void OnPostRehash() override; void OnIRCDisconnected() override; void OnIRCConnected() override; - EModRet OnIRCConnecting(CIRCSock *pIRCSock) override; - void OnIRCConnectionError(CIRCSock *pIRCSock) override; - EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName) override; + EModRet OnIRCConnecting(CIRCSock* pIRCSock) override; + void OnIRCConnectionError(CIRCSock* pIRCSock) override; + EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, + CString& sRealName) override; EModRet OnBroadcast(CString& sMessage) override; - void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) override; - void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) override; - void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override; + void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange) override; + void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) override; + void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override; EModRet OnRaw(CString& sLine) override; EModRet OnStatusCommand(CString& sCommand) override; void OnModCommand(const CString& sCommand) override; void OnModNotice(const CString& sMessage) override; void OnModCTCP(const CString& sMessage) override; - void OnQuit(const CNick& Nick, const CString& sMessage, const std::vector& vChans) override; - void OnNick(const CNick& Nick, const CString& sNewNick, const std::vector& vChans) override; - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override; + void OnQuit(const CNick& Nick, const CString& sMessage, + const std::vector& vChans) override; + void OnNick(const CNick& Nick, const CString& sNewNick, + const std::vector& vChans) override; + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override; EModRet OnJoining(CChan& Channel) override; void OnJoin(const CNick& Nick, CChan& Channel) override; - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override; + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override; EModRet OnChanBufferStarting(CChan& Chan, CClient& Client) override; EModRet OnChanBufferEnding(CChan& Chan, CClient& Client) override; - EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine) override; + EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, + CString& sLine) override; EModRet OnPrivBufferPlayLine(CClient& Client, CString& sLine) override; void OnClientLogin() override; void OnClientDisconnect() override; @@ -92,11 +107,13 @@ public: EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override; EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override; EModRet OnPrivAction(CNick& Nick, CString& sMessage) override; - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override; EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override; EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override; EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override; - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override; EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override; bool OnServerCapAvailable(const CString& sCap) override; void OnServerCapResult(const CString& sCap, bool bSuccess) override; @@ -109,8 +126,10 @@ public: EModRet OnRawMessage(CMessage& Message) override; EModRet OnNumericMessage(CNumericMessage& Message) override; - void OnQuitMessage(CQuitMessage& Message, const std::vector& vChans) override; - void OnNickMessage(CNickMessage& Message, const std::vector& vChans) override; + void OnQuitMessage(CQuitMessage& Message, + const std::vector& vChans) override; + void OnNickMessage(CNickMessage& Message, + const std::vector& vChans) override; void OnKickMessage(CKickMessage& Message) override; void OnJoinMessage(CJoinMessage& Message) override; void OnPartMessage(CPartMessage& Message) override; @@ -150,36 +169,40 @@ enum ELoadPerlMod { class CPerlTimer : public CTimer { SV* m_perlObj; -public: - CPerlTimer(CPerlModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription, SV* perlObj) - : CTimer (pModule, uInterval, uCycles, sLabel, sDescription), m_perlObj(newSVsv(perlObj)) { + + public: + CPerlTimer(CPerlModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription, SV* perlObj) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), + m_perlObj(newSVsv(perlObj)) { pModule->AddTimer(this); } void RunJob() override; - SV* GetPerlObj() { - return sv_2mortal(newSVsv(m_perlObj)); - } + SV* GetPerlObj() { return sv_2mortal(newSVsv(m_perlObj)); } ~CPerlTimer(); }; -inline CPerlTimer* CreatePerlTimer(CPerlModule* pModule, unsigned int uInterval, unsigned int uCycles, - const CString& sLabel, const CString& sDescription, SV* perlObj) { - return new CPerlTimer(pModule, uInterval, uCycles, sLabel, sDescription, perlObj); +inline CPerlTimer* CreatePerlTimer(CPerlModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription, SV* perlObj) { + return new CPerlTimer(pModule, uInterval, uCycles, sLabel, sDescription, + perlObj); } class CPerlSocket : public CSocket { SV* m_perlObj; -public: - CPerlSocket(CPerlModule* pModule, SV* perlObj) : CSocket(pModule), m_perlObj(newSVsv(perlObj)) {} - SV* GetPerlObj() { - return sv_2mortal(newSVsv(m_perlObj)); - } + + public: + CPerlSocket(CPerlModule* pModule, SV* perlObj) + : CSocket(pModule), m_perlObj(newSVsv(perlObj)) {} + SV* GetPerlObj() { return sv_2mortal(newSVsv(m_perlObj)); } ~CPerlSocket(); void Connected() override; void Disconnected() override; void Timeout() override; void ConnectionRefused() override; - void ReadData(const char *data, size_t len) override; + void ReadData(const char* data, size_t len) override; void ReadLine(const CString& sLine) override; Csock* GetSockObj(const CString& sHost, unsigned short uPort) override; }; @@ -209,25 +232,15 @@ inline bool HaveCharset() { return false; } -inline int _GetSOMAXCONN() { - return SOMAXCONN; -} +inline int _GetSOMAXCONN() { return SOMAXCONN; } -inline int GetVersionMajor() { - return VERSION_MAJOR; -} +inline int GetVersionMajor() { return VERSION_MAJOR; } -inline int GetVersionMinor() { - return VERSION_MINOR; -} +inline int GetVersionMinor() { return VERSION_MINOR; } -inline double GetVersion() { - return VERSION; -} +inline double GetVersion() { return VERSION; } -inline CString GetVersionExtra() { - return ZNC_VERSION_EXTRA; -} +inline CString GetVersionExtra() { return ZNC_VERSION_EXTRA; } #if HAVE_VISIBILITY #pragma GCC visibility pop #endif diff --git a/modules/modperl/pstring.h b/modules/modperl/pstring.h index a81e9e8f..255bfd0c 100644 --- a/modules/modperl/pstring.h +++ b/modules/modperl/pstring.h @@ -17,70 +17,61 @@ #pragma once class PString : public CString { - public: - enum EType { - STRING, - INT, - UINT, - NUM, - BOOL - }; + public: + enum EType { STRING, INT, UINT, NUM, BOOL }; - PString() : CString() { m_eType = STRING; } - PString(const char* c) : CString(c) { m_eType = STRING; } - PString(const CString& s) : CString(s) { m_eType = STRING; } - PString(int i) : CString(i) { m_eType = INT; } - PString(u_int i) : CString(i) { m_eType = UINT; } - PString(long i) : CString(i) { m_eType = INT; } - PString(u_long i) : CString(i) { m_eType = UINT; } - PString(long long i) : CString(i) { m_eType = INT; } - PString(unsigned long long i) : CString(i) { m_eType = UINT; } - PString(double i) : CString(i) { m_eType = NUM; } - PString(bool b) : CString((b ? "1" : "0")) { m_eType = BOOL; } - PString(SV* sv) { - STRLEN len = SvCUR(sv); - char* c = SvPV(sv, len); - char* c2 = new char[len+1]; - memcpy(c2, c, len); - c2[len] = 0; - *this = c2; - delete[] c2; + PString() : CString() { m_eType = STRING; } + PString(const char* c) : CString(c) { m_eType = STRING; } + PString(const CString& s) : CString(s) { m_eType = STRING; } + PString(int i) : CString(i) { m_eType = INT; } + PString(u_int i) : CString(i) { m_eType = UINT; } + PString(long i) : CString(i) { m_eType = INT; } + PString(u_long i) : CString(i) { m_eType = UINT; } + PString(long long i) : CString(i) { m_eType = INT; } + PString(unsigned long long i) : CString(i) { m_eType = UINT; } + PString(double i) : CString(i) { m_eType = NUM; } + PString(bool b) : CString((b ? "1" : "0")) { m_eType = BOOL; } + PString(SV* sv) { + STRLEN len = SvCUR(sv); + char* c = SvPV(sv, len); + char* c2 = new char[len + 1]; + memcpy(c2, c, len); + c2[len] = 0; + *this = c2; + delete[] c2; + } + + virtual ~PString() {} + + EType GetType() const { return m_eType; } + void SetType(EType e) { m_eType = e; } + + SV* GetSV(bool bMakeMortal = true) const { + SV* pSV = nullptr; + switch (GetType()) { + case NUM: + pSV = newSVnv(ToDouble()); + break; + case INT: + pSV = newSViv(ToLongLong()); + break; + case UINT: + case BOOL: + pSV = newSVuv(ToULongLong()); + break; + case STRING: + default: + pSV = newSVpv(data(), length()); + break; } - virtual ~PString() {} - - EType GetType() const { return m_eType; } - void SetType(EType e) { m_eType = e; } - - SV* GetSV(bool bMakeMortal = true) const - { - SV* pSV = nullptr; - switch (GetType()) { - case NUM: - pSV = newSVnv(ToDouble()); - break; - case INT: - pSV = newSViv(ToLongLong()); - break; - case UINT: - case BOOL: - pSV = newSVuv(ToULongLong()); - break; - case STRING: - default: - pSV = newSVpv(data(), length()); - break; - } - - if (bMakeMortal) { - pSV = sv_2mortal(pSV); - } - - return pSV; + if (bMakeMortal) { + pSV = sv_2mortal(pSV); } - private: - EType m_eType; + return pSV; + } + + private: + EType m_eType; }; - - diff --git a/modules/modpython.cpp b/modules/modpython.cpp index de013ea8..19ef95f0 100644 --- a/modules/modpython.cpp +++ b/modules/modpython.cpp @@ -31,54 +31,54 @@ using std::vector; using std::set; -class CModPython: public CModule { - +class CModPython : public CModule { PyObject* m_PyZNCModule; PyObject* m_PyFormatException; vector m_vpObject; -public: - + public: CString GetPyExceptionStr() { - PyObject* ptype; - PyObject* pvalue; - PyObject* ptraceback; - PyErr_Fetch(&ptype, &pvalue, &ptraceback); - CString result; - if (!pvalue) { - Py_INCREF(Py_None); - pvalue = Py_None; - } - if (!ptraceback) { - Py_INCREF(Py_None); - ptraceback = Py_None; - } - PyErr_NormalizeException(&ptype, &pvalue, &ptraceback); - PyObject* strlist = PyObject_CallFunctionObjArgs(m_PyFormatException, ptype, pvalue, ptraceback, nullptr); - Py_CLEAR(ptype); - Py_CLEAR(pvalue); - Py_CLEAR(ptraceback); - if (!strlist) { - return "Couldn't get exact error message"; - } + PyObject* ptype; + PyObject* pvalue; + PyObject* ptraceback; + PyErr_Fetch(&ptype, &pvalue, &ptraceback); + CString result; + if (!pvalue) { + Py_INCREF(Py_None); + pvalue = Py_None; + } + if (!ptraceback) { + Py_INCREF(Py_None); + ptraceback = Py_None; + } + PyErr_NormalizeException(&ptype, &pvalue, &ptraceback); + PyObject* strlist = PyObject_CallFunctionObjArgs( + m_PyFormatException, ptype, pvalue, ptraceback, nullptr); + Py_CLEAR(ptype); + Py_CLEAR(pvalue); + Py_CLEAR(ptraceback); + if (!strlist) { + return "Couldn't get exact error message"; + } - if (PySequence_Check(strlist)) { - PyObject* strlist_fast = PySequence_Fast(strlist, "Shouldn't happen (1)"); - PyObject** items = PySequence_Fast_ITEMS(strlist_fast); - Py_ssize_t L = PySequence_Fast_GET_SIZE(strlist_fast); - for (Py_ssize_t i = 0; i < L; ++i) { - PyObject* utf8 = PyUnicode_AsUTF8String(items[i]); - result += PyBytes_AsString(utf8); - Py_CLEAR(utf8); - } - Py_CLEAR(strlist_fast); - } else { - result = "Can't get exact error message"; + if (PySequence_Check(strlist)) { + PyObject* strlist_fast = + PySequence_Fast(strlist, "Shouldn't happen (1)"); + PyObject** items = PySequence_Fast_ITEMS(strlist_fast); + Py_ssize_t L = PySequence_Fast_GET_SIZE(strlist_fast); + for (Py_ssize_t i = 0; i < L; ++i) { + PyObject* utf8 = PyUnicode_AsUTF8String(items[i]); + result += PyBytes_AsString(utf8); + Py_CLEAR(utf8); } + Py_CLEAR(strlist_fast); + } else { + result = "Can't get exact error message"; + } - Py_CLEAR(strlist); + Py_CLEAR(strlist); - return result; + return result; } MODCONSTRUCTOR(CModPython) { @@ -105,7 +105,8 @@ public: sMessage = "Couldn't import python module traceback"; return false; } - m_PyFormatException = PyObject_GetAttrString(pyModuleTraceback, "format_exception"); + m_PyFormatException = + PyObject_GetAttrString(pyModuleTraceback, "format_exception"); if (!m_PyFormatException) { sMessage = "Couldn't get traceback.format_exception"; Py_CLEAR(pyModuleTraceback); @@ -125,7 +126,9 @@ public: return false; } Py_CLEAR(pySysModule); - PyObject* pyIgnored = PyObject_CallMethod(pySysPath, const_cast("append"), const_cast("s"), sTmp.c_str()); + PyObject* pyIgnored = + PyObject_CallMethod(pySysPath, const_cast("append"), + const_cast("s"), sTmp.c_str()); if (!pyIgnored) { sMessage = GetPyExceptionStr(); Py_CLEAR(pyIgnored); @@ -143,8 +146,10 @@ public: return true; } - virtual EModRet OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg) override { + virtual EModRet OnModuleLoading(const CString& sModName, + const CString& sArgs, + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg) override { PyObject* pyFunc = PyObject_GetAttrString(m_PyZNCModule, "load_module"); if (!pyFunc) { sRetMsg = GetPyExceptionStr(); @@ -152,14 +157,19 @@ public: bSuccess = false; return HALT; } - PyObject* pyRes = PyObject_CallFunction(pyFunc, const_cast("ssiNNNN"), - sModName.c_str(), - sArgs.c_str(), - (int)eType, - (eType == CModInfo::GlobalModule ? Py_None : SWIG_NewInstanceObj(GetUser(), SWIG_TypeQuery("CUser*"), 0)), - (eType == CModInfo::NetworkModule ? SWIG_NewInstanceObj(GetNetwork(), SWIG_TypeQuery("CIRCNetwork*"), 0) : Py_None), - CPyRetString::wrap(sRetMsg), - SWIG_NewInstanceObj(reinterpret_cast(this), SWIG_TypeQuery("CModPython*"), 0)); + PyObject* pyRes = PyObject_CallFunction( + pyFunc, const_cast("ssiNNNN"), sModName.c_str(), + sArgs.c_str(), (int)eType, + (eType == CModInfo::GlobalModule + ? Py_None + : SWIG_NewInstanceObj(GetUser(), SWIG_TypeQuery("CUser*"), 0)), + (eType == CModInfo::NetworkModule + ? SWIG_NewInstanceObj(GetNetwork(), + SWIG_TypeQuery("CIRCNetwork*"), 0) + : Py_None), + CPyRetString::wrap(sRetMsg), + SWIG_NewInstanceObj(reinterpret_cast(this), + SWIG_TypeQuery("CModPython*"), 0)); if (!pyRes) { sRetMsg = GetPyExceptionStr(); DEBUG("modpython: " << sRetMsg); @@ -194,18 +204,21 @@ public: return HALT; } - EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg) override { + EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg) override { CPyModule* pMod = AsPyModule(pModule); if (pMod) { CString sModName = pMod->GetModName(); - PyObject* pyFunc = PyObject_GetAttrString(m_PyZNCModule, "unload_module"); + PyObject* pyFunc = + PyObject_GetAttrString(m_PyZNCModule, "unload_module"); if (!pyFunc) { sRetMsg = GetPyExceptionStr(); DEBUG("modpython: " << sRetMsg); bSuccess = false; return HALT; } - PyObject* pyRes = PyObject_CallFunctionObjArgs(pyFunc, pMod->GetPyObj(), nullptr); + PyObject* pyRes = + PyObject_CallFunctionObjArgs(pyFunc, pMod->GetPyObj(), nullptr); if (!pyRes) { sRetMsg = GetPyExceptionStr(); DEBUG("modpython: " << sRetMsg); @@ -228,18 +241,19 @@ public: } virtual EModRet OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg) override { - PyObject* pyFunc = PyObject_GetAttrString(m_PyZNCModule, "get_mod_info"); + bool& bSuccess, CString& sRetMsg) override { + PyObject* pyFunc = + PyObject_GetAttrString(m_PyZNCModule, "get_mod_info"); if (!pyFunc) { sRetMsg = GetPyExceptionStr(); DEBUG("modpython: " << sRetMsg); bSuccess = false; return HALT; } - PyObject* pyRes = PyObject_CallFunction(pyFunc, const_cast("sNN"), - sModule.c_str(), - CPyRetString::wrap(sRetMsg), - SWIG_NewInstanceObj(&ModInfo, SWIG_TypeQuery("CModInfo*"), 0)); + PyObject* pyRes = PyObject_CallFunction( + pyFunc, const_cast("sNN"), sModule.c_str(), + CPyRetString::wrap(sRetMsg), + SWIG_NewInstanceObj(&ModInfo, SWIG_TypeQuery("CModInfo*"), 0)); if (!pyRes) { sRetMsg = GetPyExceptionStr(); DEBUG("modpython: " << sRetMsg); @@ -268,29 +282,34 @@ public: return HALT; } bSuccess = false; - sRetMsg = CString("Shouldn't happen. ") + __PRETTY_FUNCTION__ + " on " + __FILE__ + ":" + CString(__LINE__); + sRetMsg = CString("Shouldn't happen. ") + __PRETTY_FUNCTION__ + " on " + + __FILE__ + ":" + CString(__LINE__); DEBUG(sRetMsg); return HALT; } - void TryAddModInfo(const CString& sPath, const CString& sName, set& ssMods, set& ssAlready, CModInfo::EModuleType eType) { + void TryAddModInfo(const CString& sPath, const CString& sName, + set& ssMods, set& ssAlready, + CModInfo::EModuleType eType) { if (ssAlready.count(sName)) { return; } - PyObject* pyFunc = PyObject_GetAttrString(m_PyZNCModule, "get_mod_info_path"); + PyObject* pyFunc = + PyObject_GetAttrString(m_PyZNCModule, "get_mod_info_path"); if (!pyFunc) { CString sRetMsg = GetPyExceptionStr(); - DEBUG("modpython tried to get info about [" << sPath << "] (1) but: " << sRetMsg); + DEBUG("modpython tried to get info about [" + << sPath << "] (1) but: " << sRetMsg); return; } CModInfo ModInfo; - PyObject* pyRes = PyObject_CallFunction(pyFunc, const_cast("ssN"), - sPath.c_str(), - sName.c_str(), - SWIG_NewInstanceObj(&ModInfo, SWIG_TypeQuery("CModInfo*"), 0)); + PyObject* pyRes = PyObject_CallFunction( + pyFunc, const_cast("ssN"), sPath.c_str(), sName.c_str(), + SWIG_NewInstanceObj(&ModInfo, SWIG_TypeQuery("CModInfo*"), 0)); if (!pyRes) { CString sRetMsg = GetPyExceptionStr(); - DEBUG("modpython tried to get info about [" << sPath << "] (2) but: " << sRetMsg); + DEBUG("modpython tried to get info about [" + << sPath << "] (2) but: " << sRetMsg); Py_CLEAR(pyFunc); return; } @@ -298,7 +317,8 @@ public: long int x = PyLong_AsLong(pyRes); if (PyErr_Occurred()) { CString sRetMsg = GetPyExceptionStr(); - DEBUG("modpython tried to get info about [" << sPath << "] (3) but: " << sRetMsg); + DEBUG("modpython tried to get info about [" + << sPath << "] (3) but: " << sRetMsg); Py_CLEAR(pyRes); return; } @@ -309,7 +329,8 @@ public: } } - void OnGetAvailableMods(set& ssMods, CModInfo::EModuleType eType) override { + void OnGetAvailableMods(set& ssMods, + CModInfo::EModuleType eType) override { CDir Dir; CModules::ModDirList dirs = CModules::GetModDirs(); @@ -342,7 +363,9 @@ public: virtual ~CModPython() { if (!m_PyZNCModule) { - DEBUG("~CModPython(): seems like CModPython::OnLoad() didn't initialize python"); + DEBUG( + "~CModPython(): seems like CModPython::OnLoad() didn't " + "initialize python"); return; } PyObject* pyFunc = PyObject_GetAttrString(m_PyZNCModule, "unload_all"); @@ -354,7 +377,9 @@ public: PyObject* pyRes = PyObject_CallFunctionObjArgs(pyFunc, nullptr); if (!pyRes) { CString sRetMsg = GetPyExceptionStr(); - DEBUG("modpython tried to unload all modules in its destructor, but: " << sRetMsg); + DEBUG( + "modpython tried to unload all modules in its destructor, but: " + << sRetMsg); } Py_CLEAR(pyRes); Py_CLEAR(pyFunc); @@ -363,7 +388,6 @@ public: Py_CLEAR(m_PyZNCModule); Py_Finalize(); } - }; CString CPyModule::GetPyExceptionStr() { @@ -383,7 +407,8 @@ VWebSubPages& CPyModule::GetSubPages() { void CPyTimer::RunJob() { CPyModule* pMod = AsPyModule(GetModule()); if (pMod) { - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("RunJob"), const_cast("")); + PyObject* pyRes = PyObject_CallMethod( + m_pyObj, const_cast("RunJob"), const_cast("")); if (!pyRes) { CString sRetMsg = m_pModPython->GetPyExceptionStr(); DEBUG("python timer failed: " << sRetMsg); @@ -396,7 +421,8 @@ void CPyTimer::RunJob() { CPyTimer::~CPyTimer() { CPyModule* pMod = AsPyModule(GetModule()); if (pMod) { - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("OnShutdown"), const_cast("")); + PyObject* pyRes = PyObject_CallMethod( + m_pyObj, const_cast("OnShutdown"), const_cast("")); if (!pyRes) { CString sRetMsg = m_pModPython->GetPyExceptionStr(); DEBUG("python timer shutdown failed: " << sRetMsg); @@ -406,56 +432,69 @@ CPyTimer::~CPyTimer() { } } -#define CHECKCLEARSOCK(Func)\ -if (!pyRes) {\ - CString sRetMsg = m_pModPython->GetPyExceptionStr();\ - DEBUG("python socket failed in " Func ": " << sRetMsg);\ - Close();\ -}\ -Py_CLEAR(pyRes) +#define CHECKCLEARSOCK(Func) \ + if (!pyRes) { \ + CString sRetMsg = m_pModPython->GetPyExceptionStr(); \ + DEBUG("python socket failed in " Func ": " << sRetMsg); \ + Close(); \ + } \ + Py_CLEAR(pyRes) -#define CBSOCK(Func) void CPySocket::Func() {\ - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("On" #Func), const_cast(""));\ - CHECKCLEARSOCK(#Func);\ -} +#define CBSOCK(Func) \ + void CPySocket::Func() { \ + PyObject* pyRes = PyObject_CallMethod( \ + m_pyObj, const_cast("On" #Func), const_cast("")); \ + CHECKCLEARSOCK(#Func); \ + } CBSOCK(Connected); CBSOCK(Disconnected); CBSOCK(Timeout); CBSOCK(ConnectionRefused); -void CPySocket::ReadData(const char *data, size_t len) { - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("OnReadData"), const_cast("y#"), data, (int)len); +void CPySocket::ReadData(const char* data, size_t len) { + PyObject* pyRes = + PyObject_CallMethod(m_pyObj, const_cast("OnReadData"), + const_cast("y#"), data, (int)len); CHECKCLEARSOCK("OnReadData"); } void CPySocket::ReadLine(const CString& sLine) { - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("OnReadLine"), const_cast("s"), sLine.c_str()); + PyObject* pyRes = + PyObject_CallMethod(m_pyObj, const_cast("OnReadLine"), + const_cast("s"), sLine.c_str()); CHECKCLEARSOCK("OnReadLine"); } Csock* CPySocket::GetSockObj(const CString& sHost, unsigned short uPort) { CPySocket* result = nullptr; - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("_Accepted"), const_cast("sH"), sHost.c_str(), uPort); + PyObject* pyRes = + PyObject_CallMethod(m_pyObj, const_cast("_Accepted"), + const_cast("sH"), sHost.c_str(), uPort); if (!pyRes) { CString sRetMsg = m_pModPython->GetPyExceptionStr(); DEBUG("python socket failed in OnAccepted: " << sRetMsg); Close(); } - int res = SWIG_ConvertPtr(pyRes, (void**)&result, SWIG_TypeQuery("CPySocket*"), 0); + int res = SWIG_ConvertPtr(pyRes, (void**)&result, + SWIG_TypeQuery("CPySocket*"), 0); if (!SWIG_IsOK(res)) { - DEBUG("python socket was expected to return new socket from OnAccepted, but error=" << res); + DEBUG( + "python socket was expected to return new socket from OnAccepted, " + "but error=" + << res); Close(); result = nullptr; } - if (!result) { - DEBUG("modpython: OnAccepted didn't return new socket"); - } + if (!result) { + DEBUG("modpython: OnAccepted didn't return new socket"); + } Py_CLEAR(pyRes); return result; } CPySocket::~CPySocket() { - PyObject* pyRes = PyObject_CallMethod(m_pyObj, const_cast("OnShutdown"), const_cast("")); + PyObject* pyRes = PyObject_CallMethod( + m_pyObj, const_cast("OnShutdown"), const_cast("")); if (!pyRes) { CString sRetMsg = m_pModPython->GetPyExceptionStr(); DEBUG("python socket failed in OnShutdown: " << sRetMsg); @@ -464,7 +503,8 @@ CPySocket::~CPySocket() { Py_CLEAR(m_pyObj); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("modpython"); } diff --git a/modules/modpython/module.h b/modules/modpython/module.h index 34a3acfb..0faec88f 100644 --- a/modules/modpython/module.h +++ b/modules/modpython/module.h @@ -19,7 +19,7 @@ // This class is used from python to call functions which accept CString& // __str__ is added to it in modpython.i class String { -public: + public: CString s; String(const CString& s = "") : s(s) {} @@ -34,15 +34,17 @@ class CPyModule : public CModule { PyObject* m_pyObj; CModPython* m_pModPython; VWebSubPages* _GetSubPages(); -public: - CPyModule(CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, const CString& sDataPath, - CModInfo::EModuleType eType, PyObject* pyObj, CModPython* pModPython) - : CModule(nullptr, pUser, pNetwork, sModName, sDataPath, eType) { + + public: + CPyModule(CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, + const CString& sDataPath, CModInfo::EModuleType eType, + PyObject* pyObj, CModPython* pModPython) + : CModule(nullptr, pUser, pNetwork, sModName, sDataPath, eType) { m_pyObj = pyObj; Py_INCREF(pyObj); m_pModPython = pModPython; } - PyObject* GetPyObj() { // borrows + PyObject* GetPyObj() { // borrows return m_pyObj; } PyObject* GetNewPyObj() { @@ -54,46 +56,59 @@ public: delete this; } CString GetPyExceptionStr(); - CModPython* GetModPython() { - return m_pModPython; - } + CModPython* GetModPython() { return m_pModPython; } bool OnBoot() override; bool WebRequiresLogin() override; bool WebRequiresAdmin() override; CString GetWebMenuTitle() override; bool OnWebPreRequest(CWebSock& WebSock, const CString& sPageName) override; - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override; + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override; VWebSubPages& GetSubPages() override; void OnPreRehash() override; void OnPostRehash() override; void OnIRCDisconnected() override; void OnIRCConnected() override; - EModRet OnIRCConnecting(CIRCSock *pIRCSock) override; - void OnIRCConnectionError(CIRCSock *pIRCSock) override; - EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName) override; + EModRet OnIRCConnecting(CIRCSock* pIRCSock) override; + void OnIRCConnectionError(CIRCSock* pIRCSock) override; + EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, + CString& sRealName) override; EModRet OnBroadcast(CString& sMessage) override; - void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) override; - void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override; - void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) override; - void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override; + void OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange) override; + void OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override; + void OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) override; + void OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override; EModRet OnRaw(CString& sLine) override; EModRet OnStatusCommand(CString& sCommand) override; void OnModCommand(const CString& sCommand) override; void OnModNotice(const CString& sMessage) override; void OnModCTCP(const CString& sMessage) override; - void OnQuit(const CNick& Nick, const CString& sMessage, const std::vector& vChans) override; - void OnNick(const CNick& Nick, const CString& sNewNick, const std::vector& vChans) override; - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override; + void OnQuit(const CNick& Nick, const CString& sMessage, + const std::vector& vChans) override; + void OnNick(const CNick& Nick, const CString& sNewNick, + const std::vector& vChans) override; + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override; EModRet OnJoining(CChan& Channel) override; void OnJoin(const CNick& Nick, CChan& Channel) override; - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override; + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override; EModRet OnChanBufferStarting(CChan& Chan, CClient& Client) override; EModRet OnChanBufferEnding(CChan& Chan, CClient& Client) override; - EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine) override; + EModRet OnChanBufferPlayLine(CChan& Chan, CClient& Client, + CString& sLine) override; EModRet OnPrivBufferPlayLine(CClient& Client, CString& sLine) override; void OnClientLogin() override; void OnClientDisconnect() override; @@ -112,11 +127,13 @@ public: EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override; EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override; EModRet OnPrivAction(CNick& Nick, CString& sMessage) override; - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override; EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override; EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override; EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override; - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override; + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override; EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override; bool OnServerCapAvailable(const CString& sCap) override; void OnServerCapResult(const CString& sCap, bool bSuccess) override; @@ -129,8 +146,10 @@ public: EModRet OnRawMessage(CMessage& Message) override; EModRet OnNumericMessage(CNumericMessage& Message) override; - void OnQuitMessage(CQuitMessage& Message, const std::vector& vChans) override; - void OnNickMessage(CNickMessage& Message, const std::vector& vChans) override; + void OnQuitMessage(CQuitMessage& Message, + const std::vector& vChans) override; + void OnNickMessage(CNickMessage& Message, + const std::vector& vChans) override; void OnKickMessage(CKickMessage& Message) override; void OnJoinMessage(CJoinMessage& Message) override; void OnPartMessage(CPartMessage& Message) override; @@ -160,18 +179,26 @@ public: // Global Modules EModRet OnAddUser(CUser& User, CString& sErrorRet) override; EModRet OnDeleteUser(CUser& User) override; - void OnClientConnect(CZNCSock* pSock, const CString& sHost, unsigned short uPort) override; - void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override; + void OnClientConnect(CZNCSock* pSock, const CString& sHost, + unsigned short uPort) override; + void OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP) override; EModRet OnUnknownUserRaw(CClient* pClient, CString& sLine) override; EModRet OnUnknownUserRawMessage(CMessage& Message) override; - bool IsClientCapSupported(CClient* pClient, const CString& sCap, bool bState) override; - void OnClientCapRequest(CClient* pClient, const CString& sCap, bool bState) override; - virtual EModRet OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg) override; - EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg) override; + bool IsClientCapSupported(CClient* pClient, const CString& sCap, + bool bState) override; + void OnClientCapRequest(CClient* pClient, const CString& sCap, + bool bState) override; + virtual EModRet OnModuleLoading(const CString& sModName, + const CString& sArgs, + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg) override; + EModRet OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg) override; virtual EModRet OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg) override; - void OnGetAvailableMods(std::set& ssMods, CModInfo::EModuleType eType) override; + bool& bSuccess, CString& sRetMsg) override; + void OnGetAvailableMods(std::set& ssMods, + CModInfo::EModuleType eType) override; void OnClientCapLs(CClient* pClient, SCString& ssCaps) override; EModRet OnLoginAttempt(std::shared_ptr Auth) override; }; @@ -180,16 +207,25 @@ static inline CPyModule* AsPyModule(CModule* p) { return dynamic_cast(p); } -inline CPyModule* CreatePyModule(CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, const CString& sDataPath, CModInfo::EModuleType eType, PyObject* pyObj, CModPython* pModPython) { - return new CPyModule(pUser, pNetwork, sModName, sDataPath, eType, pyObj, pModPython); +inline CPyModule* CreatePyModule(CUser* pUser, CIRCNetwork* pNetwork, + const CString& sModName, + const CString& sDataPath, + CModInfo::EModuleType eType, PyObject* pyObj, + CModPython* pModPython) { + return new CPyModule(pUser, pNetwork, sModName, sDataPath, eType, pyObj, + pModPython); } class CPyTimer : public CTimer { PyObject* m_pyObj; CModPython* m_pModPython; -public: - CPyTimer(CPyModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription, PyObject* pyObj) - : CTimer (pModule, uInterval, uCycles, sLabel, sDescription), m_pyObj(pyObj) { + + public: + CPyTimer(CPyModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription, + PyObject* pyObj) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), + m_pyObj(pyObj) { Py_INCREF(pyObj); pModule->AddTimer(this); m_pModPython = pModule->GetModPython(); @@ -203,16 +239,20 @@ public: ~CPyTimer(); }; -inline CPyTimer* CreatePyTimer(CPyModule* pModule, unsigned int uInterval, unsigned int uCycles, - const CString& sLabel, const CString& sDescription, PyObject* pyObj) { - return new CPyTimer(pModule, uInterval, uCycles, sLabel, sDescription, pyObj); +inline CPyTimer* CreatePyTimer(CPyModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription, PyObject* pyObj) { + return new CPyTimer(pModule, uInterval, uCycles, sLabel, sDescription, + pyObj); } class CPySocket : public CSocket { PyObject* m_pyObj; CModPython* m_pModPython; -public: - CPySocket(CPyModule* pModule, PyObject* pyObj) : CSocket(pModule), m_pyObj(pyObj) { + + public: + CPySocket(CPyModule* pModule, PyObject* pyObj) + : CSocket(pModule), m_pyObj(pyObj) { Py_INCREF(pyObj); m_pModPython = pModule->GetModPython(); } @@ -226,7 +266,7 @@ public: void Disconnected() override; void Timeout() override; void ConnectionRefused() override; - void ReadData(const char *data, size_t len) override; + void ReadData(const char* data, size_t len) override; void ReadLine(const CString& sLine) override; Csock* GetSockObj(const CString& sHost, unsigned short uPort) override; }; @@ -256,62 +296,40 @@ inline bool HaveCharset_() { return false; } -inline int GetSOMAXCONN() { - return SOMAXCONN; -} +inline int GetSOMAXCONN() { return SOMAXCONN; } -inline int GetVersionMajor() { - return VERSION_MAJOR; -} +inline int GetVersionMajor() { return VERSION_MAJOR; } -inline int GetVersionMinor() { - return VERSION_MINOR; -} +inline int GetVersionMinor() { return VERSION_MINOR; } -inline double GetVersion() { - return VERSION; -} +inline double GetVersion() { return VERSION; } -inline CString GetVersionExtra() { - return ZNC_VERSION_EXTRA; -} +inline CString GetVersionExtra() { return ZNC_VERSION_EXTRA; } class MCString_iter { -public: + public: MCString_iter() {} MCString::iterator x; MCString_iter(MCString::iterator z) : x(z) {} - void plusplus() { - ++x; - } - CString get() { - return x->first; - } - bool is_end(CModule* m) { - return m->EndNV() == x; - } + void plusplus() { ++x; } + CString get() { return x->first; } + bool is_end(CModule* m) { return m->EndNV() == x; } }; class CModulesIter { -public: - CModulesIter(CModules *pModules) { + public: + CModulesIter(CModules* pModules) { m_pModules = pModules; m_it = pModules->begin(); } - void plusplus() { - ++m_it; - } + void plusplus() { ++m_it; } - const CModule* get() const { - return *m_it; - } + const CModule* get() const { return *m_it; } - bool is_end() const { - return m_pModules->end() == m_it; - } + bool is_end() const { return m_pModules->end() == m_it; } - CModules *m_pModules; + CModules* m_pModules; CModules::const_iterator m_it; }; diff --git a/modules/modpython/ret.h b/modules/modpython/ret.h index 93e19b63..7a114758 100644 --- a/modules/modpython/ret.h +++ b/modules/modpython/ret.h @@ -17,21 +17,23 @@ #pragma once class CPyRetString { -public: + public: CString& s; CPyRetString(CString& S) : s(S) {} static PyObject* wrap(CString& S) { CPyRetString* x = new CPyRetString(S); - return SWIG_NewInstanceObj(x, SWIG_TypeQuery("CPyRetString*"), SWIG_POINTER_OWN); + return SWIG_NewInstanceObj(x, SWIG_TypeQuery("CPyRetString*"), + SWIG_POINTER_OWN); } }; class CPyRetBool { -public: + public: bool& b; CPyRetBool(bool& B) : b(B) {} static PyObject* wrap(bool& B) { CPyRetBool* x = new CPyRetBool(B); - return SWIG_NewInstanceObj(x, SWIG_TypeQuery("CPyRetBool*"), SWIG_POINTER_OWN); + return SWIG_NewInstanceObj(x, SWIG_TypeQuery("CPyRetBool*"), + SWIG_POINTER_OWN); } }; diff --git a/modules/modtcl.cpp b/modules/modtcl.cpp index 6ff4044a..72df6a32 100644 --- a/modules/modtcl.cpp +++ b/modules/modtcl.cpp @@ -25,44 +25,49 @@ using std::vector; using std::map; -#define STDVAR (ClientData cd, Tcl_Interp *irp, int argc, const char *argv[]) +#define STDVAR (ClientData cd, Tcl_Interp * irp, int argc, const char* argv[]) -#define BADARGS(nl, nh, example) do { \ - if ((argc < (nl)) || (argc > (nh))) { \ - Tcl_AppendResult(irp, "wrong # args: should be \"", \ - argv[0], (example), "\"", nullptr); \ - return TCL_ERROR; \ - } \ -} while (0) +#define BADARGS(nl, nh, example) \ + do { \ + if ((argc < (nl)) || (argc > (nh))) { \ + Tcl_AppendResult(irp, "wrong # args: should be \"", argv[0], \ + (example), "\"", nullptr); \ + return TCL_ERROR; \ + } \ + } while (0) class CModTcl; class CModTclTimer : public CTimer { -public: - - CModTclTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), m_pParent(nullptr) {} + public: + CModTclTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), + m_pParent(nullptr) {} virtual ~CModTclTimer() {} -protected: + + protected: void RunJob() override; CModTcl* m_pParent; }; class CModTclStartTimer : public CTimer { -public: - - CModTclStartTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), m_pParent(nullptr) {} + public: + CModTclStartTimer(CModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription), + m_pParent(nullptr) {} virtual ~CModTclStartTimer() {} -protected: + + protected: void RunJob() override; CModTcl* m_pParent; }; - class CModTcl : public CModule { -public: - MODCONSTRUCTOR(CModTcl) { - interp = nullptr; - } + public: + MODCONSTRUCTOR(CModTcl) { interp = nullptr; } virtual ~CModTcl() { if (interp) { @@ -78,7 +83,9 @@ public: } #endif - AddTimer(new CModTclStartTimer(this, 1, 1, "ModTclStarter", "Timer for modtcl to load the interpreter.")); + AddTimer( + new CModTclStartTimer(this, 1, 1, "ModTclStarter", + "Timer for modtcl to load the interpreter.")); return true; } @@ -87,30 +94,44 @@ public: interp = Tcl_CreateInterp(); Tcl_Init(interp); - Tcl_CreateCommand(interp, "Binds::ProcessPubm", tcl_Bind, this, nullptr); - Tcl_CreateCommand(interp, "Binds::ProcessMsgm", tcl_Bind, this, nullptr); - Tcl_CreateCommand(interp, "Binds::ProcessTime", tcl_Bind, this, nullptr); - Tcl_CreateCommand(interp, "Binds::ProcessEvnt", tcl_Bind, this, nullptr); - Tcl_CreateCommand(interp, "Binds::ProcessNick", tcl_Bind, this, nullptr); - Tcl_CreateCommand(interp, "Binds::ProcessKick", tcl_Bind, this, nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessPubm", tcl_Bind, this, + nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessMsgm", tcl_Bind, this, + nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessTime", tcl_Bind, this, + nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessEvnt", tcl_Bind, this, + nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessNick", tcl_Bind, this, + nullptr); + Tcl_CreateCommand(interp, "Binds::ProcessKick", tcl_Bind, this, + nullptr); Tcl_CreateCommand(interp, "PutIRC", tcl_PutIRC, this, nullptr); Tcl_CreateCommand(interp, "PutModule", tcl_PutModule, this, nullptr); Tcl_CreateCommand(interp, "PutStatus", tcl_PutStatus, this, nullptr); - Tcl_CreateCommand(interp, "PutStatusNotice", tcl_PutStatusNotice, this, nullptr); + Tcl_CreateCommand(interp, "PutStatusNotice", tcl_PutStatusNotice, this, + nullptr); Tcl_CreateCommand(interp, "PutUser", tcl_PutUser, this, nullptr); Tcl_CreateCommand(interp, "GetCurNick", tcl_GetCurNick, this, nullptr); - Tcl_CreateCommand(interp, "GetUsername", tcl_GetUsername, this, nullptr); - Tcl_CreateCommand(interp, "GetRealName", tcl_GetRealName, this, nullptr); + Tcl_CreateCommand(interp, "GetUsername", tcl_GetUsername, this, + nullptr); + Tcl_CreateCommand(interp, "GetRealName", tcl_GetRealName, this, + nullptr); Tcl_CreateCommand(interp, "GetVHost", tcl_GetBindHost, this, nullptr); - Tcl_CreateCommand(interp, "GetBindHost", tcl_GetBindHost, this, nullptr); + Tcl_CreateCommand(interp, "GetBindHost", tcl_GetBindHost, this, + nullptr); Tcl_CreateCommand(interp, "GetChans", tcl_GetChans, this, nullptr); - Tcl_CreateCommand(interp, "GetChannelUsers", tcl_GetChannelUsers, this, nullptr); - Tcl_CreateCommand(interp, "GetChannelModes", tcl_GetChannelModes, this, nullptr); + Tcl_CreateCommand(interp, "GetChannelUsers", tcl_GetChannelUsers, this, + nullptr); + Tcl_CreateCommand(interp, "GetChannelModes", tcl_GetChannelModes, this, + nullptr); Tcl_CreateCommand(interp, "GetServer", tcl_GetServer, this, nullptr); - Tcl_CreateCommand(interp, "GetServerOnline", tcl_GetServerOnline, this, nullptr); + Tcl_CreateCommand(interp, "GetServerOnline", tcl_GetServerOnline, this, + nullptr); Tcl_CreateCommand(interp, "GetModules", tcl_GetModules, this, nullptr); - Tcl_CreateCommand(interp, "GetClientCount", tcl_GetClientCount, this, nullptr); + Tcl_CreateCommand(interp, "GetClientCount", tcl_GetClientCount, this, + nullptr); Tcl_CreateCommand(interp, "exit", tcl_exit, this, nullptr); @@ -121,7 +142,9 @@ public: } } - AddTimer(new CModTclTimer(this, 1, 0, "ModTclUpdate", "Timer for modtcl to process pending events and idle callbacks.")); + AddTimer(new CModTclTimer( + this, 1, 0, "ModTclUpdate", + "Timer for modtcl to process pending events and idle callbacks.")); } void OnModCommand(const CString& sCommand) override { @@ -129,8 +152,7 @@ public: VCString vsResult; CString sCmd = sCommand; - if (sCmd.Token(0).CaseCmp(".tcl") == 0) - sCmd = sCmd.Token(1,true); + if (sCmd.Token(0).CaseCmp(".tcl") == 0) sCmd = sCmd.Token(1, true); if (sCmd.Left(1).CaseCmp(".") == 0) sCmd = "Binds::ProcessDcc - - {" + sCmd + "}"; @@ -147,49 +169,49 @@ public: } void TclUpdate() { - while (Tcl_DoOneEvent(TCL_DONT_WAIT)) {} - i = Tcl_Eval(interp,"Binds::ProcessTime"); + while (Tcl_DoOneEvent(TCL_DONT_WAIT)) { + } + i = Tcl_Eval(interp, "Binds::ProcessTime"); if (i != TCL_OK) { PutModule(Tcl_GetStringResult(interp)); } } CString TclEscape(CString sLine) { - sLine.Replace("\\","\\\\"); - sLine.Replace("{","\\{"); - sLine.Replace("}","\\}"); + sLine.Replace("\\", "\\\\"); + sLine.Replace("{", "\\{"); + sLine.Replace("}", "\\}"); return sLine; } void OnPreRehash() override { - if (interp) - Tcl_Eval(interp,"Binds::ProcessEvnt prerehash"); + if (interp) Tcl_Eval(interp, "Binds::ProcessEvnt prerehash"); } void OnPostRehash() override { if (interp) { - Tcl_Eval(interp,"rehash"); - Tcl_Eval(interp,"Binds::ProcessEvnt rehash"); + Tcl_Eval(interp, "rehash"); + Tcl_Eval(interp, "Binds::ProcessEvnt rehash"); } } void OnIRCConnected() override { - if (interp) - Tcl_Eval(interp, "Binds::ProcessEvnt init-server"); + if (interp) Tcl_Eval(interp, "Binds::ProcessEvnt init-server"); } void OnIRCDisconnected() override { - if (interp) - Tcl_Eval(interp, "Binds::ProcessEvnt disconnect-server"); + if (interp) Tcl_Eval(interp, "Binds::ProcessEvnt disconnect-server"); } EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override { CString sMes = TclEscape(sMessage); CString sNick = TclEscape(CString(Nick.GetNick())); - CString sHost = TclEscape(CString(Nick.GetIdent() + "@" + Nick.GetHost())); + CString sHost = + TclEscape(CString(Nick.GetIdent() + "@" + Nick.GetHost())); CString sChannel = TclEscape(CString(Channel.GetName())); - CString sCommand = "Binds::ProcessPubm {" + sNick + "} {" + sHost + "} - {" + sChannel + "} {" + sMes + "}"; + CString sCommand = "Binds::ProcessPubm {" + sNick + "} {" + sHost + + "} - {" + sChannel + "} {" + sMes + "}"; i = Tcl_Eval(interp, sCommand.c_str()); if (i != TCL_OK) { PutModule(Tcl_GetStringResult(interp)); @@ -200,9 +222,11 @@ public: EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override { CString sMes = TclEscape(sMessage); CString sNick = TclEscape(CString(Nick.GetNick())); - CString sHost = TclEscape(CString(Nick.GetIdent() + "@" + Nick.GetHost())); + CString sHost = + TclEscape(CString(Nick.GetIdent() + "@" + Nick.GetHost())); - CString sCommand = "Binds::ProcessMsgm {" + sNick + "} {" + sHost + "} - {" + sMes + "}"; + CString sCommand = "Binds::ProcessMsgm {" + sNick + "} {" + sHost + + "} - {" + sMes + "}"; i = Tcl_Eval(interp, sCommand.c_str()); if (i != TCL_OK) { PutModule(Tcl_GetStringResult(interp)); @@ -210,16 +234,21 @@ public: return CONTINUE; } - void OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) override { + void OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) override { CString sOldNick = TclEscape(CString(OldNick.GetNick())); CString sNewNickTmp = TclEscape(sNewNick); - CString sHost = TclEscape(CString(OldNick.GetIdent() + "@" + OldNick.GetHost())); + CString sHost = + TclEscape(CString(OldNick.GetIdent() + "@" + OldNick.GetHost())); CString sCommand; - // Nick change is triggered for each common chan so that binds can be chan specific + // Nick change is triggered for each common chan so that binds can be + // chan specific unsigned int nLength = vChans.size(); for (unsigned int n = 0; n < nLength; n++) { - sCommand = "Binds::ProcessNick {" + sOldNick + "} {" + sHost + "} - {" + vChans[n]->GetName() + "} {" + sNewNickTmp + "}"; + sCommand = "Binds::ProcessNick {" + sOldNick + "} {" + sHost + + "} - {" + vChans[n]->GetName() + "} {" + sNewNickTmp + + "}"; i = Tcl_Eval(interp, sCommand.c_str()); if (i != TCL_OK) { PutModule(Tcl_GetStringResult(interp)); @@ -227,28 +256,31 @@ public: } } - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override { + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override { CString sOpNick = TclEscape(CString(OpNick.GetNick())); CString sNick = TclEscape(sKickedNick); - CString sOpHost = TclEscape(CString(OpNick.GetIdent() + "@" + OpNick.GetHost())); + CString sOpHost = + TclEscape(CString(OpNick.GetIdent() + "@" + OpNick.GetHost())); - CString sCommand = "Binds::ProcessKick {" + sOpNick + "} {" + sOpHost + "} - {" + Channel.GetName() + "} {" + sNick + "} {" + sMessage + "}"; + CString sCommand = "Binds::ProcessKick {" + sOpNick + "} {" + sOpHost + + "} - {" + Channel.GetName() + "} {" + sNick + "} {" + + sMessage + "}"; i = Tcl_Eval(interp, sCommand.c_str()); if (i != TCL_OK) { PutModule(Tcl_GetStringResult(interp)); } } - -private: - Tcl_Interp *interp; + private: + Tcl_Interp* interp; int i; - static CString argvit(const char *argv[], unsigned int end, unsigned int begin, CString delim) { + static CString argvit(const char* argv[], unsigned int end, + unsigned int begin, CString delim) { CString sRet; unsigned int i; - if (begin < end) - sRet = CString(argv[begin]); + if (begin < end) sRet = CString(argv[begin]); for (i = begin + 1; i < end; i++) { sRet = sRet + delim + CString(argv[i]); @@ -258,36 +290,40 @@ private: } // Placeholder for binds incase binds.tcl isn't used - static int tcl_Bind STDVAR {return TCL_OK;} + static int tcl_Bind STDVAR { return TCL_OK; } static int tcl_GetCurNick STDVAR { - CModTcl *mod = static_cast(cd); - Tcl_SetResult(irp, (char *)mod->GetNetwork()->GetCurNick().c_str(), TCL_VOLATILE); + CModTcl* mod = static_cast(cd); + Tcl_SetResult(irp, (char*)mod->GetNetwork()->GetCurNick().c_str(), + TCL_VOLATILE); return TCL_OK; } static int tcl_GetUsername STDVAR { - CModTcl *mod = static_cast(cd); - Tcl_SetResult(irp, (char *)mod->GetUser()->GetUserName().c_str(), TCL_VOLATILE); + CModTcl* mod = static_cast(cd); + Tcl_SetResult(irp, (char*)mod->GetUser()->GetUserName().c_str(), + TCL_VOLATILE); return TCL_OK; } static int tcl_GetRealName STDVAR { - CModTcl *mod = static_cast(cd); - Tcl_SetResult(irp, (char *)mod->GetUser()->GetRealName().c_str(), TCL_VOLATILE); + CModTcl* mod = static_cast(cd); + Tcl_SetResult(irp, (char*)mod->GetUser()->GetRealName().c_str(), + TCL_VOLATILE); return TCL_OK; } static int tcl_GetBindHost STDVAR { - CModTcl *mod = static_cast(cd); - Tcl_SetResult(irp, (char *)mod->GetUser()->GetBindHost().c_str(), TCL_VOLATILE); + CModTcl* mod = static_cast(cd); + Tcl_SetResult(irp, (char*)mod->GetUser()->GetBindHost().c_str(), + TCL_VOLATILE); return TCL_OK; } static int tcl_GetChans STDVAR { - char *p; - const char *l[1]; - CModTcl *mod = static_cast(cd); + char* p; + const char* l[1]; + CModTcl* mod = static_cast(cd); BADARGS(1, 1, ""); @@ -297,21 +333,21 @@ private: l[0] = pChan->GetName().c_str(); p = Tcl_Merge(1, l); Tcl_AppendElement(irp, p); - Tcl_Free((char *)p); + Tcl_Free((char*)p); } return TCL_OK; } static int tcl_GetChannelUsers STDVAR { - char *p; - const char *l[4]; - CModTcl *mod = static_cast(cd); + char* p; + const char* l[4]; + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " channel"); CString sChannel = argvit(argv, argc, 1, " "); - CChan *pChannel = mod->GetNetwork()->FindChan(sChannel); + CChan* pChannel = mod->GetNetwork()->FindChan(sChannel); if (!pChannel) { CString sMsg = "invalid channel: " + sChannel; @@ -319,8 +355,9 @@ private: return TCL_ERROR; } - const map& msNicks = pChannel->GetNicks(); - for (map::const_iterator it = msNicks.begin(); it != msNicks.end(); ++it) { + const map& msNicks = pChannel->GetNicks(); + for (map::const_iterator it = msNicks.begin(); + it != msNicks.end(); ++it) { const CNick& Nick = it->second; l[0] = (Nick.GetNick()).c_str(); l[1] = (Nick.GetIdent()).c_str(); @@ -328,19 +365,19 @@ private: l[3] = (Nick.GetPermStr()).c_str(); p = Tcl_Merge(4, l); Tcl_AppendElement(irp, p); - Tcl_Free((char *)p); + Tcl_Free((char*)p); } return TCL_OK; } static int tcl_GetChannelModes STDVAR { - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " channel"); CString sChannel = argvit(argv, argc, 1, " "); - CChan *pChannel = mod->GetNetwork()->FindChan(sChannel); + CChan* pChannel = mod->GetNetwork()->FindChan(sChannel); CString sMsg; if (!pChannel) { @@ -355,7 +392,7 @@ private: } static int tcl_GetServer STDVAR { - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); CServer* pServer = mod->GetNetwork()->GetCurrentServer(); CString sMsg; if (pServer) @@ -365,19 +402,18 @@ private: } static int tcl_GetServerOnline STDVAR { - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); CIRCSock* pIRCSock = mod->GetNetwork()->GetIRCSock(); CString sMsg = "0"; - if (pIRCSock) - sMsg = CString(pIRCSock->GetStartTime()); + if (pIRCSock) sMsg = CString(pIRCSock->GetStartTime()); Tcl_SetResult(irp, (char*)sMsg.c_str(), TCL_VOLATILE); return TCL_OK; } static int tcl_GetModules STDVAR { - char *p; - const char *l[3]; - CModTcl *mod = static_cast(cd); + char* p; + const char* l[3]; + CModTcl* mod = static_cast(cd); BADARGS(1, 1, ""); @@ -387,32 +423,34 @@ private: for (unsigned int b = 0; b < GModules.size(); b++) { l[0] = GModules[b]->GetModName().c_str(); l[1] = GModules[b]->GetArgs().c_str(); - l[2] = "1"; // IsGlobal + l[2] = "1"; // IsGlobal p = Tcl_Merge(3, l); Tcl_AppendElement(irp, p); - Tcl_Free((char *)p); + Tcl_Free((char*)p); } for (unsigned int b = 0; b < Modules.size(); b++) { l[0] = Modules[b]->GetModName().c_str(); l[1] = Modules[b]->GetArgs().c_str(); - l[2] = "0"; // IsGlobal + l[2] = "0"; // IsGlobal p = Tcl_Merge(3, l); Tcl_AppendElement(irp, p); - Tcl_Free((char *)p); + Tcl_Free((char*)p); } return TCL_OK; } static int tcl_GetClientCount STDVAR { - CModTcl *mod = static_cast(cd); - Tcl_SetResult(irp, (char *)CString(mod->GetNetwork()->GetClients().size()).c_str(), TCL_VOLATILE); + CModTcl* mod = static_cast(cd); + Tcl_SetResult( + irp, (char*)CString(mod->GetNetwork()->GetClients().size()).c_str(), + TCL_VOLATILE); return TCL_OK; } static int tcl_PutIRC STDVAR { CString sMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " string"); sMsg = argvit(argv, argc, 1, " "); @@ -423,11 +461,11 @@ private: static int tcl_PutModule STDVAR { CString sMsg; VCString vsMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " string"); sMsg = argvit(argv, argc, 1, " "); - //mod->PutModule(sMsg); + // mod->PutModule(sMsg); sMsg.Split("\n", vsMsg); unsigned int a = 0; for (a = 0; a < vsMsg.size(); a++) @@ -437,7 +475,7 @@ private: static int tcl_PutStatus STDVAR { CString sMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " string"); sMsg = argvit(argv, argc, 1, " "); @@ -447,7 +485,7 @@ private: static int tcl_PutStatusNotice STDVAR { CString sMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " string"); sMsg = argvit(argv, argc, 1, " "); @@ -457,7 +495,7 @@ private: static int tcl_PutUser STDVAR { CString sMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(2, 999, " string"); sMsg = argvit(argv, argc, 1, " "); @@ -467,11 +505,11 @@ private: static int tcl_exit STDVAR { CString sMsg; - CModTcl *mod = static_cast(cd); + CModTcl* mod = static_cast(cd); BADARGS(1, 2, " ?reason?"); - if (! mod->GetUser()->IsAdmin()) { + if (!mod->GetUser()->IsAdmin()) { sMsg = "You need to be administrator to shutdown the bnc."; Tcl_SetResult(irp, (char*)sMsg.c_str(), TCL_VOLATILE); return TCL_ERROR; @@ -479,7 +517,8 @@ private: if (argc > 1) { sMsg = argvit(argv, argc, 1, " "); CZNC::Get().Broadcast(sMsg); - usleep(100000); // Sleep for 10ms to attempt to allow the previous Broadcast() to go through to all users + usleep(100000); // Sleep for 10ms to attempt to allow the previous + // Broadcast() to go through to all users } throw CException(CException::EX_Shutdown); @@ -489,18 +528,17 @@ private: }; void CModTclTimer::RunJob() { - CModTcl *p = (CModTcl *)GetModule(); - if (p) - p->TclUpdate(); + CModTcl* p = (CModTcl*)GetModule(); + if (p) p->TclUpdate(); } void CModTclStartTimer::RunJob() { - CModTcl *p = (CModTcl *)GetModule(); - if (p) - p->Start(); + CModTcl* p = (CModTcl*)GetModule(); + if (p) p->Start(); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("modtcl"); Info.SetHasArgs(true); Info.SetArgsHelpText("Absolute path to modtcl.tcl file"); diff --git a/modules/modules_online.cpp b/modules/modules_online.cpp index 645ed1c6..d9a6d421 100644 --- a/modules/modules_online.cpp +++ b/modules/modules_online.cpp @@ -19,26 +19,25 @@ #include class CFOModule : public CModule { -public: + public: MODCONSTRUCTOR(CFOModule) {} virtual ~CFOModule() {} bool IsOnlineModNick(const CString& sNick) { const CString& sPrefix = GetUser()->GetStatusPrefix(); - if (!sNick.StartsWith(sPrefix)) - return false; + if (!sNick.StartsWith(sPrefix)) return false; CString sModNick = sNick.substr(sPrefix.length()); if (sModNick.Equals("status") || - GetNetwork()->GetModules().FindModule(sModNick) || - GetUser()->GetModules().FindModule(sModNick) || - CZNC::Get().GetModules().FindModule(sModNick)) + GetNetwork()->GetModules().FindModule(sModNick) || + GetUser()->GetModules().FindModule(sModNick) || + CZNC::Get().GetModules().FindModule(sModNick)) return true; return false; } EModRet OnUserRaw(CString& sLine) override { - //Handle ISON + // Handle ISON if (sLine.Token(0).Equals("ison")) { VCString vsNicks; @@ -57,7 +56,8 @@ public: if (!GetNetwork()->GetIRCSock()) { // if we are not connected to any IRC server, send // an empty or module-nick filled response. - PutUser(":irc.znc.in 303 " + GetClient()->GetNick() + " :" + sBNCNicks); + PutUser(":irc.znc.in 303 " + GetClient()->GetNick() + " :" + + sBNCNicks); } else { // We let the server handle this request and then act on // the 303 response from the IRC server. @@ -65,15 +65,18 @@ public: } } - //Handle WHOIS + // Handle WHOIS if (sLine.Token(0).Equals("whois")) { CString sNick = sLine.Token(1); if (IsOnlineModNick(sNick)) { CIRCNetwork* pNetwork = GetNetwork(); - PutUser(":znc.in 311 " + pNetwork->GetCurNick() + " " + sNick + " znc znc.in * :" + sNick); - PutUser(":znc.in 312 " + pNetwork->GetCurNick() + " " + sNick + " *.znc.in :Bouncer"); - PutUser(":znc.in 318 " + pNetwork->GetCurNick() + " " + sNick + " :End of /WHOIS list."); + PutUser(":znc.in 311 " + pNetwork->GetCurNick() + " " + sNick + + " znc znc.in * :" + sNick); + PutUser(":znc.in 312 " + pNetwork->GetCurNick() + " " + sNick + + " *.znc.in :Bouncer"); + PutUser(":znc.in 318 " + pNetwork->GetCurNick() + " " + sNick + + " :End of /WHOIS list."); return HALT; } @@ -83,7 +86,7 @@ public: } EModRet OnRaw(CString& sLine) override { - //Handle 303 reply if m_Requests is not empty + // Handle 303 reply if m_Requests is not empty if (sLine.Token(1) == "303" && !m_ISONRequests.empty()) { VCString::iterator it = m_ISONRequests.begin(); @@ -94,7 +97,7 @@ public: sLine += " "; } - //add BNC nicks to the reply + // add BNC nicks to the reply sLine += *it; m_ISONRequests.erase(it); } @@ -102,11 +105,12 @@ public: return CONTINUE; } -private: + private: VCString m_ISONRequests; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("modules_online"); } diff --git a/modules/nickserv.cpp b/modules/nickserv.cpp index 5df0de9e..1c87d075 100644 --- a/modules/nickserv.cpp +++ b/modules/nickserv.cpp @@ -24,24 +24,21 @@ class CNickServ : public CModule { msValues["password"] = GetNV("Password"); PutIRC(CString::NamedFormat(GetNV(sCmd), msValues)); } -public: + + public: void SetCommand(const CString& sLine) { SetNV("Password", sLine.Token(1, true)); PutModule("Password set"); } - void ClearCommand(const CString& sLine) { - DelNV("Password"); - } + void ClearCommand(const CString& sLine) { DelNV("Password"); } void SetNSNameCommand(const CString& sLine) { SetNV("NickServName", sLine.Token(1, true)); PutModule("NickServ name set"); } - void ClearNSNameCommand(const CString& sLine) { - DelNV("NickServName"); - } + void ClearNSNameCommand(const CString& sLine) { DelNV("NickServName"); } void ViewCommandsCommand(const CString& sLine) { PutModule("IDENTIFY " + GetNV("IdentifyCmd")); @@ -61,18 +58,27 @@ public: MODCONSTRUCTOR(CNickServ) { AddHelpCommand(); - AddCommand("Set", static_cast(&CNickServ::SetCommand), - "password"); - AddCommand("Clear", static_cast(&CNickServ::ClearCommand), - "", "Clear your nickserv password"); - AddCommand("SetNSName", static_cast(&CNickServ::SetNSNameCommand), - "nickname", "Set NickServ name (Useful on networks like EpiKnet, where NickServ is named Themis)"); - AddCommand("ClearNSName", static_cast(&CNickServ::ClearNSNameCommand), - "", "Reset NickServ name to default (NickServ)"); - AddCommand("ViewCommands", static_cast(&CNickServ::ViewCommandsCommand), - "", "Show patterns for lines, which are being sent to NickServ"); - AddCommand("SetCommand", static_cast(&CNickServ::SetCommandCommand), - "cmd new-pattern", "Set pattern for commands"); + AddCommand("Set", + static_cast(&CNickServ::SetCommand), + "password"); + AddCommand("Clear", static_cast( + &CNickServ::ClearCommand), + "", "Clear your nickserv password"); + AddCommand("SetNSName", static_cast( + &CNickServ::SetNSNameCommand), + "nickname", + "Set NickServ name (Useful on networks like EpiKnet, where " + "NickServ is named Themis)"); + AddCommand("ClearNSName", static_cast( + &CNickServ::ClearNSNameCommand), + "", "Reset NickServ name to default (NickServ)"); + AddCommand("ViewCommands", static_cast( + &CNickServ::ViewCommandsCommand), + "", + "Show patterns for lines, which are being sent to NickServ"); + AddCommand("SetCommand", static_cast( + &CNickServ::SetCommandCommand), + "cmd new-pattern", "Set pattern for commands"); } virtual ~CNickServ() {} @@ -91,20 +97,25 @@ public: } void HandleMessage(CNick& Nick, const CString& sMessage) { - CString sNickServName = (!GetNV("NickServName").empty()) ? GetNV("NickServName") : "NickServ"; - if (!GetNV("Password").empty() - && Nick.NickEquals(sNickServName) - && (sMessage.find("msg") != CString::npos - || sMessage.find("authenticate") != CString::npos - || sMessage.find("choose a different nickname") != CString::npos - || sMessage.find("please choose a different nick") != CString::npos - || sMessage.find("If this is your nick, identify yourself with") != CString::npos - || sMessage.find("If this is your nick, type") != CString::npos - || sMessage.find("This is a registered nickname, please identify") != CString::npos - || sMessage.StripControls_n().find("type /NickServ IDENTIFY password") != CString::npos - || sMessage.StripControls_n().find("type /msg NickServ IDENTIFY password") != CString::npos) - && sMessage.AsUpper().find("IDENTIFY") != CString::npos - && sMessage.find("help") == CString::npos) { + CString sNickServName = (!GetNV("NickServName").empty()) + ? GetNV("NickServName") + : "NickServ"; + if (!GetNV("Password").empty() && Nick.NickEquals(sNickServName) && + (sMessage.find("msg") != CString::npos || + sMessage.find("authenticate") != CString::npos || + sMessage.find("choose a different nickname") != CString::npos || + sMessage.find("please choose a different nick") != CString::npos || + sMessage.find("If this is your nick, identify yourself with") != + CString::npos || + sMessage.find("If this is your nick, type") != CString::npos || + sMessage.find("This is a registered nickname, please identify") != + CString::npos || + sMessage.StripControls_n().find( + "type /NickServ IDENTIFY password") != CString::npos || + sMessage.StripControls_n().find( + "type /msg NickServ IDENTIFY password") != CString::npos) && + sMessage.AsUpper().find("IDENTIFY") != CString::npos && + sMessage.find("help") == CString::npos) { MCString msValues; msValues["password"] = GetNV("Password"); PutIRC(CString::NamedFormat(GetNV("IdentifyCmd"), msValues)); @@ -122,7 +133,8 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("nickserv"); Info.SetHasArgs(true); Info.SetArgsHelpText("Please enter your nickserv password."); diff --git a/modules/notes.cpp b/modules/notes.cpp index 0192e09a..8d4621e4 100644 --- a/modules/notes.cpp +++ b/modules/notes.cpp @@ -21,16 +21,16 @@ using std::stringstream; class CNotesMod : public CModule { bool m_bShowNotesOnLogin{}; - void ListCommand(const CString &sLine) { - ListNotes(); - } + void ListCommand(const CString& sLine) { ListNotes(); } - void AddNoteCommand(const CString &sLine) { + void AddNoteCommand(const CString& sLine) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); if (!GetNV(sKey).empty()) { - PutModule("That note already exists. Use MOD to overwrite."); + PutModule( + "That note already exists. Use MOD to " + "overwrite."); } else if (AddNote(sKey, sValue)) { PutModule("Added note [" + sKey + "]"); } else { @@ -38,7 +38,7 @@ class CNotesMod : public CModule { } } - void ModCommand(const CString &sLine) { + void ModCommand(const CString& sLine) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); @@ -49,7 +49,7 @@ class CNotesMod : public CModule { } } - void GetCommand(const CString &sLine) { + void GetCommand(const CString& sLine) { CString sNote = GetNV(sLine.Token(1, true)); if (sNote.empty()) { @@ -59,7 +59,7 @@ class CNotesMod : public CModule { } } - void DelCommand(const CString &sLine) { + void DelCommand(const CString& sLine) { CString sKey(sLine.Token(1)); if (DelNote(sKey)) { @@ -69,17 +69,22 @@ class CNotesMod : public CModule { } } -public: + public: MODCONSTRUCTOR(CNotesMod) { using std::placeholders::_1; AddHelpCommand(); - AddCommand("List", static_cast(&CNotesMod::ListCommand)); - AddCommand("Add", static_cast(&CNotesMod::AddNoteCommand), - " "); - AddCommand("Del", static_cast(&CNotesMod::DelCommand), - "", "Delete a note"); - AddCommand("Mod", " ", "Modify a note", std::bind(&CNotesMod::ModCommand, this, _1)); - AddCommand("Get", "", "", [this](const CString& sLine){ GetCommand(sLine); }); + AddCommand("List", static_cast( + &CNotesMod::ListCommand)); + AddCommand("Add", static_cast( + &CNotesMod::AddNoteCommand), + " "); + AddCommand("Del", + static_cast(&CNotesMod::DelCommand), + "", "Delete a note"); + AddCommand("Mod", " ", "Modify a note", + std::bind(&CNotesMod::ModCommand, this, _1)); + AddCommand("Get", "", "", + [this](const CString& sLine) { GetCommand(sLine); }); } virtual ~CNotesMod() {} @@ -127,7 +132,9 @@ public: if (!sKey.empty()) { if (!bOverwrite && FindNV(sKey) != EndNV()) { - PutModNotice("That note already exists. Use /#+ to overwrite."); + PutModNotice( + "That note already exists. Use /#+ to " + "overwrite."); } else if (AddNote(sKey, sValue)) { if (!bOverwrite) { PutModNotice("Added note [" + sKey + "]"); @@ -142,9 +149,7 @@ public: return HALT; } - bool DelNote(const CString& sKey) { - return DelNV(sKey); - } + bool DelNote(const CString& sKey) { return DelNV(sKey); } bool AddNote(const CString& sKey, const CString& sNote) { if (sKey.empty()) { @@ -188,7 +193,8 @@ public: } } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { CTemplate& Row = Tmpl.AddRow("NotesLoop"); @@ -212,10 +218,13 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("notes"); Info.SetHasArgs(true); - Info.SetArgsHelpText("This user module takes up to one arguments. It can be -disableNotesOnLogin not to show notes upon client login"); + Info.SetArgsHelpText( + "This user module takes up to one arguments. It can be " + "-disableNotesOnLogin not to show notes upon client login"); } USERMODULEDEFS(CNotesMod, "Keep and replay notes") diff --git a/modules/notify_connect.cpp b/modules/notify_connect.cpp index c080e3ee..437d22bf 100644 --- a/modules/notify_connect.cpp +++ b/modules/notify_connect.cpp @@ -18,23 +18,19 @@ #include class CNotifyConnectMod : public CModule { -public: + public: MODCONSTRUCTOR(CNotifyConnectMod) {} - void OnClientLogin() override { - NotifyAdmins("attached"); - } + void OnClientLogin() override { NotifyAdmins("attached"); } - void OnClientDisconnect() override { - NotifyAdmins("detached"); - } + void OnClientDisconnect() override { NotifyAdmins("detached"); } -private: - void SendAdmins(const CString &msg) { + private: + void SendAdmins(const CString& msg) { CZNC::Get().Broadcast(msg, true, nullptr, GetClient()); } - void NotifyAdmins(const CString &event) { + void NotifyAdmins(const CString& event) { CString client = GetUser()->GetUserName(); if (GetClient()->GetIdentifier() != "") { client += "@"; @@ -46,8 +42,11 @@ private: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("notify_connect"); } -GLOBALMODULEDEFS(CNotifyConnectMod, "Notifies all admin users when a client connects or disconnects.") +GLOBALMODULEDEFS( + CNotifyConnectMod, + "Notifies all admin users when a client connects or disconnects.") diff --git a/modules/partyline.cpp b/modules/partyline.cpp index 08ec8012..1d57add0 100644 --- a/modules/partyline.cpp +++ b/modules/partyline.cpp @@ -22,15 +22,15 @@ using std::vector; using std::map; // If you change these and it breaks, you get to keep the pieces -#define CHAN_PREFIX_1 "~" -#define CHAN_PREFIX_1C '~' -#define CHAN_PREFIX CHAN_PREFIX_1 "#" +#define CHAN_PREFIX_1 "~" +#define CHAN_PREFIX_1C '~' +#define CHAN_PREFIX CHAN_PREFIX_1 "#" -#define NICK_PREFIX CString("?") -#define NICK_PREFIX_C '?' +#define NICK_PREFIX CString("?") +#define NICK_PREFIX_C '?' class CPartylineChannel { -public: + public: CPartylineChannel(const CString& sName) { m_sName = sName.AsLower(); } ~CPartylineChannel() {} @@ -43,16 +43,18 @@ public: void AddNick(const CString& s) { m_ssNicks.insert(s); } void DelNick(const CString& s) { m_ssNicks.erase(s); } - bool IsInChannel(const CString& s) { return m_ssNicks.find(s) != m_ssNicks.end(); } + bool IsInChannel(const CString& s) { + return m_ssNicks.find(s) != m_ssNicks.end(); + } -protected: - CString m_sTopic; - CString m_sName; + protected: + CString m_sTopic; + CString m_sName; set m_ssNicks; }; class CPartylineMod : public CModule { -public: + public: void ListChannelsCommand(const CString& sLine) { if (m_ssChannels.empty()) { PutModule("There are no open channels."); @@ -64,7 +66,8 @@ public: Table.AddColumn("Channel"); Table.AddColumn("Users"); - for (set::const_iterator a = m_ssChannels.begin(); a != m_ssChannels.end(); ++a) { + for (set::const_iterator a = m_ssChannels.begin(); + a != m_ssChannels.end(); ++a) { Table.AddRow(); Table.SetCell("Channel", (*a)->GetName()); @@ -76,22 +79,29 @@ public: MODCONSTRUCTOR(CPartylineMod) { AddHelpCommand(); - AddCommand("List", static_cast(&CPartylineMod::ListChannelsCommand), - "", "List all open channels"); + AddCommand("List", static_cast( + &CPartylineMod::ListChannelsCommand), + "", "List all open channels"); } virtual ~CPartylineMod() { // Kick all clients who are in partyline channels - for (set::iterator it = m_ssChannels.begin(); it != m_ssChannels.end(); ++it) { + for (set::iterator it = m_ssChannels.begin(); + it != m_ssChannels.end(); ++it) { set ssNicks = (*it)->GetNicks(); - for (set::const_iterator it2 = ssNicks.begin(); it2 != ssNicks.end(); ++it2) { + for (set::const_iterator it2 = ssNicks.begin(); + it2 != ssNicks.end(); ++it2) { CUser* pUser = CZNC::Get().FindUser(*it2); vector vClients = pUser->GetAllClients(); - for (vector::const_iterator it3 = vClients.begin(); it3 != vClients.end(); ++it3) { + for (vector::const_iterator it3 = vClients.begin(); + it3 != vClients.end(); ++it3) { CClient* pClient = *it3; - pClient->PutClient( ":*" + GetModName() + "!znc@znc.in KICK " + (*it)->GetName() + " " + pClient->GetNick() + " :" + GetModName() + " unloaded"); + pClient->PutClient(":*" + GetModName() + + "!znc@znc.in KICK " + (*it)->GetName() + + " " + pClient->GetNick() + " :" + + GetModName() + " unloaded"); } } } @@ -112,12 +122,18 @@ public: bool OnLoad(const CString& sArgs, CString& sMessage) override { const map& msUsers = CZNC::Get().GetUserMap(); - for (map::const_iterator it = msUsers.begin(); it != msUsers.end(); ++it) { + for (map::const_iterator it = msUsers.begin(); + it != msUsers.end(); ++it) { CUser* pUser = it->second; for (CClient* pClient : pUser->GetAllClients()) { CIRCNetwork* pNetwork = pClient->GetNetwork(); - if (!pNetwork || !pNetwork->IsIRCConnected() || !pNetwork->GetChanPrefixes().Contains(CHAN_PREFIX_1)) { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 005 " + pClient->GetNick() + " CHANTYPES=" + (pNetwork ? pNetwork->GetChanPrefixes() : "") + CHAN_PREFIX_1 " :are supported by this server."); + if (!pNetwork || !pNetwork->IsIRCConnected() || + !pNetwork->GetChanPrefixes().Contains(CHAN_PREFIX_1)) { + pClient->PutClient( + ":" + GetIRCServer(pNetwork) + " 005 " + + pClient->GetNick() + " CHANTYPES=" + + (pNetwork ? pNetwork->GetChanPrefixes() : "") + + CHAN_PREFIX_1 " :are supported by this server."); } } } @@ -157,7 +173,9 @@ public: if (sAction == "topic") { pChannel = FindChannel(sKey); if (pChannel && !(it->second).empty()) { - PutChan(pChannel->GetNicks(), ":irc.znc.in TOPIC " + pChannel->GetName() + " :" + it->second); + PutChan(pChannel->GetNicks(), ":irc.znc.in TOPIC " + + pChannel->GetName() + + " :" + it->second); pChannel->SetTopic(it->second); } } @@ -175,8 +193,9 @@ public: EModRet OnDeleteUser(CUser& User) override { // Loop through each chan - for (set::iterator it = m_ssChannels.begin(); it != m_ssChannels.end();) { - CPartylineChannel *pChan = *it; + for (set::iterator it = m_ssChannels.begin(); + it != m_ssChannels.end();) { + CPartylineChannel* pChan = *it; // RemoveUser() might delete channels, so make sure our // iterator doesn't break. ++it; @@ -212,16 +231,18 @@ public: CClient* pClient = GetClient(); CIRCNetwork* pNetwork = GetNetwork(); if (!pNetwork || !pNetwork->IsIRCConnected()) { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 005 " + pClient->GetNick() + " CHANTYPES=" + CHAN_PREFIX_1 " :are supported by this server."); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 005 " + + pClient->GetNick() + " CHANTYPES=" + + CHAN_PREFIX_1 " :are supported by this server."); } // Make sure this user is in the default channels - for (set::iterator a = m_ssDefaultChans.begin(); a != m_ssDefaultChans.end(); ++a) { + for (set::iterator a = m_ssDefaultChans.begin(); + a != m_ssDefaultChans.end(); ++a) { CPartylineChannel* pChannel = GetChannel(*a); const CString& sNick = pUser->GetUserName(); - if (pChannel->IsInChannel(sNick)) - continue; + if (pChannel->IsInChannel(sNick)) continue; CString sHost = pUser->GetBindHost(); const set& ssNicks = pChannel->GetNicks(); @@ -229,25 +250,36 @@ public: if (sHost.empty()) { sHost = "znc.in"; } - PutChan(ssNicks, ":" + NICK_PREFIX + sNick + "!" + pUser->GetIdent() + "@" + sHost + " JOIN " + *a, false); + PutChan(ssNicks, + ":" + NICK_PREFIX + sNick + "!" + pUser->GetIdent() + "@" + + sHost + " JOIN " + *a, + false); pChannel->AddNick(sNick); } CString sNickMask = pClient->GetNickMask(); - for (set::iterator it = m_ssChannels.begin(); it != m_ssChannels.end(); ++it) { + for (set::iterator it = m_ssChannels.begin(); + it != m_ssChannels.end(); ++it) { const set& ssNicks = (*it)->GetNicks(); if ((*it)->IsInChannel(pUser->GetUserName())) { - - pClient->PutClient(":" + sNickMask + " JOIN " + (*it)->GetName()); + pClient->PutClient(":" + sNickMask + " JOIN " + + (*it)->GetName()); if (!(*it)->GetTopic().empty()) { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 332 " + pClient->GetNickMask() + " " + (*it)->GetName() + " :" + (*it)->GetTopic()); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 332 " + + pClient->GetNickMask() + " " + + (*it)->GetName() + " :" + + (*it)->GetTopic()); } SendNickList(pUser, pNetwork, ssNicks, (*it)->GetName()); - PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + (*it)->GetName() + " +" + CString(pUser->IsAdmin() ? "o" : "v") + " " + NICK_PREFIX + pUser->GetUserName(), false); + PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + + (*it)->GetName() + " +" + + CString(pUser->IsAdmin() ? "o" : "v") + + " " + NICK_PREFIX + pUser->GetUserName(), + false); } } } @@ -255,11 +287,17 @@ public: void OnClientDisconnect() override { CUser* pUser = GetUser(); if (!pUser->IsUserAttached() && !pUser->IsBeingDeleted()) { - for (set::iterator it = m_ssChannels.begin(); it != m_ssChannels.end(); ++it) { + for (set::iterator it = m_ssChannels.begin(); + it != m_ssChannels.end(); ++it) { const set& ssNicks = (*it)->GetNicks(); if (ssNicks.find(pUser->GetUserName()) != ssNicks.end()) { - PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + (*it)->GetName() + " -ov " + NICK_PREFIX + pUser->GetUserName() + " " + NICK_PREFIX + pUser->GetUserName(), false); + PutChan(ssNicks, + ":*" + GetModName() + "!znc@znc.in MODE " + + (*it)->GetName() + " -ov " + NICK_PREFIX + + pUser->GetUserName() + " " + NICK_PREFIX + + pUser->GetUserName(), + false); } } } @@ -284,23 +322,30 @@ public: const set& ssNicks = pChannel->GetNicks(); if (!sTopic.empty()) { if (pUser->IsAdmin()) { - PutChan(ssNicks, ":" + pClient->GetNickMask() + " TOPIC " + sChannel + " :" + sTopic); + PutChan(ssNicks, ":" + pClient->GetNickMask() + + " TOPIC " + sChannel + " :" + + sTopic); pChannel->SetTopic(sTopic); SaveTopic(pChannel); } else { - pUser->PutUser(":irc.znc.in 482 " + pClient->GetNick() + " " + sChannel + " :You're not channel operator"); + pUser->PutUser(":irc.znc.in 482 " + pClient->GetNick() + + " " + sChannel + + " :You're not channel operator"); } } else { sTopic = pChannel->GetTopic(); if (sTopic.empty()) { - pUser->PutUser(":irc.znc.in 331 " + pClient->GetNick() + " " + sChannel + " :No topic is set."); + pUser->PutUser(":irc.znc.in 331 " + pClient->GetNick() + + " " + sChannel + " :No topic is set."); } else { - pUser->PutUser(":irc.znc.in 332 " + pClient->GetNick() + " " + sChannel + " :" + sTopic); + pUser->PutUser(":irc.znc.in 332 " + pClient->GetNick() + + " " + sChannel + " :" + sTopic); } } } else { - pUser->PutUser(":irc.znc.in 442 " + pClient->GetNick() + " " + sChannel + " :You're not on that channel"); + pUser->PutUser(":irc.znc.in 442 " + pClient->GetNick() + " " + + sChannel + " :You're not on that channel"); } return HALT; } @@ -314,7 +359,9 @@ public: } if (sChannel.Left(2) != CHAN_PREFIX) { - GetClient()->PutClient(":" + GetIRCServer(GetNetwork()) + " 401 " + GetClient()->GetNick() + " " + sChannel + " :No such channel"); + GetClient()->PutClient(":" + GetIRCServer(GetNetwork()) + " 401 " + + GetClient()->GetNick() + " " + sChannel + + " :No such channel"); return HALT; } @@ -326,12 +373,13 @@ public: } void PartUser(CUser* pUser, CPartylineChannel* pChannel, - const CString& sMessage = "") { + const CString& sMessage = "") { RemoveUser(pUser, pChannel, "PART", sMessage); } - void RemoveUser(CUser* pUser, CPartylineChannel* pChannel, const CString& sCommand, - const CString& sMessage = "", bool bNickAsTarget = false) { + void RemoveUser(CUser* pUser, CPartylineChannel* pChannel, + const CString& sCommand, const CString& sMessage = "", + bool bNickAsTarget = false) { if (!pChannel || !pChannel->IsInChannel(pUser->GetUserName())) { return; } @@ -340,8 +388,7 @@ public: CString sCmd = " " + sCommand + " "; CString sMsg = sMessage; - if (!sMsg.empty()) - sMsg = " :" + sMsg; + if (!sMsg.empty()) sMsg = " :" + sMsg; pChannel->DelNick(pUser->GetUserName()); @@ -353,27 +400,38 @@ public: } if (bNickAsTarget) { - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pClient = *it; - pClient->PutClient(":" + pClient->GetNickMask() + sCmd + pChannel->GetName() + " " + pClient->GetNick() + sMsg); + pClient->PutClient(":" + pClient->GetNickMask() + sCmd + + pChannel->GetName() + " " + + pClient->GetNick() + sMsg); } - PutChan(ssNicks, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + pUser->GetIdent() + "@" + sHost - + sCmd + pChannel->GetName() + " " + NICK_PREFIX + pUser->GetUserName() + sMsg, - false, true, pUser); + PutChan(ssNicks, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + + pUser->GetIdent() + "@" + sHost + sCmd + + pChannel->GetName() + " " + NICK_PREFIX + + pUser->GetUserName() + sMsg, + false, true, pUser); } else { - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pClient = *it; - pClient->PutClient(":" + pClient->GetNickMask() + sCmd + pChannel->GetName() + sMsg); + pClient->PutClient(":" + pClient->GetNickMask() + sCmd + + pChannel->GetName() + sMsg); } - PutChan(ssNicks, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + pUser->GetIdent() + "@" + sHost - + sCmd + pChannel->GetName() + sMsg, false, true, pUser); + PutChan(ssNicks, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + + pUser->GetIdent() + "@" + sHost + sCmd + + pChannel->GetName() + sMsg, + false, true, pUser); } - if (!pUser->IsBeingDeleted() && m_ssDefaultChans.find(pChannel->GetName()) != m_ssDefaultChans.end()) { + if (!pUser->IsBeingDeleted() && + m_ssDefaultChans.find(pChannel->GetName()) != + m_ssDefaultChans.end()) { JoinUser(pUser, pChannel); } @@ -389,7 +447,9 @@ public: } if (sChannel.Left(2) != CHAN_PREFIX) { - GetClient()->PutClient(":" + GetIRCServer(GetNetwork()) + " 403 " + GetClient()->GetNick() + " " + sChannel + " :Channels look like " CHAN_PREFIX "znc"); + GetClient()->PutClient(":" + GetIRCServer(GetNetwork()) + " 403 " + + GetClient()->GetNick() + " " + sChannel + + " :Channels look like " CHAN_PREFIX "znc"); return HALT; } @@ -415,33 +475,50 @@ public: sHost = "znc.in"; } - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pClient = *it; - pClient->PutClient(":" + pClient->GetNickMask() + " JOIN " + pChannel->GetName()); + pClient->PutClient(":" + pClient->GetNickMask() + " JOIN " + + pChannel->GetName()); } - PutChan(ssNicks, ":" + NICK_PREFIX + sNick + "!" + pUser->GetIdent() + "@" + sHost + " JOIN " + pChannel->GetName(), false, true, pUser); + PutChan(ssNicks, + ":" + NICK_PREFIX + sNick + "!" + pUser->GetIdent() + "@" + + sHost + " JOIN " + pChannel->GetName(), + false, true, pUser); if (!pChannel->GetTopic().empty()) { - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pClient = *it; - pClient->PutClient(":" + GetIRCServer(pClient->GetNetwork()) + " 332 " + pClient->GetNickMask() + " " + pChannel->GetName() + " :" + pChannel->GetTopic()); + pClient->PutClient( + ":" + GetIRCServer(pClient->GetNetwork()) + " 332 " + + pClient->GetNickMask() + " " + pChannel->GetName() + + " :" + pChannel->GetTopic()); } } SendNickList(pUser, nullptr, ssNicks, pChannel->GetName()); - /* Tell the other clients we have op or voice, the current user's clients already know from NAMES list */ + /* Tell the other clients we have op or voice, the current user's + * clients already know from NAMES list */ if (pUser->IsAdmin()) { - PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + pChannel->GetName() + " +o " + NICK_PREFIX + pUser->GetUserName(), false, false, pUser); + PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + + pChannel->GetName() + " +o " + + NICK_PREFIX + pUser->GetUserName(), + false, false, pUser); } - PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + pChannel->GetName() + " +v " + NICK_PREFIX + pUser->GetUserName(), false, false, pUser); + PutChan(ssNicks, ":*" + GetModName() + "!znc@znc.in MODE " + + pChannel->GetName() + " +v " + NICK_PREFIX + + pUser->GetUserName(), + false, false, pUser); } } - EModRet HandleMessage(const CString& sCmd, const CString& sTarget, const CString& sMessage) { + EModRet HandleMessage(const CString& sCmd, const CString& sTarget, + const CString& sMessage) { if (sTarget.empty()) { return CONTINUE; } @@ -463,11 +540,16 @@ public: if (cPrefix == CHAN_PREFIX_1C) { if (FindChannel(sTarget) == nullptr) { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + pClient->GetNick() + " " + sTarget + " :No such channel"); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + + pClient->GetNick() + " " + sTarget + + " :No such channel"); return HALT; } - PutChan(sTarget, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + pUser->GetIdent() + "@" + sHost + " " + sCmd + " " + sTarget + " :" + sMessage, true, false); + PutChan(sTarget, ":" + NICK_PREFIX + pUser->GetUserName() + "!" + + pUser->GetIdent() + "@" + sHost + " " + sCmd + + " " + sTarget + " :" + sMessage, + true, false); } else { CString sNick = sTarget.LeftChomp_n(1); CUser* pTargetUser = CZNC::Get().FindUser(sNick); @@ -476,17 +558,25 @@ public: vector vClients = pTargetUser->GetAllClients(); if (vClients.empty()) { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + pClient->GetNick() + " " + sTarget + " :User is not attached: " + sNick + ""); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + + pClient->GetNick() + " " + sTarget + + " :User is not attached: " + sNick + ""); return HALT; } - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pTarget = *it; - pTarget->PutClient(":" + NICK_PREFIX + pUser->GetUserName() + "!" + pUser->GetIdent() + "@" + sHost + " " + sCmd + " " + pTarget->GetNick() + " :" + sMessage); + pTarget->PutClient( + ":" + NICK_PREFIX + pUser->GetUserName() + "!" + + pUser->GetIdent() + "@" + sHost + " " + sCmd + " " + + pTarget->GetNick() + " :" + sMessage); } } else { - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + pClient->GetNick() + " " + sTarget + " :No such znc user: " + sNick + ""); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 401 " + + pClient->GetNick() + " " + sTarget + + " :No such znc user: " + sNick + ""); } } @@ -509,41 +599,46 @@ public: return HandleMessage("NOTICE", sTarget, "\001" + sMessage + "\001"); } - const CString GetIRCServer(CIRCNetwork *pNetwork) { + const CString GetIRCServer(CIRCNetwork* pNetwork) { if (!pNetwork) { return "irc.znc.in"; } const CString& sServer = pNetwork->GetIRCServer(); - if (!sServer.empty()) - return sServer; + if (!sServer.empty()) return sServer; return "irc.znc.in"; } - bool PutChan(const CString& sChan, const CString& sLine, bool bIncludeCurUser = true, bool bIncludeClient = true, CUser* pUser = nullptr, CClient* pClient = nullptr) { + bool PutChan(const CString& sChan, const CString& sLine, + bool bIncludeCurUser = true, bool bIncludeClient = true, + CUser* pUser = nullptr, CClient* pClient = nullptr) { CPartylineChannel* pChannel = FindChannel(sChan); if (pChannel != nullptr) { - PutChan(pChannel->GetNicks(), sLine, bIncludeCurUser, bIncludeClient, pUser, pClient); + PutChan(pChannel->GetNicks(), sLine, bIncludeCurUser, + bIncludeClient, pUser, pClient); return true; } return false; } - void PutChan(const set& ssNicks, const CString& sLine, bool bIncludeCurUser = true, bool bIncludeClient = true, CUser* pUser = nullptr, CClient* pClient = nullptr) { + void PutChan(const set& ssNicks, const CString& sLine, + bool bIncludeCurUser = true, bool bIncludeClient = true, + CUser* pUser = nullptr, CClient* pClient = nullptr) { const map& msUsers = CZNC::Get().GetUserMap(); - if (!pUser) - pUser = GetUser(); - if (!pClient) - pClient = GetClient(); + if (!pUser) pUser = GetUser(); + if (!pClient) pClient = GetClient(); - for (map::const_iterator it = msUsers.begin(); it != msUsers.end(); ++it) { + for (map::const_iterator it = msUsers.begin(); + it != msUsers.end(); ++it) { if (ssNicks.find(it->first) != ssNicks.end()) { if (it->second == pUser) { if (bIncludeCurUser) { - it->second->PutAllUser(sLine, nullptr, (bIncludeClient ? nullptr : pClient)); + it->second->PutAllUser( + sLine, nullptr, + (bIncludeClient ? nullptr : pClient)); } } else { it->second->PutAllUser(sLine); @@ -552,7 +647,8 @@ public: } } - void PutUserIRCNick(CUser* pUser, const CString& sPre, const CString& sPost) { + void PutUserIRCNick(CUser* pUser, const CString& sPre, + const CString& sPost) { const vector& vClients = pUser->GetAllClients(); vector::const_iterator it; for (it = vClients.begin(); it != vClients.end(); ++it) { @@ -560,10 +656,12 @@ public: } } - void SendNickList(CUser* pUser, CIRCNetwork* pNetwork, const set& ssNicks, const CString& sChan) { + void SendNickList(CUser* pUser, CIRCNetwork* pNetwork, + const set& ssNicks, const CString& sChan) { CString sNickList; - for (set::const_iterator it = ssNicks.begin(); it != ssNicks.end(); ++it) { + for (set::const_iterator it = ssNicks.begin(); + it != ssNicks.end(); ++it) { CUser* pChanUser = CZNC::Get().FindUser(*it); if (pChanUser == pUser) { @@ -577,30 +675,37 @@ public: sNickList += NICK_PREFIX + (*it) + " "; if (sNickList.size() >= 500) { - PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 353 ", " @ " + sChan + " :" + sNickList); + PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 353 ", + " @ " + sChan + " :" + sNickList); sNickList.clear(); } } if (sNickList.size()) { - PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 353 ", " @ " + sChan + " :" + sNickList); + PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 353 ", + " @ " + sChan + " :" + sNickList); } vector vClients = pUser->GetAllClients(); - for (vector::const_iterator it = vClients.begin(); it != vClients.end(); ++it) { + for (vector::const_iterator it = vClients.begin(); + it != vClients.end(); ++it) { CClient* pClient = *it; - pClient->PutClient(":" + GetIRCServer(pNetwork) + " 353 " + pClient->GetNick() + " @ " + sChan + " :" + ((pUser->IsAdmin()) ? "@" : "+") + pClient->GetNick()); + pClient->PutClient(":" + GetIRCServer(pNetwork) + " 353 " + + pClient->GetNick() + " @ " + sChan + " :" + + ((pUser->IsAdmin()) ? "@" : "+") + + pClient->GetNick()); } - PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 366 ", " " + sChan + " :End of /NAMES list."); + PutUserIRCNick(pUser, ":" + GetIRCServer(pNetwork) + " 366 ", + " " + sChan + " :End of /NAMES list."); } CPartylineChannel* FindChannel(const CString& sChan) { CString sChannel = sChan.AsLower(); - for (set::iterator it = m_ssChannels.begin(); it != m_ssChannels.end(); ++it) { - if ((*it)->GetName().AsLower() == sChannel) - return *it; + for (set::iterator it = m_ssChannels.begin(); + it != m_ssChannels.end(); ++it) { + if ((*it)->GetName().AsLower() == sChannel) return *it; } return nullptr; @@ -617,16 +722,20 @@ public: return pChannel; } -private: + private: set m_ssChannels; - set m_spInjectedPrefixes; - set m_ssDefaultChans; + set m_spInjectedPrefixes; + set m_ssDefaultChans; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("partyline"); Info.SetHasArgs(true); - Info.SetArgsHelpText("You may enter a list of channels the user joins, when entering the internal partyline."); + Info.SetArgsHelpText( + "You may enter a list of channels the user joins, when entering the " + "internal partyline."); } -GLOBALMODULEDEFS(CPartylineMod, "Internal channels and queries for users connected to znc") +GLOBALMODULEDEFS(CPartylineMod, + "Internal channels and queries for users connected to znc") diff --git a/modules/perform.cpp b/modules/perform.cpp index bd66fccb..b938db47 100644 --- a/modules/perform.cpp +++ b/modules/perform.cpp @@ -77,26 +77,34 @@ class CPerform : public CModule { u_int iNumA = sCommand.Token(1).ToUInt(); u_int iNumB = sCommand.Token(2).ToUInt(); - if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) { + if (iNumA > m_vPerform.size() || iNumA <= 0 || + iNumB > m_vPerform.size() || iNumB <= 0) { PutModule("Illegal # Requested"); } else { - std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1)); + std::iter_swap(m_vPerform.begin() + (iNumA - 1), + m_vPerform.begin() + (iNumB - 1)); PutModule("Commands Swapped."); Save(); } } -public: + public: MODCONSTRUCTOR(CPerform) { AddHelpCommand(); - AddCommand("Add", static_cast(&CPerform::Add), - "", "Adds perform command to be sent to the server on connect"); - AddCommand("Del", static_cast(&CPerform::Del), - "", "Delete a perform command"); - AddCommand("List", static_cast(&CPerform::List),"", "List the perform commands"); - AddCommand("Execute", static_cast(&CPerform::Execute),"", "Send the perform commands to the server now"); - AddCommand("Swap", static_cast(&CPerform::Swap), - " ", "Swap two perform commands"); + AddCommand("Add", static_cast(&CPerform::Add), + "", + "Adds perform command to be sent to the server on connect"); + AddCommand("Del", static_cast(&CPerform::Del), + "", "Delete a perform command"); + AddCommand("List", + static_cast(&CPerform::List), "", + "List the perform commands"); + AddCommand("Execute", + static_cast(&CPerform::Execute), "", + "Send the perform commands to the server now"); + AddCommand("Swap", + static_cast(&CPerform::Swap), + " ", "Swap two perform commands"); } virtual ~CPerform() {} @@ -104,18 +112,17 @@ public: CString ParsePerform(const CString& sArg) const { CString sPerf = sArg; - if (sPerf.Left(1) == "/") - sPerf.LeftChomp(); + if (sPerf.Left(1) == "/") sPerf.LeftChomp(); if (sPerf.Token(0).Equals("MSG")) { sPerf = "PRIVMSG " + sPerf.Token(1, true); } if ((sPerf.Token(0).Equals("PRIVMSG") || - sPerf.Token(0).Equals("NOTICE")) && - sPerf.Token(2).Left(1) != ":") { - sPerf = sPerf.Token(0) + " " + sPerf.Token(1) - + " :" + sPerf.Token(2, true); + sPerf.Token(0).Equals("NOTICE")) && + sPerf.Token(2).Left(1) != ":") { + sPerf = sPerf.Token(0) + " " + sPerf.Token(1) + " :" + + sPerf.Token(2, true); } return sPerf; @@ -135,7 +142,8 @@ public: CString GetWebMenuTitle() override { return "Perform"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName != "index") { // only accept requests to index return false; @@ -160,7 +168,7 @@ public: return true; } -private: + private: void Save() { CString sBuffer = ""; @@ -173,9 +181,12 @@ private: VCString m_vPerform; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("perform"); } -NETWORKMODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.") +NETWORKMODULEDEFS( + CPerform, + "Keeps a list of commands to be executed when ZNC connects to IRC.") diff --git a/modules/q.cpp b/modules/q.cpp index 32a4091d..fc690a85 100644 --- a/modules/q.cpp +++ b/modules/q.cpp @@ -22,11 +22,11 @@ using std::set; #ifndef Q_DEBUG_COMMUNICATION - #define Q_DEBUG_COMMUNICATION 0 +#define Q_DEBUG_COMMUNICATION 0 #endif class CQModule : public CModule { -public: + public: MODCONSTRUCTOR(CQModule) {} virtual ~CQModule() {} @@ -40,33 +40,42 @@ public: } CString sTmp; - m_bUseCloakedHost = (sTmp = GetNV("UseCloakedHost")).empty() ? true : sTmp.ToBool(); - m_bUseChallenge = (sTmp = GetNV("UseChallenge")).empty() ? true : sTmp.ToBool(); - m_bRequestPerms = GetNV("RequestPerms").ToBool(); - m_bJoinOnInvite = (sTmp = GetNV("JoinOnInvite")).empty() ? true : sTmp.ToBool(); - m_bJoinAfterCloaked = (sTmp = GetNV("JoinAfterCloaked")).empty() ? true : sTmp.ToBool(); + m_bUseCloakedHost = + (sTmp = GetNV("UseCloakedHost")).empty() ? true : sTmp.ToBool(); + m_bUseChallenge = + (sTmp = GetNV("UseChallenge")).empty() ? true : sTmp.ToBool(); + m_bRequestPerms = GetNV("RequestPerms").ToBool(); + m_bJoinOnInvite = + (sTmp = GetNV("JoinOnInvite")).empty() ? true : sTmp.ToBool(); + m_bJoinAfterCloaked = + (sTmp = GetNV("JoinAfterCloaked")).empty() ? true : sTmp.ToBool(); - // Make sure NVs are stored in config. Note: SetUseCloakedHost() is called further down. + // Make sure NVs are stored in config. Note: SetUseCloakedHost() is + // called further down. SetUseChallenge(m_bUseChallenge); SetRequestPerms(m_bRequestPerms); SetJoinOnInvite(m_bJoinOnInvite); SetJoinAfterCloaked(m_bJoinAfterCloaked); - OnIRCDisconnected(); // reset module's state + OnIRCDisconnected(); // reset module's state if (IsIRCConnected()) { // check for usermode +x if we are already connected - set scUserModes = GetNetwork()->GetIRCSock()->GetUserModes(); - if (scUserModes.find('x') != scUserModes.end()) - m_bCloaked = true; + set scUserModes = + GetNetwork()->GetIRCSock()->GetUserModes(); + if (scUserModes.find('x') != scUserModes.end()) m_bCloaked = true; - // This will only happen once, and only if the user loads the module after connecting to IRC. + // This will only happen once, and only if the user loads the module + // after connecting to IRC. // Also don't notify the user in case he already had mode +x set. if (GetNV("UseCloakedHost").empty()) { if (!m_bCloaked) - PutModule("Notice: Your host will be cloaked the next time you reconnect to IRC. " - "If you want to cloak your host now, /msg *q Cloak. You can set your preference " - "with /msg *q Set UseCloakedHost true/false."); + PutModule( + "Notice: Your host will be cloaked the next time you " + "reconnect to IRC. " + "If you want to cloak your host now, /msg *q Cloak. " + "You can set your preference " + "with /msg *q Set UseCloakedHost true/false."); m_bUseCloakedHost = true; SetUseCloakedHost(m_bUseCloakedHost); m_bJoinAfterCloaked = true; @@ -84,15 +93,14 @@ public: void OnIRCDisconnected() override { m_bCloaked = false; - m_bAuthed = false; - m_bRequestedWhoami = false; + m_bAuthed = false; + m_bRequestedWhoami = false; m_bRequestedChallenge = false; m_bCatchResponse = false; } void OnIRCConnected() override { - if (m_bUseCloakedHost) - Cloak(); + if (m_bUseCloakedHost) Cloak(); WhoAmI(); } @@ -106,22 +114,32 @@ public: Table.AddColumn("Description"); Table.AddRow(); Table.SetCell("Command", "Auth [ ]"); - Table.SetCell("Description", "Tries to authenticate you with Q. Both parameters are optional."); + Table.SetCell("Description", + "Tries to authenticate you with Q. Both parameters " + "are optional."); Table.AddRow(); Table.SetCell("Command", "Cloak"); - Table.SetCell("Description", "Tries to set usermode +x to hide your real hostname."); + Table.SetCell( + "Description", + "Tries to set usermode +x to hide your real hostname."); Table.AddRow(); Table.SetCell("Command", "Status"); - Table.SetCell("Description", "Prints the current status of the module."); + Table.SetCell("Description", + "Prints the current status of the module."); Table.AddRow(); Table.SetCell("Command", "Update"); - Table.SetCell("Description", "Re-requests the current user information from Q."); + Table.SetCell("Description", + "Re-requests the current user information from Q."); Table.AddRow(); Table.SetCell("Command", "Set "); - Table.SetCell("Description", "Changes the value of the given setting. See the list of settings below."); + Table.SetCell("Description", + "Changes the value of the given setting. See the " + "list of settings below."); Table.AddRow(); Table.SetCell("Command", "Get"); - Table.SetCell("Description", "Prints out the current configuration. See the list of settings below."); + Table.SetCell("Description", + "Prints out the current configuration. See the list " + "of settings below."); PutModule(Table); PutModule("The following settings are available:"); @@ -140,31 +158,42 @@ public: Table2.AddRow(); Table2.SetCell("Setting", "UseCloakedHost"); Table2.SetCell("Type", "Boolean"); - Table2.SetCell("Description", "Whether to cloak your hostname (+x) automatically on connect."); + Table2.SetCell("Description", + "Whether to cloak your hostname (+x) automatically " + "on connect."); Table2.AddRow(); Table2.SetCell("Setting", "UseChallenge"); Table2.SetCell("Type", "Boolean"); - Table2.SetCell("Description", "Whether to use the CHALLENGEAUTH mechanism to avoid sending passwords in cleartext."); + Table2.SetCell("Description", + "Whether to use the CHALLENGEAUTH mechanism to " + "avoid sending passwords in cleartext."); Table2.AddRow(); Table2.SetCell("Setting", "RequestPerms"); Table2.SetCell("Type", "Boolean"); - Table2.SetCell("Description", "Whether to request voice/op from Q on join/devoice/deop."); + Table2.SetCell( + "Description", + "Whether to request voice/op from Q on join/devoice/deop."); Table2.AddRow(); Table2.SetCell("Setting", "JoinOnInvite"); Table2.SetCell("Type", "Boolean"); - Table2.SetCell("Description", "Whether to join channels when Q invites you."); + Table2.SetCell("Description", + "Whether to join channels when Q invites you."); Table2.AddRow(); Table2.SetCell("Setting", "JoinAfterCloaked"); Table2.SetCell("Type", "Boolean"); - Table2.SetCell("Description", "Whether to delay joining channels until after you are cloaked."); + Table2.SetCell("Description", + "Whether to delay joining channels until after you " + "are cloaked."); PutModule(Table2); - PutModule("This module takes 2 optional parameters: "); + PutModule( + "This module takes 2 optional parameters: " + ""); PutModule("Module settings are stored between restarts."); } else if (sCommand == "set") { CString sSetting = sLine.Token(1).AsLower(); - CString sValue = sLine.Token(2); + CString sValue = sLine.Token(2); if (sSetting.empty() || sValue.empty()) { PutModule("Syntax: Set "); } else if (sSetting == "username") { @@ -200,7 +229,7 @@ public: Table.SetCell("Value", m_sUsername); Table.AddRow(); Table.SetCell("Setting", "Password"); - Table.SetCell("Value", "*****"); // m_sPassword + Table.SetCell("Value", "*****"); // m_sPassword Table.AddRow(); Table.SetCell("Setting", "UseCloakedHost"); Table.SetCell("Value", CString(m_bUseCloakedHost)); @@ -220,8 +249,8 @@ public: } else if (sCommand == "status") { PutModule("Connected: " + CString(IsIRCConnected() ? "yes" : "no")); - PutModule("Cloaked: " + CString(m_bCloaked ? "yes" : "no")); - PutModule("Authed: " + CString(m_bAuthed ? "yes" : "no")); + PutModule("Cloaked: " + CString(m_bCloaked ? "yes" : "no")); + PutModule("Authed: " + CString(m_bAuthed ? "yes" : "no")); } else { // The following commands require an IRC connection. @@ -254,7 +283,8 @@ public: EModRet OnRaw(CString& sLine) override { // use OnRaw because OnUserMode is not defined (yet?) - if (sLine.Token(1) == "396" && sLine.Token(3).find("users.quakenet.org") != CString::npos) { + if (sLine.Token(1) == "396" && + sLine.Token(3).find("users.quakenet.org") != CString::npos) { m_bCloaked = true; PutModule("Cloak successful: Your hostname is now cloaked."); @@ -285,48 +315,49 @@ public: } void OnJoin(const CNick& Nick, CChan& Channel) override { - if (m_bRequestPerms && IsSelf(Nick)) - HandleNeed(Channel, "ov"); + if (m_bRequestPerms && IsSelf(Nick)) HandleNeed(Channel, "ov"); } - void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { + void OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { if (m_bRequestPerms && IsSelf(Nick) && (!pOpNick || !IsSelf(*pOpNick))) HandleNeed(Channel, "o"); } - void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { + void OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { if (m_bRequestPerms && IsSelf(Nick) && (!pOpNick || !IsSelf(*pOpNick))) HandleNeed(Channel, "v"); } EModRet OnInvite(const CNick& Nick, const CString& sChan) override { - if (!Nick.NickEquals("Q") || !Nick.GetHost().Equals("CServe.quakenet.org")) + if (!Nick.NickEquals("Q") || + !Nick.GetHost().Equals("CServe.quakenet.org")) return CONTINUE; - if (m_bJoinOnInvite) - GetNetwork()->AddChan(sChan, false); + if (m_bJoinOnInvite) GetNetwork()->AddChan(sChan, false); return CONTINUE; } CString GetWebMenuTitle() override { return "Q"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { bool bSubmitted = (WebSock.GetParam("submitted").ToInt() != 0); if (bSubmitted) { CString FormUsername = WebSock.GetParam("user"); - if (!FormUsername.empty()) - SetUsername(FormUsername); + if (!FormUsername.empty()) SetUsername(FormUsername); CString FormPassword = WebSock.GetParam("password"); - if (!FormPassword.empty()) - SetPassword(FormPassword); + if (!FormPassword.empty()) SetPassword(FormPassword); SetUseCloakedHost(WebSock.GetParam("usecloakedhost").ToBool()); SetUseChallenge(WebSock.GetParam("usechallenge").ToBool()); SetRequestPerms(WebSock.GetParam("requestperms").ToBool()); SetJoinOnInvite(WebSock.GetParam("joinoninvite").ToBool()); - SetJoinAfterCloaked(WebSock.GetParam("joinaftercloaked").ToBool()); + SetJoinAfterCloaked( + WebSock.GetParam("joinaftercloaked").ToBool()); } Tmpl["Username"] = m_sUsername; @@ -334,19 +365,23 @@ public: CTemplate& o1 = Tmpl.AddRow("OptionLoop"); o1["Name"] = "usecloakedhost"; o1["DisplayName"] = "UseCloakedHost"; - o1["Tooltip"] = "Whether to cloak your hostname (+x) automatically on connect."; + o1["Tooltip"] = + "Whether to cloak your hostname (+x) automatically on connect."; o1["Checked"] = CString(m_bUseCloakedHost); CTemplate& o2 = Tmpl.AddRow("OptionLoop"); o2["Name"] = "usechallenge"; o2["DisplayName"] = "UseChallenge"; - o2["Tooltip"] = "Whether to use the CHALLENGEAUTH mechanism to avoid sending passwords in cleartext."; + o2["Tooltip"] = + "Whether to use the CHALLENGEAUTH mechanism to avoid sending " + "passwords in cleartext."; o2["Checked"] = CString(m_bUseChallenge); CTemplate& o3 = Tmpl.AddRow("OptionLoop"); o3["Name"] = "requestperms"; o3["DisplayName"] = "RequestPerms"; - o3["Tooltip"] = "Whether to request voice/op from Q on join/devoice/deop."; + o3["Tooltip"] = + "Whether to request voice/op from Q on join/devoice/deop."; o3["Checked"] = CString(m_bRequestPerms); CTemplate& o4 = Tmpl.AddRow("OptionLoop"); @@ -358,7 +393,9 @@ public: CTemplate& o5 = Tmpl.AddRow("OptionLoop"); o5["Name"] = "joinaftercloaked"; o5["DisplayName"] = "JoinAfterCloaked"; - o5["Tooltip"] = "Whether to delay joining channels until after you are cloaked."; + o5["Tooltip"] = + "Whether to delay joining channels until after you are " + "cloaked."; o5["Checked"] = CString(m_bJoinAfterCloaked); if (bSubmitted) { @@ -371,7 +408,7 @@ public: return false; } -private: + private: bool m_bCloaked{}; bool m_bAuthed{}; bool m_bRequestedWhoami{}; @@ -387,8 +424,7 @@ private: } void Cloak() { - if (m_bCloaked) - return; + if (m_bCloaked) return; PutModule("Cloak: Trying to cloak your hostname, setting +x..."); PutIRC("MODE " + GetNetwork()->GetIRCSock()->GetNick() + " +x"); @@ -400,16 +436,15 @@ private: } void Auth(const CString& sUsername = "", const CString& sPassword = "") { - if (m_bAuthed) - return; + if (m_bAuthed) return; - if (!sUsername.empty()) - SetUsername(sUsername); - if (!sPassword.empty()) - SetPassword(sPassword); + if (!sUsername.empty()) SetUsername(sUsername); + if (!sPassword.empty()) SetPassword(sPassword); if (m_sUsername.empty() || m_sPassword.empty()) { - PutModule("You have to set a username and password to use this module! See 'help' for details."); + PutModule( + "You have to set a username and password to use this module! " + "See 'help' for details."); return; } @@ -424,23 +459,24 @@ private: } void ChallengeAuth(CString sChallenge) { - if (m_bAuthed) - return; + if (m_bAuthed) return; - CString sUsername = m_sUsername.AsLower() - .Replace_n("[", "{") - .Replace_n("]", "}") - .Replace_n("\\", "|"); + CString sUsername = m_sUsername.AsLower() + .Replace_n("[", "{") + .Replace_n("]", "}") + .Replace_n("\\", "|"); CString sPasswordHash = m_sPassword.Left(10).SHA256(); - CString sKey = CString(sUsername + ":" + sPasswordHash).SHA256(); - CString sResponse = HMAC_SHA256(sKey, sChallenge); + CString sKey = CString(sUsername + ":" + sPasswordHash).SHA256(); + CString sResponse = HMAC_SHA256(sKey, sChallenge); PutModule("Auth: Received challenge, sending CHALLENGEAUTH request..."); - PutQ("CHALLENGEAUTH " + m_sUsername + " " + sResponse + " HMAC-SHA-256"); + PutQ("CHALLENGEAUTH " + m_sUsername + " " + sResponse + + " HMAC-SHA-256"); } EModRet HandleMessage(const CNick& Nick, CString sMessage) { - if (!Nick.NickEquals("Q") || !Nick.GetHost().Equals("CServe.quakenet.org")) + if (!Nick.NickEquals("Q") || + !Nick.GetHost().Equals("CServe.quakenet.org")) return CONTINUE; sMessage.Trim(); @@ -450,25 +486,24 @@ private: #endif // WHOAMI - if (sMessage.find("WHOAMI is only available to authed users") != CString::npos) { + if (sMessage.find("WHOAMI is only available to authed users") != + CString::npos) { m_bAuthed = false; Auth(); m_bCatchResponse = m_bRequestedWhoami; - } - else if (sMessage.find("Information for user") != CString::npos) { + } else if (sMessage.find("Information for user") != CString::npos) { m_bAuthed = true; m_msChanModes.clear(); m_bCatchResponse = m_bRequestedWhoami; m_bRequestedWhoami = true; - } - else if (m_bRequestedWhoami && sMessage.WildCmp("#*")) { + } else if (m_bRequestedWhoami && sMessage.WildCmp("#*")) { CString sChannel = sMessage.Token(0); - CString sFlags = sMessage.Token(1, true).Trim_n().TrimLeft_n("+"); + CString sFlags = sMessage.Token(1, true).Trim_n().TrimLeft_n("+"); m_msChanModes[sChannel] = sFlags; - } - else if (m_bRequestedWhoami && m_bCatchResponse - && (sMessage.Equals("End of list.") - || sMessage.Equals("account, or HELLO to create an account."))) { + } else if (m_bRequestedWhoami && m_bCatchResponse && + (sMessage.Equals("End of list.") || + sMessage.Equals( + "account, or HELLO to create an account."))) { m_bRequestedWhoami = m_bCatchResponse = false; return HALT; } @@ -478,22 +513,24 @@ private: m_bAuthed = false; PutModule("Auth failed: " + sMessage); return HALT; - } - else if (sMessage.WildCmp("You are now logged in as *.")) { + } else if (sMessage.WildCmp("You are now logged in as *.")) { m_bAuthed = true; PutModule("Auth successful: " + sMessage); WhoAmI(); return HALT; - } - else if (m_bRequestedChallenge && sMessage.Token(0).Equals("CHALLENGE")) { + } else if (m_bRequestedChallenge && + sMessage.Token(0).Equals("CHALLENGE")) { m_bRequestedChallenge = false; - if (sMessage.find("not available once you have authed") != CString::npos) { + if (sMessage.find("not available once you have authed") != + CString::npos) { m_bAuthed = true; } else { if (sMessage.find("HMAC-SHA-256") != CString::npos) { ChallengeAuth(sMessage.Token(1)); } else { - PutModule("Auth failed: Q does not support HMAC-SHA-256 for CHALLENGEAUTH, falling back to standard AUTH."); + PutModule( + "Auth failed: Q does not support HMAC-SHA-256 for " + "CHALLENGEAUTH, falling back to standard AUTH."); SetUseChallenge(false); Auth(); } @@ -502,23 +539,25 @@ private: } // prevent buffering of Q's responses - return !m_bCatchResponse && GetUser()->IsUserAttached() ? CONTINUE : HALT; + return !m_bCatchResponse && GetUser()->IsUserAttached() ? CONTINUE + : HALT; } void HandleNeed(const CChan& Channel, const CString& sPerms) { MCString::iterator it = m_msChanModes.find(Channel.GetName()); - if (it == m_msChanModes.end()) - return; + if (it == m_msChanModes.end()) return; CString sModes = it->second; - bool bMaster = (sModes.find("m") != CString::npos) || (sModes.find("n") != CString::npos); + bool bMaster = (sModes.find("m") != CString::npos) || + (sModes.find("n") != CString::npos); if (sPerms.find("o") != CString::npos) { - bool bOp = (sModes.find("o") != CString::npos); + bool bOp = (sModes.find("o") != CString::npos); bool bAutoOp = (sModes.find("a") != CString::npos); if (bMaster || bOp) { if (!bAutoOp) { - PutModule("RequestPerms: Requesting op on " + Channel.GetName()); + PutModule("RequestPerms: Requesting op on " + + Channel.GetName()); PutQ("OP " + Channel.GetName()); } return; @@ -526,11 +565,12 @@ private: } if (sPerms.find("v") != CString::npos) { - bool bVoice = (sModes.find("v") != CString::npos); + bool bVoice = (sModes.find("v") != CString::npos); bool bAutoVoice = (sModes.find("g") != CString::npos); if (bMaster || bVoice) { if (!bAutoVoice) { - PutModule("RequestPerms: Requesting voice on " + Channel.GetName()); + PutModule("RequestPerms: Requesting voice on " + + Channel.GetName()); PutQ("VOICE " + Channel.GetName()); } return; @@ -538,8 +578,7 @@ private: } } - -/* Utility Functions */ + /* Utility Functions */ bool IsIRCConnected() { CIRCSock* pIRCSock = GetNetwork()->GetIRCSock(); return pIRCSock && pIRCSock->IsAuthed(); @@ -550,18 +589,16 @@ private: } bool PackHex(const CString& sHex, CString& sPackedHex) { - if (sHex.length() % 2) - return false; + if (sHex.length() % 2) return false; sPackedHex.clear(); CString::size_type len = sHex.length() / 2; for (CString::size_type i = 0; i < len; i++) { unsigned int value; - int n = sscanf(&sHex[i*2], "%02x", &value); - if (n != 1 || value > 0xff) - return false; - sPackedHex += (unsigned char) value; + int n = sscanf(&sHex[i * 2], "%02x", &value); + if (n != 1 || value > 0xff) return false; + sPackedHex += (unsigned char)value; } return true; @@ -587,14 +624,14 @@ private: return CString(sOuterKey + sInnerHash).SHA256(); } -/* Settings */ + /* Settings */ CString m_sUsername; CString m_sPassword; - bool m_bUseCloakedHost{}; - bool m_bUseChallenge{}; - bool m_bRequestPerms{}; - bool m_bJoinOnInvite{}; - bool m_bJoinAfterCloaked{}; + bool m_bUseCloakedHost{}; + bool m_bUseChallenge{}; + bool m_bRequestPerms{}; + bool m_bJoinOnInvite{}; + bool m_bJoinAfterCloaked{}; void SetUsername(const CString& sUsername) { m_sUsername = sUsername; @@ -610,8 +647,7 @@ private: m_bUseCloakedHost = bUseCloakedHost; SetNV("UseCloakedHost", CString(bUseCloakedHost)); - if (!m_bCloaked && m_bUseCloakedHost && IsIRCConnected()) - Cloak(); + if (!m_bCloaked && m_bUseCloakedHost && IsIRCConnected()) Cloak(); } void SetUseChallenge(const bool bUseChallenge) { @@ -635,7 +671,8 @@ private: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("Q"); Info.SetHasArgs(true); Info.SetArgsHelpText("Please provide your username and password for Q."); diff --git a/modules/raw.cpp b/modules/raw.cpp index 0b5fdc06..114ca24b 100644 --- a/modules/raw.cpp +++ b/modules/raw.cpp @@ -17,7 +17,7 @@ #include class CRawMod : public CModule { -public: + public: MODCONSTRUCTOR(CRawMod) {} virtual ~CRawMod() {} @@ -26,9 +26,7 @@ public: return CONTINUE; } - void OnModCommand(const CString& sCommand) override { - PutIRC(sCommand); - } + void OnModCommand(const CString& sCommand) override { PutIRC(sCommand); } EModRet OnUserRaw(CString& sLine) override { PutModule("YOU -> [" + sLine + "]"); @@ -36,10 +34,10 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("raw"); Info.AddType(CModInfo::UserModule); } NETWORKMODULEDEFS(CRawMod, "View all of the raw traffic") - diff --git a/modules/route_replies.cpp b/modules/route_replies.cpp index a587ac5f..1f996f78 100644 --- a/modules/route_replies.cpp +++ b/modules/route_replies.cpp @@ -18,207 +18,198 @@ #include struct reply { - const char *szReply; + const char* szReply; bool bLastResponse; }; // TODO this list is far from complete, no errors are handled static const struct { - const char *szRequest; + const char* szRequest; struct reply vReplies[19]; } vRouteReplies[] = { - {"WHO", { - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {"352", false}, /* rfc1459 RPL_WHOREPLY */ - {"315", true}, /* rfc1459 RPL_ENDOFWHO */ - {"354", false}, // e.g. Quaknet uses this for WHO #chan %n - {"403", true}, // No such chan - {nullptr, true} - }}, - {"LIST", { - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {"321", false}, /* rfc1459 RPL_LISTSTART */ - {"322", false}, /* rfc1459 RPL_LIST */ - {"323", true}, /* rfc1459 RPL_LISTEND */ - {nullptr, true} - }}, - {"NAMES", { - {"353", false}, /* rfc1459 RPL_NAMREPLY */ - {"366", true}, /* rfc1459 RPL_ENDOFNAMES */ - // No such nick/channel - {"401", true}, - {nullptr, true}, - }}, - {"LUSERS", { - {"251", false}, /* rfc1459 RPL_LUSERCLIENT */ - {"252", false}, /* rfc1459 RPL_LUSEROP */ - {"253", false}, /* rfc1459 RPL_LUSERUNKNOWN */ - {"254", false}, /* rfc1459 RPL_LUSERCHANNELS */ - {"255", false}, /* rfc1459 RPL_LUSERME */ - {"265", false}, - {"266", true}, - // We don't handle 250 here since some IRCds don't sent it - //{"250", true}, - {nullptr, true} - }}, - {"WHOIS", { - {"311", false}, /* rfc1459 RPL_WHOISUSER */ - {"312", false}, /* rfc1459 RPL_WHOISSERVER */ - {"313", false}, /* rfc1459 RPL_WHOISOPERATOR */ - {"317", false}, /* rfc1459 RPL_WHOISIDLE */ - {"319", false}, /* rfc1459 RPL_WHOISCHANNELS */ - {"301", false}, /* rfc1459 RPL_AWAY */ - {"276", false}, /* oftc-hybrid RPL_WHOISCERTFP */ - {"330", false}, /* ratbox RPL_WHOISLOGGEDIN - aka ircu RPL_WHOISACCOUNT */ - {"338", false}, /* RPL_WHOISACTUALLY -- "actually using host" */ - {"378", false}, /* RPL_WHOISHOST -- real address of vhosts */ - {"671", false}, /* RPL_WHOISSECURE */ - {"307", false}, /* RPL_WHOISREGNICK */ - {"379", false}, /* RPL_WHOISMODES */ - {"760", false}, /* ircv3.2 RPL_WHOISKEYVALUE */ - {"318", true}, /* rfc1459 RPL_ENDOFWHOIS */ - {"401", true}, /* rfc1459 ERR_NOSUCHNICK */ - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {"431", true}, /* rfc1459 ERR_NONICKNAMEGIVEN */ - {nullptr, true} - }}, - {"PING", { - {"PONG", true}, - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {"409", true}, /* rfc1459 ERR_NOORIGIN */ - {nullptr, true} - }}, - {"USERHOST", { - {"302", true}, - {"461", true}, /* rfc1459 ERR_NEEDMOREPARAMS */ - {nullptr, true} - }}, - {"TIME", { - {"391", true}, /* rfc1459 RPL_TIME */ - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {nullptr, true} - }}, - {"WHOWAS", { - {"406", false}, /* rfc1459 ERR_WASNOSUCHNICK */ - {"312", false}, /* rfc1459 RPL_WHOISSERVER */ - {"314", false}, /* rfc1459 RPL_WHOWASUSER */ - {"369", true}, /* rfc1459 RPL_ENDOFWHOWAS */ - {"431", true}, /* rfc1459 ERR_NONICKNAMEGIVEN */ - {nullptr, true} - }}, - {"ISON", { - {"303", true}, /* rfc1459 RPL_ISON */ - {"461", true}, /* rfc1459 ERR_NEEDMOREPARAMS */ - {nullptr, true} - }}, - {"LINKS", { - {"364", false}, /* rfc1459 RPL_LINKS */ - {"365", true}, /* rfc1459 RPL_ENDOFLINKS */ - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {nullptr, true} - }}, - {"MAP", { - {"006", false}, - // inspircd - {"270", false}, - // SilverLeo wants this two added - {"015", false}, - {"017", true}, - {"007", true}, - {"481", true}, /* rfc1459 ERR_NOPRIVILEGES */ - {nullptr, true} - }}, - {"TRACE", { - {"200", false}, /* rfc1459 RPL_TRACELINK */ - {"201", false}, /* rfc1459 RPL_TRACECONNECTING */ - {"202", false}, /* rfc1459 RPL_TRACEHANDSHAKE */ - {"203", false}, /* rfc1459 RPL_TRACEUNKNOWN */ - {"204", false}, /* rfc1459 RPL_TRACEOPERATOR */ - {"205", false}, /* rfc1459 RPL_TRACEUSER */ - {"206", false}, /* rfc1459 RPL_TRACESERVER */ - {"208", false}, /* rfc1459 RPL_TRACENEWTYPE */ - {"261", false}, /* rfc1459 RPL_TRACELOG */ - {"262", true}, - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {nullptr, true} - }}, - {"USERS", { - {"265", false}, - {"266", true}, - {"392", false}, /* rfc1459 RPL_USERSSTART */ - {"393", false}, /* rfc1459 RPL_USERS */ - {"394", true}, /* rfc1459 RPL_ENDOFUSERS */ - {"395", false}, /* rfc1459 RPL_NOUSERS */ - {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ - {"424", true}, /* rfc1459 ERR_FILEERROR */ - {"446", true}, /* rfc1459 ERR_USERSDISABLED */ - {nullptr, true}, - }}, - {"METADATA", { - {"761", false}, /* ircv3.2 RPL_KEYVALUE */ - {"762", true}, /* ircv3.2 RPL_METADATAEND */ - {"765", true}, /* ircv3.2 ERR_TARGETINVALID */ - {"766", true}, /* ircv3.2 ERR_NOMATCHINGKEYS */ - {"767", true}, /* ircv3.2 ERR_KEYINVALID */ - {"768", true}, /* ircv3.2 ERR_KEYNOTSET */ - {"769", true}, /* ircv3.2 ERR_KEYNOPERMISSION */ - {nullptr, true}, - }}, - // This is just a list of all possible /mode replies stuffed together. - // Since there should never be more than one of these going on, this - // should work fine and makes the code simpler. - {"MODE", { - // "You're not a channel operator" - {"482", true}, - // MODE I - {"346", false}, - {"347", true}, - // MODE b - {"367", false}, - {"368", true}, - // MODE e - {"348", false}, - {"349", true}, - {"467", true}, /* rfc1459 ERR_KEYSET */ - {"472", true}, /* rfc1459 ERR_UNKNOWNMODE */ - {"501", true}, /* rfc1459 ERR_UMODEUNKNOWNFLAG */ - {"502", true}, /* rfc1459 ERR_USERSDONTMATCH */ - {nullptr, true}, - }}, - // END (last item!) - {nullptr, {{nullptr, true}}} -}; + {"WHO", + {{"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {"352", false}, /* rfc1459 RPL_WHOREPLY */ + {"315", true}, /* rfc1459 RPL_ENDOFWHO */ + {"354", false}, // e.g. Quaknet uses this for WHO #chan %n + {"403", true}, // No such chan + {nullptr, true}}}, + {"LIST", + {{"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {"321", false}, /* rfc1459 RPL_LISTSTART */ + {"322", false}, /* rfc1459 RPL_LIST */ + {"323", true}, /* rfc1459 RPL_LISTEND */ + {nullptr, true}}}, + {"NAMES", + { + {"353", false}, /* rfc1459 RPL_NAMREPLY */ + {"366", true}, /* rfc1459 RPL_ENDOFNAMES */ + // No such nick/channel + {"401", true}, + {nullptr, true}, + }}, + {"LUSERS", + {{"251", false}, /* rfc1459 RPL_LUSERCLIENT */ + {"252", false}, /* rfc1459 RPL_LUSEROP */ + {"253", false}, /* rfc1459 RPL_LUSERUNKNOWN */ + {"254", false}, /* rfc1459 RPL_LUSERCHANNELS */ + {"255", false}, /* rfc1459 RPL_LUSERME */ + {"265", false}, + {"266", true}, + // We don't handle 250 here since some IRCds don't sent it + //{"250", true}, + {nullptr, true}}}, + {"WHOIS", + {{"311", false}, /* rfc1459 RPL_WHOISUSER */ + {"312", false}, /* rfc1459 RPL_WHOISSERVER */ + {"313", false}, /* rfc1459 RPL_WHOISOPERATOR */ + {"317", false}, /* rfc1459 RPL_WHOISIDLE */ + {"319", false}, /* rfc1459 RPL_WHOISCHANNELS */ + {"301", false}, /* rfc1459 RPL_AWAY */ + {"276", false}, /* oftc-hybrid RPL_WHOISCERTFP */ + {"330", false}, /* ratbox RPL_WHOISLOGGEDIN + aka ircu RPL_WHOISACCOUNT */ + {"338", false}, /* RPL_WHOISACTUALLY -- "actually using host" */ + {"378", false}, /* RPL_WHOISHOST -- real address of vhosts */ + {"671", false}, /* RPL_WHOISSECURE */ + {"307", false}, /* RPL_WHOISREGNICK */ + {"379", false}, /* RPL_WHOISMODES */ + {"760", false}, /* ircv3.2 RPL_WHOISKEYVALUE */ + {"318", true}, /* rfc1459 RPL_ENDOFWHOIS */ + {"401", true}, /* rfc1459 ERR_NOSUCHNICK */ + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {"431", true}, /* rfc1459 ERR_NONICKNAMEGIVEN */ + {nullptr, true}}}, + {"PING", + {{"PONG", true}, + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {"409", true}, /* rfc1459 ERR_NOORIGIN */ + {nullptr, true}}}, + {"USERHOST", + {{"302", true}, + {"461", true}, /* rfc1459 ERR_NEEDMOREPARAMS */ + {nullptr, true}}}, + {"TIME", + {{"391", true}, /* rfc1459 RPL_TIME */ + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {nullptr, true}}}, + {"WHOWAS", + {{"406", false}, /* rfc1459 ERR_WASNOSUCHNICK */ + {"312", false}, /* rfc1459 RPL_WHOISSERVER */ + {"314", false}, /* rfc1459 RPL_WHOWASUSER */ + {"369", true}, /* rfc1459 RPL_ENDOFWHOWAS */ + {"431", true}, /* rfc1459 ERR_NONICKNAMEGIVEN */ + {nullptr, true}}}, + {"ISON", + {{"303", true}, /* rfc1459 RPL_ISON */ + {"461", true}, /* rfc1459 ERR_NEEDMOREPARAMS */ + {nullptr, true}}}, + {"LINKS", + {{"364", false}, /* rfc1459 RPL_LINKS */ + {"365", true}, /* rfc1459 RPL_ENDOFLINKS */ + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {nullptr, true}}}, + {"MAP", + {{"006", false}, + // inspircd + {"270", false}, + // SilverLeo wants this two added + {"015", false}, + {"017", true}, + {"007", true}, + {"481", true}, /* rfc1459 ERR_NOPRIVILEGES */ + {nullptr, true}}}, + {"TRACE", + {{"200", false}, /* rfc1459 RPL_TRACELINK */ + {"201", false}, /* rfc1459 RPL_TRACECONNECTING */ + {"202", false}, /* rfc1459 RPL_TRACEHANDSHAKE */ + {"203", false}, /* rfc1459 RPL_TRACEUNKNOWN */ + {"204", false}, /* rfc1459 RPL_TRACEOPERATOR */ + {"205", false}, /* rfc1459 RPL_TRACEUSER */ + {"206", false}, /* rfc1459 RPL_TRACESERVER */ + {"208", false}, /* rfc1459 RPL_TRACENEWTYPE */ + {"261", false}, /* rfc1459 RPL_TRACELOG */ + {"262", true}, + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {nullptr, true}}}, + {"USERS", + { + {"265", false}, + {"266", true}, + {"392", false}, /* rfc1459 RPL_USERSSTART */ + {"393", false}, /* rfc1459 RPL_USERS */ + {"394", true}, /* rfc1459 RPL_ENDOFUSERS */ + {"395", false}, /* rfc1459 RPL_NOUSERS */ + {"402", true}, /* rfc1459 ERR_NOSUCHSERVER */ + {"424", true}, /* rfc1459 ERR_FILEERROR */ + {"446", true}, /* rfc1459 ERR_USERSDISABLED */ + {nullptr, true}, + }}, + {"METADATA", + { + {"761", false}, /* ircv3.2 RPL_KEYVALUE */ + {"762", true}, /* ircv3.2 RPL_METADATAEND */ + {"765", true}, /* ircv3.2 ERR_TARGETINVALID */ + {"766", true}, /* ircv3.2 ERR_NOMATCHINGKEYS */ + {"767", true}, /* ircv3.2 ERR_KEYINVALID */ + {"768", true}, /* ircv3.2 ERR_KEYNOTSET */ + {"769", true}, /* ircv3.2 ERR_KEYNOPERMISSION */ + {nullptr, true}, + }}, + // This is just a list of all possible /mode replies stuffed together. + // Since there should never be more than one of these going on, this + // should work fine and makes the code simpler. + {"MODE", + {// "You're not a channel operator" + {"482", true}, + // MODE I + {"346", false}, + {"347", true}, + // MODE b + {"367", false}, + {"368", true}, + // MODE e + {"348", false}, + {"349", true}, + {"467", true}, /* rfc1459 ERR_KEYSET */ + {"472", true}, /* rfc1459 ERR_UNKNOWNMODE */ + {"501", true}, /* rfc1459 ERR_UMODEUNKNOWNFLAG */ + {"502", true}, /* rfc1459 ERR_USERSDONTMATCH */ + {nullptr, true}, + }}, + // END (last item!) + {nullptr, {{nullptr, true}}}}; class CRouteTimeout : public CTimer { -public: - CRouteTimeout(CModule* pModule, unsigned int uInterval, unsigned int uCycles, - const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} + public: + CRouteTimeout(CModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CRouteTimeout() {} -protected: + protected: void RunJob() override; }; struct queued_req { CString sLine; - const struct reply *reply; + const struct reply* reply; }; -typedef std::map > requestQueue; +typedef std::map> requestQueue; -class CRouteRepliesMod : public CModule -{ -public: - MODCONSTRUCTOR(CRouteRepliesMod) - { +class CRouteRepliesMod : public CModule { + public: + MODCONSTRUCTOR(CRouteRepliesMod) { m_pDoing = nullptr; m_pReplies = nullptr; AddHelpCommand(); - AddCommand("Silent", static_cast(&CRouteRepliesMod::SilentCommand), - "[yes|no]", "Decides whether to show the timeout messages or not"); + AddCommand("Silent", static_cast( + &CRouteRepliesMod::SilentCommand), + "[yes|no]", + "Decides whether to show the timeout messages or not"); } virtual ~CRouteRepliesMod() { @@ -236,8 +227,7 @@ public: } } - void OnIRCConnected() override - { + void OnIRCConnected() override { m_pDoing = nullptr; m_pReplies = nullptr; m_vsPending.clear(); @@ -246,13 +236,11 @@ public: RemTimer("RouteTimeout"); } - void OnIRCDisconnected() override - { - OnIRCConnected(); // Let's keep it in one place + void OnIRCDisconnected() override { + OnIRCConnected(); // Let's keep it in one place } - void OnClientDisconnect() override - { + void OnClientDisconnect() override { requestQueue::iterator it; if (GetClient() == m_pDoing) { @@ -265,19 +253,16 @@ public: it = m_vsPending.find(GetClient()); - if (it != m_vsPending.end()) - m_vsPending.erase(it); + if (it != m_vsPending.end()) m_vsPending.erase(it); SendRequest(); } - EModRet OnRaw(CString& sLine) override - { + EModRet OnRaw(CString& sLine) override { CString sCmd = sLine.Token(1).AsUpper(); size_t i = 0; - if (!m_pReplies) - return CONTINUE; + if (!m_pReplies) return CONTINUE; // Is this a "not enough arguments" error? if (sCmd == "461") { @@ -286,8 +271,7 @@ public: if (m_sLastRequest.Token(0).Equals(sOrigCmd)) { // This is the reply to the last request - if (RouteReply(sLine, true)) - return HALTCORE; + if (RouteReply(sLine, true)) return HALTCORE; return CONTINUE; } } @@ -307,42 +291,37 @@ public: return CONTINUE; } - EModRet OnUserRaw(CString& sLine) override - { + EModRet OnUserRaw(CString& sLine) override { CString sCmd = sLine.Token(0).AsUpper(); - if (!GetNetwork()->GetIRCSock()) - return CONTINUE; + if (!GetNetwork()->GetIRCSock()) return CONTINUE; if (sCmd.Equals("MODE")) { // Check if this is a mode request that needs to be handled // If there are arguments to a mode change, // we must not route it. - if (!sLine.Token(3, true).empty()) - return CONTINUE; + if (!sLine.Token(3, true).empty()) return CONTINUE; // Grab the mode change parameter CString sMode = sLine.Token(2); // If this is a channel mode request, znc core replies to it - if (sMode.empty()) - return CONTINUE; + if (sMode.empty()) return CONTINUE; // Check if this is a mode change or a specific // mode request (the later needs to be routed). sMode.TrimPrefix("+"); - if (sMode.length() != 1) - return CONTINUE; + if (sMode.length() != 1) return CONTINUE; // Now just check if it's one of the supported modes switch (sMode[0]) { - case 'I': - case 'b': - case 'e': - break; - default: - return CONTINUE; + case 'I': + case 'b': + case 'e': + break; + default: + return CONTINUE; } // Ok, this looks like we should route it. @@ -351,9 +330,7 @@ public: for (size_t i = 0; vRouteReplies[i].szRequest != nullptr; i++) { if (vRouteReplies[i].szRequest == sCmd) { - struct queued_req req = { - sLine, vRouteReplies[i].vReplies - }; + struct queued_req req = {sLine, vRouteReplies[i].vReplies}; m_vsPending[GetClient()].push_back(req); SendRequest(); @@ -364,22 +341,24 @@ public: return CONTINUE; } - void Timeout() - { + void Timeout() { // The timer will be deleted after this by the event loop if (!GetNV("silent_timeouts").ToBool()) { - PutModule("This module hit a timeout which is probably a connectivity issue."); - PutModule("However, if you can provide steps to reproduce this issue, please do report a bug."); - PutModule("To disable this message, do \"/msg " + GetModNick() - + " silent yes\""); + PutModule( + "This module hit a timeout which is probably a connectivity " + "issue."); + PutModule( + "However, if you can provide steps to reproduce this issue, " + "please do report a bug."); + PutModule("To disable this message, do \"/msg " + GetModNick() + + " silent yes\""); PutModule("Last request: " + m_sLastRequest); PutModule("Expected replies: "); for (size_t i = 0; m_pReplies[i].szReply != nullptr; i++) { if (m_pReplies[i].bLastResponse) - PutModule(m_pReplies[i].szReply + - CString(" (last)")); + PutModule(m_pReplies[i].szReply + CString(" (last)")); else PutModule(m_pReplies[i].szReply); } @@ -390,11 +369,9 @@ public: SendRequest(); } -private: - bool RouteReply(const CString& sLine, bool bFinished = false) - { - if (!m_pDoing) - return false; + private: + bool RouteReply(const CString& sLine, bool bFinished = false) { + if (!m_pDoing) return false; // TODO: RouteReply(const CMessage& Message, bool bFinished = false) m_pDoing->PutClient(CMessage(sLine)); @@ -411,15 +388,12 @@ private: return true; } - void SendRequest() - { + void SendRequest() { requestQueue::iterator it; - if (m_pDoing || m_pReplies) - return; + if (m_pDoing || m_pReplies) return; - if (m_vsPending.empty()) - return; + if (m_vsPending.empty()) return; it = m_vsPending.begin(); @@ -432,13 +406,14 @@ private: // When we are called from the timer, we need to remove it. // We can't delete it (segfault on return), thus we // just stop it. The main loop will delete it. - CTimer *pTimer = FindTimer("RouteTimeout"); + CTimer* pTimer = FindTimer("RouteTimeout"); if (pTimer) { pTimer->Stop(); UnlinkTimer(pTimer); } - AddTimer(new CRouteTimeout(this, 60, 1, "RouteTimeout", - "Recover from missing / wrong server replies")); + AddTimer( + new CRouteTimeout(this, 60, 1, "RouteTimeout", + "Recover from missing / wrong server replies")); m_pDoing = it->first; m_pReplies = it->second[0].reply; @@ -458,21 +433,22 @@ private: PutModule("Timeout messages are " + sPrefix + "abled."); } - CClient *m_pDoing; - const struct reply *m_pReplies; - requestQueue m_vsPending; + CClient* m_pDoing; + const struct reply* m_pReplies; + requestQueue m_vsPending; // This field is only used for display purpose. - CString m_sLastRequest; + CString m_sLastRequest; }; -void CRouteTimeout::RunJob() -{ - CRouteRepliesMod *pMod = (CRouteRepliesMod *) GetModule(); +void CRouteTimeout::RunJob() { + CRouteRepliesMod* pMod = (CRouteRepliesMod*)GetModule(); pMod->Timeout(); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("route_replies"); } -NETWORKMODULEDEFS(CRouteRepliesMod, "Send replies (e.g. to /who) to the right client only") +NETWORKMODULEDEFS(CRouteRepliesMod, + "Send replies (e.g. to /who) to the right client only") diff --git a/modules/sample.cpp b/modules/sample.cpp index 2d47602b..315b773e 100644 --- a/modules/sample.cpp +++ b/modules/sample.cpp @@ -22,8 +22,9 @@ using std::vector; #ifdef HAVE_PTHREAD class CSampleJob : public CModuleJob { -public: - CSampleJob(CModule *pModule) : CModuleJob(pModule, "sample", "Message the user after a delay") {} + public: + CSampleJob(CModule* pModule) + : CModuleJob(pModule, "sample", "Message the user after a delay") {} ~CSampleJob() { if (wasCancelled()) { @@ -40,64 +41,59 @@ public: for (int i = 0; i < 10; i++) { // Regularly check if we were cancelled - if (wasCancelled()) - return; + if (wasCancelled()) return; sleep(1); } } - void runMain() override { - GetModule()->PutModule("Sample job done"); - } + void runMain() override { GetModule()->PutModule("Sample job done"); } }; #endif class CSampleTimer : public CTimer { -public: - - CSampleTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} + public: + CSampleTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CSampleTimer() {} -private: -protected: - void RunJob() override { - GetModule()->PutModule("TEST!!!!"); - } + private: + protected: + void RunJob() override { GetModule()->PutModule("TEST!!!!"); } }; class CSampleMod : public CModule { -public: + public: MODCONSTRUCTOR(CSampleMod) {} bool OnLoad(const CString& sArgs, CString& sMessage) override { PutModule("I'm being loaded with the arguments: [" + sArgs + "]"); - //AddTimer(new CSampleTimer(this, 300, 0, "Sample", "Sample timer for sample things.")); - //AddTimer(new CSampleTimer(this, 5, 20, "Another", "Another sample timer.")); - //AddTimer(new CSampleTimer(this, 25000, 5, "Third", "A third sample timer.")); +// AddTimer(new CSampleTimer(this, 300, 0, "Sample", "Sample timer for sample +// things.")); +// AddTimer(new CSampleTimer(this, 5, 20, "Another", "Another sample timer.")); +// AddTimer(new CSampleTimer(this, 25000, 5, "Third", "A third sample timer.")); #ifdef HAVE_PTHREAD AddJob(new CSampleJob(this)); #endif return true; } - virtual ~CSampleMod() { - PutModule("I'm being unloaded!"); - } + virtual ~CSampleMod() { PutModule("I'm being unloaded!"); } bool OnBoot() override { - // This is called when the app starts up (only modules that are loaded in the config will get this event) + // This is called when the app starts up (only modules that are loaded + // in the config will get this event) return true; } - void OnIRCConnected() override { - PutModule("You got connected BoyOh."); - } + void OnIRCConnected() override { PutModule("You got connected BoyOh."); } void OnIRCDisconnected() override { PutModule("You got disconnected BoyOh."); } - EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName) override { + EModRet OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, + CString& sRealName) override { sRealName += " - ZNC"; return CONTINUE; } @@ -108,28 +104,47 @@ public: return CONTINUE; } - void OnChanPermission(const CNick& OpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) override { - PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + "] set mode [" + Channel.GetName() + ((bAdded) ? "] +" : "] -") + CString(uMode) + " " + Nick.GetNick()); + void OnChanPermission(const CNick& OpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange) override { + PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + + "] set mode [" + Channel.GetName() + + ((bAdded) ? "] +" : "] -") + CString(uMode) + " " + + Nick.GetNick()); } - void OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { - PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + "] opped [" + Nick.GetNick() + "] on [" + Channel.GetName() + "]"); + void OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { + PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + + "] opped [" + Nick.GetNick() + "] on [" + Channel.GetName() + + "]"); } - void OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { - PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + "] deopped [" + Nick.GetNick() + "] on [" + Channel.GetName() + "]"); + void OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { + PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + + "] deopped [" + Nick.GetNick() + "] on [" + + Channel.GetName() + "]"); } - void OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { - PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + "] voiced [" + Nick.GetNick() + "] on [" + Channel.GetName() + "]"); + void OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { + PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + + "] voiced [" + Nick.GetNick() + "] on [" + Channel.GetName() + + "]"); } - void OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) override { - PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + "] devoiced [" + Nick.GetNick() + "] on [" + Channel.GetName() + "]"); + void OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) override { + PutModule(((bNoChange) ? "[0] [" : "[1] [") + OpNick.GetNick() + + "] devoiced [" + Nick.GetNick() + "] on [" + + Channel.GetName() + "]"); } - void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override { - PutModule("* " + OpNick.GetNick() + " sets mode: " + sModes + " " + sArgs + " (" + Channel.GetName() + ")"); + void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override { + PutModule("* " + OpNick.GetNick() + " sets mode: " + sModes + " " + + sArgs + " (" + Channel.GetName() + ")"); } EModRet OnRaw(CString& sLine) override { @@ -142,12 +157,17 @@ public: return CONTINUE; } - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override { - PutModule("[" + OpNick.GetNick() + "] kicked [" + sKickedNick + "] from [" + Channel.GetName() + "] with the msg [" + sMessage + "]"); + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override { + PutModule("[" + OpNick.GetNick() + "] kicked [" + sKickedNick + + "] from [" + Channel.GetName() + "] with the msg [" + + sMessage + "]"); } - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override { - PutModule("* Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + Nick.GetHost() + ") (" + sMessage + ")"); + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override { + PutModule("* Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + + Nick.GetHost() + ") (" + sMessage + ")"); } EModRet OnTimerAutoJoin(CChan& Channel) override { @@ -156,16 +176,20 @@ public: } void OnJoin(const CNick& Nick, CChan& Channel) override { - PutModule("* Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + Nick.GetHost() + ")"); + PutModule("* Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + + Nick.GetHost() + ")"); } - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override { - PutModule("* Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + Nick.GetHost() + ")"); + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override { + PutModule("* Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "!" + + Nick.GetHost() + ")"); } EModRet OnInvite(const CNick& Nick, const CString& sChan) override { if (sChan.Equals("#test")) { - PutModule(Nick.GetNick() + " invited us to " + sChan + ", ignoring invites to " + sChan); + PutModule(Nick.GetNick() + " invited us to " + sChan + + ", ignoring invites to " + sChan); return HALT; } @@ -173,7 +197,8 @@ public: return CONTINUE; } - void OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) override { + void OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) override { PutModule("* " + OldNick.GetNick() + " is now known as " + sNewNick); } @@ -203,8 +228,10 @@ public: return CONTINUE; } - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { - PutModule("[" + Nick.GetNick() + "] chanctcp [" + sMessage + "] to [" + Channel.GetName() + "]"); + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { + PutModule("[" + Nick.GetNick() + "] chanctcp [" + sMessage + "] to [" + + Channel.GetName() + "]"); sMessage = "\00311,5 " + sMessage + " \003"; return CONTINUE; @@ -224,21 +251,25 @@ public: return CONTINUE; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { - PutModule("[" + Nick.GetNick() + "] channotice [" + sMessage + "] to [" + Channel.GetName() + "]"); + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { + PutModule("[" + Nick.GetNick() + "] channotice [" + sMessage + + "] to [" + Channel.GetName() + "]"); sMessage = "\00311,5 " + sMessage + " \003"; return CONTINUE; } EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override { - PutModule("* " + Nick.GetNick() + " changes topic on " + Channel.GetName() + " to '" + sTopic + "'"); + PutModule("* " + Nick.GetNick() + " changes topic on " + + Channel.GetName() + " to '" + sTopic + "'"); return CONTINUE; } EModRet OnUserTopic(CString& sTarget, CString& sTopic) override { - PutModule("* " + GetClient()->GetNick() + " changed topic on " + sTarget + " to '" + sTopic + "'"); + PutModule("* " + GetClient()->GetNick() + " changed topic on " + + sTarget + " to '" + sTopic + "'"); return CONTINUE; } @@ -285,11 +316,11 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("sample"); Info.SetHasArgs(true); Info.SetArgsHelpText("Description of module arguments goes here."); } MODULEDEFS(CSampleMod, "To be used as a sample for writing modules") - diff --git a/modules/sasl.cpp b/modules/sasl.cpp index b7a5af90..dfa6f2cc 100644 --- a/modules/sasl.cpp +++ b/modules/sasl.cpp @@ -19,38 +19,30 @@ #include static const struct { - const char *szName; - const char *szDescription; - const bool bDefault; + const char* szName; + const char* szDescription; + const bool bDefault; } SupportedMechanisms[] = { - { "EXTERNAL", "TLS certificate, for use with the *cert module", true }, - { "PLAIN", "Plain text negotiation, this should work always if the network supports SASL", true } -}; + {"EXTERNAL", "TLS certificate, for use with the *cert module", true}, + {"PLAIN", + "Plain text negotiation, this should work always if the network " + "supports SASL", + true}}; -#define NV_REQUIRE_AUTH "require_auth" -#define NV_MECHANISMS "mechanisms" +#define NV_REQUIRE_AUTH "require_auth" +#define NV_MECHANISMS "mechanisms" class Mechanisms : public VCString { -public: - void SetIndex(unsigned int uiIndex) { - m_uiIndex = uiIndex; - } + public: + void SetIndex(unsigned int uiIndex) { m_uiIndex = uiIndex; } - unsigned int GetIndex() const { - return m_uiIndex; - } + unsigned int GetIndex() const { return m_uiIndex; } - bool HasNext() const { - return size() > (m_uiIndex + 1); - } + bool HasNext() const { return size() > (m_uiIndex + 1); } - void IncrementIndex() { - m_uiIndex++; - } + void IncrementIndex() { m_uiIndex++; } - CString GetCurrent() const { - return at(m_uiIndex); - } + CString GetCurrent() const { return at(m_uiIndex); } CString GetNext() const { if (HasNext()) { @@ -60,21 +52,28 @@ public: return ""; } -private: + private: unsigned int m_uiIndex = 0; }; class CSASLMod : public CModule { -public: + public: MODCONSTRUCTOR(CSASLMod) { - AddCommand("Help", static_cast(&CSASLMod::PrintHelp), - "search", "Generate this output"); - AddCommand("Set", static_cast(&CSASLMod::Set), - " []", "Set username and password for the mechanisms that need them. Password is optional"); - AddCommand("Mechanism", static_cast(&CSASLMod::SetMechanismCommand), - "[mechanism[ ...]]", "Set the mechanisms to be attempted (in order)"); - AddCommand("RequireAuth", static_cast(&CSASLMod::RequireAuthCommand), - "[yes|no]", "Don't connect unless SASL authentication succeeds"); + AddCommand("Help", + static_cast(&CSASLMod::PrintHelp), + "search", "Generate this output"); + AddCommand("Set", static_cast(&CSASLMod::Set), + " []", + "Set username and password for the mechanisms that need " + "them. Password is optional"); + AddCommand("Mechanism", static_cast( + &CSASLMod::SetMechanismCommand), + "[mechanism[ ...]]", + "Set the mechanisms to be attempted (in order)"); + AddCommand( + "RequireAuth", + static_cast(&CSASLMod::RequireAuthCommand), + "[yes|no]", "Don't connect unless SASL authentication succeeds"); m_bAuthenticated = false; } @@ -88,7 +87,7 @@ public: for (const auto& it : SupportedMechanisms) { Mechanisms.AddRow(); - Mechanisms.SetCell("Mechanism", it.szName); + Mechanisms.SetCell("Mechanism", it.szName); Mechanisms.SetCell("Description", it.szDescription); } @@ -179,7 +178,8 @@ public: void Authenticate(const CString& sLine) { if (m_Mechanisms.GetCurrent().Equals("PLAIN") && sLine.Equals("+")) { - CString sAuthLine = GetNV("username") + '\0' + GetNV("username") + '\0' + GetNV("password"); + CString sAuthLine = GetNV("username") + '\0' + GetNV("username") + + '\0' + GetNV("password"); sAuthLine.Base64Encode(); PutIRC("AUTHENTICATE " + sAuthLine); } else { @@ -212,16 +212,19 @@ public: } } - EModRet OnRaw(CString &sLine) override { + EModRet OnRaw(CString& sLine) override { if (sLine.Token(0).Equals("AUTHENTICATE")) { Authenticate(sLine.Token(1, true)); } else if (sLine.Token(1).Equals("903")) { /* SASL success! */ GetNetwork()->GetIRCSock()->ResumeCap(); m_bAuthenticated = true; - DEBUG("sasl: Authenticated with mechanism [" << m_Mechanisms.GetCurrent() << "]"); - } else if (sLine.Token(1).Equals("904") || sLine.Token(1).Equals("905")) { - DEBUG("sasl: Mechanism [" << m_Mechanisms.GetCurrent() << "] failed."); + DEBUG("sasl: Authenticated with mechanism [" + << m_Mechanisms.GetCurrent() << "]"); + } else if (sLine.Token(1).Equals("904") || + sLine.Token(1).Equals("905")) { + DEBUG("sasl: Mechanism [" << m_Mechanisms.GetCurrent() + << "] failed."); PutModule(m_Mechanisms.GetCurrent() + " mechanism failed."); if (m_Mechanisms.HasNext()) { @@ -253,13 +256,12 @@ public: CheckRequireAuth(); } - void OnIRCDisconnected() override { - m_bAuthenticated = false; - } + void OnIRCDisconnected() override { m_bAuthenticated = false; } CString GetWebMenuTitle() override { return "SASL"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName != "index") { // only accept requests to index return false; @@ -290,13 +292,16 @@ public: return true; } -private: + private: Mechanisms m_Mechanisms; bool m_bAuthenticated; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("sasl"); } -NETWORKMODULEDEFS(CSASLMod, "Adds support for sasl authentication capability to authenticate to an IRC server") +NETWORKMODULEDEFS(CSASLMod, + "Adds support for sasl authentication capability to " + "authenticate to an IRC server") diff --git a/modules/savebuff.cpp b/modules/savebuff.cpp index 99739b65..386c4366 100644 --- a/modules/savebuff.cpp +++ b/modules/savebuff.cpp @@ -36,106 +36,110 @@ using std::vector; #define LEGACY_VERIFICATION_TOKEN "::__:SAVEBUFF:__::" #define CHAN_VERIFICATION_TOKEN "::__:CHANBUFF:__::" #define QUERY_VERIFICATION_TOKEN "::__:QUERYBUFF:__::" -// this is basically plain text, but so is having the pass in the command line so *shrug* +// this is basically plain text, but so is having the pass in the command line +// so *shrug* // you could at least do something kind of cool like a bunch of unprintable text #define CRYPT_LAME_PASS "::__:NOPASS:__::" #define CRYPT_ASK_PASS "--ask-pass" class CSaveBuff; -class CSaveBuffJob : public CTimer -{ -public: - CSaveBuffJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} +class CSaveBuffJob : public CTimer { + public: + CSaveBuffJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CSaveBuffJob() {} -protected: + protected: void RunJob() override; }; -class CSaveBuff : public CModule -{ -public: - MODCONSTRUCTOR(CSaveBuff) - { +class CSaveBuff : public CModule { + public: + MODCONSTRUCTOR(CSaveBuff) { m_bBootError = false; AddHelpCommand(); - AddCommand("SetPass", static_cast(&CSaveBuff::OnSetPassCommand), "", "Sets the password"); - AddCommand("Replay", static_cast(&CSaveBuff::OnReplayCommand), "", "Replays the buffer"); - AddCommand("Save", static_cast(&CSaveBuff::OnSaveCommand), "", "Saves all buffers"); + AddCommand("SetPass", static_cast( + &CSaveBuff::OnSetPassCommand), + "", "Sets the password"); + AddCommand("Replay", static_cast( + &CSaveBuff::OnReplayCommand), + "", "Replays the buffer"); + AddCommand("Save", static_cast( + &CSaveBuff::OnSaveCommand), + "", "Saves all buffers"); } - virtual ~CSaveBuff() - { - if (!m_bBootError) - { + virtual ~CSaveBuff() { + if (!m_bBootError) { SaveBuffersToDisk(); } } - bool OnLoad(const CString& sArgs, CString& sMessage) override - { - if( sArgs == CRYPT_ASK_PASS ) - { - char *pPass = getpass( "Enter pass for savebuff: " ); - if( pPass ) - m_sPassword = CBlowfish::MD5( pPass ); - else - { + bool OnLoad(const CString& sArgs, CString& sMessage) override { + if (sArgs == CRYPT_ASK_PASS) { + char* pPass = getpass("Enter pass for savebuff: "); + if (pPass) + m_sPassword = CBlowfish::MD5(pPass); + else { m_bBootError = true; sMessage = "Nothing retrieved from console. aborting"; } - } - else if( sArgs.empty() ) - m_sPassword = CBlowfish::MD5( CRYPT_LAME_PASS ); + } else if (sArgs.empty()) + m_sPassword = CBlowfish::MD5(CRYPT_LAME_PASS); else m_sPassword = CBlowfish::MD5(sArgs); - AddTimer(new CSaveBuffJob(this, 60, 0, "SaveBuff", "Saves the current buffer to disk every 1 minute")); + AddTimer(new CSaveBuffJob( + this, 60, 0, "SaveBuff", + "Saves the current buffer to disk every 1 minute")); - return( !m_bBootError ); + return (!m_bBootError); } - bool OnBoot() override - { + bool OnBoot() override { CDir saveDir(GetSavePath()); for (CFile* pFile : saveDir) { CString sName; CString sBuffer; - EBufferType eType = DecryptBuffer(pFile->GetLongName(), sBuffer, sName); + EBufferType eType = + DecryptBuffer(pFile->GetLongName(), sBuffer, sName); switch (eType) { - case InvalidBuffer: - m_sPassword = ""; - CUtils::PrintError("[" + GetModName() + ".so] Failed to Decrypt [" + pFile->GetLongName() + "]"); - if (!sName.empty()) { - PutUser(":***!znc@znc.in PRIVMSG " + sName + " :Failed to decrypt this buffer, did you change the encryption pass?"); - } - break; - case ChanBuffer: - if (CChan *pChan = GetNetwork()->FindChan(sName)) { - BootStrap(pChan, sBuffer); - } - break; - case QueryBuffer: - if (CQuery* pQuery = GetNetwork()->AddQuery(sName)) { - BootStrap(pQuery, sBuffer); - } - break; - default: - break; + case InvalidBuffer: + m_sPassword = ""; + CUtils::PrintError("[" + GetModName() + + ".so] Failed to Decrypt [" + + pFile->GetLongName() + "]"); + if (!sName.empty()) { + PutUser(":***!znc@znc.in PRIVMSG " + sName + + " :Failed to decrypt this buffer, did you " + "change the encryption pass?"); + } + break; + case ChanBuffer: + if (CChan* pChan = GetNetwork()->FindChan(sName)) { + BootStrap(pChan, sBuffer); + } + break; + case QueryBuffer: + if (CQuery* pQuery = GetNetwork()->AddQuery(sName)) { + BootStrap(pQuery, sBuffer); + } + break; + default: + break; } } return true; } - template - void BootStrap(T *pTarget, const CString& sContent) - { + template + void BootStrap(T* pTarget, const CString& sContent) { if (!pTarget->GetBuffer().IsEmpty()) - return; // in this case the module was probably reloaded + return; // in this case the module was probably reloaded VCString vsLines; VCString::iterator it; @@ -145,8 +149,7 @@ public: for (it = vsLines.begin(); it != vsLines.end(); ++it) { CString sLine(*it); sLine.Trim(); - if (sLine[0] == '@' && it+1 != vsLines.end()) - { + if (sLine[0] == '@' && it + 1 != vsLines.end()) { CString sTimestamp = sLine.Token(0); sTimestamp.TrimLeft("@"); timeval ts; @@ -159,16 +162,15 @@ public: sText.Trim(); pTarget->AddBuffer(sFormat, sText, &ts); - } else - { + } else { // Old format, escape the line and use as is. pTarget->AddBuffer(_NAMEDFMT(sLine)); } } } - void SaveBufferToDisk(const CBuffer& Buffer, const CString& sPath, const CString& sHeader) - { + void SaveBufferToDisk(const CBuffer& Buffer, const CString& sPath, + const CString& sHeader) { CFile File(sPath); CString sContent = sHeader + "\n"; @@ -176,10 +178,8 @@ public: for (unsigned int uIdx = 0; uIdx < uSize; uIdx++) { const CBufLine& Line = Buffer.GetBufLine(uIdx); timeval ts = Line.GetTime(); - sContent += - "@" + CString(ts.tv_sec) + "," + CString(ts.tv_usec) + " " + - Line.GetFormat() + "\n" + - Line.GetText() + "\n"; + sContent += "@" + CString(ts.tv_sec) + "," + CString(ts.tv_usec) + + " " + Line.GetFormat() + "\n" + Line.GetText() + "\n"; } CBlowfish c(m_sPassword, BF_ENCRYPT); @@ -192,23 +192,23 @@ public: File.Close(); } - void SaveBuffersToDisk() - { - if (!m_sPassword.empty()) - { + void SaveBuffersToDisk() { + if (!m_sPassword.empty()) { set ssPaths; const vector& vChans = GetNetwork()->GetChans(); for (CChan* pChan : vChans) { CString sPath = GetPath(pChan->GetName()); - SaveBufferToDisk(pChan->GetBuffer(), sPath, CHAN_VERIFICATION_TOKEN + pChan->GetName()); + SaveBufferToDisk(pChan->GetBuffer(), sPath, + CHAN_VERIFICATION_TOKEN + pChan->GetName()); ssPaths.insert(sPath); } const vector& vQueries = GetNetwork()->GetQueries(); for (CQuery* pQuery : vQueries) { CString sPath = GetPath(pQuery->GetName()); - SaveBufferToDisk(pQuery->GetBuffer(), sPath, QUERY_VERIFICATION_TOKEN + pQuery->GetName()); + SaveBufferToDisk(pQuery->GetBuffer(), sPath, + QUERY_VERIFICATION_TOKEN + pQuery->GetName()); ssPaths.insert(sPath); } @@ -219,35 +219,32 @@ public: pFile->Delete(); } } - } - else - { - PutModule( "Password is unset usually meaning the decryption failed. You can setpass to the appropriate pass and things should start working, or setpass to a new pass and save to reinstantiate" ); + } else { + PutModule( + "Password is unset usually meaning the decryption failed. You " + "can setpass to the appropriate pass and things should start " + "working, or setpass to a new pass and save to reinstantiate"); } } - void OnSetPassCommand(const CString& sCmdLine) - { + void OnSetPassCommand(const CString& sCmdLine) { CString sArgs = sCmdLine.Token(1, true); - if(sArgs.empty()) - sArgs = CRYPT_LAME_PASS; + if (sArgs.empty()) sArgs = CRYPT_LAME_PASS; PutModule("Password set to [" + sArgs + "]"); m_sPassword = CBlowfish::MD5(sArgs); } - void OnModCommand(const CString& sCmdLine) override - { + void OnModCommand(const CString& sCmdLine) override { CString sCommand = sCmdLine.Token(0); - CString sArgs = sCmdLine.Token(1, true); + CString sArgs = sCmdLine.Token(1, true); if (sCommand.Equals("dumpbuff")) { // for testing purposes - hidden from help CString sFile; CString sName; - if (DecryptBuffer(GetPath(sArgs), sFile, sName)) - { + if (DecryptBuffer(GetPath(sArgs), sFile, sName)) { VCString vsLines; sFile.Split("\n", vsLines); @@ -261,27 +258,23 @@ public: } } - void OnReplayCommand(const CString& sCmdLine) - { + void OnReplayCommand(const CString& sCmdLine) { CString sArgs = sCmdLine.Token(1, true); Replay(sArgs); PutModule("Replayed " + sArgs); } - void OnSaveCommand(const CString& sCmdLine) - { + void OnSaveCommand(const CString& sCmdLine) { SaveBuffersToDisk(); PutModule("Done."); } - void Replay(const CString & sBuffer) - { + void Replay(const CString& sBuffer) { CString sFile; CString sName; PutUser(":***!znc@znc.in PRIVMSG " + sBuffer + " :Buffer Playback..."); - if (DecryptBuffer(GetPath(sBuffer), sFile, sName)) - { + if (DecryptBuffer(GetPath(sBuffer), sFile, sName)) { VCString vsLines; sFile.Split("\n", vsLines); @@ -292,16 +285,14 @@ public: PutUser(":***!znc@znc.in PRIVMSG " + sBuffer + " :Playback Complete."); } - CString GetPath(const CString & sTarget) const - { + CString GetPath(const CString& sTarget) const { CString sBuffer = GetUser()->GetUserName() + sTarget.AsLower(); CString sRet = GetSavePath(); sRet += "/" + CBlowfish::MD5(sBuffer, true); - return(sRet); + return (sRet); } - CString FindLegacyBufferName(const CString & sPath) const - { + CString FindLegacyBufferName(const CString& sPath) const { const vector& vChans = GetNetwork()->GetChans(); for (CChan* pChan : vChans) { const CString& sName = pChan->GetName(); @@ -312,8 +303,8 @@ public: return CString(); } -private: - bool m_bBootError; + private: + bool m_bBootError; CString m_sPassword; enum EBufferType { @@ -323,39 +314,31 @@ private: QueryBuffer }; - EBufferType DecryptBuffer(const CString& sPath, CString& sBuffer, CString& sName) - { + EBufferType DecryptBuffer(const CString& sPath, CString& sBuffer, + CString& sName) { CString sContent; sBuffer = ""; CFile File(sPath); if (sPath.empty() || !File.Open() || !File.ReadFile(sContent)) - return EmptyBuffer; + return EmptyBuffer; File.Close(); - if (!sContent.empty()) - { + if (!sContent.empty()) { CBlowfish c(m_sPassword, BF_DECRYPT); sBuffer = c.Crypt(sContent); - if (sBuffer.TrimPrefix(LEGACY_VERIFICATION_TOKEN)) - { + if (sBuffer.TrimPrefix(LEGACY_VERIFICATION_TOKEN)) { sName = FindLegacyBufferName(sPath); return ChanBuffer; - } - else if (sBuffer.TrimPrefix(CHAN_VERIFICATION_TOKEN)) - { + } else if (sBuffer.TrimPrefix(CHAN_VERIFICATION_TOKEN)) { sName = sBuffer.FirstLine(); - if (sBuffer.TrimLeft(sName + "\n")) - return ChanBuffer; - } - else if (sBuffer.TrimPrefix(QUERY_VERIFICATION_TOKEN)) - { + if (sBuffer.TrimLeft(sName + "\n")) return ChanBuffer; + } else if (sBuffer.TrimPrefix(QUERY_VERIFICATION_TOKEN)) { sName = sBuffer.FirstLine(); - if (sBuffer.TrimLeft(sName + "\n")) - return QueryBuffer; + if (sBuffer.TrimLeft(sName + "\n")) return QueryBuffer; } PutModule("Unable to decode Encrypted file [" + sPath + "]"); @@ -365,18 +348,19 @@ private: } }; - -void CSaveBuffJob::RunJob() -{ - CSaveBuff *p = (CSaveBuff *)GetModule(); +void CSaveBuffJob::RunJob() { + CSaveBuff* p = (CSaveBuff*)GetModule(); p->SaveBuffersToDisk(); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("savebuff"); Info.SetHasArgs(true); - Info.SetArgsHelpText("This user module takes up to one arguments. Either --ask-pass or the password itself (which may contain spaces) or nothing"); + Info.SetArgsHelpText( + "This user module takes up to one arguments. Either --ask-pass or the " + "password itself (which may contain spaces) or nothing"); } -NETWORKMODULEDEFS(CSaveBuff, "Stores channel and query buffers to disk, encrypted") - +NETWORKMODULEDEFS(CSaveBuff, + "Stores channel and query buffers to disk, encrypted") diff --git a/modules/schat.cpp b/modules/schat.cpp index e56a83cc..709f97e6 100644 --- a/modules/schat.cpp +++ b/modules/schat.cpp @@ -33,63 +33,55 @@ using std::vector; class CSChat; -class CRemMarkerJob : public CTimer -{ -public: - CRemMarkerJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, - const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} +class CRemMarkerJob : public CTimer { + public: + CRemMarkerJob(CModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CRemMarkerJob() {} - void SetNick(const CString & sNick) - { - m_sNick = sNick; - } + void SetNick(const CString& sNick) { m_sNick = sNick; } -protected: + protected: void RunJob() override; CString m_sNick; }; -class CSChatSock : public CSocket -{ -public: - CSChatSock(CSChat *pMod, const CString& sChatNick); - CSChatSock(CSChat *pMod, const CString& sChatNick, const CString& sHost, - u_short iPort, int iTimeout = 60); +class CSChatSock : public CSocket { + public: + CSChatSock(CSChat* pMod, const CString& sChatNick); + CSChatSock(CSChat* pMod, const CString& sChatNick, const CString& sHost, + u_short iPort, int iTimeout = 60); ~CSChatSock() {} - Csock *GetSockObj(const CS_STRING & sHostname, u_short iPort) override - { - CSChatSock *p = new CSChatSock(m_pModule, m_sChatNick, sHostname, iPort); - return(p); + Csock* GetSockObj(const CS_STRING& sHostname, u_short iPort) override { + CSChatSock* p = + new CSChatSock(m_pModule, m_sChatNick, sHostname, iPort); + return (p); } - bool ConnectionFrom(const CS_STRING & sHost, u_short iPort) override - { - Close(); // close the listener after the first connection - return(true); + bool ConnectionFrom(const CS_STRING& sHost, u_short iPort) override { + Close(); // close the listener after the first connection + return (true); } void Connected() override; void Timeout() override; - const CString & GetChatNick() const { return(m_sChatNick); } + const CString& GetChatNick() const { return (m_sChatNick); } void PutQuery(const CString& sText); - void ReadLine(const CS_STRING & sLine) override; + void ReadLine(const CS_STRING& sLine) override; void Disconnected() override; - void AddLine(const CString & sLine) - { + void AddLine(const CString& sLine) { m_vBuffer.insert(m_vBuffer.begin(), sLine); - if (m_vBuffer.size() > 200) - m_vBuffer.pop_back(); + if (m_vBuffer.size() > 200) m_vBuffer.pop_back(); } - void DumpBuffer() - { + void DumpBuffer() { if (m_vBuffer.empty()) { // Always show a message to the user, so he knows // this schat still exists. @@ -97,27 +89,24 @@ public: } else { // Buffer playback vector::reverse_iterator it = m_vBuffer.rbegin(); - for (; it != m_vBuffer.rend(); ++it) - ReadLine(*it); + for (; it != m_vBuffer.rend(); ++it) ReadLine(*it); m_vBuffer.clear(); } } -private: - CSChat *m_pModule; - CString m_sChatNick; + private: + CSChat* m_pModule; + CString m_sChatNick; VCString m_vBuffer; }; -class CSChat : public CModule -{ -public: +class CSChat : public CModule { + public: MODCONSTRUCTOR(CSChat) {} virtual ~CSChat() {} - bool OnLoad(const CString & sArgs, CString & sMessage) override - { + bool OnLoad(const CString& sArgs, CString& sMessage) override { m_sPemFile = sArgs; if (m_sPemFile.empty()) { @@ -132,36 +121,32 @@ public: return true; } - void OnClientLogin() override - { + void OnClientLogin() override { set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CSChatSock *p = (CSChatSock*) *it; + CSChatSock* p = (CSChatSock*)*it; - if (p->GetType() == CSChatSock::LISTENER) - continue; + if (p->GetType() == CSChatSock::LISTENER) continue; p->DumpBuffer(); } } - EModRet OnUserRaw(CString & sLine) override - { + EModRet OnUserRaw(CString& sLine) override { if (sLine.StartsWith("schat ")) { OnModCommand("chat " + sLine.substr(6)); - return(HALT); + return (HALT); } else if (sLine.Equals("schat")) { PutModule("SChat User Area ..."); OnModCommand("help"); - return(HALT); + return (HALT); } - return(CONTINUE); + return (CONTINUE); } - void OnModCommand(const CString& sCommand) override - { + void OnModCommand(const CString& sCommand) override { CString sCom = sCommand.Token(0); CString sArgs = sCommand.Token(1, true); @@ -169,7 +154,7 @@ public: CString sNick = "(s)" + sArgs; set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CSChatSock *pSock = (CSChatSock*) *it; + CSChatSock* pSock = (CSChatSock*)*it; if (pSock->GetChatNick().Equals(sNick)) { PutModule("Already Connected to [" + sArgs + "]"); @@ -177,12 +162,13 @@ public: } } - CSChatSock *pSock = new CSChatSock(this, sNick); + CSChatSock* pSock = new CSChatSock(this, sNick); pSock->SetCipher("HIGH"); pSock->SetPemLocation(m_sPemFile); - u_short iPort = GetManager()->ListenRand(pSock->GetSockName() + "::LISTENER", - GetUser()->GetLocalDCCIP(), true, SOMAXCONN, pSock, 60); + u_short iPort = GetManager()->ListenRand( + pSock->GetSockName() + "::LISTENER", GetUser()->GetLocalDCCIP(), + true, SOMAXCONN, pSock, 60); if (iPort == 0) { PutModule("Failed to start chat!"); @@ -210,11 +196,11 @@ public: for (it = BeginSockets(); it != EndSockets(); ++it) { Table.AddRow(); - CSChatSock *pSock = (CSChatSock*) *it; + CSChatSock* pSock = (CSChatSock*)*it; Table.SetCell("Nick", pSock->GetChatNick()); unsigned long long iStartTime = pSock->GetStartTime(); time_t iTime = iStartTime / 1000; - char *pTime = ctime(&iTime); + char* pTime = ctime(&iTime); if (pTime) { CString sTime = pTime; sTime.Trim(); @@ -225,7 +211,7 @@ public: Table.SetCell("Status", "Established"); Table.SetCell("Host", pSock->GetRemoteIP()); Table.SetCell("Port", CString(pSock->GetRemotePort())); - SSL_SESSION *pSession = pSock->GetSSLSession(); + SSL_SESSION* pSession = pSock->GetSSLSession(); if (pSession && pSession->cipher && pSession->cipher->name) Table.SetCell("Cipher", pSession->cipher->name); @@ -240,12 +226,11 @@ public: PutModule("No SDCCs currently in session"); } else if (sCom.Equals("close")) { - if (!sArgs.StartsWith("(s)")) - sArgs = "(s)" + sArgs; + if (!sArgs.StartsWith("(s)")) sArgs = "(s)" + sArgs; set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { - CSChatSock *pSock = (CSChatSock*) *it; + CSChatSock* pSock = (CSChatSock*)*it; if (sArgs.Equals(pSock->GetChatNick())) { pSock->Close(); @@ -265,11 +250,11 @@ public: set::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { Table.AddRow(); - Csock *pSock = *it; + Csock* pSock = *it; Table.SetCell("SockName", pSock->GetSockName()); unsigned long long iStartTime = pSock->GetStartTime(); time_t iTime = iStartTime / 1000; - char *pTime = ctime(&iTime); + char* pTime = ctime(&iTime); if (pTime) { CString sTime = pTime; sTime.Trim(); @@ -281,11 +266,13 @@ public: Table.SetCell("Type", "Outbound"); else Table.SetCell("Type", "Inbound"); - Table.SetCell("LocalIP:Port", pSock->GetLocalIP() + ":" + - CString(pSock->GetLocalPort())); - Table.SetCell("RemoteIP:Port", pSock->GetRemoteIP() + ":" + - CString(pSock->GetRemotePort())); - SSL_SESSION *pSession = pSock->GetSSLSession(); + Table.SetCell("LocalIP:Port", + pSock->GetLocalIP() + ":" + + CString(pSock->GetLocalPort())); + Table.SetCell("RemoteIP:Port", + pSock->GetRemoteIP() + ":" + + CString(pSock->GetRemotePort())); + SSL_SESSION* pSession = pSock->GetSSLSession(); if (pSession && pSession->cipher && pSession->cipher->name) Table.SetCell("Cipher", pSession->cipher->name); else @@ -293,8 +280,9 @@ public: } else { Table.SetCell("Type", "Listener"); - Table.SetCell("LocalIP:Port", pSock->GetLocalIP() + - ":" + CString(pSock->GetLocalPort())); + Table.SetCell("LocalIP:Port", + pSock->GetLocalIP() + ":" + + CString(pSock->GetLocalPort())); Table.SetCell("RemoteIP:Port", "0.0.0.0:0"); } } @@ -319,8 +307,7 @@ public: PutModule("Unknown command [" + sCom + "] [" + sArgs + "]"); } - EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override - { + EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override { if (sMessage.StartsWith("DCC SCHAT ")) { // chat ip port unsigned long iIP = sMessage.Token(3).ToULong(); @@ -332,95 +319,92 @@ public: pTmp.first = iIP; pTmp.second = iPort; - sMask = "(s)" + Nick.GetNick() + "!" + "(s)" + - Nick.GetNick() + "@" + CUtils::GetIP(iIP); + sMask = "(s)" + Nick.GetNick() + "!" + "(s)" + Nick.GetNick() + + "@" + CUtils::GetIP(iIP); m_siiWaitingChats["(s)" + Nick.GetNick()] = pTmp; SendToUser(sMask, "*** Incoming DCC SCHAT, Accept ? (yes/no)"); - CRemMarkerJob *p = new CRemMarkerJob(this, 60, 1, - "Remove (s)" + Nick.GetNick(), - "Removes this nicks entry for waiting DCC."); + CRemMarkerJob* p = new CRemMarkerJob( + this, 60, 1, "Remove (s)" + Nick.GetNick(), + "Removes this nicks entry for waiting DCC."); p->SetNick("(s)" + Nick.GetNick()); AddTimer(p); - return(HALT); + return (HALT); } } - return(CONTINUE); + return (CONTINUE); } - void AcceptSDCC(const CString & sNick, u_long iIP, u_short iPort) - { - CSChatSock *p = new CSChatSock(this, sNick, CUtils::GetIP(iIP), iPort, 60); + void AcceptSDCC(const CString& sNick, u_long iIP, u_short iPort) { + CSChatSock* p = + new CSChatSock(this, sNick, CUtils::GetIP(iIP), iPort, 60); GetManager()->Connect(CUtils::GetIP(iIP), iPort, p->GetSockName(), 60, - true, GetUser()->GetLocalDCCIP(), p); - RemTimer("Remove " + sNick); // delete any associated timer to this nick + true, GetUser()->GetLocalDCCIP(), p); + RemTimer("Remove " + + sNick); // delete any associated timer to this nick } - EModRet OnUserMsg(CString& sTarget, CString& sMessage) override - { + EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { if (sTarget.Left(3) == "(s)") { CString sSockName = GetModName().AsUpper() + "::" + sTarget; - CSChatSock *p = (CSChatSock *)FindSocket(sSockName); + CSChatSock* p = (CSChatSock*)FindSocket(sSockName); if (!p) { - map< CString,pair< u_long,u_short > >::iterator it; + map>::iterator it; it = m_siiWaitingChats.find(sTarget); if (it != m_siiWaitingChats.end()) { if (!sMessage.Equals("yes")) SendToUser(sTarget + "!" + sTarget + "@" + - CUtils::GetIP(it->second.first), - "Refusing to accept DCC SCHAT!"); + CUtils::GetIP(it->second.first), + "Refusing to accept DCC SCHAT!"); else - AcceptSDCC(sTarget, it->second.first, it->second.second); + AcceptSDCC(sTarget, it->second.first, + it->second.second); m_siiWaitingChats.erase(it); - return(HALT); + return (HALT); } PutModule("No such SCHAT to [" + sTarget + "]"); } else p->Write(sMessage + "\n"); - return(HALT); + return (HALT); } - return(CONTINUE); + return (CONTINUE); } - void RemoveMarker(const CString & sNick) - { - map< CString,pair< u_long,u_short > >::iterator it = m_siiWaitingChats.find(sNick); - if (it != m_siiWaitingChats.end()) - m_siiWaitingChats.erase(it); + void RemoveMarker(const CString& sNick) { + map>::iterator it = + m_siiWaitingChats.find(sNick); + if (it != m_siiWaitingChats.end()) m_siiWaitingChats.erase(it); } - void SendToUser(const CString & sFrom, const CString & sText) - { + void SendToUser(const CString& sFrom, const CString& sText) { //:*schat!znc@znc.in PRIVMSG Jim : - CString sSend = ":" + sFrom + " PRIVMSG " + GetNetwork()->GetCurNick() + " :" + sText; + CString sSend = ":" + sFrom + " PRIVMSG " + GetNetwork()->GetCurNick() + + " :" + sText; PutUser(sSend); } - bool IsAttached() - { - return(GetNetwork()->IsUserAttached()); - } + bool IsAttached() { return (GetNetwork()->IsUserAttached()); } -private: - map< CString,pair< u_long,u_short > > m_siiWaitingChats; - CString m_sPemFile; + private: + map> m_siiWaitingChats; + CString m_sPemFile; }; - //////////////////// methods //////////////// -CSChatSock::CSChatSock(CSChat *pMod, const CString& sChatNick) : CSocket(pMod) { +CSChatSock::CSChatSock(CSChat* pMod, const CString& sChatNick) : CSocket(pMod) { m_pModule = pMod; m_sChatNick = sChatNick; SetSockName(pMod->GetModName().AsUpper() + "::" + m_sChatNick); } -CSChatSock::CSChatSock(CSChat *pMod, const CString& sChatNick, const CString& sHost, - u_short iPort, int iTimeout) : CSocket(pMod, sHost, iPort, iTimeout) { +CSChatSock::CSChatSock(CSChat* pMod, const CString& sChatNick, + const CString& sHost, u_short iPort, int iTimeout) + : CSocket(pMod, sHost, iPort, iTimeout) { m_pModule = pMod; EnableReadLine(); m_sChatNick = sChatNick; @@ -428,11 +412,11 @@ CSChatSock::CSChatSock(CSChat *pMod, const CString& sChatNick, const CString& sH } void CSChatSock::PutQuery(const CString& sText) { - m_pModule->SendToUser(m_sChatNick + "!" + m_sChatNick + "@" + GetRemoteIP(), sText); + m_pModule->SendToUser(m_sChatNick + "!" + m_sChatNick + "@" + GetRemoteIP(), + sText); } -void CSChatSock::ReadLine(const CS_STRING & sLine) -{ +void CSChatSock::ReadLine(const CS_STRING& sLine) { if (m_pModule) { CString sText = sLine; @@ -445,42 +429,37 @@ void CSChatSock::ReadLine(const CS_STRING & sLine) } } -void CSChatSock::Disconnected() -{ - if (m_pModule) - PutQuery("*** Disconnected."); +void CSChatSock::Disconnected() { + if (m_pModule) PutQuery("*** Disconnected."); } -void CSChatSock::Connected() -{ +void CSChatSock::Connected() { SetTimeout(0); - if (m_pModule) - PutQuery("*** Connected."); + if (m_pModule) PutQuery("*** Connected."); } -void CSChatSock::Timeout() -{ +void CSChatSock::Timeout() { if (m_pModule) { if (GetType() == LISTENER) - m_pModule->PutModule("Timeout while waiting for [" + m_sChatNick + "]"); + m_pModule->PutModule("Timeout while waiting for [" + m_sChatNick + + "]"); else PutQuery("*** Connection Timed out."); } } -void CRemMarkerJob::RunJob() -{ - CSChat *p = (CSChat *)GetModule(); +void CRemMarkerJob::RunJob() { + CSChat* p = (CSChat*)GetModule(); p->RemoveMarker(m_sNick); // store buffer } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("schat"); Info.SetHasArgs(true); Info.SetArgsHelpText("Path to .pem file, if differs from main ZNC's one"); } NETWORKMODULEDEFS(CSChat, "Secure cross platform (:P) chat system") - diff --git a/modules/send_raw.cpp b/modules/send_raw.cpp index bfa9e4a2..63140209 100644 --- a/modules/send_raw.cpp +++ b/modules/send_raw.cpp @@ -20,18 +20,20 @@ using std::vector; using std::map; -class CSendRaw_Mod: public CModule { +class CSendRaw_Mod : public CModule { void SendClient(const CString& sLine) { - CUser *pUser = CZNC::Get().FindUser(sLine.Token(1)); + CUser* pUser = CZNC::Get().FindUser(sLine.Token(1)); if (pUser) { - CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2)); + CIRCNetwork* pNetwork = pUser->FindNetwork(sLine.Token(2)); if (pNetwork) { pNetwork->PutUser(sLine.Token(3, true)); - PutModule("Sent [" + sLine.Token(3, true) + "] to " + pUser->GetUserName() + "/" + pNetwork->GetName()); + PutModule("Sent [" + sLine.Token(3, true) + "] to " + + pUser->GetUserName() + "/" + pNetwork->GetName()); } else { - PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]"); + PutModule("Network [" + sLine.Token(2) + + "] not found for user [" + sLine.Token(1) + "]"); } } else { PutModule("User [" + sLine.Token(1) + "] not found"); @@ -39,16 +41,19 @@ class CSendRaw_Mod: public CModule { } void SendServer(const CString& sLine) { - CUser *pUser = CZNC::Get().FindUser(sLine.Token(1)); + CUser* pUser = CZNC::Get().FindUser(sLine.Token(1)); if (pUser) { - CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2)); + CIRCNetwork* pNetwork = pUser->FindNetwork(sLine.Token(2)); if (pNetwork) { pNetwork->PutIRC(sLine.Token(3, true)); - PutModule("Sent [" + sLine.Token(3, true) + "] to IRC Server of " + pUser->GetUserName() + "/" + pNetwork->GetName()); + PutModule("Sent [" + sLine.Token(3, true) + + "] to IRC Server of " + pUser->GetUserName() + "/" + + pNetwork->GetName()); } else { - PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]"); + PutModule("Network [" + sLine.Token(2) + + "] not found for user [" + sLine.Token(1) + "]"); } } else { PutModule("User [" + sLine.Token(1) + "] not found"); @@ -60,7 +65,7 @@ class CSendRaw_Mod: public CModule { GetClient()->PutClient(sData); } -public: + public: virtual ~CSendRaw_Mod() {} bool OnLoad(const CString& sArgs, CString& sErrorMsg) override { @@ -75,16 +80,19 @@ public: CString GetWebMenuTitle() override { return "Send Raw"; } bool WebRequiresAdmin() override { return true; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { if (WebSock.IsPost()) { - CUser *pUser = CZNC::Get().FindUser(WebSock.GetParam("network").Token(0, false, "/")); + CUser* pUser = CZNC::Get().FindUser( + WebSock.GetParam("network").Token(0, false, "/")); if (!pUser) { WebSock.GetSession()->AddError("User not found"); return true; } - CIRCNetwork *pNetwork = pUser->FindNetwork(WebSock.GetParam("network").Token(1, false, "/")); + CIRCNetwork* pNetwork = pUser->FindNetwork( + WebSock.GetParam("network").Token(1, false, "/")); if (!pNetwork) { WebSock.GetSession()->AddError("Network not found"); return true; @@ -106,7 +114,7 @@ public: WebSock.GetSession()->AddSuccess("Line sent"); } - const map& msUsers = CZNC::Get().GetUserMap(); + const map& msUsers = CZNC::Get().GetUserMap(); for (const auto& it : msUsers) { CTemplate& l = Tmpl.AddRow("UserLoop"); l["Username"] = it.second->GetUserName(); @@ -127,17 +135,26 @@ public: MODCONSTRUCTOR(CSendRaw_Mod) { AddHelpCommand(); - AddCommand("Client", static_cast(&CSendRaw_Mod::SendClient), - "[user] [network] [data to send]", "The data will be sent to the user's IRC client(s)"); - AddCommand("Server", static_cast(&CSendRaw_Mod::SendServer), - "[user] [network] [data to send]", "The data will be sent to the IRC server the user is connected to"); - AddCommand("Current", static_cast(&CSendRaw_Mod::CurrentClient), - "[data to send]", "The data will be sent to your current client"); + AddCommand("Client", static_cast( + &CSendRaw_Mod::SendClient), + "[user] [network] [data to send]", + "The data will be sent to the user's IRC client(s)"); + AddCommand( + "Server", + static_cast(&CSendRaw_Mod::SendServer), + "[user] [network] [data to send]", + "The data will be sent to the IRC server the user is connected to"); + AddCommand( + "Current", + static_cast(&CSendRaw_Mod::CurrentClient), + "[data to send]", "The data will be sent to your current client"); } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("send_raw"); } -USERMODULEDEFS(CSendRaw_Mod, "Lets you send some raw IRC lines as/to someone else") +USERMODULEDEFS(CSendRaw_Mod, + "Lets you send some raw IRC lines as/to someone else") diff --git a/modules/shell.cpp b/modules/shell.cpp index b1f7429b..0b30ca6d 100644 --- a/modules/shell.cpp +++ b/modules/shell.cpp @@ -25,8 +25,9 @@ using std::vector; class CShellMod; class CShellSock : public CExecSock { -public: - CShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) : CExecSock() { + public: + CShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) + : CExecSock() { EnableReadLine(); m_pParent = pShellMod; m_pClient = pClient; @@ -43,21 +44,20 @@ public: close(GetWSock()); SetWSock(open("/dev/null", O_WRONLY)); } - // These next two function's bodies are at the bottom of the file since they reference CShellMod + // These next two function's bodies are at the bottom of the file since they + // reference CShellMod void ReadLine(const CString& sData) override; void Disconnected() override; CShellMod* m_pParent; -private: - CClient* m_pClient; + private: + CClient* m_pClient; }; class CShellMod : public CModule { -public: - MODCONSTRUCTOR(CShellMod) { - m_sPath = CZNC::Get().GetHomePath(); - } + public: + MODCONSTRUCTOR(CShellMod) { m_sPath = CZNC::Get().GetHomePath(); } virtual ~CShellMod() { vector vSocks = GetManager()->FindSocksByName("SHELL"); @@ -67,8 +67,7 @@ public: } } - bool OnLoad(const CString& sArgs, CString& sMessage) override - { + bool OnLoad(const CString& sArgs, CString& sMessage) override { #ifndef MOD_SHELL_ALLOW_EVERYONE if (!GetUser()->IsAdmin()) { sMessage = "You must be admin to use the shell module"; @@ -83,7 +82,10 @@ public: CString sCommand = sLine.Token(0); if (sCommand.Equals("cd")) { CString sArg = sLine.Token(1, true); - CString sPath = CDir::ChangeDir(m_sPath, (sArg.empty() ? CString(CZNC::Get().GetHomePath()) : sArg), CZNC::Get().GetHomePath()); + CString sPath = CDir::ChangeDir( + m_sPath, + (sArg.empty() ? CString(CZNC::Get().GetHomePath()) : sArg), + CZNC::Get().GetHomePath()); CFile Dir(sPath); if (Dir.IsDir()) { @@ -103,14 +105,19 @@ public: void PutShell(const CString& sMsg) { CString sPath = m_sPath.Replace_n(" ", "_"); CString sSource = ":" + GetModNick() + "!shell@" + sPath; - CString sLine = sSource + " PRIVMSG " + GetClient()->GetNick() + " :" + sMsg; + CString sLine = + sSource + " PRIVMSG " + GetClient()->GetNick() + " :" + sMsg; GetClient()->PutClient(sLine); } void RunCommand(const CString& sCommand) { - GetManager()->AddSock(new CShellSock(this, GetClient(), "cd " + m_sPath + " && " + sCommand), "SHELL"); + GetManager()->AddSock( + new CShellSock(this, GetClient(), + "cd " + m_sPath + " && " + sCommand), + "SHELL"); } -private: + + private: CString m_sPath; }; @@ -128,16 +135,16 @@ void CShellSock::ReadLine(const CString& sData) { void CShellSock::Disconnected() { // If there is some incomplete line in the buffer, read it // (e.g. echo echo -n "hi" triggered this) - CString &sBuffer = GetInternalReadBuffer(); - if (!sBuffer.empty()) - ReadLine(sBuffer); + CString& sBuffer = GetInternalReadBuffer(); + if (!sBuffer.empty()) ReadLine(sBuffer); m_pParent->SetClient(m_pClient); m_pParent->PutShell("znc$"); m_pParent->SetClient(nullptr); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("shell"); } diff --git a/modules/simple_away.cpp b/modules/simple_away.cpp index a0ac0cbb..87d55610 100644 --- a/modules/simple_away.cpp +++ b/modules/simple_away.cpp @@ -19,44 +19,61 @@ #include #define SIMPLE_AWAY_DEFAULT_REASON "Auto away at %awaytime%" -#define SIMPLE_AWAY_DEFAULT_TIME 60 - +#define SIMPLE_AWAY_DEFAULT_TIME 60 class CSimpleAway; class CSimpleAwayJob : public CTimer { -public: - CSimpleAwayJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) - : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} + public: + CSimpleAwayJob(CModule* pModule, unsigned int uInterval, + unsigned int uCycles, const CString& sLabel, + const CString& sDescription) + : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CSimpleAwayJob() {} -protected: + protected: void RunJob() override; }; class CSimpleAway : public CModule { -private: - CString m_sReason; + private: + CString m_sReason; unsigned int m_iAwayWait; unsigned int m_iMinClients; - bool m_bClientSetAway; - bool m_bWeSetAway; + bool m_bClientSetAway; + bool m_bWeSetAway; -public: + public: MODCONSTRUCTOR(CSimpleAway) { - m_sReason = SIMPLE_AWAY_DEFAULT_REASON; - m_iAwayWait = SIMPLE_AWAY_DEFAULT_TIME; - m_iMinClients = 1; + m_sReason = SIMPLE_AWAY_DEFAULT_REASON; + m_iAwayWait = SIMPLE_AWAY_DEFAULT_TIME; + m_iMinClients = 1; m_bClientSetAway = false; - m_bWeSetAway = false; + m_bWeSetAway = false; AddHelpCommand(); - AddCommand("Reason", static_cast(&CSimpleAway::OnReasonCommand), "[]", "Prints or sets the away reason (%awaytime% is replaced with the time you were set away, supports substitutions using ExpandString)"); - AddCommand("Timer", static_cast(&CSimpleAway::OnTimerCommand), "", "Prints the current time to wait before setting you away"); - AddCommand("SetTimer", static_cast(&CSimpleAway::OnSetTimerCommand), "", "Sets the time to wait before setting you away"); - AddCommand("DisableTimer", static_cast(&CSimpleAway::OnDisableTimerCommand), "", "Disables the wait time before setting you away"); - AddCommand("MinClients", static_cast(&CSimpleAway::OnMinClientsCommand), "", "Get or set the minimum number of clients before going away"); + AddCommand("Reason", static_cast( + &CSimpleAway::OnReasonCommand), + "[]", + "Prints or sets the away reason (%awaytime% is replaced " + "with the time you were set away, supports substitutions " + "using ExpandString)"); + AddCommand( + "Timer", + static_cast(&CSimpleAway::OnTimerCommand), + "", "Prints the current time to wait before setting you away"); + AddCommand("SetTimer", static_cast( + &CSimpleAway::OnSetTimerCommand), + "", + "Sets the time to wait before setting you away"); + AddCommand("DisableTimer", static_cast( + &CSimpleAway::OnDisableTimerCommand), + "", "Disables the wait time before setting you away"); + AddCommand( + "MinClients", static_cast( + &CSimpleAway::OnMinClientsCommand), + "", "Get or set the minimum number of clients before going away"); } virtual ~CSimpleAway() {} @@ -74,8 +91,7 @@ public: sReasonArg = sArgs.Token(2, true); } else { CString sAwayWait = GetNV("awaywait"); - if (!sAwayWait.empty()) - SetAwayWait(sAwayWait.ToUInt(), false); + if (!sAwayWait.empty()) SetAwayWait(sAwayWait.ToUInt(), false); sReasonArg = sArgs; } @@ -84,14 +100,12 @@ public: SetReason(sReasonArg); } else { CString sSavedReason = GetNV("reason"); - if (!sSavedReason.empty()) - SetReason(sSavedReason, false); + if (!sSavedReason.empty()) SetReason(sSavedReason, false); } // MinClients CString sMinClients = GetNV("minclients"); - if (!sMinClients.empty()) - SetMinClients(sMinClients.ToUInt(), false); + if (!sMinClients.empty()) SetMinClients(sMinClients.ToUInt(), false); // Set away on load, required if loaded via webadmin if (GetNetwork()->IsIRCConnected() && MinClientsConnected()) @@ -108,14 +122,12 @@ public: } void OnClientLogin() override { - if (MinClientsConnected()) - SetBack(); + if (MinClientsConnected()) SetBack(); } void OnClientDisconnect() override { /* There might still be other clients */ - if (!MinClientsConnected()) - SetAway(); + if (!MinClientsConnected()) SetAway(); } void OnReasonCommand(const CString& sLine) { @@ -131,8 +143,8 @@ public: } void OnTimerCommand(const CString& sLine) { - PutModule("Current timer setting: " - + CString(m_iAwayWait) + " seconds"); + PutModule("Current timer setting: " + CString(m_iAwayWait) + + " seconds"); } void OnSetTimerCommand(const CString& sLine) { @@ -141,8 +153,7 @@ public: if (m_iAwayWait == 0) PutModule("Timer disabled"); else - PutModule("Timer set to " - + CString(m_iAwayWait) + " seconds"); + PutModule("Timer set to " + CString(m_iAwayWait) + " seconds"); } void OnDisableTimerCommand(const CString& sLine) { @@ -159,9 +170,8 @@ public: } } - EModRet OnUserRaw(CString &sLine) override { - if (!sLine.Token(0).Equals("AWAY")) - return CONTINUE; + EModRet OnUserRaw(CString& sLine) override { + if (!sLine.Token(0).Equals("AWAY")) return CONTINUE; // If a client set us away, we don't touch that away message const CString sArg = sLine.Token(1, true).Trim_n(" "); @@ -178,8 +188,8 @@ public: void SetAway(bool bTimer = true) { if (bTimer) { RemTimer("simple_away"); - AddTimer(new CSimpleAwayJob(this, m_iAwayWait, 1, - "simple_away", "Sets you away after detach")); + AddTimer(new CSimpleAwayJob(this, m_iAwayWait, 1, "simple_away", + "Sets you away after detach")); } else { if (!m_bClientSetAway) { PutIRC("AWAY :" + ExpandReason()); @@ -196,54 +206,54 @@ public: } } -private: - bool MinClientsConnected() - { + private: + bool MinClientsConnected() { return GetNetwork()->GetClients().size() >= m_iMinClients; } CString ExpandReason() { CString sReason = m_sReason; - if (sReason.empty()) - sReason = SIMPLE_AWAY_DEFAULT_REASON; + if (sReason.empty()) sReason = SIMPLE_AWAY_DEFAULT_REASON; time_t iTime = time(nullptr); CString sTime = CUtils::CTime(iTime, GetUser()->GetTimezone()); sReason.Replace("%awaytime%", sTime); sReason = ExpandString(sReason); - sReason.Replace("%s", sTime); // Backwards compatibility with previous syntax, where %s was substituted with sTime. ZNC <= 1.6.x + sReason.Replace("%s", sTime); // Backwards compatibility with previous + // syntax, where %s was substituted with + // sTime. ZNC <= 1.6.x return sReason; } -/* Settings */ + /* Settings */ void SetReason(CString& sReason, bool bSave = true) { - if (bSave) - SetNV("reason", sReason); + if (bSave) SetNV("reason", sReason); m_sReason = sReason; } void SetAwayWait(unsigned int iAwayWait, bool bSave = true) { - if (bSave) - SetNV("awaywait", CString(iAwayWait)); + if (bSave) SetNV("awaywait", CString(iAwayWait)); m_iAwayWait = iAwayWait; } void SetMinClients(unsigned int iMinClients, bool bSave = true) { - if (bSave) - SetNV("minclients", CString(iMinClients)); + if (bSave) SetNV("minclients", CString(iMinClients)); m_iMinClients = iMinClients; } }; -void CSimpleAwayJob::RunJob() { - ((CSimpleAway*)GetModule())->SetAway(false); -} +void CSimpleAwayJob::RunJob() { ((CSimpleAway*)GetModule())->SetAway(false); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("simple_away"); Info.SetHasArgs(true); - Info.SetArgsHelpText("You might enter up to 3 arguments, like -notimer awaymessage or -timer 5 awaymessage."); + Info.SetArgsHelpText( + "You might enter up to 3 arguments, like -notimer awaymessage or " + "-timer 5 awaymessage."); } -NETWORKMODULEDEFS(CSimpleAway, "This module will automatically set you away on IRC while you are disconnected from the bouncer.") +NETWORKMODULEDEFS(CSimpleAway, + "This module will automatically set you away on IRC while " + "you are disconnected from the bouncer.") diff --git a/modules/stickychan.cpp b/modules/stickychan.cpp index f5bc8254..7642755f 100644 --- a/modules/stickychan.cpp +++ b/modules/stickychan.cpp @@ -19,35 +19,34 @@ using std::vector; -class CStickyChan : public CModule -{ -public: +class CStickyChan : public CModule { + public: MODCONSTRUCTOR(CStickyChan) { AddHelpCommand(); - AddCommand("Stick", static_cast(&CStickyChan::OnStickCommand), "<#channel> [key]", "Sticks a channel"); - AddCommand("Unstick", static_cast(&CStickyChan::OnUnstickCommand), "<#channel>", "Unsticks a channel"); - AddCommand("List", static_cast(&CStickyChan::OnListCommand), "", "Lists sticky channels"); - } - virtual ~CStickyChan() - { + AddCommand("Stick", static_cast( + &CStickyChan::OnStickCommand), + "<#channel> [key]", "Sticks a channel"); + AddCommand("Unstick", static_cast( + &CStickyChan::OnUnstickCommand), + "<#channel>", "Unsticks a channel"); + AddCommand("List", static_cast( + &CStickyChan::OnListCommand), + "", "Lists sticky channels"); } + virtual ~CStickyChan() {} bool OnLoad(const CString& sArgs, CString& sMessage) override; - EModRet OnUserPart(CString& sChannel, CString& sMessage) override - { + EModRet OnUserPart(CString& sChannel, CString& sMessage) override { if (!GetNetwork()) { return CONTINUE; } - for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) - { - if (sChannel.Equals(it->first)) - { + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { + if (sChannel.Equals(it->first)) { CChan* pChan = GetNetwork()->FindChan(sChannel); - if (pChan) - { + if (pChan) { pChan->JoinUser(); return HALT; } @@ -57,12 +56,13 @@ public: return CONTINUE; } - virtual void OnMode(const CNick& pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) override { + virtual void OnMode(const CNick& pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, + bool bNoChange) override { if (uMode == CChan::M_Key) { if (bAdded) { // We ignore channel key "*" because of some broken nets. - if (sArg != "*") - { + if (sArg != "*") { SetNV(Channel.GetName(), sArg, true); } } else { @@ -71,8 +71,7 @@ public: } } - void OnStickCommand(const CString& sCommand) - { + void OnStickCommand(const CString& sCommand) { CString sChannel = sCommand.Token(1).AsLower(); if (sChannel.empty()) { PutModule("Usage: Stick <#channel> [key]"); @@ -94,47 +93,44 @@ public: void OnListCommand(const CString& sCommand) { int i = 1; - for (MCString::iterator it = BeginNV(); it != EndNV(); ++it, i++) - { + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it, i++) { if (it->second.empty()) PutModule(CString(i) + ": " + it->first); else - PutModule(CString(i) + ": " + it->first + " (" + it->second + ")"); + PutModule(CString(i) + ": " + it->first + " (" + it->second + + ")"); } PutModule(" -- End of List"); } - void RunJob() - { + void RunJob() { CIRCNetwork* pNetwork = GetNetwork(); - if (!pNetwork->GetIRCSock()) - return; + if (!pNetwork->GetIRCSock()) return; - for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) - { - CChan *pChan = pNetwork->FindChan(it->first); + for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { + CChan* pChan = pNetwork->FindChan(it->first); if (!pChan) { pChan = new CChan(it->first, pNetwork, true); - if (!it->second.empty()) - pChan->SetKey(it->second); + if (!it->second.empty()) pChan->SetKey(it->second); if (!pNetwork->AddChan(pChan)) { /* AddChan() deleted that channel */ - PutModule("Could not join [" + it->first - + "] (# prefix missing?)"); + PutModule("Could not join [" + it->first + + "] (# prefix missing?)"); continue; } } if (!pChan->IsOn() && pNetwork->IsIRCConnected()) { PutModule("Joining [" + pChan->GetName() + "]"); - PutIRC("JOIN " + pChan->GetName() + (pChan->GetKey().empty() - ? "" : " " + pChan->GetKey())); + PutIRC("JOIN " + pChan->GetName() + + (pChan->GetKey().empty() ? "" : " " + pChan->GetKey())); } } } CString GetWebMenuTitle() override { return "Sticky Chans"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "index") { bool bSubmitted = (WebSock.GetParam("submitted").ToInt() != 0); @@ -143,14 +139,15 @@ public: const CString sChan = pChan->GetName(); bool bStick = FindNV(sChan) != EndNV(); - if(bSubmitted) { - bool bNewStick = WebSock.GetParam("stick_" + sChan).ToBool(); - if(bNewStick && !bStick) - SetNV(sChan, ""); // no password support for now unless chansaver is active too - else if(!bNewStick && bStick) { + if (bSubmitted) { + bool bNewStick = + WebSock.GetParam("stick_" + sChan).ToBool(); + if (bNewStick && !bStick) + SetNV(sChan, ""); // no password support for now unless + // chansaver is active too + else if (!bNewStick && bStick) { MCString::iterator it = FindNV(sChan); - if(it != EndNV()) - DelNV(it); + if (it != EndNV()) DelNV(it); } bStick = bNewStick; } @@ -160,7 +157,7 @@ public: Row["Sticky"] = CString(bStick); } - if(bSubmitted) { + if (bSubmitted) { WebSock.GetSession()->AddSuccess("Changes have been saved!"); } @@ -170,20 +167,25 @@ public: return false; } - bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { if (sPageName == "webadmin/channel") { CString sChan = Tmpl["ChanName"]; bool bStick = FindNV(sChan) != EndNV(); if (Tmpl["WebadminAction"].Equals("display")) { Tmpl["Sticky"] = CString(bStick); - } else if (WebSock.GetParam("embed_stickychan_presented").ToBool()) { - bool bNewStick = WebSock.GetParam("embed_stickychan_sticky").ToBool(); - if(bNewStick && !bStick) { - SetNV(sChan, ""); // no password support for now unless chansaver is active too + } else if (WebSock.GetParam("embed_stickychan_presented") + .ToBool()) { + bool bNewStick = + WebSock.GetParam("embed_stickychan_sticky").ToBool(); + if (bNewStick && !bStick) { + SetNV(sChan, ""); // no password support for now unless + // chansaver is active too WebSock.GetSession()->AddSuccess("Channel become sticky!"); - } else if(!bNewStick && bStick) { + } else if (!bNewStick && bStick) { DelNV(sChan); - WebSock.GetSession()->AddSuccess("Channel stopped being sticky!"); + WebSock.GetSession()->AddSuccess( + "Channel stopped being sticky!"); } } return true; @@ -195,14 +197,18 @@ public: CString sNumeric = sLine.Token(1); if (sNumeric.Equals("479")) { - // ERR_BADCHANNAME (juped channels or illegal channel name - ircd hybrid) - // prevent the module from getting into an infinite loop of trying to join it. + // ERR_BADCHANNAME (juped channels or illegal channel name - ircd + // hybrid) + // prevent the module from getting into an infinite loop of trying + // to join it. // :irc.network.net 479 mynick #channel :Illegal channel name CString sChannel = sLine.Token(3); for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { if (sChannel.Equals(it->first)) { - PutModule("Channel [" + sChannel + "] cannot be joined, it is an illegal channel name. Unsticking."); + PutModule("Channel [" + sChannel + + "] cannot be joined, it is an illegal channel " + "name. Unsticking."); OnUnstickCommand("unstick " + sChannel); return CONTINUE; } @@ -213,14 +219,11 @@ public: } }; - -static void RunTimer(CModule * pModule, CFPTimer *pTimer) -{ - ((CStickyChan *)pModule)->RunJob(); +static void RunTimer(CModule* pModule, CFPTimer* pTimer) { + ((CStickyChan*)pModule)->RunJob(); } -bool CStickyChan::OnLoad(const CString& sArgs, CString& sMessage) -{ +bool CStickyChan::OnLoad(const CString& sArgs, CString& sMessage) { VCString vsChans; sArgs.Split(",", vsChans, false); @@ -234,13 +237,15 @@ bool CStickyChan::OnLoad(const CString& sArgs, CString& sMessage) SetArgs(""); AddTimer(RunTimer, "StickyChanTimer", 15); - return(true); + return (true); } -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("stickychan"); Info.SetHasArgs(true); Info.SetArgsHelpText("List of channels, separated by comma."); } -NETWORKMODULEDEFS(CStickyChan, "configless sticky chans, keeps you there very stickily even") +NETWORKMODULEDEFS(CStickyChan, + "configless sticky chans, keeps you there very stickily even") diff --git a/modules/stripcontrols.cpp b/modules/stripcontrols.cpp index 22981bae..4173e4c9 100644 --- a/modules/stripcontrols.cpp +++ b/modules/stripcontrols.cpp @@ -17,7 +17,7 @@ #include class CStripControlsMod : public CModule { -public: + public: MODCONSTRUCTOR(CStripControlsMod) {} EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override { @@ -25,7 +25,8 @@ public: return CONTINUE; } - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { sMessage.StripControls(); return CONTINUE; } @@ -35,7 +36,8 @@ public: return CONTINUE; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { sMessage.StripControls(); return CONTINUE; } @@ -51,9 +53,12 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("stripcontrols"); Info.AddType(CModInfo::UserModule); } -NETWORKMODULEDEFS(CStripControlsMod, "Strips control codes (Colors, Bold, ..) from channel and private messages.") +NETWORKMODULEDEFS(CStripControlsMod, + "Strips control codes (Colors, Bold, ..) from channel and " + "private messages.") diff --git a/modules/watch.cpp b/modules/watch.cpp index d49984a3..d60fbdd9 100644 --- a/modules/watch.cpp +++ b/modules/watch.cpp @@ -22,7 +22,7 @@ using std::vector; using std::set; class CWatchSource { -public: + public: CWatchSource(const CString& sSource, bool bNegated) { m_sSource = sSource; m_bNegated = bNegated; @@ -36,15 +36,16 @@ public: // Setters // !Setters -private: -protected: - bool m_bNegated; + private: + protected: + bool m_bNegated; CString m_sSource; }; class CWatchEntry { -public: - CWatchEntry(const CString& sHostMask, const CString& sTarget, const CString& sPattern) { + public: + CWatchEntry(const CString& sHostMask, const CString& sTarget, + const CString& sPattern) { m_bDisabled = false; m_bDetachedClientOnly = false; m_bDetachedChannelOnly = false; @@ -68,7 +69,8 @@ public: } virtual ~CWatchEntry() {} - bool IsMatch(const CNick& Nick, const CString& sText, const CString& sSource, const CIRCNetwork* pNetwork) { + bool IsMatch(const CNick& Nick, const CString& sText, + const CString& sSource, const CIRCNetwork* pNetwork) { if (IsDisabled()) { return false; } @@ -81,7 +83,8 @@ public: for (unsigned int a = 0; a < m_vsSources.size(); a++) { const CWatchSource& WatchSource = m_vsSources[a]; - if (sSource.WildCmp(WatchSource.GetSource(), CString::CaseInsensitive)) { + if (sSource.WildCmp(WatchSource.GetSource(), + CString::CaseInsensitive)) { if (WatchSource.IsNegated()) { return false; } else { @@ -91,18 +94,17 @@ public: } } - if (!bGoodSource) - return false; + if (!bGoodSource) return false; if (!Nick.GetHostMask().WildCmp(m_sHostMask, CString::CaseInsensitive)) return false; - return (sText.WildCmp(pNetwork->ExpandString(m_sPattern), CString::CaseInsensitive)); + return (sText.WildCmp(pNetwork->ExpandString(m_sPattern), + CString::CaseInsensitive)); } - bool operator ==(const CWatchEntry& WatchEntry) { - return (GetHostMask().Equals(WatchEntry.GetHostMask()) - && GetTarget().Equals(WatchEntry.GetTarget()) - && GetPattern().Equals(WatchEntry.GetPattern()) - ); + bool operator==(const CWatchEntry& WatchEntry) { + return (GetHostMask().Equals(WatchEntry.GetHostMask()) && + GetTarget().Equals(WatchEntry.GetTarget()) && + GetPattern().Equals(WatchEntry.GetPattern())); } // Getters @@ -157,19 +159,19 @@ public: } } // !Setters -private: -protected: - CString m_sHostMask; - CString m_sTarget; - CString m_sPattern; - bool m_bDisabled; - bool m_bDetachedClientOnly; - bool m_bDetachedChannelOnly; + private: + protected: + CString m_sHostMask; + CString m_sTarget; + CString m_sPattern; + bool m_bDisabled; + bool m_bDetachedClientOnly; + bool m_bDetachedChannelOnly; vector m_vsSources; }; class CWatcherMod : public CModule { -public: + public: MODCONSTRUCTOR(CWatcherMod) { m_Buffer.SetLineCount(500); Load(); @@ -177,9 +179,11 @@ public: virtual ~CWatcherMod() {} - void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs) override { - Process(OpNick, "* " + OpNick.GetNick() + " sets mode: " + sModes + " " + - sArgs + " on " + Channel.GetName(), Channel.GetName()); + void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, + const CString& sArgs) override { + Process(OpNick, "* " + OpNick.GetNick() + " sets mode: " + sModes + + " " + sArgs + " on " + Channel.GetName(), + Channel.GetName()); } void OnClientLogin() override { @@ -193,43 +197,63 @@ public: m_Buffer.Clear(); } - void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) override { - Process(OpNick, "* " + OpNick.GetNick() + " kicked " + sKickedNick + " from " + - Channel.GetName() + " because [" + sMessage + "]", Channel.GetName()); + void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, + const CString& sMessage) override { + Process(OpNick, + "* " + OpNick.GetNick() + " kicked " + sKickedNick + " from " + + Channel.GetName() + " because [" + sMessage + "]", + Channel.GetName()); } - void OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) override { - Process(Nick, "* Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") " - "(" + sMessage + ")", ""); + void OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) override { + Process(Nick, "* Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + + "@" + Nick.GetHost() + + ") " + "(" + + sMessage + ")", + ""); } void OnJoin(const CNick& Nick, CChan& Channel) override { - Process(Nick, "* " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") joins " + - Channel.GetName(), Channel.GetName()); + Process(Nick, "* " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + + Nick.GetHost() + ") joins " + Channel.GetName(), + Channel.GetName()); } - void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) override { - Process(Nick, "* " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") parts " + - Channel.GetName() + "(" + sMessage + ")", Channel.GetName()); + void OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) override { + Process(Nick, "* " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + + Nick.GetHost() + ") parts " + Channel.GetName() + + "(" + sMessage + ")", + Channel.GetName()); } - void OnNick(const CNick& OldNick, const CString& sNewNick, const vector& vChans) override { - Process(OldNick, "* " + OldNick.GetNick() + " is now known as " + sNewNick, ""); + void OnNick(const CNick& OldNick, const CString& sNewNick, + const vector& vChans) override { + Process(OldNick, + "* " + OldNick.GetNick() + " is now known as " + sNewNick, ""); } EModRet OnCTCPReply(CNick& Nick, CString& sMessage) override { - Process(Nick, "* CTCP: " + Nick.GetNick() + " reply [" + sMessage + "]", "priv"); + Process(Nick, "* CTCP: " + Nick.GetNick() + " reply [" + sMessage + "]", + "priv"); return CONTINUE; } EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override { - Process(Nick, "* CTCP: " + Nick.GetNick() + " [" + sMessage + "]", "priv"); + Process(Nick, "* CTCP: " + Nick.GetNick() + " [" + sMessage + "]", + "priv"); return CONTINUE; } - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { - Process(Nick, "* CTCP: " + Nick.GetNick() + " [" + sMessage + "] to " - "[" + Channel.GetName() + "]", Channel.GetName()); + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { + Process(Nick, "* CTCP: " + Nick.GetNick() + " [" + sMessage + + "] to " + "[" + + Channel.GetName() + "]", + Channel.GetName()); return CONTINUE; } @@ -238,8 +262,11 @@ public: return CONTINUE; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { - Process(Nick, "-" + Nick.GetNick() + ":" + Channel.GetName() + "- " + sMessage, Channel.GetName()); + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { + Process(Nick, "-" + Nick.GetNick() + ":" + Channel.GetName() + "- " + + sMessage, + Channel.GetName()); return CONTINUE; } @@ -249,14 +276,17 @@ public: } EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override { - Process(Nick, "<" + Nick.GetNick() + ":" + Channel.GetName() + "> " + sMessage, Channel.GetName()); + Process(Nick, "<" + Nick.GetNick() + ":" + Channel.GetName() + "> " + + sMessage, + Channel.GetName()); return CONTINUE; } void OnModCommand(const CString& sCommand) override { CString sCmdName = sCommand.Token(0); if (sCmdName.Equals("ADD") || sCmdName.Equals("WATCH")) { - Watch(sCommand.Token(1), sCommand.Token(2), sCommand.Token(3, true)); + Watch(sCommand.Token(1), sCommand.Token(2), + sCommand.Token(3, true)); } else if (sCmdName.Equals("HELP")) { Help(); } else if (sCmdName.Equals("LIST")) { @@ -310,7 +340,8 @@ public: m_Buffer.SetLineCount(sCount.ToUInt()); } - PutModule("Buffer count is set to [" + CString(m_Buffer.GetLineCount()) + "]"); + PutModule("Buffer count is set to [" + + CString(m_Buffer.GetLineCount()) + "]"); } else if (sCmdName.Equals("DEL")) { Remove(sCommand.Token(1).ToUInt()); } else { @@ -318,29 +349,38 @@ public: } } -private: - void Process(const CNick& Nick, const CString& sMessage, const CString& sSource) { + private: + void Process(const CNick& Nick, const CString& sMessage, + const CString& sSource) { set sHandledTargets; CIRCNetwork* pNetwork = GetNetwork(); CChan* pChannel = pNetwork->FindChan(sSource); - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { CWatchEntry& WatchEntry = *it; - if (pNetwork->IsUserAttached() && WatchEntry.IsDetachedClientOnly()) { + if (pNetwork->IsUserAttached() && + WatchEntry.IsDetachedClientOnly()) { continue; } - if (pChannel && !pChannel->IsDetached() && WatchEntry.IsDetachedChannelOnly()) { + if (pChannel && !pChannel->IsDetached() && + WatchEntry.IsDetachedChannelOnly()) { continue; } if (WatchEntry.IsMatch(Nick, sMessage, sSource, pNetwork) && - sHandledTargets.count(WatchEntry.GetTarget()) < 1) { + sHandledTargets.count(WatchEntry.GetTarget()) < 1) { if (pNetwork->IsUserAttached()) { - pNetwork->PutUser(":" + WatchEntry.GetTarget() + "!watch@znc.in PRIVMSG " + pNetwork->GetCurNick() + " :" + sMessage); + pNetwork->PutUser(":" + WatchEntry.GetTarget() + + "!watch@znc.in PRIVMSG " + + pNetwork->GetCurNick() + " :" + sMessage); } else { - m_Buffer.AddLine(":" + _NAMEDFMT(WatchEntry.GetTarget()) + "!watch@znc.in PRIVMSG {target} :{text}", sMessage); + m_Buffer.AddLine( + ":" + _NAMEDFMT(WatchEntry.GetTarget()) + + "!watch@znc.in PRIVMSG {target} :{text}", + sMessage); } sHandledTargets.insert(WatchEntry.GetTarget()); } @@ -348,80 +388,86 @@ private: } void SetDisabled(unsigned int uIdx, bool bDisabled) { - if (uIdx == (unsigned int) ~0) { - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + if (uIdx == (unsigned int)~0) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { (*it).SetDisabled(bDisabled); } - PutModule(((bDisabled) ? "Disabled all entries." : "Enabled all entries.")); + PutModule(((bDisabled) ? "Disabled all entries." + : "Enabled all entries.")); Save(); return; } - uIdx--; // "convert" index to zero based + uIdx--; // "convert" index to zero based if (uIdx >= m_lsWatchers.size()) { PutModule("Invalid Id"); return; } list::iterator it = m_lsWatchers.begin(); - for (unsigned int a = 0; a < uIdx; a++) - ++it; + for (unsigned int a = 0; a < uIdx; a++) ++it; (*it).SetDisabled(bDisabled); - PutModule("Id " + CString(uIdx +1) + ((bDisabled) ? " Disabled" : " Enabled")); + PutModule("Id " + CString(uIdx + 1) + + ((bDisabled) ? " Disabled" : " Enabled")); Save(); } void SetDetachedClientOnly(unsigned int uIdx, bool bDetachedClientOnly) { - if (uIdx == (unsigned int) ~0) { - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + if (uIdx == (unsigned int)~0) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { (*it).SetDetachedClientOnly(bDetachedClientOnly); } - PutModule(CString("Set DetachedClientOnly for all entries to: ") + ((bDetachedClientOnly) ? "Yes" : "No")); + PutModule(CString("Set DetachedClientOnly for all entries to: ") + + ((bDetachedClientOnly) ? "Yes" : "No")); Save(); return; } - uIdx--; // "convert" index to zero based + uIdx--; // "convert" index to zero based if (uIdx >= m_lsWatchers.size()) { PutModule("Invalid Id"); return; } list::iterator it = m_lsWatchers.begin(); - for (unsigned int a = 0; a < uIdx; a++) - ++it; + for (unsigned int a = 0; a < uIdx; a++) ++it; (*it).SetDetachedClientOnly(bDetachedClientOnly); - PutModule("Id " + CString(uIdx +1) + " set to: " + ((bDetachedClientOnly) ? "Yes" : "No")); + PutModule("Id " + CString(uIdx + 1) + " set to: " + + ((bDetachedClientOnly) ? "Yes" : "No")); Save(); } void SetDetachedChannelOnly(unsigned int uIdx, bool bDetachedChannelOnly) { - if (uIdx == (unsigned int) ~0) { - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + if (uIdx == (unsigned int)~0) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { (*it).SetDetachedChannelOnly(bDetachedChannelOnly); } - PutModule(CString("Set DetachedChannelOnly for all entries to: ") + ((bDetachedChannelOnly) ? "Yes" : "No")); + PutModule(CString("Set DetachedChannelOnly for all entries to: ") + + ((bDetachedChannelOnly) ? "Yes" : "No")); Save(); return; } - uIdx--; // "convert" index to zero based + uIdx--; // "convert" index to zero based if (uIdx >= m_lsWatchers.size()) { PutModule("Invalid Id"); return; } list::iterator it = m_lsWatchers.begin(); - for (unsigned int a = 0; a < uIdx; a++) - ++it; + for (unsigned int a = 0; a < uIdx; a++) ++it; (*it).SetDetachedChannelOnly(bDetachedChannelOnly); - PutModule("Id " + CString(uIdx +1) + " set to: " + ((bDetachedChannelOnly) ? "Yes" : "No")); + PutModule("Id " + CString(uIdx + 1) + " set to: " + + ((bDetachedChannelOnly) ? "Yes" : "No")); Save(); } @@ -438,7 +484,8 @@ private: unsigned int uIdx = 1; - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it, uIdx++) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it, uIdx++) { CWatchEntry& WatchEntry = *it; Table.AddRow(); @@ -448,8 +495,10 @@ private: Table.SetCell("Pattern", WatchEntry.GetPattern()); Table.SetCell("Sources", WatchEntry.GetSourcesStr()); Table.SetCell("Off", (WatchEntry.IsDisabled()) ? "Off" : ""); - Table.SetCell("DetachedClientOnly", (WatchEntry.IsDetachedClientOnly()) ? "Yes" : "No"); - Table.SetCell("DetachedChannelOnly", (WatchEntry.IsDetachedChannelOnly()) ? "Yes" : "No"); + Table.SetCell("DetachedClientOnly", + (WatchEntry.IsDetachedClientOnly()) ? "Yes" : "No"); + Table.SetCell("DetachedChannelOnly", + (WatchEntry.IsDetachedChannelOnly()) ? "Yes" : "No"); } if (Table.size()) { @@ -470,15 +519,17 @@ private: unsigned int uIdx = 1; - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it, uIdx++) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it, uIdx++) { CWatchEntry& WatchEntry = *it; - PutModule("/msg " + GetModNick() + " ADD " + WatchEntry.GetHostMask() + " " + - WatchEntry.GetTarget() + " " + WatchEntry.GetPattern()); + PutModule("/msg " + GetModNick() + " ADD " + + WatchEntry.GetHostMask() + " " + WatchEntry.GetTarget() + + " " + WatchEntry.GetPattern()); if (WatchEntry.GetSourcesStr().size()) { - PutModule("/msg " + GetModNick() + " SETSOURCES " + CString(uIdx) + " " + - WatchEntry.GetSourcesStr()); + PutModule("/msg " + GetModNick() + " SETSOURCES " + + CString(uIdx) + " " + WatchEntry.GetSourcesStr()); } if (WatchEntry.IsDisabled()) { @@ -486,11 +537,13 @@ private: } if (WatchEntry.IsDetachedClientOnly()) { - PutModule("/msg " + GetModNick() + " SETDETACHEDCLIENTONLY " + CString(uIdx) + " TRUE"); + PutModule("/msg " + GetModNick() + " SETDETACHEDCLIENTONLY " + + CString(uIdx) + " TRUE"); } if (WatchEntry.IsDetachedChannelOnly()) { - PutModule("/msg " + GetModNick() + " SETDETACHEDCHANNELONLY " + CString(uIdx) + " TRUE"); + PutModule("/msg " + GetModNick() + " SETDETACHEDCHANNELONLY " + + CString(uIdx) + " TRUE"); } } @@ -498,34 +551,32 @@ private: } void SetSources(unsigned int uIdx, const CString& sSources) { - uIdx--; // "convert" index to zero based + uIdx--; // "convert" index to zero based if (uIdx >= m_lsWatchers.size()) { PutModule("Invalid Id"); return; } list::iterator it = m_lsWatchers.begin(); - for (unsigned int a = 0; a < uIdx; a++) - ++it; + for (unsigned int a = 0; a < uIdx; a++) ++it; (*it).SetSources(sSources); - PutModule("Sources set for Id " + CString(uIdx +1) + "."); + PutModule("Sources set for Id " + CString(uIdx + 1) + "."); Save(); } void Remove(unsigned int uIdx) { - uIdx--; // "convert" index to zero based + uIdx--; // "convert" index to zero based if (uIdx >= m_lsWatchers.size()) { PutModule("Invalid Id"); return; } list::iterator it = m_lsWatchers.begin(); - for (unsigned int a = 0; a < uIdx; a++) - ++it; + for (unsigned int a = 0; a < uIdx; a++) ++it; m_lsWatchers.erase(it); - PutModule("Id " + CString(uIdx +1) + " Removed."); + PutModule("Id " + CString(uIdx + 1) + " Removed."); Save(); } @@ -545,11 +596,13 @@ private: Table.AddRow(); Table.SetCell("Command", "Dump"); - Table.SetCell("Description", "Dump a list of all current entries to be used later."); + Table.SetCell("Description", + "Dump a list of all current entries to be used later."); Table.AddRow(); Table.SetCell("Command", "Del "); - Table.SetCell("Description", "Deletes Id from the list of watched entries."); + Table.SetCell("Description", + "Deletes Id from the list of watched entries."); Table.AddRow(); Table.SetCell("Command", "Clear"); @@ -564,20 +617,26 @@ private: Table.SetCell("Description", "Disable (but don't delete) an entry."); Table.AddRow(); - Table.SetCell("Command", "SetDetachedClientOnly "); - Table.SetCell("Description", "Enable or disable detached client only for an entry."); + Table.SetCell("Command", + "SetDetachedClientOnly "); + Table.SetCell("Description", + "Enable or disable detached client only for an entry."); Table.AddRow(); - Table.SetCell("Command", "SetDetachedChannelOnly "); - Table.SetCell("Description", "Enable or disable detached channel only for an entry."); + Table.SetCell("Command", + "SetDetachedChannelOnly "); + Table.SetCell("Description", + "Enable or disable detached channel only for an entry."); Table.AddRow(); Table.SetCell("Command", "Buffer [Count]"); - Table.SetCell("Description", "Show/Set the amount of buffered lines while detached."); + Table.SetCell("Description", + "Show/Set the amount of buffered lines while detached."); Table.AddRow(); Table.SetCell("Command", "SetSources [#chan priv #foo* !#bar]"); - Table.SetCell("Description", "Set the source channels that you care about."); + Table.SetCell("Description", + "Set the source channels that you care about."); Table.AddRow(); Table.SetCell("Command", "Help"); @@ -586,24 +645,30 @@ private: PutModule(Table); } - void Watch(const CString& sHostMask, const CString& sTarget, const CString& sPattern, bool bNotice = false) { + void Watch(const CString& sHostMask, const CString& sTarget, + const CString& sPattern, bool bNotice = false) { CString sMessage; if (sHostMask.size()) { CWatchEntry WatchEntry(sHostMask, sTarget, sPattern); bool bExists = false; - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { if (*it == WatchEntry) { - sMessage = "Entry for [" + WatchEntry.GetHostMask() + "] already exists."; + sMessage = "Entry for [" + WatchEntry.GetHostMask() + + "] already exists."; bExists = true; break; } } if (!bExists) { - sMessage = "Adding entry: [" + WatchEntry.GetHostMask() + "] watching for " - "[" + WatchEntry.GetPattern() + "] -> [" + WatchEntry.GetTarget() + "]"; + sMessage = "Adding entry: [" + WatchEntry.GetHostMask() + + "] watching for " + "[" + + WatchEntry.GetPattern() + "] -> [" + + WatchEntry.GetTarget() + "]"; m_lsWatchers.push_back(WatchEntry); } } else { @@ -620,11 +685,12 @@ private: void Save() { ClearNV(false); - for (list::iterator it = m_lsWatchers.begin(); it != m_lsWatchers.end(); ++it) { + for (list::iterator it = m_lsWatchers.begin(); + it != m_lsWatchers.end(); ++it) { CWatchEntry& WatchEntry = *it; CString sSave; - sSave = WatchEntry.GetHostMask() + "\n"; + sSave = WatchEntry.GetHostMask() + "\n"; sSave += WatchEntry.GetTarget() + "\n"; sSave += WatchEntry.GetPattern() + "\n"; sSave += (WatchEntry.IsDisabled() ? "disabled\n" : "enabled\n"); @@ -674,16 +740,17 @@ private: m_lsWatchers.push_back(WatchEntry); } - if (bWarn) - PutModule("WARNING: malformed entry found while loading"); + if (bWarn) PutModule("WARNING: malformed entry found while loading"); } - list m_lsWatchers; - CBuffer m_Buffer; + list m_lsWatchers; + CBuffer m_Buffer; }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.SetWikiPage("watch"); } -NETWORKMODULEDEFS(CWatcherMod, "Copy activity from a specific user into a separate window") +NETWORKMODULEDEFS(CWatcherMod, + "Copy activity from a specific user into a separate window") diff --git a/modules/webadmin.cpp b/modules/webadmin.cpp index ebe11af3..33fae584 100644 --- a/modules/webadmin.cpp +++ b/modules/webadmin.cpp @@ -31,7 +31,7 @@ using std::map; // pUser can be nullptr if only global modules are needed FOR_EACH_MODULE(i, pUser) { // i is local variable of type CModules::iterator, - // so *i has type CModule* + // so *i has type CModule* } */ struct FOR_EACH_MODULE_Type { @@ -43,51 +43,64 @@ struct FOR_EACH_MODULE_Type { CModules CMtemp; CModules& CMuser; CModules& CMnet; - FOR_EACH_MODULE_Type(CUser* pUser) : CMuser(pUser ? pUser->GetModules() : CMtemp), CMnet(CMtemp) { + FOR_EACH_MODULE_Type(CUser* pUser) + : CMuser(pUser ? pUser->GetModules() : CMtemp), CMnet(CMtemp) { where = AtGlobal; } - FOR_EACH_MODULE_Type(CIRCNetwork* pNetwork) : CMuser(pNetwork ? pNetwork->GetUser()->GetModules() : CMtemp), CMnet(pNetwork ? pNetwork->GetModules() : CMtemp) { + FOR_EACH_MODULE_Type(CIRCNetwork* pNetwork) + : CMuser(pNetwork ? pNetwork->GetUser()->GetModules() : CMtemp), + CMnet(pNetwork ? pNetwork->GetModules() : CMtemp) { where = AtGlobal; } - FOR_EACH_MODULE_Type(std::pair arg) : CMuser(arg.first ? arg.first->GetModules() : CMtemp), CMnet(arg.second ? arg.second->GetModules() : CMtemp) { + FOR_EACH_MODULE_Type(std::pair arg) + : CMuser(arg.first ? arg.first->GetModules() : CMtemp), + CMnet(arg.second ? arg.second->GetModules() : CMtemp) { where = AtGlobal; } operator bool() { return false; } }; -inline bool FOR_EACH_MODULE_CanContinue(FOR_EACH_MODULE_Type& state, CModules::iterator& i) { - if (state.where == FOR_EACH_MODULE_Type::AtGlobal && i == CZNC::Get().GetModules().end()) { +inline bool FOR_EACH_MODULE_CanContinue(FOR_EACH_MODULE_Type& state, + CModules::iterator& i) { + if (state.where == FOR_EACH_MODULE_Type::AtGlobal && + i == CZNC::Get().GetModules().end()) { i = state.CMuser.begin(); state.where = FOR_EACH_MODULE_Type::AtUser; } - if (state.where == FOR_EACH_MODULE_Type::AtUser && i == state.CMuser.end()) { + if (state.where == FOR_EACH_MODULE_Type::AtUser && + i == state.CMuser.end()) { i = state.CMnet.begin(); state.where = FOR_EACH_MODULE_Type::AtNetwork; } - return !(state.where == FOR_EACH_MODULE_Type::AtNetwork && i == state.CMnet.end()); + return !(state.where == FOR_EACH_MODULE_Type::AtNetwork && + i == state.CMnet.end()); } -#define FOR_EACH_MODULE(I, pUserOrNetwork)\ - if (FOR_EACH_MODULE_Type FOR_EACH_MODULE_Var = pUserOrNetwork) {} else\ - for (CModules::iterator I = CZNC::Get().GetModules().begin(); FOR_EACH_MODULE_CanContinue(FOR_EACH_MODULE_Var, I); ++I) +#define FOR_EACH_MODULE(I, pUserOrNetwork) \ + if (FOR_EACH_MODULE_Type FOR_EACH_MODULE_Var = pUserOrNetwork) { \ + } else \ + for (CModules::iterator I = CZNC::Get().GetModules().begin(); \ + FOR_EACH_MODULE_CanContinue(FOR_EACH_MODULE_Var, I); ++I) class CWebAdminMod : public CModule { -public: + public: MODCONSTRUCTOR(CWebAdminMod) { VPair vParams; vParams.push_back(make_pair("user", "")); - AddSubPage(std::make_shared("settings", "Global Settings", CWebSubPage::F_ADMIN)); - AddSubPage(std::make_shared("edituser", "Your Settings", vParams)); - AddSubPage(std::make_shared("traffic", "Traffic Info", vParams)); - AddSubPage(std::make_shared("listusers", "Manage Users", CWebSubPage::F_ADMIN)); + AddSubPage(std::make_shared("settings", "Global Settings", + CWebSubPage::F_ADMIN)); + AddSubPage(std::make_shared("edituser", "Your Settings", + vParams)); + AddSubPage( + std::make_shared("traffic", "Traffic Info", vParams)); + AddSubPage(std::make_shared("listusers", "Manage Users", + CWebSubPage::F_ADMIN)); } - virtual ~CWebAdminMod() { - } + virtual ~CWebAdminMod() {} bool OnLoad(const CString& sArgStr, CString& sMessage) override { - if (sArgStr.empty() || CModInfo::GlobalModule != GetType()) - return true; + if (sArgStr.empty() || CModInfo::GlobalModule != GetType()) return true; // We don't accept any arguments, but for backwards // compatibility we have to do some magic here. @@ -121,8 +134,7 @@ public: } // No arguments left: Only port sharing - if (sArgs.empty() && bShareIRCPorts) - return true; + if (sArgs.empty() && bShareIRCPorts) return true; if (sArgs.find(" ") != CString::npos) { sListenHost = sArgs.Token(0); @@ -149,8 +161,9 @@ public: } // Now turn that into a listener instance - CListener *pListener = new CListener(uPort, sListenHost, sURIPrefix, bSSL, - (!bIPv6 ? ADDR_IPV4ONLY : ADDR_ALL), CListener::ACCEPT_HTTP); + CListener* pListener = new CListener( + uPort, sListenHost, sURIPrefix, bSSL, + (!bIPv6 ? ADDR_IPV4ONLY : ADDR_ALL), CListener::ACCEPT_HTTP); if (!pListener->Listen()) { sMessage = "Failed to add backwards-compatible listener"; @@ -183,7 +196,8 @@ public: CString sArg = WebSock.GetParam("password"); if (sArg != WebSock.GetParam("password2")) { - WebSock.PrintErrorPage("Invalid Submission [Passwords do not match]"); + WebSock.PrintErrorPage( + "Invalid Submission [Passwords do not match]"); return nullptr; } @@ -208,17 +222,42 @@ public: WebSock.GetRawParam("ctcpreplies").Split("\n", vsArgs); for (const CString& sReply : vsArgs) { - pNewUser->AddCTCPReply(sReply.Token(0).Trim_n(), sReply.Token(1, true).Trim_n()); + pNewUser->AddCTCPReply(sReply.Token(0).Trim_n(), + sReply.Token(1, true).Trim_n()); } - sArg = WebSock.GetParam("nick"); if (!sArg.empty()) { pNewUser->SetNick(sArg); } - sArg = WebSock.GetParam("altnick"); if (!sArg.empty()) { pNewUser->SetAltNick(sArg); } - sArg = WebSock.GetParam("statusprefix"); if (!sArg.empty()) { pNewUser->SetStatusPrefix(sArg); } - sArg = WebSock.GetParam("ident"); if (!sArg.empty()) { pNewUser->SetIdent(sArg); } - sArg = WebSock.GetParam("realname"); if (!sArg.empty()) { pNewUser->SetRealName(sArg); } - sArg = WebSock.GetParam("quitmsg"); if (!sArg.empty()) { pNewUser->SetQuitMsg(sArg); } - sArg = WebSock.GetParam("chanmodes"); if (!sArg.empty()) { pNewUser->SetDefaultChanModes(sArg); } - sArg = WebSock.GetParam("timestampformat"); if (!sArg.empty()) { pNewUser->SetTimestampFormat(sArg); } + sArg = WebSock.GetParam("nick"); + if (!sArg.empty()) { + pNewUser->SetNick(sArg); + } + sArg = WebSock.GetParam("altnick"); + if (!sArg.empty()) { + pNewUser->SetAltNick(sArg); + } + sArg = WebSock.GetParam("statusprefix"); + if (!sArg.empty()) { + pNewUser->SetStatusPrefix(sArg); + } + sArg = WebSock.GetParam("ident"); + if (!sArg.empty()) { + pNewUser->SetIdent(sArg); + } + sArg = WebSock.GetParam("realname"); + if (!sArg.empty()) { + pNewUser->SetRealName(sArg); + } + sArg = WebSock.GetParam("quitmsg"); + if (!sArg.empty()) { + pNewUser->SetQuitMsg(sArg); + } + sArg = WebSock.GetParam("chanmodes"); + if (!sArg.empty()) { + pNewUser->SetDefaultChanModes(sArg); + } + sArg = WebSock.GetParam("timestampformat"); + if (!sArg.empty()) { + pNewUser->SetTimestampFormat(sArg); + } sArg = WebSock.GetParam("bindhost"); // To change BindHosts be admin or don't have DenySetBindHost @@ -230,7 +269,7 @@ public: if (!sArg2.empty()) { pNewUser->SetDCCBindHost(sArg2); } - } else if (pUser){ + } else if (pUser) { pNewUser->SetBindHost(pUser->GetBindHost()); pNewUser->SetDCCBindHost(pUser->GetDCCBindHost()); } @@ -252,15 +291,20 @@ public: } pNewUser->SetSkinName(WebSock.GetParam("skin")); - pNewUser->SetAutoClearChanBuffer(WebSock.GetParam("autoclearchanbuffer").ToBool()); + pNewUser->SetAutoClearChanBuffer( + WebSock.GetParam("autoclearchanbuffer").ToBool()); pNewUser->SetMultiClients(WebSock.GetParam("multiclients").ToBool()); - pNewUser->SetTimestampAppend(WebSock.GetParam("appendtimestamp").ToBool()); - pNewUser->SetTimestampPrepend(WebSock.GetParam("prependtimestamp").ToBool()); + pNewUser->SetTimestampAppend( + WebSock.GetParam("appendtimestamp").ToBool()); + pNewUser->SetTimestampPrepend( + WebSock.GetParam("prependtimestamp").ToBool()); pNewUser->SetTimezone(WebSock.GetParam("timezone")); pNewUser->SetJoinTries(WebSock.GetParam("jointries").ToUInt()); pNewUser->SetMaxJoins(WebSock.GetParam("maxjoins").ToUInt()); - pNewUser->SetAutoClearQueryBuffer(WebSock.GetParam("autoclearquerybuffer").ToBool()); - pNewUser->SetMaxQueryBuffers(WebSock.GetParam("maxquerybuffers").ToUInt()); + pNewUser->SetAutoClearQueryBuffer( + WebSock.GetParam("autoclearquerybuffer").ToBool()); + pNewUser->SetMaxQueryBuffers( + WebSock.GetParam("maxquerybuffers").ToUInt()); #ifdef HAVE_ICU CString sEncodingUtf = WebSock.GetParam("encoding_utf"); @@ -282,8 +326,10 @@ public: if (spSession->IsAdmin()) { pNewUser->SetDenyLoadMod(WebSock.GetParam("denyloadmod").ToBool()); - pNewUser->SetDenySetBindHost(WebSock.GetParam("denysetbindhost").ToBool()); - sArg = WebSock.GetParam("maxnetworks"); if (!sArg.empty()) pNewUser->SetMaxNetworks(sArg.ToUInt()); + pNewUser->SetDenySetBindHost( + WebSock.GetParam("denysetbindhost").ToBool()); + sArg = WebSock.GetParam("maxnetworks"); + if (!sArg.empty()) pNewUser->SetMaxNetworks(sArg.ToUInt()); } else if (pUser) { pNewUser->SetDenyLoadMod(pUser->DenyLoadMod()); pNewUser->SetDenySetBindHost(pUser->DenySetBindHost()); @@ -302,7 +348,8 @@ public: WebSock.GetParamValues("loadmod", vsArgs); // disallow unload webadmin from itself - if (CModInfo::UserModule == GetType() && pUser == CZNC::Get().FindUser(WebSock.GetUser())) { + if (CModInfo::UserModule == GetType() && + pUser == CZNC::Get().FindUser(WebSock.GetUser())) { bool bLoadedWebadmin = false; for (const CString& s : vsArgs) { CString sModName = s.TrimRight_n("\r"); @@ -325,11 +372,15 @@ public: CString sArgs = WebSock.GetParam("modargs_" + sModName); try { - if (!pNewUser->GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule, pNewUser, nullptr, sModRet)) { - sModLoadError = "Unable to load module [" + sModName + "] [" + sModRet + "]"; + if (!pNewUser->GetModules().LoadModule( + sModName, sArgs, CModInfo::UserModule, pNewUser, + nullptr, sModRet)) { + sModLoadError = "Unable to load module [" + + sModName + "] [" + sModRet + "]"; } } catch (...) { - sModLoadError = "Unable to load module [" + sModName + "] [" + sArgs + "]"; + sModLoadError = "Unable to load module [" + sModName + + "] [" + sArgs + "]"; } if (!sModLoadError.empty()) { @@ -348,8 +399,11 @@ public: CString sModLoadError; try { - if (!pNewUser->GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule, pNewUser, nullptr, sModRet)) { - sModLoadError = "Unable to load module [" + sModName + "] [" + sModRet + "]"; + if (!pNewUser->GetModules().LoadModule( + sModName, sArgs, CModInfo::UserModule, pNewUser, + nullptr, sModRet)) { + sModLoadError = "Unable to load module [" + sModName + + "] [" + sModRet + "]"; } } catch (...) { sModLoadError = "Unable to load module [" + sModName + "]"; @@ -366,8 +420,8 @@ public: } CString SafeGetUserNameParam(CWebSock& WebSock) { - CString sUserName = WebSock.GetParam("user"); // check for POST param - if(sUserName.empty() && !WebSock.IsPost()) { + CString sUserName = WebSock.GetParam("user"); // check for POST param + if (sUserName.empty() && !WebSock.IsPost()) { // if no POST param named user has been given and we are not // saving this form, fall back to using the GET parameter. sUserName = WebSock.GetParam("user", false); @@ -376,8 +430,8 @@ public: } CString SafeGetNetworkParam(CWebSock& WebSock) { - CString sNetwork = WebSock.GetParam("network"); // check for POST param - if(sNetwork.empty() && !WebSock.IsPost()) { + CString sNetwork = WebSock.GetParam("network"); // check for POST param + if (sNetwork.empty() && !WebSock.IsPost()) { // if no POST param named user has been given and we are not // saving this form, fall back to using the GET parameter. sNetwork = WebSock.GetParam("network", false); @@ -401,7 +455,8 @@ public: } CString GetWebMenuTitle() override { return "webadmin"; } - bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) override { + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { std::shared_ptr spSession = WebSock.GetSession(); if (sPageName == "settings") { @@ -422,7 +477,8 @@ public: CUser* pUser = SafeGetUserFromParam(WebSock); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || spSession->GetUser() != pUser)) { return false; } @@ -436,7 +492,9 @@ public: CIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || !pNetwork || spSession->GetUser() != pNetwork->GetUser())) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || !pNetwork || + spSession->GetUser() != pNetwork->GetUser())) { return false; } @@ -456,7 +514,8 @@ public: CUser* pUser = CZNC::Get().FindUser(sUser); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || spSession->GetUser() != pUser)) { return false; } @@ -465,7 +524,9 @@ public: CIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || !pNetwork || spSession->GetUser() != pNetwork->GetUser())) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || !pNetwork || + spSession->GetUser() != pNetwork->GetUser())) { return false; } @@ -475,7 +536,7 @@ public: } CString sChan = WebSock.GetParam("name"); - if(sChan.empty() && !WebSock.IsPost()) { + if (sChan.empty() && !WebSock.IsPost()) { sChan = WebSock.GetParam("name", false); } CChan* pChan = pNetwork->FindChan(sChan); @@ -489,7 +550,9 @@ public: CIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || !pNetwork || spSession->GetUser() != pNetwork->GetUser())) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || !pNetwork || + spSession->GetUser() != pNetwork->GetUser())) { return false; } @@ -503,7 +566,9 @@ public: CIRCNetwork* pNetwork = SafeGetNetworkFromParam(WebSock); // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || !pNetwork || spSession->GetUser() != pNetwork->GetUser())) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || !pNetwork || + spSession->GetUser() != pNetwork->GetUser())) { return false; } @@ -541,7 +606,8 @@ public: CUser* pUser = CZNC::Get().FindUser(sUser); if (pUser && pUser == spSession->GetUser()) { - WebSock.PrintErrorPage("Please don't delete yourself, suicide is not the answer!"); + WebSock.PrintErrorPage( + "Please don't delete yourself, suicide is not the answer!"); return true; } else if (CZNC::Get().DeleteUser(sUser)) { WebSock.Redirect(GetWebPath() + "listusers"); @@ -554,14 +620,15 @@ public: CString sUserName = SafeGetUserNameParam(WebSock); CUser* pUser = CZNC::Get().FindUser(sUserName); - if(!pUser) { - if(sUserName.empty()) { + if (!pUser) { + if (sUserName.empty()) { pUser = spSession->GetUser(); - } // else: the "no such user" message will be printed. + } // else: the "no such user" message will be printed. } // Admin||Self Check - if (!spSession->IsAdmin() && (!spSession->GetUser() || spSession->GetUser() != pUser)) { + if (!spSession->IsAdmin() && + (!spSession->GetUser() || spSession->GetUser() != pUser)) { return false; } @@ -596,7 +663,8 @@ public: return false; } - bool ChanPage(CWebSock& WebSock, CTemplate& Tmpl, CIRCNetwork* pNetwork, CChan* pChan = nullptr) { + bool ChanPage(CWebSock& WebSock, CTemplate& Tmpl, CIRCNetwork* pNetwork, + CChan* pChan = nullptr) { std::shared_ptr spSession = WebSock.GetSession(); Tmpl.SetFile("add_edit_chan.tmpl"); CUser* pUser = pNetwork->GetUser(); @@ -612,16 +680,22 @@ public: CTemplate& breadUser = Tmpl.AddRow("BreadCrumbs"); breadUser["Text"] = "Edit User [" + pUser->GetUserName() + "]"; - breadUser["URL"] = GetWebPath() + "edituser?user=" + pUser->GetUserName(); + breadUser["URL"] = + GetWebPath() + "edituser?user=" + pUser->GetUserName(); CTemplate& breadNet = Tmpl.AddRow("BreadCrumbs"); breadNet["Text"] = "Edit Network [" + pNetwork->GetName() + "]"; - breadNet["URL"] = GetWebPath() + "editnetwork?user=" + pUser->GetUserName() + "&network=" + pNetwork->GetName(); + breadNet["URL"] = GetWebPath() + "editnetwork?user=" + + pUser->GetUserName() + "&network=" + + pNetwork->GetName(); CTemplate& breadChan = Tmpl.AddRow("BreadCrumbs"); if (pChan) { Tmpl["Action"] = "editchan"; Tmpl["Edit"] = "true"; - Tmpl["Title"] = "Edit Channel" + CString(" [" + pChan->GetName() + "]") + " of Network [" + pNetwork->GetName() + "] of User [" + pNetwork->GetUser()->GetUserName() + "]"; + Tmpl["Title"] = + "Edit Channel" + CString(" [" + pChan->GetName() + "]") + + " of Network [" + pNetwork->GetName() + "] of User [" + + pNetwork->GetUser()->GetUserName() + "]"; Tmpl["ChanName"] = pChan->GetName(); Tmpl["BufferSize"] = CString(pChan->GetBufferCount()); Tmpl["DefModes"] = pChan->GetDefaultModes(); @@ -633,7 +707,9 @@ public: } } else { Tmpl["Action"] = "addchan"; - Tmpl["Title"] = "Add Channel" + CString(" for User [" + pUser->GetUserName() + "]"); + Tmpl["Title"] = + "Add Channel" + + CString(" for User [" + pUser->GetUserName() + "]"); Tmpl["BufferSize"] = CString(pUser->GetBufferCount()); Tmpl["DefModes"] = CString(pUser->GetDefaultChanModes()); Tmpl["InConfig"] = "true"; @@ -646,23 +722,31 @@ public: o2["Name"] = "autoclearchanbuffer"; o2["DisplayName"] = "Auto Clear Chan Buffer"; o2["Tooltip"] = "Automatically Clear Channel Buffer After Playback"; - if ((pChan && pChan->AutoClearChanBuffer()) || (!pChan && pUser->AutoClearChanBuffer())) { o2["Checked"] = "true"; } + if ((pChan && pChan->AutoClearChanBuffer()) || + (!pChan && pUser->AutoClearChanBuffer())) { + o2["Checked"] = "true"; + } CTemplate& o3 = Tmpl.AddRow("OptionLoop"); o3["Name"] = "detached"; o3["DisplayName"] = "Detached"; - if (pChan && pChan->IsDetached()) { o3["Checked"] = "true"; } + if (pChan && pChan->IsDetached()) { + o3["Checked"] = "true"; + } CTemplate& o4 = Tmpl.AddRow("OptionLoop"); o4["Name"] = "disabled"; o4["DisplayName"] = "Disabled"; - if (pChan && pChan->IsDisabled()) { o4["Checked"] = "true"; } + if (pChan && pChan->IsDisabled()) { + o4["Checked"] = "true"; + } FOR_EACH_MODULE(i, pNetwork) { CTemplate& mod = Tmpl.AddRow("EmbeddedModuleLoop"); mod.insert(Tmpl.begin(), Tmpl.end()); mod["WebadminAction"] = "display"; - if ((*i)->OnEmbeddedWebRequest(WebSock, "webadmin/channel", mod)) { + if ((*i)->OnEmbeddedWebRequest(WebSock, "webadmin/channel", + mod)) { mod["Embed"] = WebSock.FindTmpl(*i, "WebadminChan.tmpl"); mod["ModName"] = (*i)->GetModName(); } @@ -683,13 +767,15 @@ public: pChan = new CChan(sChanName, pNetwork, true); if (pNetwork->FindChan(pChan->GetName())) { - WebSock.PrintErrorPage("Channel [" + pChan->GetName() + "] already exists"); + WebSock.PrintErrorPage("Channel [" + pChan->GetName() + + "] already exists"); delete pChan; return true; } if (!pNetwork->AddChan(pChan)) { - WebSock.PrintErrorPage("Could not add channel [" + sChanName + "]"); + WebSock.PrintErrorPage("Could not add channel [" + sChanName + + "]"); return true; } } @@ -704,9 +790,11 @@ public: } pChan->SetDefaultModes(WebSock.GetParam("defmodes")); pChan->SetInConfig(WebSock.GetParam("save").ToBool()); - bool bAutoClearChanBuffer = WebSock.GetParam("autoclearchanbuffer").ToBool(); + bool bAutoClearChanBuffer = + WebSock.GetParam("autoclearchanbuffer").ToBool(); if (pChan->AutoClearChanBuffer() != bAutoClearChanBuffer) { - pChan->SetAutoClearChanBuffer(WebSock.GetParam("autoclearchanbuffer").ToBool()); + pChan->SetAutoClearChanBuffer( + WebSock.GetParam("autoclearchanbuffer").ToBool()); } pChan->SetKey(WebSock.GetParam("key")); @@ -734,19 +822,28 @@ public: } if (!CZNC::Get().WriteConfig()) { - WebSock.PrintErrorPage("Channel added/modified, but config was not written"); + WebSock.PrintErrorPage( + "Channel added/modified, but config was not written"); return true; } if (WebSock.HasParam("submit_return")) { - WebSock.Redirect(GetWebPath() + "editnetwork?user=" + pUser->GetUserName().Escape_n(CString::EURL) + "&network=" + pNetwork->GetName().Escape_n(CString::EURL)); + WebSock.Redirect(GetWebPath() + "editnetwork?user=" + + pUser->GetUserName().Escape_n(CString::EURL) + + "&network=" + + pNetwork->GetName().Escape_n(CString::EURL)); } else { - WebSock.Redirect(GetWebPath() + "editchan?user=" + pUser->GetUserName().Escape_n(CString::EURL) + "&network=" + pNetwork->GetName().Escape_n(CString::EURL) + "&name=" + pChan->GetName().Escape_n(CString::EURL)); + WebSock.Redirect( + GetWebPath() + "editchan?user=" + + pUser->GetUserName().Escape_n(CString::EURL) + "&network=" + + pNetwork->GetName().Escape_n(CString::EURL) + "&name=" + + pChan->GetName().Escape_n(CString::EURL)); } return true; } - bool NetworkPage(CWebSock& WebSock, CTemplate& Tmpl, CUser* pUser, CIRCNetwork* pNetwork = nullptr) { + bool NetworkPage(CWebSock& WebSock, CTemplate& Tmpl, CUser* pUser, + CIRCNetwork* pNetwork = nullptr) { std::shared_ptr spSession = WebSock.GetSession(); Tmpl.SetFile("add_edit_network.tmpl"); @@ -754,7 +851,8 @@ public: Tmpl["Username"] = pUser->GetUserName(); set ssNetworkMods; - CZNC::Get().GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule); + CZNC::Get().GetModules().GetAvailableMods(ssNetworkMods, + CModInfo::NetworkModule); for (const CModInfo& Info : ssNetworkMods) { CTemplate& l = Tmpl.AddRow("ModuleLoop"); @@ -765,7 +863,8 @@ public: l["ArgsHelpText"] = Info.GetArgsHelpText(); if (pNetwork) { - CModule *pModule = pNetwork->GetModules().FindModule(Info.GetName()); + CModule* pModule = + pNetwork->GetModules().FindModule(Info.GetName()); if (pModule) { l["Checked"] = "true"; l["Args"] = pModule->GetArgs(); @@ -773,12 +872,17 @@ public: } // Check if module is loaded globally - l["CanBeLoadedGlobally"] = CString(Info.SupportsType(CModInfo::GlobalModule)); - l["LoadedGlobally"] = CString(CZNC::Get().GetModules().FindModule(Info.GetName()) != nullptr); + l["CanBeLoadedGlobally"] = + CString(Info.SupportsType(CModInfo::GlobalModule)); + l["LoadedGlobally"] = + CString(CZNC::Get().GetModules().FindModule( + Info.GetName()) != nullptr); // Check if module is loaded by user - l["CanBeLoadedByUser"] = CString(Info.SupportsType(CModInfo::UserModule)); - l["LoadedByUser"] = CString(pUser->GetModules().FindModule(Info.GetName()) != nullptr); + l["CanBeLoadedByUser"] = + CString(Info.SupportsType(CModInfo::UserModule)); + l["LoadedByUser"] = CString( + pUser->GetModules().FindModule(Info.GetName()) != nullptr); if (!spSession->IsAdmin() && pUser->DenyLoadMod()) { l["Disabled"] = "true"; @@ -786,7 +890,8 @@ public: } // To change BindHosts be admin or don't have DenySetBindHost - if (spSession->IsAdmin() || !spSession->GetUser()->DenySetBindHost()) { + if (spSession->IsAdmin() || + !spSession->GetUser()->DenySetBindHost()) { Tmpl["BindHostEdit"] = "true"; if (pNetwork) { Tmpl["BindHost"] = pNetwork->GetBindHost(); @@ -795,13 +900,16 @@ public: CTemplate& breadUser = Tmpl.AddRow("BreadCrumbs"); breadUser["Text"] = "Edit User [" + pUser->GetUserName() + "]"; - breadUser["URL"] = GetWebPath() + "edituser?user=" + pUser->GetUserName(); + breadUser["URL"] = + GetWebPath() + "edituser?user=" + pUser->GetUserName(); CTemplate& breadNet = Tmpl.AddRow("BreadCrumbs"); if (pNetwork) { Tmpl["Action"] = "editnetwork"; Tmpl["Edit"] = "true"; - Tmpl["Title"] = "Edit Network" + CString(" [" + pNetwork->GetName() + "]") + " of User [" + pUser->GetUserName() + "]"; + Tmpl["Title"] = "Edit Network" + + CString(" [" + pNetwork->GetName() + "]") + + " of User [" + pUser->GetUserName() + "]"; Tmpl["Name"] = pNetwork->GetName(); Tmpl["Nick"] = pNetwork->GetNick(); @@ -811,13 +919,15 @@ public: Tmpl["QuitMsg"] = pNetwork->GetQuitMsg(); - Tmpl["FloodProtection"] = CString(CIRCSock::IsFloodProtected(pNetwork->GetFloodRate())); + Tmpl["FloodProtection"] = CString( + CIRCSock::IsFloodProtected(pNetwork->GetFloodRate())); Tmpl["FloodRate"] = CString(pNetwork->GetFloodRate()); Tmpl["FloodBurst"] = CString(pNetwork->GetFloodBurst()); Tmpl["JoinDelay"] = CString(pNetwork->GetJoinDelay()); - Tmpl["IRCConnectEnabled"] = CString(pNetwork->GetIRCConnectEnabled()); + Tmpl["IRCConnectEnabled"] = + CString(pNetwork->GetIRCConnectEnabled()); breadNet["Text"] = "Edit Network [" + pNetwork->GetName() + "]"; @@ -840,7 +950,8 @@ public: if (pChan->HasBufferCountSet()) { l["BufferSize"] = CString(pChan->GetBufferCount()); } else { - l["BufferSize"] = CString(pChan->GetBufferCount()) + " (default)"; + l["BufferSize"] = + CString(pChan->GetBufferCount()) + " (default)"; } l["Options"] = pChan->GetOptions(); @@ -854,12 +965,16 @@ public: } } else { if (!spSession->IsAdmin() && !pUser->HasSpaceForNewNetwork()) { - WebSock.PrintErrorPage("Network number limit reached. Ask an admin to increase the limit for you, or delete unneeded networks from Your Settings."); + WebSock.PrintErrorPage( + "Network number limit reached. Ask an admin to " + "increase the limit for you, or delete unneeded " + "networks from Your Settings."); return true; } Tmpl["Action"] = "addnetwork"; - Tmpl["Title"] = "Add Network for User [" + pUser->GetUserName() + "]"; + Tmpl["Title"] = + "Add Network for User [" + pUser->GetUserName() + "]"; Tmpl["IRCConnectEnabled"] = "true"; Tmpl["FloodProtection"] = "true"; Tmpl["FloodRate"] = "1.0"; @@ -872,7 +987,8 @@ public: CTemplate& mod = Tmpl.AddRow("EmbeddedModuleLoop"); mod.insert(Tmpl.begin(), Tmpl.end()); mod["WebadminAction"] = "display"; - if ((*i)->OnEmbeddedWebRequest(WebSock, "webadmin/network", mod)) { + if ((*i)->OnEmbeddedWebRequest(WebSock, "webadmin/network", + mod)) { mod["Embed"] = WebSock.FindTmpl(*i, "WebadminNetwork.tmpl"); mod["ModName"] = (*i)->GetModName(); } @@ -883,7 +999,8 @@ public: CTemplate& l = Tmpl.AddRow("EncodingLoop"); l["Encoding"] = sEncoding; } - const CString sEncoding = pNetwork ? pNetwork->GetEncoding() : "^UTF-8"; + const CString sEncoding = + pNetwork ? pNetwork->GetEncoding() : "^UTF-8"; if (sEncoding.empty()) { Tmpl["EncodingUtf"] = "legacy"; } else if (sEncoding[0] == '*') { @@ -909,8 +1026,11 @@ public: WebSock.PrintErrorPage("Network name is a required argument"); return true; } - if (!pNetwork && !spSession->IsAdmin() && !pUser->HasSpaceForNewNetwork()) { - WebSock.PrintErrorPage("Network number limit reached. Ask an admin to increase the limit for you, or delete few old ones from Your Settings"); + if (!pNetwork && !spSession->IsAdmin() && + !pUser->HasSpaceForNewNetwork()) { + WebSock.PrintErrorPage( + "Network number limit reached. Ask an admin to increase the " + "limit for you, or delete few old ones from Your Settings"); return true; } if (!pNetwork || pNetwork->GetName() != sName) { @@ -923,7 +1043,8 @@ public: } if (pOldNetwork) { for (CModule* pModule : pOldNetwork->GetModules()) { - CString sPath = pUser->GetUserPath() + "/networks/" + sName + "/moddata/" + pModule->GetModName(); + CString sPath = pUser->GetUserPath() + "/networks/" + + sName + "/moddata/" + pModule->GetModName(); pModule->MoveRegistry(sPath); } pNetwork->Clone(*pOldNetwork, false); @@ -991,7 +1112,7 @@ public: WebSock.GetParamValues("channel", vsArgs); for (const CString& sChan : vsArgs) { - CChan *pChan = pNetwork->FindChan(sChan.TrimRight_n("\r")); + CChan* pChan = pNetwork->FindChan(sChan.TrimRight_n("\r")); if (pChan) { pChan->SetInConfig(WebSock.GetParam("save_" + sChan).ToBool()); } @@ -1008,15 +1129,20 @@ public: if (!sModName.empty()) { CString sArgs = WebSock.GetParam("modargs_" + sModName); - CModule *pMod = pNetwork->GetModules().FindModule(sModName); + CModule* pMod = pNetwork->GetModules().FindModule(sModName); if (!pMod) { - if (!pNetwork->GetModules().LoadModule(sModName, sArgs, CModInfo::NetworkModule, pUser, pNetwork, sModRet)) { - sModLoadError = "Unable to load module [" + sModName + "] [" + sModRet + "]"; + if (!pNetwork->GetModules().LoadModule( + sModName, sArgs, CModInfo::NetworkModule, pUser, + pNetwork, sModRet)) { + sModLoadError = "Unable to load module [" + + sModName + "] [" + sModRet + "]"; } } else if (pMod->GetArgs() != sArgs) { - if (!pNetwork->GetModules().ReloadModule(sModName, sArgs, pUser, pNetwork, sModRet)) { - sModLoadError = "Unable to reload module [" + sModName + "] [" + sModRet + "]"; + if (!pNetwork->GetModules().ReloadModule( + sModName, sArgs, pUser, pNetwork, sModRet)) { + sModLoadError = "Unable to reload module [" + + sModName + "] [" + sModRet + "]"; } } @@ -1032,7 +1158,8 @@ public: set ssUnloadMods; for (const CModule* pCurMod : vCurMods) { - if (ssArgs.find(pCurMod->GetModName()) == ssArgs.end() && pCurMod->GetModName() != GetModName()) { + if (ssArgs.find(pCurMod->GetModName()) == ssArgs.end() && + pCurMod->GetModName() != GetModName()) { ssUnloadMods.insert(pCurMod->GetModName()); } } @@ -1050,14 +1177,19 @@ public: } if (!CZNC::Get().WriteConfig()) { - WebSock.PrintErrorPage("Network added/modified, but config was not written"); + WebSock.PrintErrorPage( + "Network added/modified, but config was not written"); return true; } if (WebSock.HasParam("submit_return")) { - WebSock.Redirect(GetWebPath() + "edituser?user=" + pUser->GetUserName().Escape_n(CString::EURL)); + WebSock.Redirect(GetWebPath() + "edituser?user=" + + pUser->GetUserName().Escape_n(CString::EURL)); } else { - WebSock.Redirect(GetWebPath() + "editnetwork?user=" + pUser->GetUserName().Escape_n(CString::EURL) + "&network=" + pNetwork->GetName().Escape_n(CString::EURL)); + WebSock.Redirect(GetWebPath() + "editnetwork?user=" + + pUser->GetUserName().Escape_n(CString::EURL) + + "&network=" + + pNetwork->GetName().Escape_n(CString::EURL)); } return true; } @@ -1090,11 +1222,13 @@ public: pUser->DeleteNetwork(sNetwork); if (!CZNC::Get().WriteConfig()) { - WebSock.PrintErrorPage("Network deleted, but config was not written"); + WebSock.PrintErrorPage( + "Network deleted, but config was not written"); return true; } - WebSock.Redirect(GetWebPath() + "edituser?user=" + pUser->GetUserName().Escape_n(CString::EURL)); + WebSock.Redirect(GetWebPath() + "edituser?user=" + + pUser->GetUserName().Escape_n(CString::EURL)); return false; } @@ -1110,11 +1244,15 @@ public: pNetwork->PutIRC("PART " + sChan); if (!CZNC::Get().WriteConfig()) { - WebSock.PrintErrorPage("Channel deleted, but config was not written"); + WebSock.PrintErrorPage( + "Channel deleted, but config was not written"); return true; } - WebSock.Redirect(GetWebPath() + "editnetwork?user=" + pNetwork->GetUser()->GetUserName().Escape_n(CString::EURL) + "&network=" + pNetwork->GetName().Escape_n(CString::EURL)); + WebSock.Redirect( + GetWebPath() + "editnetwork?user=" + + pNetwork->GetUser()->GetUserName().Escape_n(CString::EURL) + + "&network=" + pNetwork->GetName().Escape_n(CString::EURL)); return false; } @@ -1173,7 +1311,9 @@ public: l["IRCNick"] = pNetwork->GetIRCNick().GetNick(); CServer* pServer = pNetwork->GetCurrentServer(); if (pServer) { - l["Server"] = pServer->GetName() + ":" + (pServer->IsSSL() ? "+" : "") + CString(pServer->GetPort()); + l["Server"] = pServer->GetName() + ":" + + (pServer->IsSSL() ? "+" : "") + + CString(pServer->GetPort()); } } @@ -1199,7 +1339,8 @@ public: CTemplate& l = Tmpl.AddRow("EncodingLoop"); l["Encoding"] = sEncoding; } - const CString sEncoding = pUser ? pUser->GetClientEncoding() : "^UTF-8"; + const CString sEncoding = + pUser ? pUser->GetClientEncoding() : "^UTF-8"; if (sEncoding.empty()) { Tmpl["EncodingUtf"] = "legacy"; } else if (sEncoding[0] == '*') { @@ -1218,7 +1359,8 @@ public: #endif // To change BindHosts be admin or don't have DenySetBindHost - if (spSession->IsAdmin() || !spSession->GetUser()->DenySetBindHost()) { + if (spSession->IsAdmin() || + !spSession->GetUser()->DenySetBindHost()) { Tmpl["BindHostEdit"] = "true"; if (pUser) { Tmpl["BindHost"] = pUser->GetBindHost(); @@ -1250,32 +1392,41 @@ public: l["HasArgs"] = CString(Info.GetHasArgs()); l["ArgsHelpText"] = Info.GetArgsHelpText(); - CModule *pModule = nullptr; + CModule* pModule = nullptr; if (pUser) { pModule = pUser->GetModules().FindModule(Info.GetName()); // Check if module is loaded by all or some networks - const vector& userNetworks = pUser->GetNetworks(); + const vector& userNetworks = + pUser->GetNetworks(); unsigned int networksWithRenderedModuleCount = 0; for (const CIRCNetwork* pCurrentNetwork : userNetworks) { - const CModules& networkModules = pCurrentNetwork->GetModules(); + const CModules& networkModules = + pCurrentNetwork->GetModules(); if (networkModules.FindModule(Info.GetName())) { networksWithRenderedModuleCount++; } } - l["CanBeLoadedByNetwork"] = CString(Info.SupportsType(CModInfo::NetworkModule)); - l["LoadedByAllNetworks"] = CString(networksWithRenderedModuleCount == userNetworks.size()); - l["LoadedBySomeNetworks"] = CString(networksWithRenderedModuleCount != 0); + l["CanBeLoadedByNetwork"] = + CString(Info.SupportsType(CModInfo::NetworkModule)); + l["LoadedByAllNetworks"] = CString( + networksWithRenderedModuleCount == userNetworks.size()); + l["LoadedBySomeNetworks"] = + CString(networksWithRenderedModuleCount != 0); } if (pModule) { l["Checked"] = "true"; l["Args"] = pModule->GetArgs(); - if (CModInfo::UserModule == GetType() && Info.GetName() == GetModName()) { + if (CModInfo::UserModule == GetType() && + Info.GetName() == GetModName()) { l["Disabled"] = "true"; } } - l["CanBeLoadedGlobally"] = CString(Info.SupportsType(CModInfo::GlobalModule)); + l["CanBeLoadedGlobally"] = + CString(Info.SupportsType(CModInfo::GlobalModule)); // Check if module is loaded globally - l["LoadedGlobally"] = CString(CZNC::Get().GetModules().FindModule(Info.GetName()) != nullptr); + l["LoadedGlobally"] = + CString(CZNC::Get().GetModules().FindModule( + Info.GetName()) != nullptr); if (!spSession->IsAdmin() && pUser && pUser->DenyLoadMod()) { l["Disabled"] = "true"; @@ -1285,49 +1436,69 @@ public: CTemplate& o1 = Tmpl.AddRow("OptionLoop"); o1["Name"] = "autoclearchanbuffer"; o1["DisplayName"] = "Auto Clear Chan Buffer"; - o1["Tooltip"] = "Automatically Clear Channel Buffer After Playback (the default value for new channels)"; - if (!pUser || pUser->AutoClearChanBuffer()) { o1["Checked"] = "true"; } + o1["Tooltip"] = + "Automatically Clear Channel Buffer After Playback (the " + "default value for new channels)"; + if (!pUser || pUser->AutoClearChanBuffer()) { + o1["Checked"] = "true"; + } /* o2 used to be auto cycle which was removed */ CTemplate& o4 = Tmpl.AddRow("OptionLoop"); o4["Name"] = "multiclients"; o4["DisplayName"] = "Multi Clients"; - if (!pUser || pUser->MultiClients()) { o4["Checked"] = "true"; } + if (!pUser || pUser->MultiClients()) { + o4["Checked"] = "true"; + } CTemplate& o7 = Tmpl.AddRow("OptionLoop"); o7["Name"] = "appendtimestamp"; o7["DisplayName"] = "Append Timestamps"; - if (pUser && pUser->GetTimestampAppend()) { o7["Checked"] = "true"; } + if (pUser && pUser->GetTimestampAppend()) { + o7["Checked"] = "true"; + } CTemplate& o8 = Tmpl.AddRow("OptionLoop"); o8["Name"] = "prependtimestamp"; o8["DisplayName"] = "Prepend Timestamps"; - if (pUser && pUser->GetTimestampPrepend()) { o8["Checked"] = "true"; } + if (pUser && pUser->GetTimestampPrepend()) { + o8["Checked"] = "true"; + } if (spSession->IsAdmin()) { CTemplate& o9 = Tmpl.AddRow("OptionLoop"); o9["Name"] = "denyloadmod"; o9["DisplayName"] = "Deny LoadMod"; - if (pUser && pUser->DenyLoadMod()) { o9["Checked"] = "true"; } + if (pUser && pUser->DenyLoadMod()) { + o9["Checked"] = "true"; + } CTemplate& o10 = Tmpl.AddRow("OptionLoop"); o10["Name"] = "isadmin"; o10["DisplayName"] = "Admin"; - if (pUser && pUser->IsAdmin()) { o10["Checked"] = "true"; } - if (pUser && pUser == CZNC::Get().FindUser(WebSock.GetUser())) { o10["Disabled"] = "true"; } + if (pUser && pUser->IsAdmin()) { + o10["Checked"] = "true"; + } + if (pUser && pUser == CZNC::Get().FindUser(WebSock.GetUser())) { + o10["Disabled"] = "true"; + } CTemplate& o11 = Tmpl.AddRow("OptionLoop"); o11["Name"] = "denysetbindhost"; o11["DisplayName"] = "Deny SetBindHost"; - if (pUser && pUser->DenySetBindHost()) { o11["Checked"] = "true"; } + if (pUser && pUser->DenySetBindHost()) { + o11["Checked"] = "true"; + } } CTemplate& o12 = Tmpl.AddRow("OptionLoop"); o12["Name"] = "autoclearquerybuffer"; o12["DisplayName"] = "Auto Clear Query Buffer"; o12["Tooltip"] = "Automatically Clear Query Buffer After Playback"; - if (!pUser || pUser->AutoClearQueryBuffer()) { o12["Checked"] = "true"; } + if (!pUser || pUser->AutoClearQueryBuffer()) { + o12["Checked"] = "true"; + } FOR_EACH_MODULE(i, pUser) { CTemplate& mod = Tmpl.AddRow("EmbeddedModuleLoop"); @@ -1342,11 +1513,13 @@ public: return true; } - /* If pUser is nullptr, we are adding a user, else we are editing this one */ + /* If pUser is nullptr, we are adding a user, else we are editing this + * one */ CString sUsername = WebSock.GetParam("user"); if (!pUser && CZNC::Get().FindUser(sUsername)) { - WebSock.PrintErrorPage("Invalid Submission [User " + sUsername + " already exists]"); + WebSock.PrintErrorPage("Invalid Submission [User " + sUsername + + " already exists]"); return true; } @@ -1361,7 +1534,7 @@ public: if (!pUser) { CString sClone = WebSock.GetParam("clone"); - if (CUser *pCloneUser = CZNC::Get().FindUser(sClone)) { + if (CUser* pCloneUser = CZNC::Get().FindUser(sClone)) { pNewUser->CloneNetworks(*pCloneUser); } @@ -1394,14 +1567,16 @@ public: } if (!CZNC::Get().WriteConfig()) { - WebSock.PrintErrorPage("User " + sAction + ", but config was not written"); + WebSock.PrintErrorPage("User " + sAction + + ", but config was not written"); return true; } if (spSession->IsAdmin() && WebSock.HasParam("submit_return")) { WebSock.Redirect(GetWebPath() + "listusers"); } else { - WebSock.Redirect(GetWebPath() + "edituser?user=" + pUser->GetUserName()); + WebSock.Redirect(GetWebPath() + "edituser?user=" + + pUser->GetUserName()); } /* we don't want the template to be printed while we redirect */ @@ -1410,7 +1585,7 @@ public: bool ListUsersPage(CWebSock& WebSock, CTemplate& Tmpl) { std::shared_ptr spSession = WebSock.GetSession(); - const map& msUsers = CZNC::Get().GetUserMap(); + const map& msUsers = CZNC::Get().GetUserMap(); Tmpl["Title"] = "Manage Users"; Tmpl["Action"] = "listusers"; @@ -1435,7 +1610,7 @@ public: Tmpl["Title"] = "Traffic Info"; Tmpl["Uptime"] = CZNC::Get().GetUptime(); - const map& msUsers = CZNC::Get().GetUserMap(); + const map& msUsers = CZNC::Get().GetUserMap(); Tmpl["TotalUsers"] = CString(msUsers.size()); size_t uiNetworks = 0, uiAttached = 0, uiClients = 0, uiServers = 0; @@ -1472,10 +1647,12 @@ public: Tmpl["TotalIRCConnections"] = CString(uiServers); CZNC::TrafficStatsPair Users, ZNC, Total; - CZNC::TrafficStatsMap traffic = CZNC::Get().GetTrafficStats(Users, ZNC, Total); + CZNC::TrafficStatsMap traffic = + CZNC::Get().GetTrafficStats(Users, ZNC, Total); for (const auto& it : traffic) { - if (!spSession->IsAdmin() && !spSession->GetUser()->GetUserName().Equals(it.first)) { + if (!spSession->IsAdmin() && + !spSession->GetUser()->GetUserName().Equals(it.first)) { continue; } @@ -1487,14 +1664,16 @@ public: l["Total"] = CString::ToByteStr(it.second.first + it.second.second); CZNC::TrafficStatsPair NetworkTotal; - CZNC::TrafficStatsMap NetworkTraffic = CZNC::Get().GetNetworkTrafficStats(it.first, NetworkTotal); + CZNC::TrafficStatsMap NetworkTraffic = + CZNC::Get().GetNetworkTrafficStats(it.first, NetworkTotal); for (const auto& it2 : NetworkTraffic) { CTemplate& l2 = Tmpl.AddRow("TrafficLoop"); l2["Network"] = it2.first; l2["In"] = CString::ToByteStr(it2.second.first); l2["Out"] = CString::ToByteStr(it2.second.second); - l2["Total"] = CString::ToByteStr(it2.second.first + it2.second.second); + l2["Total"] = + CString::ToByteStr(it2.second.first + it2.second.second); } } @@ -1535,7 +1714,8 @@ public: if (bIPv6) { eAddr = ADDR_IPV6ONLY; } else { - WebSock.GetSession()->AddError("Choose either IPv4 or IPv6 or both."); + WebSock.GetSession()->AddError( + "Choose either IPv4 or IPv6 or both."); return SettingsPage(WebSock, Tmpl); } } @@ -1551,18 +1731,21 @@ public: if (bWeb) { eAccept = CListener::ACCEPT_HTTP; } else { - WebSock.GetSession()->AddError("Choose either IRC or Web or both."); + WebSock.GetSession()->AddError( + "Choose either IRC or Web or both."); return SettingsPage(WebSock, Tmpl); } } CString sMessage; - if (CZNC::Get().AddListener(uPort, sHost, sURIPrefix, bSSL, eAddr, eAccept, sMessage)) { + if (CZNC::Get().AddListener(uPort, sHost, sURIPrefix, bSSL, eAddr, + eAccept, sMessage)) { if (!sMessage.empty()) { WebSock.GetSession()->AddSuccess(sMessage); } if (!CZNC::Get().WriteConfig()) { - WebSock.GetSession()->AddError("Port changed, but config was not written"); + WebSock.GetSession()->AddError( + "Port changed, but config was not written"); } } else { WebSock.GetSession()->AddError(sMessage); @@ -1597,10 +1780,12 @@ public: if (pListener) { CZNC::Get().DelListener(pListener); if (!CZNC::Get().WriteConfig()) { - WebSock.GetSession()->AddError("Port changed, but config was not written"); + WebSock.GetSession()->AddError( + "Port changed, but config was not written"); } } else { - WebSock.GetSession()->AddError("The specified listener was not found."); + WebSock.GetSession()->AddError( + "The specified listener was not found."); } return SettingsPage(WebSock, Tmpl); @@ -1616,7 +1801,8 @@ public: Tmpl["ConnectDelay"] = CString(CZNC::Get().GetConnectDelay()); Tmpl["ServerThrottle"] = CString(CZNC::Get().GetServerThrottle()); Tmpl["AnonIPLimit"] = CString(CZNC::Get().GetAnonIPLimit()); - Tmpl["ProtectWebSessions"] = CString(CZNC::Get().GetProtectWebSessions()); + Tmpl["ProtectWebSessions"] = + CString(CZNC::Get().GetProtectWebSessions()); Tmpl["HideVersion"] = CString(CZNC::Get().GetHideVersion()); const VCString& vsMotd = CZNC::Get().GetMotd(); @@ -1632,15 +1818,19 @@ public: l["Port"] = CString(pListener->GetPort()); l["BindHost"] = pListener->GetBindHost(); - l["IsWeb"] = CString(pListener->GetAcceptType() != CListener::ACCEPT_IRC); - l["IsIRC"] = CString(pListener->GetAcceptType() != CListener::ACCEPT_HTTP); + l["IsWeb"] = CString(pListener->GetAcceptType() != + CListener::ACCEPT_IRC); + l["IsIRC"] = CString(pListener->GetAcceptType() != + CListener::ACCEPT_HTTP); l["URIPrefix"] = pListener->GetURIPrefix() + "/"; // simple protection for user from shooting his own foot // TODO check also for hosts/families - // such check is only here, user still can forge HTTP request to delete web port - l["SuggestDeletion"] = CString(pListener->GetPort() != WebSock.GetLocalPort()); + // such check is only here, user still can forge HTTP request to + // delete web port + l["SuggestDeletion"] = + CString(pListener->GetPort() != WebSock.GetLocalPort()); #ifdef HAVE_LIBSSL if (pListener->IsSSL()) { @@ -1679,16 +1869,19 @@ public: } set ssGlobalMods; - CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule); + CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, + CModInfo::GlobalModule); for (const CModInfo& Info : ssGlobalMods) { CTemplate& l = Tmpl.AddRow("ModuleLoop"); - CModule *pModule = CZNC::Get().GetModules().FindModule(Info.GetName()); + CModule* pModule = + CZNC::Get().GetModules().FindModule(Info.GetName()); if (pModule) { l["Checked"] = "true"; l["Args"] = pModule->GetArgs(); - if (CModInfo::GlobalModule == GetType() && Info.GetName() == GetModName()) { + if (CModInfo::GlobalModule == GetType() && + Info.GetName() == GetModName()) { l["Disabled"] = "true"; } } @@ -1699,49 +1892,64 @@ public: l["HasArgs"] = CString(Info.GetHasArgs()); l["ArgsHelpText"] = Info.GetArgsHelpText(); - // Check if the module is loaded by all or some users, and/or by all or some networks + // Check if the module is loaded by all or some users, and/or by + // all or some networks unsigned int usersWithRenderedModuleCount = 0; unsigned int networksWithRenderedModuleCount = 0; unsigned int networksCount = 0; - const map& allUsers = CZNC::Get().GetUserMap(); + const map& allUsers = CZNC::Get().GetUserMap(); for (const auto& it : allUsers) { const CUser* pUser = it.second; - + // Count users which has loaded a render module const CModules& userModules = pUser->GetModules(); if (userModules.FindModule(Info.GetName())) { usersWithRenderedModuleCount++; } // Count networks which has loaded a render module - const vector& userNetworks = pUser->GetNetworks(); + const vector& userNetworks = + pUser->GetNetworks(); networksCount += userNetworks.size(); - for (const CIRCNetwork* pCurrentNetwork : userNetworks) - { - if (pCurrentNetwork->GetModules().FindModule(Info.GetName())) { + for (const CIRCNetwork* pCurrentNetwork : userNetworks) { + if (pCurrentNetwork->GetModules().FindModule( + Info.GetName())) { networksWithRenderedModuleCount++; } } } - l["CanBeLoadedByNetwork"] = CString(Info.SupportsType(CModInfo::NetworkModule)); - l["LoadedByAllNetworks"] = CString(networksWithRenderedModuleCount == networksCount); - l["LoadedBySomeNetworks"] = CString(networksWithRenderedModuleCount != 0); + l["CanBeLoadedByNetwork"] = + CString(Info.SupportsType(CModInfo::NetworkModule)); + l["LoadedByAllNetworks"] = + CString(networksWithRenderedModuleCount == networksCount); + l["LoadedBySomeNetworks"] = + CString(networksWithRenderedModuleCount != 0); - l["CanBeLoadedByUser"] = CString(Info.SupportsType(CModInfo::UserModule)); - l["LoadedByAllUsers"] = CString(usersWithRenderedModuleCount == allUsers.size()); - l["LoadedBySomeUsers"] = CString(usersWithRenderedModuleCount != 0); + l["CanBeLoadedByUser"] = + CString(Info.SupportsType(CModInfo::UserModule)); + l["LoadedByAllUsers"] = + CString(usersWithRenderedModuleCount == allUsers.size()); + l["LoadedBySomeUsers"] = + CString(usersWithRenderedModuleCount != 0); } return true; } CString sArg; - sArg = WebSock.GetParam("statusprefix"); CZNC::Get().SetStatusPrefix(sArg); - sArg = WebSock.GetParam("maxbufsize"); CZNC::Get().SetMaxBufferSize(sArg.ToUInt()); - sArg = WebSock.GetParam("connectdelay"); CZNC::Get().SetConnectDelay(sArg.ToUInt()); - sArg = WebSock.GetParam("serverthrottle"); CZNC::Get().SetServerThrottle(sArg.ToUInt()); - sArg = WebSock.GetParam("anoniplimit"); CZNC::Get().SetAnonIPLimit(sArg.ToUInt()); - sArg = WebSock.GetParam("protectwebsessions"); CZNC::Get().SetProtectWebSessions(sArg.ToBool()); - sArg = WebSock.GetParam("hideversion"); CZNC::Get().SetHideVersion(sArg.ToBool()); + sArg = WebSock.GetParam("statusprefix"); + CZNC::Get().SetStatusPrefix(sArg); + sArg = WebSock.GetParam("maxbufsize"); + CZNC::Get().SetMaxBufferSize(sArg.ToUInt()); + sArg = WebSock.GetParam("connectdelay"); + CZNC::Get().SetConnectDelay(sArg.ToUInt()); + sArg = WebSock.GetParam("serverthrottle"); + CZNC::Get().SetServerThrottle(sArg.ToUInt()); + sArg = WebSock.GetParam("anoniplimit"); + CZNC::Get().SetAnonIPLimit(sArg.ToUInt()); + sArg = WebSock.GetParam("protectwebsessions"); + CZNC::Get().SetProtectWebSessions(sArg.ToBool()); + sArg = WebSock.GetParam("hideversion"); + CZNC::Get().SetHideVersion(sArg.ToBool()); VCString vsArgs; WebSock.GetRawParam("motd").Split("\n", vsArgs); @@ -1764,14 +1972,19 @@ public: if (!sModName.empty()) { CString sArgs = WebSock.GetParam("modargs_" + sModName); - CModule *pMod = CZNC::Get().GetModules().FindModule(sModName); + CModule* pMod = CZNC::Get().GetModules().FindModule(sModName); if (!pMod) { - if (!CZNC::Get().GetModules().LoadModule(sModName, sArgs, CModInfo::GlobalModule, nullptr, nullptr, sModRet)) { - sModLoadError = "Unable to load module [" + sModName + "] [" + sModRet + "]"; + if (!CZNC::Get().GetModules().LoadModule( + sModName, sArgs, CModInfo::GlobalModule, nullptr, + nullptr, sModRet)) { + sModLoadError = "Unable to load module [" + sModName + + "] [" + sModRet + "]"; } } else if (pMod->GetArgs() != sArgs) { - if (!CZNC::Get().GetModules().ReloadModule(sModName, sArgs, nullptr, nullptr, sModRet)) { - sModLoadError = "Unable to reload module [" + sModName + "] [" + sModRet + "]"; + if (!CZNC::Get().GetModules().ReloadModule( + sModName, sArgs, nullptr, nullptr, sModRet)) { + sModLoadError = "Unable to reload module [" + sModName + + "] [" + sModRet + "]"; } } @@ -1787,7 +2000,8 @@ public: for (const CModule* pCurMod : vCurMods) { if (ssArgs.find(pCurMod->GetModName()) == ssArgs.end() && - (CModInfo::GlobalModule != GetType() || pCurMod->GetModName() != GetModName())) { + (CModInfo::GlobalModule != GetType() || + pCurMod->GetModName() != GetModName())) { ssUnloadMods.insert(pCurMod->GetModName()); } } @@ -1797,7 +2011,8 @@ public: } if (!CZNC::Get().WriteConfig()) { - WebSock.GetSession()->AddError("Settings changed, but config was not written"); + WebSock.GetSession()->AddError( + "Settings changed, but config was not written"); } WebSock.Redirect(GetWebPath() + "settings"); @@ -1806,7 +2021,8 @@ public: } }; -template<> void TModInfo(CModInfo& Info) { +template <> +void TModInfo(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("webadmin"); } diff --git a/src/Buffer.cpp b/src/Buffer.cpp index 34f69bb7..6439df71 100644 --- a/src/Buffer.cpp +++ b/src/Buffer.cpp @@ -19,10 +19,12 @@ #include #include -CBufLine::CBufLine(const CMessage& Format, const CString& sText) : m_Message(Format), m_sText(sText) { -} +CBufLine::CBufLine(const CMessage& Format, const CString& sText) + : m_Message(Format), m_sText(sText) {} -CBufLine::CBufLine(const CString& sFormat, const CString& sText, const timeval* ts, const MCString& mssTags) : m_sText(sText) { +CBufLine::CBufLine(const CString& sFormat, const CString& sText, + const timeval* ts, const MCString& mssTags) + : m_sText(sText) { m_Message.Parse(sFormat); m_Message.SetTags(mssTags); @@ -43,7 +45,8 @@ void CBufLine::UpdateTime() { m_Message.SetTime(tv); } -CMessage CBufLine::ToMessage(const CClient& Client, const MCString& mssParams) const { +CMessage CBufLine::ToMessage(const CClient& Client, + const MCString& mssParams) const { CMessage Line = m_Message; CString sSender = Line.GetNick().GetNickMask(); @@ -53,19 +56,22 @@ CMessage CBufLine::ToMessage(const CClient& Client, const MCString& mssParams) c if (Client.HasServerTime()) { mssThisParams["text"] = m_sText; } else { - mssThisParams["text"] = Client.GetUser()->AddTimestamp(Line.GetTime().tv_sec, m_sText); + mssThisParams["text"] = + Client.GetUser()->AddTimestamp(Line.GetTime().tv_sec, m_sText); } // make a copy of params, because the following loop modifies the original VCString vsParams = Line.GetParams(); for (unsigned int uIdx = 0; uIdx < vsParams.size(); ++uIdx) { - Line.SetParam(uIdx, CString::NamedFormat(vsParams[uIdx], mssThisParams)); + Line.SetParam(uIdx, + CString::NamedFormat(vsParams[uIdx], mssThisParams)); } return Line; } -CString CBufLine::GetLine(const CClient& Client, const MCString& mssParams) const { +CString CBufLine::GetLine(const CClient& Client, + const MCString& mssParams) const { CMessage Line = ToMessage(Client, mssParams); // Note: Discard all tags (except the time tag, conditionally) to @@ -84,12 +90,12 @@ CString CBufLine::GetLine(const CClient& Client, const MCString& mssParams) cons return Line.ToString(); } -CBuffer::CBuffer(unsigned int uLineCount) : m_uLineCount(uLineCount) { -} +CBuffer::CBuffer(unsigned int uLineCount) : m_uLineCount(uLineCount) {} CBuffer::~CBuffer() {} -CBuffer::size_type CBuffer::AddLine(const CMessage& Format, const CString& sText) { +CBuffer::size_type CBuffer::AddLine(const CMessage& Format, + const CString& sText) { if (!m_uLineCount) { return 0; } @@ -102,7 +108,9 @@ CBuffer::size_type CBuffer::AddLine(const CMessage& Format, const CString& sText return size(); } -CBuffer::size_type CBuffer::UpdateLine(const CString& sCommand, const CMessage& Format, const CString& sText) { +CBuffer::size_type CBuffer::UpdateLine(const CString& sCommand, + const CMessage& Format, + const CString& sText) { for (CBufLine& Line : *this) { if (Line.GetCommand().Equals(sCommand)) { Line = CBufLine(Format, sText); @@ -113,7 +121,8 @@ CBuffer::size_type CBuffer::UpdateLine(const CString& sCommand, const CMessage& return AddLine(Format, sText); } -CBuffer::size_type CBuffer::UpdateExactLine(const CMessage& Format, const CString& sText) { +CBuffer::size_type CBuffer::UpdateExactLine(const CMessage& Format, + const CString& sText) { for (CBufLine& Line : *this) { if (Line.Equals(Format)) { return size(); @@ -123,7 +132,9 @@ CBuffer::size_type CBuffer::UpdateExactLine(const CMessage& Format, const CStrin return AddLine(Format, sText); } -CBuffer::size_type CBuffer::AddLine(const CString& sFormat, const CString& sText, const timeval* ts, const MCString& mssTags) { +CBuffer::size_type CBuffer::AddLine(const CString& sFormat, + const CString& sText, const timeval* ts, + const MCString& mssTags) { CMessage Message(sFormat); if (ts) { Message.SetTime(*ts); @@ -132,11 +143,14 @@ CBuffer::size_type CBuffer::AddLine(const CString& sFormat, const CString& sText return AddLine(Message, sText); } -CBuffer::size_type CBuffer::UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText) { +CBuffer::size_type CBuffer::UpdateLine(const CString& sMatch, + const CString& sFormat, + const CString& sText) { return UpdateLine(CMessage(sMatch).GetCommand(), CMessage(sFormat), sText); } -CBuffer::size_type CBuffer::UpdateExactLine(const CString& sFormat, const CString& sText) { +CBuffer::size_type CBuffer::UpdateExactLine(const CString& sFormat, + const CString& sText) { return UpdateExactLine(CMessage(sFormat, sText)); } @@ -144,7 +158,8 @@ const CBufLine& CBuffer::GetBufLine(unsigned int uIdx) const { return (*this)[uIdx]; } -CString CBuffer::GetLine(size_type uIdx, const CClient& Client, const MCString& msParams) const { +CString CBuffer::GetLine(size_type uIdx, const CClient& Client, + const MCString& msParams) const { return (*this)[uIdx].GetLine(Client, msParams); } diff --git a/src/Chan.cpp b/src/Chan.cpp index f387e869..d19689e6 100644 --- a/src/Chan.cpp +++ b/src/Chan.cpp @@ -26,29 +26,29 @@ using std::set; using std::vector; using std::map; -CChan::CChan(const CString& sName, CIRCNetwork* pNetwork, bool bInConfig, CConfig *pConfig) - : m_bDetached(false), - m_bIsOn(false), - m_bAutoClearChanBuffer(pNetwork->GetUser()->AutoClearChanBuffer()), - m_bInConfig(bInConfig), - m_bDisabled(false), - m_bHasBufferCountSet(false), - m_bHasAutoClearChanBufferSet(false), - m_sName(sName.Token(0)), - m_sKey(sName.Token(1)), - m_sTopic(""), - m_sTopicOwner(""), - m_ulTopicDate(0), - m_ulCreationDate(0), - m_pNetwork(pNetwork), - m_Nick(), - m_uJoinTries(0), - m_sDefaultModes(""), - m_msNicks(), - m_Buffer(), - m_bModeKnown(false), - m_musModes() -{ +CChan::CChan(const CString& sName, CIRCNetwork* pNetwork, bool bInConfig, + CConfig* pConfig) + : m_bDetached(false), + m_bIsOn(false), + m_bAutoClearChanBuffer(pNetwork->GetUser()->AutoClearChanBuffer()), + m_bInConfig(bInConfig), + m_bDisabled(false), + m_bHasBufferCountSet(false), + m_bHasAutoClearChanBufferSet(false), + m_sName(sName.Token(0)), + m_sKey(sName.Token(1)), + m_sTopic(""), + m_sTopicOwner(""), + m_ulTopicDate(0), + m_ulCreationDate(0), + m_pNetwork(pNetwork), + m_Nick(), + m_uJoinTries(0), + m_sDefaultModes(""), + m_msNicks(), + m_Buffer(), + m_bModeKnown(false), + m_musModes() { if (!m_pNetwork->IsChan(m_sName)) { m_sName = "#" + m_sName; } @@ -63,25 +63,24 @@ CChan::CChan(const CString& sName, CIRCNetwork* pNetwork, bool bInConfig, CConfi if (pConfig->FindStringEntry("autoclearchanbuffer", sValue)) SetAutoClearChanBuffer(sValue.ToBool()); if (pConfig->FindStringEntry("keepbuffer", sValue)) - SetAutoClearChanBuffer(!sValue.ToBool()); // XXX Compatibility crap, added in 0.207 + SetAutoClearChanBuffer( + !sValue.ToBool()); // XXX Compatibility crap, added in 0.207 if (pConfig->FindStringEntry("detached", sValue)) SetDetached(sValue.ToBool()); if (pConfig->FindStringEntry("disabled", sValue)) - if (sValue.ToBool()) - Disable(); + if (sValue.ToBool()) Disable(); if (pConfig->FindStringEntry("autocycle", sValue)) if (sValue.Equals("true")) - CUtils::PrintError("WARNING: AutoCycle has been removed, instead try -> LoadModule = autocycle " + sName); - if (pConfig->FindStringEntry("key", sValue)) - SetKey(sValue); - if (pConfig->FindStringEntry("modes", sValue)) - SetDefaultModes(sValue); + CUtils::PrintError( + "WARNING: AutoCycle has been removed, instead try -> " + "LoadModule = autocycle " + + sName); + if (pConfig->FindStringEntry("key", sValue)) SetKey(sValue); + if (pConfig->FindStringEntry("modes", sValue)) SetDefaultModes(sValue); } } -CChan::~CChan() { - ClearNicks(); -} +CChan::~CChan() { ClearNicks(); } void CChan::Reset() { m_bIsOn = false; @@ -102,13 +101,11 @@ CConfig CChan::ToConfig() const { if (m_bHasBufferCountSet) config.AddKeyValuePair("Buffer", CString(GetBufferCount())); if (m_bHasAutoClearChanBufferSet) - config.AddKeyValuePair("AutoClearChanBuffer", CString(AutoClearChanBuffer())); - if (IsDetached()) - config.AddKeyValuePair("Detached", "true"); - if (IsDisabled()) - config.AddKeyValuePair("Disabled", "true"); - if (!GetKey().empty()) - config.AddKeyValuePair("Key", GetKey()); + config.AddKeyValuePair("AutoClearChanBuffer", + CString(AutoClearChanBuffer())); + if (IsDetached()) config.AddKeyValuePair("Detached", "true"); + if (IsDisabled()) config.AddKeyValuePair("Disabled", "true"); + if (!GetKey().empty()) config.AddKeyValuePair("Key", GetKey()); if (!GetDefaultModes().empty()) config.AddKeyValuePair("Modes", GetDefaultModes()); @@ -138,7 +135,8 @@ void CChan::Clone(CChan& chan) { } void CChan::Cycle() const { - m_pNetwork->PutIRC("PART " + GetName() + "\r\nJOIN " + GetName() + " " + GetKey()); + m_pNetwork->PutIRC("PART " + GetName() + "\r\nJOIN " + GetName() + " " + + GetKey()); } void CChan::JoinUser(const CString& sKey) { @@ -149,14 +147,25 @@ void CChan::JoinUser(const CString& sKey) { } void CChan::AttachUser(CClient* pClient) { - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " JOIN :" + GetName(), pClient); + m_pNetwork->PutUser( + ":" + m_pNetwork->GetIRCNick().GetNickMask() + " JOIN :" + GetName(), + pClient); if (!GetTopic().empty()) { - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 332 " + m_pNetwork->GetIRCNick().GetNick() + " " + GetName() + " :" + GetTopic(), pClient); - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 333 " + m_pNetwork->GetIRCNick().GetNick() + " " + GetName() + " " + GetTopicOwner() + " " + CString(GetTopicDate()), pClient); + m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 332 " + + m_pNetwork->GetIRCNick().GetNick() + " " + + GetName() + " :" + GetTopic(), + pClient); + m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 333 " + + m_pNetwork->GetIRCNick().GetNick() + " " + + GetName() + " " + GetTopicOwner() + " " + + CString(GetTopicDate()), + pClient); } - CString sPre = ":" + m_pNetwork->GetIRCServer() + " 353 " + m_pNetwork->GetIRCNick().GetNick() + " " + GetModeForNames() + " " + GetName() + " :"; + CString sPre = ":" + m_pNetwork->GetIRCServer() + " 353 " + + m_pNetwork->GetIRCNick().GetNick() + " " + + GetModeForNames() + " " + GetName() + " :"; CString sLine = sPre; CString sPerm, sNick; @@ -168,7 +177,8 @@ void CChan::AttachUser(CClient* pClient) { else pThisClient = pClient; - for (map::iterator a = m_msNicks.begin(); a != m_msNicks.end(); ++a) { + for (map::iterator a = m_msNicks.begin(); + a != m_msNicks.end(); ++a) { if (pThisClient->HasNamesx()) { sPerm = a->second.GetPermStr(); } else { @@ -178,8 +188,10 @@ void CChan::AttachUser(CClient* pClient) { sPerm += c; } } - if (pThisClient->HasUHNames() && !a->second.GetIdent().empty() && !a->second.GetHost().empty()) { - sNick = a->first + "!" + a->second.GetIdent() + "@" + a->second.GetHost(); + if (pThisClient->HasUHNames() && !a->second.GetIdent().empty() && + !a->second.GetHost().empty()) { + sNick = a->first + "!" + a->second.GetIdent() + "@" + + a->second.GetHost(); } else { sNick = a->first; } @@ -194,11 +206,14 @@ void CChan::AttachUser(CClient* pClient) { } } - if (pClient) // We only want to do this for one client + if (pClient) // We only want to do this for one client break; } - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 366 " + m_pNetwork->GetIRCNick().GetNick() + " " + GetName() + " :End of /NAMES list.", pClient); + m_pNetwork->PutUser(":" + m_pNetwork->GetIRCServer() + " 366 " + + m_pNetwork->GetIRCNick().GetNick() + " " + + GetName() + " :End of /NAMES list.", + pClient); m_bDetached = false; // Send Buffer @@ -207,7 +222,8 @@ void CChan::AttachUser(CClient* pClient) { void CChan::DetachUser() { if (!m_bDetached) { - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PART " + GetName()); + m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + + " PART " + GetName()); m_bDetached = true; } } @@ -231,7 +247,7 @@ CString CChan::GetModeForNames() const { for (const auto& it : m_musModes) { if (it.first == 's') { sMode = "@"; - } else if ((it.first == 'p') && sMode.empty()){ + } else if ((it.first == 'p') && sMode.empty()) { sMode = "*"; } } @@ -257,7 +273,8 @@ void CChan::InheritAutoClearChanBuffer(bool b) { if (!m_bHasAutoClearChanBufferSet) { m_bAutoClearChanBuffer = b; - if (m_bAutoClearChanBuffer && !IsDetached() && m_pNetwork->IsUserOnline()) { + if (m_bAutoClearChanBuffer && !IsDetached() && + m_pNetwork->IsUserOnline()) { ClearBuffer(); } } @@ -268,7 +285,8 @@ void CChan::ResetAutoClearChanBuffer() { m_bHasAutoClearChanBufferSet = false; } -void CChan::OnWho(const CString& sNick, const CString& sIdent, const CString& sHost) { +void CChan::OnWho(const CString& sNick, const CString& sIdent, + const CString& sHost) { CNick* pNick = FindNick(sNick); if (pNick) { @@ -288,11 +306,11 @@ void CChan::ModeChange(const CString& sModes, const CNick* pOpNick) { CNick* OpNick = FindNick(pOpNick->GetNick()); /* If nothing was found, use the original pOpNick, else use the * CNick* from FindNick() */ - if (OpNick) - pOpNick = OpNick; + if (OpNick) pOpNick = OpNick; } - NETWORKMODULECALL(OnRawMode2(pOpNick, *this, sModeArg, sArgs), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL(OnRawMode2(pOpNick, *this, sModeArg, sArgs), + m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); for (unsigned int a = 0; a < sModeArg.size(); a++) { const unsigned char& uMode = sModeArg[a]; @@ -305,7 +323,8 @@ void CChan::ModeChange(const CString& sModes, const CNick* pOpNick) { CString sArg = GetModeArg(sArgs); CNick* pNick = FindNick(sArg); if (pNick) { - unsigned char uPerm = m_pNetwork->GetIRCSock()->GetPermFromMode(uMode); + unsigned char uPerm = + m_pNetwork->GetIRCSock()->GetPermFromMode(uMode); if (uPerm) { bool bNoChange = (pNick->HasPerm(uPerm) == bAdd); @@ -324,19 +343,34 @@ void CChan::ModeChange(const CString& sModes, const CNick* pOpNick) { } } - NETWORKMODULECALL(OnChanPermission2(pOpNick, *pNick, *this, uMode, bAdd, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL(OnChanPermission2(pOpNick, *pNick, *this, + uMode, bAdd, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, + nullptr, NOTHING); if (uMode == CChan::M_Op) { if (bAdd) { - NETWORKMODULECALL(OnOp2(pOpNick, *pNick, *this, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL( + OnOp2(pOpNick, *pNick, *this, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + NOTHING); } else { - NETWORKMODULECALL(OnDeop2(pOpNick, *pNick, *this, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL( + OnDeop2(pOpNick, *pNick, *this, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + NOTHING); } } else if (uMode == CChan::M_Voice) { if (bAdd) { - NETWORKMODULECALL(OnVoice2(pOpNick, *pNick, *this, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL( + OnVoice2(pOpNick, *pNick, *this, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + NOTHING); } else { - NETWORKMODULECALL(OnDevoice2(pOpNick, *pNick, *this, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL( + OnDevoice2(pOpNick, *pNick, *this, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + NOTHING); } } } @@ -371,7 +405,9 @@ void CChan::ModeChange(const CString& sModes, const CNick* pOpNick) { } else { bNoChange = !HasMode(uMode); } - NETWORKMODULECALL(OnMode2(pOpNick, *this, uMode, sArg, bAdd, bNoChange), m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); + NETWORKMODULECALL( + OnMode2(pOpNick, *this, uMode, sArg, bAdd, bNoChange), + m_pNetwork->GetUser(), m_pNetwork, nullptr, NOTHING); if (!bList) { (bAdd) ? AddMode(uMode, sArg) : RemMode(uMode); @@ -437,13 +473,11 @@ bool CChan::RemMode(unsigned char uMode) { CString CChan::GetModeArg(CString& sArgs) const { CString sRet = sArgs.substr(0, sArgs.find(' ')); - sArgs = (sRet.size() < sArgs.size()) ? sArgs.substr(sRet.size() +1) : ""; + sArgs = (sRet.size() < sArgs.size()) ? sArgs.substr(sRet.size() + 1) : ""; return sRet; } -void CChan::ClearNicks() { - m_msNicks.clear(); -} +void CChan::ClearNicks() { m_msNicks.clear(); } int CChan::AddNicks(const CString& sNicks) { int iRet = 0; @@ -476,10 +510,10 @@ bool CChan::AddNick(const CString& sNick) { // The UHNames extension gets us nick!ident@host instead of just plain nick sIdent = sTmp.Token(1, true, "!"); - sHost = sIdent.Token(1, true, "@"); + sHost = sIdent.Token(1, true, "@"); sIdent = sIdent.Token(0, false, "@"); // Get the nick - sTmp = sTmp.Token(0, false, "!"); + sTmp = sTmp.Token(0, false, "!"); CNick tmpNick(sTmp); CNick* pNick = FindNick(sTmp); @@ -488,10 +522,8 @@ bool CChan::AddNick(const CString& sNick) { pNick->SetNetwork(m_pNetwork); } - if (!sIdent.empty()) - pNick->SetIdent(sIdent); - if (!sHost.empty()) - pNick->SetHost(sHost); + if (!sIdent.empty()) pNick->SetIdent(sIdent); + if (!sHost.empty()) pNick->SetHost(sHost); for (CString::size_type i = 0; i < sPrefix.length(); i++) { pNick->AddPerm(sPrefix[i]); @@ -523,7 +555,7 @@ map CChan::GetPermCounts() const { } bool CChan::RemNick(const CString& sNick) { - map::iterator it; + map::iterator it; set::iterator it2; it = m_msNicks.find(sNick); @@ -537,7 +569,7 @@ bool CChan::RemNick(const CString& sNick) { } bool CChan::ChangeNick(const CString& sOldNick, const CString& sNewNick) { - map::iterator it = m_msNicks.find(sOldNick); + map::iterator it = m_msNicks.find(sOldNick); if (it == m_msNicks.end()) { return false; @@ -546,7 +578,8 @@ bool CChan::ChangeNick(const CString& sOldNick, const CString& sNewNick) { // Rename this nick it->second.SetNick(sNewNick); - // Insert a new element into the map then erase the old one, do this to change the key to the new nick + // Insert a new element into the map then erase the old one, do this to + // change the key to the new nick m_msNicks[sNewNick] = it->second; m_msNicks.erase(it); @@ -554,12 +587,12 @@ bool CChan::ChangeNick(const CString& sOldNick, const CString& sNewNick) { } const CNick* CChan::FindNick(const CString& sNick) const { - map::const_iterator it = m_msNicks.find(sNick); + map::const_iterator it = m_msNicks.find(sNick); return (it != m_msNicks.end()) ? &it->second : nullptr; } CNick* CChan::FindNick(const CString& sNick) { - map::iterator it = m_msNicks.find(sNick); + map::iterator it = m_msNicks.find(sNick); return (it != m_msNicks.end()) ? &it->second : nullptr; } @@ -572,46 +605,57 @@ void CChan::SendBuffer(CClient* pClient) { void CChan::SendBuffer(CClient* pClient, const CBuffer& Buffer) { if (m_pNetwork && m_pNetwork->IsUserAttached()) { - // in the event that pClient is nullptr, need to send this to all clients for the user - // I'm presuming here that pClient is listed inside vClients thus vClients at this + // in the event that pClient is nullptr, need to send this to all + // clients for the user + // I'm presuming here that pClient is listed inside vClients thus + // vClients at this // point can't be empty. // - // This loop has to be cycled twice to maintain the existing behavior which is + // This loop has to be cycled twice to maintain the existing behavior + // which is // 1. OnChanBufferStarting // 2. OnChanBufferPlayLine // 3. ClearBuffer() if not keeping the buffer // 4. OnChanBufferEnding // - // With the exception of ClearBuffer(), this needs to happen per client, and + // With the exception of ClearBuffer(), this needs to happen per client, + // and // if pClient is not nullptr, the loops break after the first iteration. // // Rework this if you like ... if (!Buffer.IsEmpty()) { - const vector & vClients = m_pNetwork->GetClients(); + const vector& vClients = m_pNetwork->GetClients(); for (CClient* pEachClient : vClients) { - CClient * pUseClient = (pClient ? pClient : pEachClient); + CClient* pUseClient = (pClient ? pClient : pEachClient); bool bWasPlaybackActive = pUseClient->IsPlaybackActive(); pUseClient->SetPlaybackActive(true); bool bSkipStatusMsg = pUseClient->HasServerTime(); - NETWORKMODULECALL(OnChanBufferStarting(*this, *pUseClient), m_pNetwork->GetUser(), m_pNetwork, nullptr, &bSkipStatusMsg); + NETWORKMODULECALL(OnChanBufferStarting(*this, *pUseClient), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + &bSkipStatusMsg); if (!bSkipStatusMsg) { - m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + GetName() + " :Buffer Playback...", pUseClient); + m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + GetName() + + " :Buffer Playback...", + pUseClient); } bool bBatch = pUseClient->HasBatch(); CString sBatchName = GetName().MD5(); if (bBatch) { - m_pNetwork->PutUser(":znc.in BATCH +" + sBatchName + " znc.in/playback " + GetName(), pUseClient); + m_pNetwork->PutUser(":znc.in BATCH +" + sBatchName + + " znc.in/playback " + GetName(), + pUseClient); } size_t uSize = Buffer.Size(); for (size_t uIdx = 0; uIdx < uSize; uIdx++) { const CBufLine& BufLine = Buffer.GetBufLine(uIdx); - CMessage Message = BufLine.ToMessage(*pUseClient, MCString::EmptyMap); + CMessage Message = + BufLine.ToMessage(*pUseClient, MCString::EmptyMap); Message.SetChan(this); Message.SetNetwork(m_pNetwork); Message.SetClient(pClient); @@ -619,25 +663,31 @@ void CChan::SendBuffer(CClient* pClient, const CBuffer& Buffer) { Message.SetTag("batch", sBatchName); } bool bNotShowThisLine = false; - NETWORKMODULECALL(OnChanBufferPlayMessage(Message), m_pNetwork->GetUser(), m_pNetwork, nullptr, &bNotShowThisLine); + NETWORKMODULECALL(OnChanBufferPlayMessage(Message), + m_pNetwork->GetUser(), m_pNetwork, + nullptr, &bNotShowThisLine); if (bNotShowThisLine) continue; m_pNetwork->PutUser(Message, pUseClient); } bSkipStatusMsg = pUseClient->HasServerTime(); - NETWORKMODULECALL(OnChanBufferEnding(*this, *pUseClient), m_pNetwork->GetUser(), m_pNetwork, nullptr, &bSkipStatusMsg); + NETWORKMODULECALL(OnChanBufferEnding(*this, *pUseClient), + m_pNetwork->GetUser(), m_pNetwork, nullptr, + &bSkipStatusMsg); if (!bSkipStatusMsg) { - m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + GetName() + " :Playback Complete.", pUseClient); + m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + GetName() + + " :Playback Complete.", + pUseClient); } if (bBatch) { - m_pNetwork->PutUser(":znc.in BATCH -" + sBatchName, pUseClient); + m_pNetwork->PutUser(":znc.in BATCH -" + sBatchName, + pUseClient); } pUseClient->SetPlaybackActive(bWasPlaybackActive); - if (pClient) - break; + if (pClient) break; } } } diff --git a/src/Client.cpp b/src/Client.cpp index 0a2f6d57..9d2a02cf 100644 --- a/src/Client.cpp +++ b/src/Client.cpp @@ -25,52 +25,53 @@ using std::set; using std::map; using std::vector; -#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) { \ - CModule *pModule = nullptr; \ - if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \ - try { \ - pModule->SetClient(CLIENT); \ - pModule->FUNC; \ - pModule->SetClient(nullptr); \ - } catch (const CModule::EModException& e) { \ - if (e == CModule::UNLOAD) { \ - (NETWORK)->GetModules().UnloadModule(MOD); \ - } \ - } \ - } else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \ - try { \ - pModule->SetClient(CLIENT); \ - pModule->SetNetwork(NETWORK); \ - pModule->FUNC; \ - pModule->SetClient(nullptr); \ - pModule->SetNetwork(nullptr); \ - } catch (const CModule::EModException& e) { \ - if (e == CModule::UNLOAD) { \ - (USER)->GetModules().UnloadModule(MOD); \ - } \ - } \ - } else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \ - try { \ - pModule->SetClient(CLIENT); \ - pModule->SetNetwork(NETWORK); \ - pModule->SetUser(USER); \ - pModule->FUNC; \ - pModule->SetClient(nullptr); \ - pModule->SetNetwork(nullptr); \ - pModule->SetUser(nullptr); \ - } catch (const CModule::EModException& e) { \ - if (e == CModule::UNLOAD) { \ - CZNC::Get().GetModules().UnloadModule(MOD); \ - } \ - } \ - } else { \ - PutStatus("No such module [" + MOD + "]"); \ - } \ -} +#define CALLMOD(MOD, CLIENT, USER, NETWORK, FUNC) \ + { \ + CModule* pModule = nullptr; \ + if (NETWORK && (pModule = (NETWORK)->GetModules().FindModule(MOD))) { \ + try { \ + pModule->SetClient(CLIENT); \ + pModule->FUNC; \ + pModule->SetClient(nullptr); \ + } catch (const CModule::EModException& e) { \ + if (e == CModule::UNLOAD) { \ + (NETWORK)->GetModules().UnloadModule(MOD); \ + } \ + } \ + } else if ((pModule = (USER)->GetModules().FindModule(MOD))) { \ + try { \ + pModule->SetClient(CLIENT); \ + pModule->SetNetwork(NETWORK); \ + pModule->FUNC; \ + pModule->SetClient(nullptr); \ + pModule->SetNetwork(nullptr); \ + } catch (const CModule::EModException& e) { \ + if (e == CModule::UNLOAD) { \ + (USER)->GetModules().UnloadModule(MOD); \ + } \ + } \ + } else if ((pModule = CZNC::Get().GetModules().FindModule(MOD))) { \ + try { \ + pModule->SetClient(CLIENT); \ + pModule->SetNetwork(NETWORK); \ + pModule->SetUser(USER); \ + pModule->FUNC; \ + pModule->SetClient(nullptr); \ + pModule->SetNetwork(nullptr); \ + pModule->SetUser(nullptr); \ + } catch (const CModule::EModException& e) { \ + if (e == CModule::UNLOAD) { \ + CZNC::Get().GetModules().UnloadModule(MOD); \ + } \ + } \ + } else { \ + PutStatus("No such module [" + MOD + "]"); \ + } \ + } CClient::~CClient() { if (m_spAuth) { - CClientAuth* pAuth = (CClientAuth*) &(*m_spAuth); + CClientAuth* pAuth = (CClientAuth*)&(*m_spAuth); pAuth->Invalidate(); } if (m_pUser != nullptr) { @@ -81,12 +82,15 @@ CClient::~CClient() { void CClient::SendRequiredPasswordNotice() { PutClient(":irc.znc.in 464 " + GetNick() + " :Password required"); - PutClient(":irc.znc.in NOTICE AUTH :*** " - "You need to send your password. " - "Configure your client to send a server password."); - PutClient(":irc.znc.in NOTICE AUTH :*** " - "To connect now, you can use /quote PASS :, " - "or /quote PASS /: to connect to a specific network."); + PutClient( + ":irc.znc.in NOTICE AUTH :*** " + "You need to send your password. " + "Configure your client to send a server password."); + PutClient( + ":irc.znc.in NOTICE AUTH :*** " + "To connect now, you can use /quote PASS :, " + "or /quote PASS /: to connect to a " + "specific network."); } void CClient::ReadLine(const CString& sData) { @@ -104,7 +108,8 @@ void CClient::ReadLine(const CString& sData) { bool bReturn = false; if (IsAttached()) { - NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnUserRaw(sLine), m_pUser, m_pNetwork, this, + &bReturn); } else { GLOBALMODULECALL(OnUnknownUserRaw(this, sLine), &bReturn); } @@ -115,7 +120,8 @@ void CClient::ReadLine(const CString& sData) { Message.SetTags(mssTags); if (IsAttached()) { - NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnUserRawMessage(Message), m_pUser, m_pNetwork, this, + &bReturn); } else { GLOBALMODULECALL(OnUnknownUserRawMessage(Message), &bReturn); } @@ -123,7 +129,8 @@ void CClient::ReadLine(const CString& sData) { CString sCommand = Message.GetCommand(); - if (!IsAttached()) { // The following commands happen before authentication with ZNC + if (!IsAttached()) { // The following commands happen before authentication + // with ZNC if (sCommand.Equals("PASS")) { m_bGotPass = true; @@ -139,7 +146,8 @@ void CClient::ReadLine(const CString& sData) { m_bGotNick = true; AuthUser(); - return; // Don't forward this msg. ZNC will handle nick changes until auth is complete + return; // Don't forward this msg. ZNC will handle nick changes + // until auth is complete } else if (sCommand.Equals("USER")) { CString sAuthLine = Message.GetParam(0); @@ -215,11 +223,10 @@ void CClient::ReadLine(const CString& sData) { PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); } -void CClient::SetNick(const CString& s) { - m_sNick = s; -} +void CClient::SetNick(const CString& s) { m_sNick = s; } -void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect, bool bReconnect) { +void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect, + bool bReconnect) { if (bDisconnect) { if (m_pNetwork) { m_pNetwork->ClientDisconnected(this); @@ -228,7 +235,8 @@ void CClient::SetNetwork(CIRCNetwork* pNetwork, bool bDisconnect, bool bReconnec const vector& vChans = m_pNetwork->GetChans(); for (const CChan* pChan : vChans) { if (!(pChan->IsDetached())) { - PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PART " + pChan->GetName()); + PutClient(":" + m_pNetwork->GetIRCNick().GetNickMask() + + " PART " + pChan->GetName()); } } } else if (m_pUser) { @@ -308,9 +316,9 @@ void CClient::AuthUser() { CZNC::Get().AuthUser(m_spAuth); } -CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername, const CString& sPassword) - : CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) { -} +CClientAuth::CClientAuth(CClient* pClient, const CString& sUsername, + const CString& sPassword) + : CAuthBase(sUsername, sPassword, pClient), m_pClient(pClient) {} void CClientAuth::RefusedLogin(const CString& sReason) { if (m_pClient) { @@ -319,14 +327,11 @@ void CClientAuth::RefusedLogin(const CString& sReason) { } CString CAuthBase::GetRemoteIP() const { - if (m_pSock) - return m_pSock->GetRemoteIP(); + if (m_pSock) return m_pSock->GetRemoteIP(); return ""; } -void CAuthBase::Invalidate() { - m_pSock = nullptr; -} +void CAuthBase::Invalidate() { m_pSock = nullptr; } void CAuthBase::AcceptLogin(CUser& User) { if (m_pSock) { @@ -336,8 +341,7 @@ void CAuthBase::AcceptLogin(CUser& User) { } void CAuthBase::RefuseLogin(const CString& sReason) { - if (!m_pSock) - return; + if (!m_pSock) return; CUser* pUser = CZNC::Get().FindUser(GetUsername()); @@ -345,8 +349,10 @@ void CAuthBase::RefuseLogin(const CString& sReason) { // login. Use sReason because there are other reasons than "wrong // password" for a login to be rejected (e.g. fail2ban). if (pUser) { - pUser->PutStatus("A client from [" + GetRemoteIP() + "] attempted " - "to login as you, but was rejected [" + sReason + "]."); + pUser->PutStatus("A client from [" + GetRemoteIP() + + "] attempted " + "to login as you, but was rejected [" + + sReason + "]."); } GLOBALMODULECALL(OnFailedLogin(GetUsername(), GetRemoteIP()), NOTHING); @@ -383,19 +389,32 @@ void CClient::AcceptLogin(CUser& User) { PutStatus("Network (" + m_sNetwork + ") doesn't exist."); } } else if (!m_pUser->GetNetworks().empty()) { - // If a user didn't supply a network, and they have a network called "default" then automatically use this network. + // If a user didn't supply a network, and they have a network called + // "default" then automatically use this network. m_pNetwork = m_pUser->FindNetwork("default"); - // If no "default" network, try "user" network. It's for compatibility with early network stuff in ZNC, which converted old configs to "user" network. + // If no "default" network, try "user" network. It's for compatibility + // with early network stuff in ZNC, which converted old configs to + // "user" network. if (!m_pNetwork) m_pNetwork = m_pUser->FindNetwork("user"); // Otherwise, just try any network of the user. if (!m_pNetwork) m_pNetwork = *m_pUser->GetNetworks().begin(); if (m_pNetwork && m_pUser->GetNetworks().size() > 1) { - PutStatusNotice("You have several networks configured, but no network was specified for the connection."); - PutStatusNotice("Selecting network [" + m_pNetwork->GetName() + "]. To see list of all configured networks, use /znc ListNetworks"); - PutStatusNotice("If you want to choose another network, use /znc JumpNetwork , or connect to ZNC with username " + m_pUser->GetUserName() + "/ (instead of just " + m_pUser->GetUserName() + ")"); + PutStatusNotice( + "You have several networks configured, but no network was " + "specified for the connection."); + PutStatusNotice("Selecting network [" + m_pNetwork->GetName() + + "]. To see list of all configured networks, use " + "/znc ListNetworks"); + PutStatusNotice( + "If you want to choose another network, use /znc JumpNetwork " + ", or connect to ZNC with username " + + m_pUser->GetUserName() + "/ (instead of just " + + m_pUser->GetUserName() + ")"); } } else { - PutStatusNotice("You have no networks configured. Use /znc AddNetwork to add one."); + PutStatusNotice( + "You have no networks configured. Use /znc AddNetwork to " + "add one."); } SetNetwork(m_pNetwork, false); @@ -405,13 +424,9 @@ void CClient::AcceptLogin(CUser& User) { NETWORKMODULECALL(OnClientLogin(), m_pUser, m_pNetwork, this, NOTHING); } -void CClient::Timeout() { - PutClient("ERROR :Closing link [Timeout]"); -} +void CClient::Timeout() { PutClient("ERROR :Closing link [Timeout]"); } -void CClient::Connected() { - DEBUG(GetSockName() << " == Connected();"); -} +void CClient::Connected() { DEBUG(GetSockName() << " == Connected();"); } void CClient::ConnectionRefused() { DEBUG(GetSockName() << " == ConnectionRefused()"); @@ -423,7 +438,8 @@ void CClient::Disconnected() { SetNetwork(nullptr, true, false); if (m_pUser) { - NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this, NOTHING); + NETWORKMODULECALL(OnClientDisconnect(), m_pUser, pNetwork, this, + NOTHING); } } @@ -436,7 +452,9 @@ void CClient::ReachedMaxBuffer() { } void CClient::BouncedOff() { - PutStatusNotice("You are being disconnected because another user just authenticated as you."); + PutStatusNotice( + "You are being disconnected because another user just authenticated as " + "you."); Close(Csock::CLT_AFTERWRITE); } @@ -447,30 +465,28 @@ void CClient::PutIRC(const CString& sLine) { } CString CClient::GetFullName() const { - if (!m_pUser) - return GetRemoteIP(); + if (!m_pUser) return GetRemoteIP(); CString sFullName = m_pUser->GetUserName(); - if (!m_sIdentifier.empty()) - sFullName += "@" + m_sIdentifier; - if (m_pNetwork) - sFullName += "/" + m_pNetwork->GetName(); + if (!m_sIdentifier.empty()) sFullName += "@" + m_sIdentifier; + if (m_pNetwork) sFullName += "/" + m_pNetwork->GetName(); return sFullName; } void CClient::PutClient(const CString& sLine) { bool bReturn = false; CString sCopy = sLine; - NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnSendToClient(sCopy, *this), m_pUser, m_pNetwork, this, + &bReturn); if (bReturn) return; DEBUG("(" << GetFullName() << ") ZNC -> CLI [" << sCopy << "]"); Write(sCopy + "\r\n"); } -bool CClient::PutClient(const CMessage& Message) -{ +bool CClient::PutClient(const CMessage& Message) { if (!m_bAwayNotify && Message.GetType() == CMessage::Type::Away) { return false; - } else if (!m_bAccountNotify && Message.GetType() == CMessage::Type::Account) { + } else if (!m_bAccountNotify && + Message.GetType() == CMessage::Type::Account) { return false; } @@ -481,45 +497,53 @@ bool CClient::PutClient(const CMessage& Message) if (Msg.GetType() == CMessage::Type::Numeric) { unsigned int uCode = Msg.As().GetCode(); - if (uCode == 352) { // RPL_WHOREPLY + if (uCode == 352) { // RPL_WHOREPLY if (!m_bNamesx && pIRCSock->HasNamesx()) { - // The server has NAMESX, but the client doesn't, so we need to remove extra prefixes + // The server has NAMESX, but the client doesn't, so we need + // to remove extra prefixes CString sNick = Msg.GetParam(6); if (sNick.size() > 1 && pIRCSock->IsPermChar(sNick[1])) { CString sNewNick = sNick; - size_t pos = sNick.find_first_not_of(pIRCSock->GetPerms()); + size_t pos = + sNick.find_first_not_of(pIRCSock->GetPerms()); if (pos >= 2 && pos != CString::npos) { sNewNick = sNick[0] + sNick.substr(pos); } Msg.SetParam(6, sNewNick); } } - } else if (uCode == 353) { // RPL_NAMES - if ((!m_bNamesx && pIRCSock->HasNamesx()) || (!m_bUHNames && pIRCSock->HasUHNames())) { - // The server has either UHNAMES or NAMESX, but the client is missing either or both + } else if (uCode == 353) { // RPL_NAMES + if ((!m_bNamesx && pIRCSock->HasNamesx()) || + (!m_bUHNames && pIRCSock->HasUHNames())) { + // The server has either UHNAMES or NAMESX, but the client + // is missing either or both CString sNicks = Msg.GetParam(3); VCString vsNicks; sNicks.Split(" ", vsNicks, false); for (CString& sNick : vsNicks) { - if (sNick.empty()) - break; + if (sNick.empty()) break; - if (!m_bNamesx && pIRCSock->HasNamesx() && pIRCSock->IsPermChar(sNick[0])) { - // The server has NAMESX, but the client doesn't, so we just use the first perm char - size_t pos = sNick.find_first_not_of(pIRCSock->GetPerms()); + if (!m_bNamesx && pIRCSock->HasNamesx() && + pIRCSock->IsPermChar(sNick[0])) { + // The server has NAMESX, but the client doesn't, so + // we just use the first perm char + size_t pos = + sNick.find_first_not_of(pIRCSock->GetPerms()); if (pos >= 2 && pos != CString::npos) { sNick = sNick[0] + sNick.substr(pos); } } if (!m_bUHNames && pIRCSock->HasUHNames()) { - // The server has UHNAMES, but the client doesn't, so we strip away ident and host + // The server has UHNAMES, but the client doesn't, + // so we strip away ident and host sNick = sNick.Token(0, false, "!"); } } - Msg.SetParam(3, CString(" ").Join(vsNicks.begin(), vsNicks.end())); + Msg.SetParam( + 3, CString(" ").Join(vsNicks.begin(), vsNicks.end())); } } } else if (Msg.GetType() == CMessage::Type::Join) { @@ -531,7 +555,8 @@ bool CClient::PutClient(const CMessage& Message) CString sLine = Msg.ToString(CMessage::ExcludeTags); - // TODO: introduce a module hook that gives control over the tags that are sent + // TODO: introduce a module hook that gives control over the tags that are + // sent MCString mssTags; if (HasServerTime()) { @@ -565,22 +590,25 @@ void CClient::PutStatusNotice(const CString& sLine) { unsigned int CClient::PutStatus(const CTable& table) { unsigned int idx = 0; CString sLine; - while (table.GetLine(idx++, sLine)) - PutStatus(sLine); + while (table.GetLine(idx++, sLine)) PutStatus(sLine); return idx - 1; } -void CClient::PutStatus(const CString& sLine) { - PutModule("status", sLine); -} +void CClient::PutStatus(const CString& sLine) { PutModule("status", sLine); } void CClient::PutModNotice(const CString& sModule, const CString& sLine) { if (!m_pUser) { return; } - DEBUG("(" << GetFullName() << ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() + ((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " << GetNick() << " :" << sLine << "]"); - Write(":" + m_pUser->GetStatusPrefix() + ((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " + GetNick() + " :" + sLine + "\r\n"); + DEBUG("(" << GetFullName() + << ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() + + ((sModule.empty()) ? "status" : sModule) + + "!znc@znc.in NOTICE " << GetNick() << " :" << sLine + << "]"); + Write(":" + m_pUser->GetStatusPrefix() + + ((sModule.empty()) ? "status" : sModule) + "!znc@znc.in NOTICE " + + GetNick() + " :" + sLine + "\r\n"); } void CClient::PutModule(const CString& sModule, const CString& sLine) { @@ -588,19 +616,25 @@ void CClient::PutModule(const CString& sModule, const CString& sLine) { return; } - DEBUG("(" << GetFullName() << ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() + ((sModule.empty()) ? "status" : sModule) + "!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine << "]"); + DEBUG("(" << GetFullName() + << ") ZNC -> CLI [:" + m_pUser->GetStatusPrefix() + + ((sModule.empty()) ? "status" : sModule) + + "!znc@znc.in PRIVMSG " << GetNick() << " :" << sLine + << "]"); VCString vsLines; sLine.Split("\n", vsLines); for (const CString& s : vsLines) { - Write(":" + m_pUser->GetStatusPrefix() + ((sModule.empty()) ? "status" : sModule) + "!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n"); + Write(":" + m_pUser->GetStatusPrefix() + + ((sModule.empty()) ? "status" : sModule) + + "!znc@znc.in PRIVMSG " + GetNick() + " :" + s + "\r\n"); } } CString CClient::GetNick(bool bAllowIRCNick) const { CString sRet; - const CIRCSock *pSock = GetIRCSock(); + const CIRCSock* pSock = GetIRCSock(); if (bAllowIRCNick && pSock && pSock->IsAuthed()) { sRet = pSock->GetNick(); } @@ -613,12 +647,15 @@ CString CClient::GetNickMask() const { return GetIRCSock()->GetNickMask(); } - CString sHost = m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost(); + CString sHost = + m_pNetwork ? m_pNetwork->GetBindHost() : m_pUser->GetBindHost(); if (sHost.empty()) { sHost = "irc.znc.in"; } - return GetNick() + "!" + (m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" + sHost; + return GetNick() + "!" + + (m_pNetwork ? m_pNetwork->GetIdent() : m_pUser->GetIdent()) + "@" + + sHost; } bool CClient::IsValidIdentifier(const CString& sIdentifier) { @@ -628,7 +665,7 @@ bool CClient::IsValidIdentifier(const CString& sIdentifier) { return false; } - const char *p = sIdentifier.c_str(); + const char* p = sIdentifier.c_str(); while (*p) { if (*p != '_' && *p != '-' && !isalnum(*p)) { return false; @@ -640,24 +677,24 @@ bool CClient::IsValidIdentifier(const CString& sIdentifier) { return true; } -void CClient::RespondCap(const CString& sResponse) -{ +void CClient::RespondCap(const CString& sResponse) { PutClient(":irc.znc.in CAP " + GetNick() + " " + sResponse); } -void CClient::HandleCap(const CMessage& Message) -{ +void CClient::HandleCap(const CMessage& Message) { CString sSubCmd = Message.GetParam(0); if (sSubCmd.Equals("LS")) { SCString ssOfferCaps; for (const auto& it : m_mCoreCaps) { bool bServerDependent = std::get<0>(it.second); - if (!bServerDependent || m_ssServerDependentCaps.count(it.first) > 0) + if (!bServerDependent || + m_ssServerDependentCaps.count(it.first) > 0) ssOfferCaps.insert(it.first); } GLOBALMODULECALL(OnClientCapLs(this, ssOfferCaps), NOTHING); - CString sRes = CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end()); + CString sRes = + CString(" ").Join(ssOfferCaps.begin(), ssOfferCaps.end()); RespondCap("LS :" + sRes); m_bInCap = true; if (Message.GetParam(1).ToInt() >= 302) { @@ -679,16 +716,17 @@ void CClient::HandleCap(const CMessage& Message) for (const CString& sToken : vsTokens) { bool bVal = true; CString sCap = sToken; - if (sCap.TrimPrefix("-")) - bVal = false; + if (sCap.TrimPrefix("-")) bVal = false; bool bAccepted = false; const auto& it = m_mCoreCaps.find(sCap); if (m_mCoreCaps.end() != it) { bool bServerDependent = std::get<0>(it->second); - bAccepted = !bServerDependent || m_ssServerDependentCaps.count(sCap) > 0; + bAccepted = !bServerDependent || + m_ssServerDependentCaps.count(sCap) > 0; } - GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal), &bAccepted); + GLOBALMODULECALL(IsClientCapSupported(this, sCap, bVal), + &bAccepted); if (!bAccepted) { // Some unsupported capability is requested @@ -701,8 +739,7 @@ void CClient::HandleCap(const CMessage& Message) for (const CString& sToken : vsTokens) { bool bVal = true; CString sCap = sToken; - if (sCap.TrimPrefix("-")) - bVal = false; + if (sCap.TrimPrefix("-")) bVal = false; auto handler_it = m_mCoreCaps.find(sCap); if (m_mCoreCaps.end() != handler_it) { @@ -720,10 +757,12 @@ void CClient::HandleCap(const CMessage& Message) RespondCap("ACK :" + Message.GetParam(1)); } else if (sSubCmd.Equals("LIST")) { - CString sList = CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end()); + CString sList = + CString(" ").Join(m_ssAcceptedCaps.begin(), m_ssAcceptedCaps.end()); RespondCap("LIST :" + sList); } else { - PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd + " :Invalid CAP subcommand"); + PutClient(":irc.znc.in 410 " + GetNick() + " " + sSubCmd + + " :Invalid CAP subcommand"); } } @@ -771,8 +810,7 @@ void CClient::ParseIdentifier(const CString& sAuthLine) { } } -void CClient::NotifyServerDependentCaps(const SCString& ssCaps) -{ +void CClient::NotifyServerDependentCaps(const SCString& ssCaps) { for (const CString& sCap : ssCaps) { const auto& it = m_mCoreCaps.find(sCap); if (m_mCoreCaps.end() != it) { @@ -784,15 +822,16 @@ void CClient::NotifyServerDependentCaps(const SCString& ssCaps) } if (HasCapNotify() && !m_ssServerDependentCaps.empty()) { - CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(), m_ssServerDependentCaps.end()); + CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(), + m_ssServerDependentCaps.end()); PutClient(":irc.znc.in CAP " + GetNick() + " NEW :" + sCaps); } } -void CClient::ClearServerDependentCaps() -{ +void CClient::ClearServerDependentCaps() { if (HasCapNotify() && !m_ssServerDependentCaps.empty()) { - CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(), m_ssServerDependentCaps.end()); + CString sCaps = CString(" ").Join(m_ssServerDependentCaps.begin(), + m_ssServerDependentCaps.end()); PutClient(":irc.znc.in CAP " + GetNick() + " DEL :" + sCaps); for (const CString& sCap : m_ssServerDependentCaps) { @@ -808,8 +847,7 @@ void CClient::ClearServerDependentCaps() } template -void CClient::AddBuffer(const T& Message) -{ +void CClient::AddBuffer(const T& Message) { const CString sTarget = Message.GetTarget(); T Format; @@ -833,19 +871,21 @@ void CClient::AddBuffer(const T& Message) } } -void CClient::EchoMessage(const CMessage& Message) -{ +void CClient::EchoMessage(const CMessage& Message) { for (CClient* pClient : GetClients()) { - if (pClient->HasEchoMessage() || (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) || pClient->HasSelfMessage()))) { - pClient->PutClient(":" + GetNickMask() + " " + Message.ToString(CMessage::ExcludePrefix)); + if (pClient->HasEchoMessage() || + (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) || + pClient->HasSelfMessage()))) { + pClient->PutClient(":" + GetNickMask() + " " + + Message.ToString(CMessage::ExcludePrefix)); } } } -set CClient::MatchChans(const CString& sPatterns) const -{ +set CClient::MatchChans(const CString& sPatterns) const { VCString vsPatterns; - sPatterns.Replace_n(",", " ").Split(" ", vsPatterns, false, "", "", true, true); + sPatterns.Replace_n(",", " ") + .Split(" ", vsPatterns, false, "", "", true, true); set sChans; for (const CString& sPattern : vsPatterns) { @@ -855,32 +895,27 @@ set CClient::MatchChans(const CString& sPatterns) const return sChans; } -unsigned int CClient::AttachChans(const std::set& sChans) -{ +unsigned int CClient::AttachChans(const std::set& sChans) { unsigned int uAttached = 0; for (CChan* pChan : sChans) { - if (!pChan->IsDetached()) - continue; + if (!pChan->IsDetached()) continue; uAttached++; pChan->AttachUser(); } return uAttached; } -unsigned int CClient::DetachChans(const std::set& sChans) -{ +unsigned int CClient::DetachChans(const std::set& sChans) { unsigned int uDetached = 0; for (CChan* pChan : sChans) { - if (pChan->IsDetached()) - continue; + if (pChan->IsDetached()) continue; uDetached++; pChan->DetachUser(); } return uDetached; } -bool CClient::OnActionMessage(CActionMessage& Message) -{ +bool CClient::OnActionMessage(CActionMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; @@ -890,21 +925,22 @@ bool CClient::OnActionMessage(CActionMessage& Message) Message.SetTarget(sTarget); bool bContinue = false; - NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserActionMessage(Message), m_pUser, m_pNetwork, + this, &bContinue); if (bContinue) continue; if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); - PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); + PutIRC(Message.ToString(CMessage::ExcludePrefix | + CMessage::ExcludeTags)); } } return true; } -bool CClient::OnCTCPMessage(CCTCPMessage& Message) -{ +bool CClient::OnCTCPMessage(CCTCPMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; @@ -924,10 +960,12 @@ bool CClient::OnCTCPMessage(CCTCPMessage& Message) // // b) CTCP reply for VERSION is set. // 1. ZNC receives CTCP VERSION from someone - // 2. ZNC replies with the configured reply (or just drops it if empty), without forwarding anything to client + // 2. ZNC replies with the configured reply (or just drops it if + // empty), without forwarding anything to client // 3. Client does not see any CTCP request, and does not reply // - // So, if user doesn't want "via ZNC" in CTCP VERSION reply, they can set custom reply. + // So, if user doesn't want "via ZNC" in CTCP VERSION reply, they + // can set custom reply. // // See more bikeshedding at github issues #820 and #1012 Message.SetText(sCTCP + " via " + CZNC::GetTag(false)); @@ -939,32 +977,35 @@ bool CClient::OnCTCPMessage(CCTCPMessage& Message) bool bContinue = false; if (Message.IsReply()) { - NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserCTCPReplyMessage(Message), m_pUser, + m_pNetwork, this, &bContinue); } else { - NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserCTCPMessage(Message), m_pUser, m_pNetwork, + this, &bContinue); } if (bContinue) continue; if (!GetIRCSock()) { // Some lagmeters do a NOTICE to their own nick, ignore those. if (!sTarget.Equals(m_sNick)) - PutStatus("Your CTCP to [" + Message.GetTarget() + "] got lost, " - "you are not connected to IRC!"); + PutStatus("Your CTCP to [" + Message.GetTarget() + + "] got lost, " + "you are not connected to IRC!"); continue; } if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); - PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); + PutIRC(Message.ToString(CMessage::ExcludePrefix | + CMessage::ExcludeTags)); } } return true; } -bool CClient::OnJoinMessage(CJoinMessage& Message) -{ +bool CClient::OnJoinMessage(CJoinMessage& Message) { CString sChans = Message.GetTarget(); CString sKeys = Message.GetKey(); @@ -980,7 +1021,8 @@ bool CClient::OnJoinMessage(CJoinMessage& Message) Message.SetTarget(vsChans[a]); Message.SetKey((a < vsKeys.size()) ? vsKeys[a] : ""); bool bContinue = false; - NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserJoinMessage(Message), m_pUser, m_pNetwork, this, + &bContinue); if (bContinue) continue; CString sChannel = Message.GetTarget(); @@ -1010,8 +1052,7 @@ bool CClient::OnJoinMessage(CJoinMessage& Message) return sChans.empty(); } -bool CClient::OnModeMessage(CModeMessage& Message) -{ +bool CClient::OnModeMessage(CModeMessage& Message) { CString sTarget = Message.GetTarget(); CString sModes = Message.GetModes(); @@ -1020,11 +1061,14 @@ bool CClient::OnModeMessage(CModeMessage& Message) // /mode reply from the server, we can answer this // request ourself. - CChan *pChan = m_pNetwork->FindChan(sTarget); + CChan* pChan = m_pNetwork->FindChan(sTarget); if (pChan && pChan->IsOn() && !pChan->GetModeString().empty()) { - PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() + " " + sTarget + " " + pChan->GetModeString()); + PutClient(":" + m_pNetwork->GetIRCServer() + " 324 " + GetNick() + + " " + sTarget + " " + pChan->GetModeString()); if (pChan->GetCreationDate() > 0) { - PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " + GetNick() + " " + sTarget + " " + CString(pChan->GetCreationDate())); + PutClient(":" + m_pNetwork->GetIRCServer() + " 329 " + + GetNick() + " " + sTarget + " " + + CString(pChan->GetCreationDate())); } return true; } @@ -1033,8 +1077,7 @@ bool CClient::OnModeMessage(CModeMessage& Message) return false; } -bool CClient::OnNoticeMessage(CNoticeMessage& Message) -{ +bool CClient::OnNoticeMessage(CNoticeMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; @@ -1045,35 +1088,38 @@ bool CClient::OnNoticeMessage(CNoticeMessage& Message) if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) { if (!sTarget.Equals("status")) { - CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModNotice(Message.GetText())); + CALLMOD(sTarget, this, m_pUser, m_pNetwork, + OnModNotice(Message.GetText())); } continue; } bool bContinue = false; - NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserNoticeMessage(Message), m_pUser, m_pNetwork, + this, &bContinue); if (bContinue) continue; if (!GetIRCSock()) { // Some lagmeters do a NOTICE to their own nick, ignore those. if (!sTarget.Equals(m_sNick)) - PutStatus("Your notice to [" + Message.GetTarget() + "] got lost, " - "you are not connected to IRC!"); + PutStatus("Your notice to [" + Message.GetTarget() + + "] got lost, " + "you are not connected to IRC!"); continue; } if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); - PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); + PutIRC(Message.ToString(CMessage::ExcludePrefix | + CMessage::ExcludeTags)); } } return true; } -bool CClient::OnPartMessage(CPartMessage& Message) -{ +bool CClient::OnPartMessage(CPartMessage& Message) { CString sChans = Message.GetTarget(); VCString vsChans; @@ -1083,7 +1129,8 @@ bool CClient::OnPartMessage(CPartMessage& Message) for (CString& sChan : vsChans) { bool bContinue = false; Message.SetTarget(sChan); - NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserPartMessage(Message), m_pUser, m_pNetwork, this, + &bContinue); if (bContinue) continue; sChan = Message.GetTarget(); @@ -1094,7 +1141,7 @@ bool CClient::OnPartMessage(CPartMessage& Message) PutStatusNotice("Removing channel [" + sChan + "]"); m_pNetwork->DelChan(sChan); } else { - sChans += (sChans.empty()) ? sChan : CString("," + sChan); + sChans += (sChans.empty()) ? sChan : CString("," + sChan); } } @@ -1107,8 +1154,7 @@ bool CClient::OnPartMessage(CPartMessage& Message) return false; } -bool CClient::OnPingMessage(CMessage& Message) -{ +bool CClient::OnPingMessage(CMessage& Message) { // All PONGs are generated by ZNC. We will still forward this to // the ircd, but all PONGs from irc will be blocked. if (!Message.GetParams().empty()) @@ -1118,25 +1164,24 @@ bool CClient::OnPingMessage(CMessage& Message) return false; } -bool CClient::OnPongMessage(CMessage& Message) -{ +bool CClient::OnPongMessage(CMessage& Message) { // Block PONGs, we already responded to the pings return true; } -bool CClient::OnQuitMessage(CQuitMessage& Message) -{ +bool CClient::OnQuitMessage(CQuitMessage& Message) { bool bReturn = false; - NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnUserQuitMessage(Message), m_pUser, m_pNetwork, this, + &bReturn); if (!bReturn) { - Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach + Close(Csock::CLT_AFTERWRITE); // Treat a client quit as a detach } - // Don't forward this msg. We don't want the client getting us disconnected. + // Don't forward this msg. We don't want the client getting us + // disconnected. return true; } -bool CClient::OnTextMessage(CTextMessage& Message) -{ +bool CClient::OnTextMessage(CTextMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; @@ -1151,51 +1196,55 @@ bool CClient::OnTextMessage(CTextMessage& Message) CString sMsg = Message.GetText(); UserCommand(sMsg); } else { - CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModCommand(Message.GetText())); + CALLMOD(sTarget, this, m_pUser, m_pNetwork, + OnModCommand(Message.GetText())); } continue; } bool bContinue = false; - NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this, &bContinue); + NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this, + &bContinue); if (bContinue) continue; if (!GetIRCSock()) { // Some lagmeters do a PRIVMSG to their own nick, ignore those. if (!sTarget.Equals(m_sNick)) - PutStatus("Your message to [" + Message.GetTarget() + "] got lost, " - "you are not connected to IRC!"); + PutStatus("Your message to [" + Message.GetTarget() + + "] got lost, " + "you are not connected to IRC!"); continue; } if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); - PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); + PutIRC(Message.ToString(CMessage::ExcludePrefix | + CMessage::ExcludeTags)); } } return true; } -bool CClient::OnTopicMessage(CTopicMessage& Message) -{ +bool CClient::OnTopicMessage(CTopicMessage& Message) { bool bReturn = false; CString sChan = Message.GetTarget(); CString sTopic = Message.GetTopic(); if (!sTopic.empty()) { - NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnUserTopicMessage(Message), m_pUser, m_pNetwork, + this, &bReturn); } else { - NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnUserTopicRequest(sChan), m_pUser, m_pNetwork, this, + &bReturn); Message.SetTarget(sChan); } return bReturn; } -bool CClient::OnOtherMessage(CMessage& Message) -{ +bool CClient::OnOtherMessage(CMessage& Message) { const CString& sCommand = Message.GetCommand(); if (sCommand.Equals("ZNC")) { @@ -1205,7 +1254,7 @@ bool CClient::OnOtherMessage(CMessage& Message) if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) { sModCommand = Message.GetParams(1); } else { - sTarget = "status"; + sTarget = "status"; sModCommand = Message.GetParams(0); } @@ -1216,9 +1265,11 @@ bool CClient::OnOtherMessage(CMessage& Message) UserCommand(sModCommand); } else { if (sModCommand.empty()) - CALLMOD(sTarget, this, m_pUser, m_pNetwork, PutModule("Hello. How may I help you?")) + CALLMOD(sTarget, this, m_pUser, m_pNetwork, + PutModule("Hello. How may I help you?")) else - CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModCommand(sModCommand)) + CALLMOD(sTarget, this, m_pUser, m_pNetwork, + OnModCommand(sModCommand)) } return true; } else if (sCommand.Equals("ATTACH")) { @@ -1236,7 +1287,8 @@ bool CClient::OnOtherMessage(CMessage& Message) set sChans = MatchChans(sPatterns); unsigned int uAttachedChans = AttachChans(sChans); - PutStatusNotice("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatusNotice("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatusNotice("Attached [" + CString(uAttachedChans) + "] channels"); return true; @@ -1255,7 +1307,8 @@ bool CClient::OnOtherMessage(CMessage& Message) set sChans = MatchChans(sPatterns); unsigned int uDetached = DetachChans(sChans); - PutStatusNotice("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatusNotice("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatusNotice("Detached [" + CString(uDetached) + "] channels"); return true; @@ -1267,7 +1320,8 @@ bool CClient::OnOtherMessage(CMessage& Message) m_bUHNames = true; } } - return true; // If the server understands it, we already enabled namesx / uhnames + return true; // If the server understands it, we already enabled namesx + // / uhnames } return false; diff --git a/src/ClientCommand.cpp b/src/ClientCommand.cpp index 40d2253a..7b0882c6 100644 --- a/src/ClientCommand.cpp +++ b/src/ClientCommand.cpp @@ -37,7 +37,8 @@ void CClient::UserCommand(CString& sLine) { } bool bReturn = false; - NETWORKMODULECALL(OnStatusCommand(sLine), m_pUser, m_pNetwork, this, &bReturn); + NETWORKMODULECALL(OnStatusCommand(sLine), m_pUser, m_pNetwork, this, + &bReturn); if (bReturn) return; const CString sCommand = sLine.Token(0); @@ -46,7 +47,8 @@ void CClient::UserCommand(CString& sLine) { HelpUser(sLine.Token(1)); } else if (sCommand.Equals("LISTNICKS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -69,7 +71,7 @@ void CClient::UserCommand(CString& sLine) { return; } - const map& msNicks = pChan->GetNicks(); + const map& msNicks = pChan->GetNicks(); CIRCSock* pIRCSock = m_pNetwork->GetIRCSock(); const CString& sPerms = (pIRCSock) ? pIRCSock->GetPerms() : ""; @@ -109,7 +111,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus(Table); } else if (sCommand.Equals("ATTACH")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -123,11 +126,13 @@ void CClient::UserCommand(CString& sLine) { set sChans = MatchChans(sPatterns); unsigned int uAttachedChans = AttachChans(sChans); - PutStatus("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatus("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatus("Attached [" + CString(uAttachedChans) + "] channels"); } else if (sCommand.Equals("DETACH")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -141,7 +146,8 @@ void CClient::UserCommand(CString& sLine) { set sChans = MatchChans(sPatterns); unsigned int uDetached = DetachChans(sChans); - PutStatus("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatus("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatus("Detached [" + CString(uDetached) + "] channels"); } else if (sCommand.Equals("VERSION")) { PutStatus(CZNC::GetTag()); @@ -215,7 +221,8 @@ void CClient::UserCommand(CString& sLine) { Table.AddRow(); Table.SetCell("Username", it.first); Table.SetCell("Networks", CString(it.second->GetNetworks().size())); - Table.SetCell("Clients", CString(it.second->GetAllClients().size())); + Table.SetCell("Clients", + CString(it.second->GetAllClients().size())); } PutStatus(Table); @@ -234,7 +241,8 @@ void CClient::UserCommand(CString& sLine) { Table.AddRow(); Table.SetCell("Username", it.first); Table.SetCell("Network", "N/A"); - Table.SetCell("Clients", CString(it.second->GetUserClients().size())); + Table.SetCell("Clients", + CString(it.second->GetUserClients().size())); const vector& vNetworks = it.second->GetNetworks(); @@ -246,12 +254,15 @@ void CClient::UserCommand(CString& sLine) { Table.SetCell("Username", "|-"); } Table.SetCell("Network", pNetwork->GetName()); - Table.SetCell("Clients", CString(pNetwork->GetClients().size())); + Table.SetCell("Clients", + CString(pNetwork->GetClients().size())); if (pNetwork->IsIRCConnected()) { Table.SetCell("OnIRC", "Yes"); Table.SetCell("IRC Server", pNetwork->GetIRCServer()); - Table.SetCell("IRC User", pNetwork->GetIRCNick().GetNickMask()); - Table.SetCell("Channels", CString(pNetwork->GetChans().size())); + Table.SetCell("IRC User", + pNetwork->GetIRCNick().GetNickMask()); + Table.SetCell("Channels", + CString(pNetwork->GetChans().size())); } else { Table.SetCell("OnIRC", "No"); } @@ -282,7 +293,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("Cleared MOTD"); } else if (m_pUser->IsAdmin() && sCommand.Equals("BROADCAST")) { CZNC::Get().Broadcast(sLine.Token(1, true)); - } else if (m_pUser->IsAdmin() && (sCommand.Equals("SHUTDOWN") || sCommand.Equals("RESTART"))) { + } else if (m_pUser->IsAdmin() && + (sCommand.Equals("SHUTDOWN") || sCommand.Equals("RESTART"))) { bool bRestart = sCommand.Equals("RESTART"); CString sMessage = sLine.Token(1, true); bool bForce = false; @@ -293,19 +305,23 @@ void CClient::UserCommand(CString& sLine) { } if (sMessage.empty()) { - sMessage = (bRestart ? "ZNC is being restarted NOW!" : "ZNC is being shut down NOW!"); + sMessage = (bRestart ? "ZNC is being restarted NOW!" + : "ZNC is being shut down NOW!"); } - if(!CZNC::Get().WriteConfig() && !bForce) { - PutStatus("ERROR: Writing config file to disk failed! Aborting. Use " + - sCommand.AsUpper() + " FORCE to ignore."); + if (!CZNC::Get().WriteConfig() && !bForce) { + PutStatus( + "ERROR: Writing config file to disk failed! Aborting. Use " + + sCommand.AsUpper() + " FORCE to ignore."); } else { CZNC::Get().Broadcast(sMessage); - throw CException(bRestart ? CException::EX_Restart : CException::EX_Shutdown); + throw CException(bRestart ? CException::EX_Restart + : CException::EX_Shutdown); } } else if (sCommand.Equals("JUMP") || sCommand.Equals("CONNECT")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -316,7 +332,7 @@ void CClient::UserCommand(CString& sLine) { CString sArgs = sLine.Token(1, true); sArgs.Trim(); - CServer *pServer = nullptr; + CServer* pServer = nullptr; if (!sArgs.empty()) { pServer = m_pNetwork->FindServer(sArgs); @@ -328,7 +344,7 @@ void CClient::UserCommand(CString& sLine) { // If we are already connecting to some server, // we have to abort that attempt - Csock *pIRCSock = GetIRCSock(); + Csock* pIRCSock = GetIRCSock(); if (pIRCSock && !pIRCSock->IsConnected()) { pIRCSock->Close(); } @@ -355,7 +371,8 @@ void CClient::UserCommand(CString& sLine) { return; } else if (sCommand.Equals("DISCONNECT")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -369,7 +386,8 @@ void CClient::UserCommand(CString& sLine) { return; } else if (sCommand.Equals("ENABLECHAN")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -382,18 +400,19 @@ void CClient::UserCommand(CString& sLine) { unsigned int uEnabled = 0; for (CChan* pChan : sChans) { - if (!pChan->IsDisabled()) - continue; + if (!pChan->IsDisabled()) continue; uEnabled++; pChan->Enable(); } - PutStatus("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatus("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatus("Enabled [" + CString(uEnabled) + "] channels"); } } else if (sCommand.Equals("DISABLECHAN")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -406,18 +425,19 @@ void CClient::UserCommand(CString& sLine) { unsigned int uDisabled = 0; for (CChan* pChan : sChans) { - if (pChan->IsDisabled()) - continue; + if (pChan->IsDisabled()) continue; uDisabled++; pChan->Disable(); } - PutStatus("There were [" + CString(sChans.size()) + "] channels matching [" + sPatterns + "]"); + PutStatus("There were [" + CString(sChans.size()) + + "] channels matching [" + sPatterns + "]"); PutStatus("Disabled [" + CString(uDisabled) + "] channels"); } } else if (sCommand.Equals("SHOWCHAN")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -433,7 +453,9 @@ void CClient::UserCommand(CString& sLine) { return; } sChan = pChan->GetPermStr() + pChan->GetName(); - CString sStatus = pChan->IsOn() ? (pChan->IsDetached() ? "Detached" : "Joined") : (pChan->IsDisabled() ? "Disabled" : "Trying"); + CString sStatus = pChan->IsOn() + ? (pChan->IsDetached() ? "Detached" : "Joined") + : (pChan->IsDisabled() ? "Disabled" : "Trying"); CTable Table; Table.AddColumn(sChan); @@ -445,11 +467,19 @@ void CClient::UserCommand(CString& sLine) { Table.AddRow(); Table.SetCell(sChan, "Buffer"); - Table.SetCell(sStatus, CString(pChan->GetBuffer().Size()) + "/" + CString(pChan->GetBufferCount()) + CString(pChan->HasBufferCountSet() ? "" : " (default)")); + Table.SetCell( + sStatus, + CString(pChan->GetBuffer().Size()) + "/" + + CString(pChan->GetBufferCount()) + + CString(pChan->HasBufferCountSet() ? "" : " (default)")); Table.AddRow(); Table.SetCell(sChan, "AutoClearChanBuffer"); - Table.SetCell(sStatus, CString(pChan->AutoClearChanBuffer() ? "yes" : "no") + CString(pChan->HasAutoClearChanBufferSet() ? "" : " (default)")); + Table.SetCell( + sStatus, + CString(pChan->AutoClearChanBuffer() ? "yes" : "no") + + CString(pChan->HasAutoClearChanBufferSet() ? "" + : " (default)")); if (pChan->IsOn()) { Table.AddRow(); @@ -470,15 +500,18 @@ void CClient::UserCommand(CString& sLine) { const CString& sPerms = pIRCSock ? pIRCSock->GetPerms() : ""; map mPerms = pChan->GetPermCounts(); for (char cPerm : sPerms) { - vsUsers.push_back(CString(cPerm) + ": " + CString(mPerms[cPerm])); + vsUsers.push_back(CString(cPerm) + ": " + + CString(mPerms[cPerm])); } - Table.SetCell(sStatus, CString(", ").Join(vsUsers.begin(), vsUsers.end())); + Table.SetCell(sStatus, + CString(", ").Join(vsUsers.begin(), vsUsers.end())); } PutStatus(Table); } else if (sCommand.Equals("LISTCHANS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -518,25 +551,33 @@ void CClient::UserCommand(CString& sLine) { Table.AddColumn("Name"); Table.AddColumn("Status"); - unsigned int uNumDetached = 0, uNumDisabled = 0, - uNumJoined = 0; + unsigned int uNumDetached = 0, uNumDisabled = 0, uNumJoined = 0; - for (const CChan *pChan : vChans) { + for (const CChan* pChan : vChans) { Table.AddRow(); Table.SetCell("Name", pChan->GetPermStr() + pChan->GetName()); - Table.SetCell("Status", ((pChan->IsOn()) ? ((pChan->IsDetached()) ? "Detached" : "Joined") : ((pChan->IsDisabled()) ? "Disabled" : "Trying"))); + Table.SetCell( + "Status", + ((pChan->IsOn()) + ? ((pChan->IsDetached()) ? "Detached" : "Joined") + : ((pChan->IsDisabled()) ? "Disabled" : "Trying"))); - if(pChan->IsDetached()) uNumDetached++; - if(pChan->IsOn()) uNumJoined++; - if(pChan->IsDisabled()) uNumDisabled++; + if (pChan->IsDetached()) uNumDetached++; + if (pChan->IsOn()) uNumJoined++; + if (pChan->IsDisabled()) uNumDisabled++; } PutStatus(Table); - PutStatus("Total: " + CString(vChans.size()) + " - Joined: " + CString(uNumJoined) + - " - Detached: " + CString(uNumDetached) + " - Disabled: " + CString(uNumDisabled)); + PutStatus("Total: " + CString(vChans.size()) + " - Joined: " + + CString(uNumJoined) + " - Detached: " + + CString(uNumDetached) + " - Disabled: " + + CString(uNumDisabled)); } else if (sCommand.Equals("ADDNETWORK")) { if (!m_pUser->IsAdmin() && !m_pUser->HasSpaceForNewNetwork()) { - PutStatus("Network number limit reached. Ask an admin to increase the limit for you, or delete unneeded networks using /znc DelNetwork "); + PutStatus( + "Network number limit reached. Ask an admin to increase the " + "limit for you, or delete unneeded networks using /znc " + "DelNetwork "); return; } @@ -553,7 +594,11 @@ void CClient::UserCommand(CString& sLine) { CString sNetworkAddError; if (m_pUser->AddNetwork(sNetwork, sNetworkAddError)) { - PutStatus("Network added. Use /znc JumpNetwork " + sNetwork + ", or connect to ZNC with username " + m_pUser->GetUserName() + "/" + sNetwork + " (instead of just " + m_pUser->GetUserName() + ") to connect to it."); + PutStatus("Network added. Use /znc JumpNetwork " + sNetwork + + ", or connect to ZNC with username " + + m_pUser->GetUserName() + "/" + sNetwork + + " (instead of just " + m_pUser->GetUserName() + + ") to connect to it."); } else { PutStatus("Unable to add that network"); PutStatus(sNetworkAddError); @@ -577,7 +622,7 @@ void CClient::UserCommand(CString& sLine) { PutStatus("Perhaps this network doesn't exist"); } } else if (sCommand.Equals("LISTNETWORKS")) { - CUser *pUser = m_pUser; + CUser* pUser = m_pUser; if (m_pUser->IsAdmin() && !sLine.Token(1).empty()) { pUser = CZNC::Get().FindUser(sLine.Token(1)); @@ -625,7 +670,9 @@ void CClient::UserCommand(CString& sLine) { CString sNewNetwork = sLine.Token(4); if (sOldUser.empty() || sOldNetwork.empty() || sNewUser.empty()) { - PutStatus("Usage: MoveNetwork [new network]"); + PutStatus( + "Usage: MoveNetwork [new " + "network]"); return; } if (sNewNetwork.empty()) { @@ -651,7 +698,8 @@ void CClient::UserCommand(CString& sLine) { } if (pNewUser->FindNetwork(sNewNetwork)) { - PutStatus("User [" + sNewUser + "] already has network [" + sNewNetwork + "]."); + PutStatus("User [" + sNewUser + "] already has network [" + + sNewNetwork + "]."); return; } @@ -662,13 +710,18 @@ void CClient::UserCommand(CString& sLine) { const CModules& vMods = pOldNetwork->GetModules(); for (CModule* pMod : vMods) { - CString sOldModPath = pOldNetwork->GetNetworkPath() + "/moddata/" + pMod->GetModName(); - CString sNewModPath = pNewUser->GetUserPath() + "/networks/" + sNewNetwork + "/moddata/" + pMod->GetModName(); + CString sOldModPath = pOldNetwork->GetNetworkPath() + "/moddata/" + + pMod->GetModName(); + CString sNewModPath = pNewUser->GetUserPath() + "/networks/" + + sNewNetwork + "/moddata/" + + pMod->GetModName(); CDir oldDir(sOldModPath); for (CFile* pFile : oldDir) { if (pFile->GetShortName() != ".registry") { - PutStatus("Some files seem to be in [" + sOldModPath + "]. You might want to move them to [" + sNewModPath + "]"); + PutStatus("Some files seem to be in [" + sOldModPath + + "]. You might want to move them to [" + + sNewModPath + "]"); break; } } @@ -677,7 +730,8 @@ void CClient::UserCommand(CString& sLine) { } CString sNetworkAddError; - CIRCNetwork* pNewNetwork = pNewUser->AddNetwork(sNewNetwork, sNetworkAddError); + CIRCNetwork* pNewNetwork = + pNewUser->AddNetwork(sNewNetwork, sNetworkAddError); if (!pNewNetwork) { PutStatus("Error adding network:" + sNetworkAddError); @@ -686,14 +740,17 @@ void CClient::UserCommand(CString& sLine) { pNewNetwork->Clone(*pOldNetwork, false); - if (m_pNetwork && m_pNetwork->GetName().Equals(sOldNetwork) && m_pUser == pOldUser) { + if (m_pNetwork && m_pNetwork->GetName().Equals(sOldNetwork) && + m_pUser == pOldUser) { SetNetwork(nullptr); } if (pOldUser->DeleteNetwork(sOldNetwork)) { PutStatus("Success."); } else { - PutStatus("Copied the network to new user, but failed to delete old network"); + PutStatus( + "Copied the network to new user, but failed to delete old " + "network"); } } else if (sCommand.Equals("JUMPNETWORK")) { CString sNetwork = sLine.Token(1); @@ -708,7 +765,7 @@ void CClient::UserCommand(CString& sLine) { return; } - CIRCNetwork *pNetwork = m_pUser->FindNetwork(sNetwork); + CIRCNetwork* pNetwork = m_pUser->FindNetwork(sNetwork); if (pNetwork) { PutStatus("Switched to " + sNetwork); SetNetwork(pNetwork); @@ -719,7 +776,8 @@ void CClient::UserCommand(CString& sLine) { CString sServer = sLine.Token(1); if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -732,11 +790,13 @@ void CClient::UserCommand(CString& sLine) { PutStatus("Server added"); } else { PutStatus("Unable to add that server"); - PutStatus("Perhaps the server is already added or openssl is disabled?"); + PutStatus( + "Perhaps the server is already added or openssl is disabled?"); } } else if (sCommand.Equals("REMSERVER") || sCommand.Equals("DELSERVER")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -761,7 +821,8 @@ void CClient::UserCommand(CString& sLine) { } } else if (sCommand.Equals("LISTSERVERS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -776,7 +837,8 @@ void CClient::UserCommand(CString& sLine) { for (const CServer* pServer : vServers) { Table.AddRow(); - Table.SetCell("Host", pServer->GetName() + (pServer == pCurServ ? "*" : "")); + Table.SetCell("Host", pServer->GetName() + + (pServer == pCurServ ? "*" : "")); Table.SetCell("Port", CString(pServer->GetPort())); Table.SetCell("SSL", (pServer->IsSSL()) ? "SSL" : ""); Table.SetCell("Pass", pServer->GetPass()); @@ -788,7 +850,8 @@ void CClient::UserCommand(CString& sLine) { } } else if (sCommand.Equals("AddTrustedServerFingerprint")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } CString sFP = sLine.Token(1); @@ -800,7 +863,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("Done."); } else if (sCommand.Equals("DelTrustedServerFingerprint")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } CString sFP = sLine.Token(1); @@ -812,7 +876,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("Done."); } else if (sCommand.Equals("ListTrustedServerFingerprints")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } const SCString& ssFPs = m_pNetwork->GetTrustedFingerprints(); @@ -826,7 +891,8 @@ void CClient::UserCommand(CString& sLine) { } } else if (sCommand.Equals("TOPICS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -906,7 +972,8 @@ void CClient::UserCommand(CString& sLine) { } return; - } else if (sCommand.Equals("LISTAVAILMODS") || sCommand.Equals("LISTAVAILABLEMODULES")) { + } else if (sCommand.Equals("LISTAVAILMODS") || + sCommand.Equals("LISTAVAILABLEMODULES")) { if (m_pUser->DenyLoadMod()) { PutStatus("Access Denied."); return; @@ -914,7 +981,8 @@ void CClient::UserCommand(CString& sLine) { if (m_pUser->IsAdmin()) { set ssGlobalMods; - CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule); + CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, + CModInfo::GlobalModule); if (ssGlobalMods.empty()) { PutStatus("No global modules available."); @@ -926,8 +994,14 @@ void CClient::UserCommand(CString& sLine) { for (const CModInfo& Info : ssGlobalMods) { GTable.AddRow(); - GTable.SetCell("Name", (CZNC::Get().GetModules().FindModule(Info.GetName()) ? "*" : " ") + Info.GetName()); - GTable.SetCell("Description", Info.GetDescription().Ellipsize(128)); + GTable.SetCell( + "Name", + (CZNC::Get().GetModules().FindModule(Info.GetName()) + ? "*" + : " ") + + Info.GetName()); + GTable.SetCell("Description", + Info.GetDescription().Ellipsize(128)); } PutStatus(GTable); @@ -947,15 +1021,21 @@ void CClient::UserCommand(CString& sLine) { for (const CModInfo& Info : ssUserMods) { Table.AddRow(); - Table.SetCell("Name", (m_pUser->GetModules().FindModule(Info.GetName()) ? "*" : " ") + Info.GetName()); - Table.SetCell("Description", Info.GetDescription().Ellipsize(128)); + Table.SetCell( + "Name", + (m_pUser->GetModules().FindModule(Info.GetName()) ? "*" + : " ") + + Info.GetName()); + Table.SetCell("Description", + Info.GetDescription().Ellipsize(128)); } PutStatus(Table); } set ssNetworkMods; - CZNC::Get().GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule); + CZNC::Get().GetModules().GetAvailableMods(ssNetworkMods, + CModInfo::NetworkModule); if (ssNetworkMods.empty()) { PutStatus("No network modules available."); @@ -967,8 +1047,15 @@ void CClient::UserCommand(CString& sLine) { for (const CModInfo& Info : ssNetworkMods) { Table.AddRow(); - Table.SetCell("Name", ((m_pNetwork && m_pNetwork->GetModules().FindModule(Info.GetName())) ? "*" : " ") + Info.GetName()); - Table.SetCell("Description", Info.GetDescription().Ellipsize(128)); + Table.SetCell( + "Name", + ((m_pNetwork && + m_pNetwork->GetModules().FindModule(Info.GetName())) + ? "*" + : " ") + + Info.GetName()); + Table.SetCell("Description", + Info.GetDescription().Ellipsize(128)); } PutStatus(Table); @@ -1001,14 +1088,16 @@ void CClient::UserCommand(CString& sLine) { } if (sMod.empty()) { - PutStatus("Usage: LoadMod [--type=global|user|network] [args]"); + PutStatus( + "Usage: LoadMod [--type=global|user|network] [args]"); return; } CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { - PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + "]"); + PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + + "]"); return; } @@ -1017,12 +1106,14 @@ void CClient::UserCommand(CString& sLine) { } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { - PutStatus("Unable to load global module [" + sMod + "]: Access Denied."); + PutStatus("Unable to load global module [" + sMod + + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { - PutStatus("Unable to load network module [" + sMod + "] Not connected with a network."); + PutStatus("Unable to load network module [" + sMod + + "] Not connected with a network."); return; } @@ -1030,25 +1121,29 @@ void CClient::UserCommand(CString& sLine) { bool b = false; switch (eType) { - case CModInfo::GlobalModule: - b = CZNC::Get().GetModules().LoadModule(sMod, sArgs, eType, nullptr, nullptr, sModRet); - break; - case CModInfo::UserModule: - b = m_pUser->GetModules().LoadModule(sMod, sArgs, eType, m_pUser, nullptr, sModRet); - break; - case CModInfo::NetworkModule: - b = m_pNetwork->GetModules().LoadModule(sMod, sArgs, eType, m_pUser, m_pNetwork, sModRet); + case CModInfo::GlobalModule: + b = CZNC::Get().GetModules().LoadModule( + sMod, sArgs, eType, nullptr, nullptr, sModRet); break; - default: - sModRet = "Unable to load module [" + sMod + "]: Unknown module type"; + case CModInfo::UserModule: + b = m_pUser->GetModules().LoadModule(sMod, sArgs, eType, + m_pUser, nullptr, sModRet); + break; + case CModInfo::NetworkModule: + b = m_pNetwork->GetModules().LoadModule( + sMod, sArgs, eType, m_pUser, m_pNetwork, sModRet); + break; + default: + sModRet = + "Unable to load module [" + sMod + "]: Unknown module type"; } - if (b) - sModRet = "Loaded module [" + sMod + "] " + sModRet; + if (b) sModRet = "Loaded module [" + sMod + "] " + sModRet; PutStatus(sModRet); return; - } else if (sCommand.Equals("UNLOADMOD") || sCommand.Equals("UNLOADMODULE")) { + } else if (sCommand.Equals("UNLOADMOD") || + sCommand.Equals("UNLOADMODULE")) { CModInfo::EModuleType eType = CModInfo::UserModule; CString sType = sLine.Token(1); CString sMod = sLine.Token(2); @@ -1079,7 +1174,8 @@ void CClient::UserCommand(CString& sLine) { CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { - PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + "]"); + PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + + "]"); return; } @@ -1087,34 +1183,38 @@ void CClient::UserCommand(CString& sLine) { } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { - PutStatus("Unable to unload global module [" + sMod + "]: Access Denied."); + PutStatus("Unable to unload global module [" + sMod + + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { - PutStatus("Unable to unload network module [" + sMod + "] Not connected with a network."); + PutStatus("Unable to unload network module [" + sMod + + "] Not connected with a network."); return; } CString sModRet; switch (eType) { - case CModInfo::GlobalModule: - CZNC::Get().GetModules().UnloadModule(sMod, sModRet); - break; - case CModInfo::UserModule: - m_pUser->GetModules().UnloadModule(sMod, sModRet); - break; - case CModInfo::NetworkModule: - m_pNetwork->GetModules().UnloadModule(sMod, sModRet); - break; - default: - sModRet = "Unable to unload module [" + sMod + "]: Unknown module type"; + case CModInfo::GlobalModule: + CZNC::Get().GetModules().UnloadModule(sMod, sModRet); + break; + case CModInfo::UserModule: + m_pUser->GetModules().UnloadModule(sMod, sModRet); + break; + case CModInfo::NetworkModule: + m_pNetwork->GetModules().UnloadModule(sMod, sModRet); + break; + default: + sModRet = "Unable to unload module [" + sMod + + "]: Unknown module type"; } PutStatus(sModRet); return; - } else if (sCommand.Equals("RELOADMOD") || sCommand.Equals("RELOADMODULE")) { + } else if (sCommand.Equals("RELOADMOD") || + sCommand.Equals("RELOADMODULE")) { CModInfo::EModuleType eType; CString sType = sLine.Token(1); CString sMod = sLine.Token(2); @@ -1141,7 +1241,9 @@ void CClient::UserCommand(CString& sLine) { } if (sMod.empty()) { - PutStatus("Usage: ReloadMod [--type=global|user|network] [args]"); + PutStatus( + "Usage: ReloadMod [--type=global|user|network] " + "[args]"); return; } @@ -1149,7 +1251,8 @@ void CClient::UserCommand(CString& sLine) { CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { - PutStatus("Unable to find modinfo for [" + sMod + "] [" + sRetMsg + "]"); + PutStatus("Unable to find modinfo for [" + sMod + "] [" + + sRetMsg + "]"); return; } @@ -1157,34 +1260,42 @@ void CClient::UserCommand(CString& sLine) { } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { - PutStatus("Unable to reload global module [" + sMod + "]: Access Denied."); + PutStatus("Unable to reload global module [" + sMod + + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { - PutStatus("Unable to load network module [" + sMod + "] Not connected with a network."); + PutStatus("Unable to load network module [" + sMod + + "] Not connected with a network."); return; } CString sModRet; switch (eType) { - case CModInfo::GlobalModule: - CZNC::Get().GetModules().ReloadModule(sMod, sArgs, nullptr, nullptr, sModRet); - break; - case CModInfo::UserModule: - m_pUser->GetModules().ReloadModule(sMod, sArgs, m_pUser, nullptr, sModRet); - break; - case CModInfo::NetworkModule: - m_pNetwork->GetModules().ReloadModule(sMod, sArgs, m_pUser, m_pNetwork, sModRet); - break; - default: - sModRet = "Unable to reload module [" + sMod + "]: Unknown module type"; + case CModInfo::GlobalModule: + CZNC::Get().GetModules().ReloadModule(sMod, sArgs, nullptr, + nullptr, sModRet); + break; + case CModInfo::UserModule: + m_pUser->GetModules().ReloadModule(sMod, sArgs, m_pUser, + nullptr, sModRet); + break; + case CModInfo::NetworkModule: + m_pNetwork->GetModules().ReloadModule(sMod, sArgs, m_pUser, + m_pNetwork, sModRet); + break; + default: + sModRet = "Unable to reload module [" + sMod + + "]: Unknown module type"; } PutStatus(sModRet); return; - } else if ((sCommand.Equals("UPDATEMOD") || sCommand.Equals("UPDATEMODULE")) && m_pUser->IsAdmin() ) { + } else if ((sCommand.Equals("UPDATEMOD") || + sCommand.Equals("UPDATEMODULE")) && + m_pUser->IsAdmin()) { CString sMod = sLine.Token(1); if (sMod.empty()) { @@ -1196,11 +1307,16 @@ void CClient::UserCommand(CString& sLine) { if (CZNC::Get().UpdateModule(sMod)) { PutStatus("Done"); } else { - PutStatus("Done, but there were errors, [" + sMod + "] could not be loaded everywhere."); + PutStatus("Done, but there were errors, [" + sMod + + "] could not be loaded everywhere."); } - } else if ((sCommand.Equals("SETBINDHOST") || sCommand.Equals("SETVHOST")) && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { + } else if ((sCommand.Equals("SETBINDHOST") || + sCommand.Equals("SETVHOST")) && + (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command. Try SetUserBindHost instead"); + PutStatus( + "You must be connected with a network to use this command. Try " + "SetUserBindHost instead"); return; } CString sArg = sLine.Token(1); @@ -1216,8 +1332,10 @@ void CClient::UserCommand(CString& sLine) { } m_pNetwork->SetBindHost(sArg); - PutStatus("Set bind host for network [" + m_pNetwork->GetName() + "] to [" + m_pNetwork->GetBindHost() + "]"); - } else if (sCommand.Equals("SETUSERBINDHOST") && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { + PutStatus("Set bind host for network [" + m_pNetwork->GetName() + + "] to [" + m_pNetwork->GetBindHost() + "]"); + } else if (sCommand.Equals("SETUSERBINDHOST") && + (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { CString sArg = sLine.Token(1); if (sArg.empty()) { @@ -1232,24 +1350,36 @@ void CClient::UserCommand(CString& sLine) { m_pUser->SetBindHost(sArg); PutStatus("Set bind host to [" + m_pUser->GetBindHost() + "]"); - } else if ((sCommand.Equals("CLEARBINDHOST") || sCommand.Equals("CLEARVHOST")) && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { + } else if ((sCommand.Equals("CLEARBINDHOST") || + sCommand.Equals("CLEARVHOST")) && + (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command. Try ClearUserBindHost instead"); + PutStatus( + "You must be connected with a network to use this command. Try " + "ClearUserBindHost instead"); return; } m_pNetwork->SetBindHost(""); PutStatus("Bind host cleared for this network."); - } else if (sCommand.Equals("CLEARUSERBINDHOST") && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { + } else if (sCommand.Equals("CLEARUSERBINDHOST") && + (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { m_pUser->SetBindHost(""); PutStatus("Bind host cleared for your user."); } else if (sCommand.Equals("SHOWBINDHOST")) { - PutStatus("This user's default bind host " + (m_pUser->GetBindHost().empty() ? "not set" : "is [" + m_pUser->GetBindHost() + "]")); + PutStatus("This user's default bind host " + + (m_pUser->GetBindHost().empty() + ? "not set" + : "is [" + m_pUser->GetBindHost() + "]")); if (m_pNetwork) { - PutStatus("This network's bind host " + (m_pNetwork->GetBindHost().empty() ? "not set" : "is [" + m_pNetwork->GetBindHost() + "]")); + PutStatus("This network's bind host " + + (m_pNetwork->GetBindHost().empty() + ? "not set" + : "is [" + m_pNetwork->GetBindHost() + "]")); } } else if (sCommand.Equals("PLAYBUFFER")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1296,7 +1426,8 @@ void CClient::UserCommand(CString& sLine) { } } else if (sCommand.Equals("CLEARBUFFER")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1322,10 +1453,12 @@ void CClient::UserCommand(CString& sLine) { m_pNetwork->DelQuery(pQuery->GetName()); } - PutStatus("[" + CString(uMatches) + "] buffers matching [" + sBuffer + "] have been cleared"); + PutStatus("[" + CString(uMatches) + "] buffers matching [" + sBuffer + + "] have been cleared"); } else if (sCommand.Equals("CLEARALLCHANNELBUFFERS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1335,7 +1468,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("All channel buffers have been cleared"); } else if (sCommand.Equals("CLEARALLQUERYBUFFERS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1343,7 +1477,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("All query buffers have been cleared"); } else if (sCommand.Equals("CLEARALLBUFFERS")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1354,7 +1489,8 @@ void CClient::UserCommand(CString& sLine) { PutStatus("All buffers have been cleared"); } else if (sCommand.Equals("SETBUFFER")) { if (!m_pNetwork) { - PutStatus("You must be connected with a network to use this command"); + PutStatus( + "You must be connected with a network to use this command"); return; } @@ -1371,27 +1507,28 @@ void CClient::UserCommand(CString& sLine) { for (CChan* pChan : vChans) { uMatches++; - if (!pChan->SetBufferCount(uLineCount)) - uFail++; + if (!pChan->SetBufferCount(uLineCount)) uFail++; } vector vQueries = m_pNetwork->FindQueries(sBuffer); for (CQuery* pQuery : vQueries) { uMatches++; - if (!pQuery->SetBufferCount(uLineCount)) - uFail++; + if (!pQuery->SetBufferCount(uLineCount)) uFail++; } PutStatus("BufferCount for [" + CString(uMatches - uFail) + - "] buffer was set to [" + CString(uLineCount) + "]"); + "] buffer was set to [" + CString(uLineCount) + "]"); if (uFail > 0) { - PutStatus("Setting BufferCount failed for [" + CString(uFail) + "] buffers, " - "max buffer count is " + CString(CZNC::Get().GetMaxBufferSize())); + PutStatus("Setting BufferCount failed for [" + CString(uFail) + + "] buffers, " + "max buffer count is " + + CString(CZNC::Get().GetMaxBufferSize())); } } else if (m_pUser->IsAdmin() && sCommand.Equals("TRAFFIC")) { CZNC::TrafficStatsPair Users, ZNC, Total; - CZNC::TrafficStatsMap traffic = CZNC::Get().GetTrafficStats(Users, ZNC, Total); + CZNC::TrafficStatsMap traffic = + CZNC::Get().GetTrafficStats(Users, ZNC, Total); CTable Table; Table.AddColumn("Username"); @@ -1404,7 +1541,8 @@ void CClient::UserCommand(CString& sLine) { Table.SetCell("Username", it.first); Table.SetCell("In", CString::ToByteStr(it.second.first)); Table.SetCell("Out", CString::ToByteStr(it.second.second)); - Table.SetCell("Total", CString::ToByteStr(it.second.first + it.second.second)); + Table.SetCell("Total", CString::ToByteStr(it.second.first + + it.second.second)); } Table.AddRow(); @@ -1429,7 +1567,8 @@ void CClient::UserCommand(CString& sLine) { } else if (sCommand.Equals("UPTIME")) { PutStatus("Running for " + CZNC::Get().GetUptime()); } else if (m_pUser->IsAdmin() && - (sCommand.Equals("LISTPORTS") || sCommand.Equals("ADDPORT") || sCommand.Equals("DELPORT"))) { + (sCommand.Equals("LISTPORTS") || sCommand.Equals("ADDPORT") || + sCommand.Equals("DELPORT"))) { UserPortCommand(sLine); } else { PutStatus("Unknown command [" + sCommand + "] try 'Help'"); @@ -1454,14 +1593,23 @@ void CClient::UserPortCommand(CString& sLine) { for (const CListener* pListener : vpListeners) { Table.AddRow(); Table.SetCell("Port", CString(pListener->GetPort())); - Table.SetCell("BindHost", (pListener->GetBindHost().empty() ? CString("*") : pListener->GetBindHost())); + Table.SetCell("BindHost", (pListener->GetBindHost().empty() + ? CString("*") + : pListener->GetBindHost())); Table.SetCell("SSL", CString(pListener->IsSSL())); EAddrType eAddr = pListener->GetAddrType(); - Table.SetCell("Proto", (eAddr == ADDR_ALL ? "All" : (eAddr == ADDR_IPV4ONLY ? "IPv4" : "IPv6"))); + Table.SetCell("Proto", + (eAddr == ADDR_ALL + ? "All" + : (eAddr == ADDR_IPV4ONLY ? "IPv4" : "IPv6"))); CListener::EAcceptType eAccept = pListener->GetAcceptType(); - Table.SetCell("IRC/Web", (eAccept == CListener::ACCEPT_ALL ? "All" : (eAccept == CListener::ACCEPT_IRC ? "IRC" : "Web"))); + Table.SetCell( + "IRC/Web", + (eAccept == CListener::ACCEPT_ALL + ? "All" + : (eAccept == CListener::ACCEPT_IRC ? "IRC" : "Web"))); Table.SetCell("URIPrefix", pListener->GetURIPrefix() + "/"); } @@ -1501,13 +1649,16 @@ void CClient::UserPortCommand(CString& sLine) { } if (sPort.empty() || sAddr.empty() || sAccept.empty()) { - PutStatus("Usage: AddPort <[+]port> [bindhost [uriprefix]]"); + PutStatus( + "Usage: AddPort <[+]port> " + "[bindhost [uriprefix]]"); } else { bool bSSL = (sPort.StartsWith("+")); const CString sBindHost = sLine.Token(4); const CString sURIPrefix = sLine.Token(5); - CListener* pListener = new CListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept); + CListener* pListener = new CListener(uPort, sBindHost, sURIPrefix, + bSSL, eAddr, eAccept); if (!pListener->Listen()) { delete pListener; @@ -1525,7 +1676,8 @@ void CClient::UserPortCommand(CString& sLine) { } else { const CString sBindHost = sLine.Token(3); - CListener* pListener = CZNC::Get().FindListener(uPort, sBindHost, eAddr); + CListener* pListener = + CZNC::Get().FindListener(uPort, sBindHost, eAddr); if (pListener) { CZNC::Get().DelListener(pListener); @@ -1537,9 +1689,11 @@ void CClient::UserPortCommand(CString& sLine) { } } -static void AddCommandHelp(CTable& Table, const CString& sCmd, const CString& sArgs, const CString& sDesc, const CString& sFilter = "") -{ - if (sFilter.empty() || sCmd.StartsWith(sFilter) || sCmd.AsLower().WildCmp(sFilter.AsLower())) { +static void AddCommandHelp(CTable& Table, const CString& sCmd, + const CString& sArgs, const CString& sDesc, + const CString& sFilter = "") { + if (sFilter.empty() || sCmd.StartsWith(sFilter) || + sCmd.AsLower().WildCmp(sFilter.AsLower())) { Table.AddRow(); Table.SetCell("Command", sCmd + " " + sArgs); Table.SetCell("Description", sDesc); @@ -1552,92 +1706,167 @@ void CClient::HelpUser(const CString& sFilter) { Table.AddColumn("Description"); if (sFilter.empty()) { - PutStatus("In the following list all occurrences of <#chan> support wildcards (* and ?)"); + PutStatus( + "In the following list all occurrences of <#chan> support " + "wildcards (* and ?)"); PutStatus("(Except ListNicks)"); } - AddCommandHelp(Table, "Version", "", "Print which version of ZNC this is", sFilter); + AddCommandHelp(Table, "Version", "", "Print which version of ZNC this is", + sFilter); AddCommandHelp(Table, "ListMods", "", "List all loaded modules", sFilter); - AddCommandHelp(Table, "ListAvailMods", "", "List all available modules", sFilter); - if (!m_pUser->IsAdmin()) { // If they are an admin we will add this command below with an argument + AddCommandHelp(Table, "ListAvailMods", "", "List all available modules", + sFilter); + if (!m_pUser->IsAdmin()) { // If they are an admin we will add this command + // below with an argument AddCommandHelp(Table, "ListChans", "", "List all channels", sFilter); } - AddCommandHelp(Table, "ListNicks", "<#chan>", "List all nicks on a channel", sFilter); + AddCommandHelp(Table, "ListNicks", "<#chan>", "List all nicks on a channel", + sFilter); if (!m_pUser->IsAdmin()) { - AddCommandHelp(Table, "ListClients", "", "List all clients connected to your ZNC user", sFilter); + AddCommandHelp(Table, "ListClients", "", + "List all clients connected to your ZNC user", sFilter); } - AddCommandHelp(Table, "ListServers", "", "List all servers of current IRC network", sFilter); + AddCommandHelp(Table, "ListServers", "", + "List all servers of current IRC network", sFilter); - AddCommandHelp(Table, "AddNetwork", "", "Add a network to your user", sFilter); - AddCommandHelp(Table, "DelNetwork", "", "Delete a network from your user", sFilter); + AddCommandHelp(Table, "AddNetwork", "", "Add a network to your user", + sFilter); + AddCommandHelp(Table, "DelNetwork", "", + "Delete a network from your user", sFilter); AddCommandHelp(Table, "ListNetworks", "", "List all networks", sFilter); if (m_pUser->IsAdmin()) { - AddCommandHelp(Table, "MoveNetwork", " [new network]", "Move an IRC network from one user to another", sFilter); + AddCommandHelp(Table, "MoveNetwork", + " [new network]", + "Move an IRC network from one user to another", sFilter); } - AddCommandHelp(Table, "JumpNetwork", "", "Jump to another network (Alternatively, you can connect to ZNC several times, using `user/network` as username)", sFilter); + AddCommandHelp(Table, "JumpNetwork", "", + "Jump to another network (Alternatively, you can connect to " + "ZNC several times, using `user/network` as username)", + sFilter); - AddCommandHelp(Table, "AddServer", " [[+]port] [pass]", "Add a server to the list of alternate/backup servers of current IRC network.", sFilter); - AddCommandHelp(Table, "DelServer", " [port] [pass]", "Remove a server from the list of alternate/backup servers of current IRC network", sFilter); + AddCommandHelp(Table, "AddServer", " [[+]port] [pass]", + "Add a server to the list of alternate/backup servers of " + "current IRC network.", + sFilter); + AddCommandHelp(Table, "DelServer", " [port] [pass]", + "Remove a server from the list of alternate/backup servers " + "of current IRC network", + sFilter); - AddCommandHelp(Table, "AddTrustedServerFingerprint", "", "Add a trusted server SSL certificate fingerprint (SHA-256) to current IRC network.", sFilter); - AddCommandHelp(Table, "DelTrustedServerFingerprint", "", "Delete a trusted server SSL certificate from current IRC network.", sFilter); - AddCommandHelp(Table, "ListTrustedServerFingerprints", "", "List all trusted server SSL certificates of current IRC network.", sFilter); + AddCommandHelp(Table, "AddTrustedServerFingerprint", "", + "Add a trusted server SSL certificate fingerprint (SHA-256) " + "to current IRC network.", + sFilter); + AddCommandHelp( + Table, "DelTrustedServerFingerprint", "", + "Delete a trusted server SSL certificate from current IRC network.", + sFilter); + AddCommandHelp( + Table, "ListTrustedServerFingerprints", "", + "List all trusted server SSL certificates of current IRC network.", + sFilter); - AddCommandHelp(Table, "ShowChan", "<#chan>", "Show channel details", sFilter); + AddCommandHelp(Table, "ShowChan", "<#chan>", "Show channel details", + sFilter); AddCommandHelp(Table, "EnableChan", "<#chans>", "Enable channels", sFilter); - AddCommandHelp(Table, "DisableChan", "<#chans>", "Disable channels", sFilter); + AddCommandHelp(Table, "DisableChan", "<#chans>", "Disable channels", + sFilter); AddCommandHelp(Table, "Attach", "<#chans>", "Attach to channels", sFilter); - AddCommandHelp(Table, "Detach", "<#chans>", "Detach from channels", sFilter); - AddCommandHelp(Table, "Topics", "", "Show topics in all your channels", sFilter); + AddCommandHelp(Table, "Detach", "<#chans>", "Detach from channels", + sFilter); + AddCommandHelp(Table, "Topics", "", "Show topics in all your channels", + sFilter); - AddCommandHelp(Table, "PlayBuffer", "<#chan|query>", "Play back the specified buffer", sFilter); - AddCommandHelp(Table, "ClearBuffer", "<#chan|query>", "Clear the specified buffer", sFilter); - AddCommandHelp(Table, "ClearAllBuffers", "", "Clear all channel and query buffers", sFilter); - AddCommandHelp(Table, "ClearAllChannelBuffers", "", "Clear the channel buffers", sFilter); - AddCommandHelp(Table, "ClearAllQueryBuffers", "", "Clear the query buffers", sFilter); - AddCommandHelp(Table, "SetBuffer", "<#chan|query> [linecount]", "Set the buffer count", sFilter); + AddCommandHelp(Table, "PlayBuffer", "<#chan|query>", + "Play back the specified buffer", sFilter); + AddCommandHelp(Table, "ClearBuffer", "<#chan|query>", + "Clear the specified buffer", sFilter); + AddCommandHelp(Table, "ClearAllBuffers", "", + "Clear all channel and query buffers", sFilter); + AddCommandHelp(Table, "ClearAllChannelBuffers", "", + "Clear the channel buffers", sFilter); + AddCommandHelp(Table, "ClearAllQueryBuffers", "", "Clear the query buffers", + sFilter); + AddCommandHelp(Table, "SetBuffer", "<#chan|query> [linecount]", + "Set the buffer count", sFilter); if (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost()) { - AddCommandHelp(Table, "SetBindHost", "", "Set the bind host for this connection", sFilter); - AddCommandHelp(Table, "SetUserBindHost", "", "Set the default bind host for this user", sFilter); - AddCommandHelp(Table, "ClearBindHost", "", "Clear the bind host for this connection", sFilter); - AddCommandHelp(Table, "ClearUserBindHost", "", "Clear the default bind host for this user", sFilter); + AddCommandHelp(Table, "SetBindHost", "", + "Set the bind host for this connection", sFilter); + AddCommandHelp(Table, "SetUserBindHost", "", + "Set the default bind host for this user", sFilter); + AddCommandHelp(Table, "ClearBindHost", "", + "Clear the bind host for this connection", sFilter); + AddCommandHelp(Table, "ClearUserBindHost", "", + "Clear the default bind host for this user", sFilter); } - AddCommandHelp(Table, "ShowBindHost", "", "Show currently selected bind host", sFilter); - AddCommandHelp(Table, "Jump", "[server]", "Jump to the next or the specified server", sFilter); - AddCommandHelp(Table, "Disconnect", "[message]", "Disconnect from IRC", sFilter); + AddCommandHelp(Table, "ShowBindHost", "", + "Show currently selected bind host", sFilter); + AddCommandHelp(Table, "Jump", "[server]", + "Jump to the next or the specified server", sFilter); + AddCommandHelp(Table, "Disconnect", "[message]", "Disconnect from IRC", + sFilter); AddCommandHelp(Table, "Connect", "", "Reconnect to IRC", sFilter); - AddCommandHelp(Table, "Uptime", "", "Show for how long ZNC has been running", sFilter); + AddCommandHelp(Table, "Uptime", "", + "Show for how long ZNC has been running", sFilter); if (!m_pUser->DenyLoadMod()) { - AddCommandHelp(Table, "LoadMod", "[--type=global|user|network] ", "Load a module", sFilter); - AddCommandHelp(Table, "UnloadMod", "[--type=global|user|network] ", "Unload a module", sFilter); - AddCommandHelp(Table, "ReloadMod", "[--type=global|user|network] ", "Reload a module", sFilter); + AddCommandHelp(Table, "LoadMod", + "[--type=global|user|network] ", "Load a module", + sFilter); + AddCommandHelp(Table, "UnloadMod", + "[--type=global|user|network] ", + "Unload a module", sFilter); + AddCommandHelp(Table, "ReloadMod", + "[--type=global|user|network] ", + "Reload a module", sFilter); if (m_pUser->IsAdmin()) { - AddCommandHelp(Table, "UpdateMod", "", "Reload a module everywhere", sFilter); + AddCommandHelp(Table, "UpdateMod", "", + "Reload a module everywhere", sFilter); } } - AddCommandHelp(Table, "ShowMOTD", "", "Show ZNC's message of the day", sFilter); + AddCommandHelp(Table, "ShowMOTD", "", "Show ZNC's message of the day", + sFilter); if (m_pUser->IsAdmin()) { - AddCommandHelp(Table, "SetMOTD", "", "Set ZNC's message of the day", sFilter); - AddCommandHelp(Table, "AddMOTD", "", "Append to ZNC's MOTD", sFilter); + AddCommandHelp(Table, "SetMOTD", "", + "Set ZNC's message of the day", sFilter); + AddCommandHelp(Table, "AddMOTD", "", + "Append to ZNC's MOTD", sFilter); AddCommandHelp(Table, "ClearMOTD", "", "Clear ZNC's MOTD", sFilter); - AddCommandHelp(Table, "ListPorts", "", "Show all active listeners", sFilter); - AddCommandHelp(Table, "AddPort", "<[+]port> [bindhost [uriprefix]]", "Add another port for ZNC to listen on", sFilter); - AddCommandHelp(Table, "DelPort", " [bindhost]", "Remove a port from ZNC", sFilter); - AddCommandHelp(Table, "Rehash", "", "Reload global settings, modules, and listeners from znc.conf", sFilter); - AddCommandHelp(Table, "SaveConfig", "", "Save the current settings to disk", sFilter); - AddCommandHelp(Table, "ListUsers", "", "List all ZNC users and their connection status", sFilter); - AddCommandHelp(Table, "ListAllUserNetworks", "", "List all ZNC users and their networks", sFilter); - AddCommandHelp(Table, "ListChans", "[user ]", "List all channels", sFilter); - AddCommandHelp(Table, "ListClients", "[user]", "List all connected clients", sFilter); - AddCommandHelp(Table, "Traffic", "", "Show basic traffic stats for all ZNC users", sFilter); - AddCommandHelp(Table, "Broadcast", "[message]", "Broadcast a message to all ZNC users", sFilter); - AddCommandHelp(Table, "Shutdown", "[message]", "Shut down ZNC completely", sFilter); + AddCommandHelp(Table, "ListPorts", "", "Show all active listeners", + sFilter); + AddCommandHelp( + Table, "AddPort", + "<[+]port> [bindhost [uriprefix]]", + "Add another port for ZNC to listen on", sFilter); + AddCommandHelp(Table, "DelPort", " [bindhost]", + "Remove a port from ZNC", sFilter); + AddCommandHelp( + Table, "Rehash", "", + "Reload global settings, modules, and listeners from znc.conf", + sFilter); + AddCommandHelp(Table, "SaveConfig", "", + "Save the current settings to disk", sFilter); + AddCommandHelp(Table, "ListUsers", "", + "List all ZNC users and their connection status", + sFilter); + AddCommandHelp(Table, "ListAllUserNetworks", "", + "List all ZNC users and their networks", sFilter); + AddCommandHelp(Table, "ListChans", "[user ]", + "List all channels", sFilter); + AddCommandHelp(Table, "ListClients", "[user]", + "List all connected clients", sFilter); + AddCommandHelp(Table, "Traffic", "", + "Show basic traffic stats for all ZNC users", sFilter); + AddCommandHelp(Table, "Broadcast", "[message]", + "Broadcast a message to all ZNC users", sFilter); + AddCommandHelp(Table, "Shutdown", "[message]", + "Shut down ZNC completely", sFilter); AddCommandHelp(Table, "Restart", "[message]", "Restart ZNC", sFilter); } diff --git a/src/Config.cpp b/src/Config.cpp index 9cce510c..ce1cfc6b 100644 --- a/src/Config.cpp +++ b/src/Config.cpp @@ -24,28 +24,20 @@ struct ConfigStackEntry { CString sName; CConfig Config; - ConfigStackEntry(const CString& Tag, const CString Name) : sTag(Tag), sName(Name), Config() { - } + ConfigStackEntry(const CString& Tag, const CString Name) + : sTag(Tag), sName(Name), Config() {} }; -CConfigEntry::CConfigEntry() - : m_pSubConfig(nullptr) { -} +CConfigEntry::CConfigEntry() : m_pSubConfig(nullptr) {} CConfigEntry::CConfigEntry(const CConfig& Config) - : m_pSubConfig(new CConfig(Config)) { + : m_pSubConfig(new CConfig(Config)) {} + +CConfigEntry::CConfigEntry(const CConfigEntry& other) : m_pSubConfig(nullptr) { + if (other.m_pSubConfig) m_pSubConfig = new CConfig(*other.m_pSubConfig); } -CConfigEntry::CConfigEntry(const CConfigEntry& other) - : m_pSubConfig(nullptr) { - if (other.m_pSubConfig) - m_pSubConfig = new CConfig(*other.m_pSubConfig); -} - -CConfigEntry::~CConfigEntry() -{ - delete m_pSubConfig; -} +CConfigEntry::~CConfigEntry() { delete m_pSubConfig; } CConfigEntry& CConfigEntry::operator=(const CConfigEntry& other) { delete m_pSubConfig; @@ -56,13 +48,12 @@ CConfigEntry& CConfigEntry::operator=(const CConfigEntry& other) { return *this; } -bool CConfig::Parse(CFile& file, CString& sErrorMsg) -{ +bool CConfig::Parse(CFile& file, CString& sErrorMsg) { CString sLine; unsigned int uLineNum = 0; - CConfig *pActiveConfig = this; + CConfig* pActiveConfig = this; std::stack ConfigStack; - bool bCommented = false; // support for /**/ style comments + bool bCommented = false; // support for /**/ style comments if (!file.Seek(0)) { sErrorMsg = "Could not seek to the beginning of the config."; @@ -72,14 +63,15 @@ bool CConfig::Parse(CFile& file, CString& sErrorMsg) while (file.ReadLine(sLine)) { uLineNum++; -#define ERROR(arg) do { \ - std::stringstream stream; \ - stream << "Error on line " << uLineNum << ": " << arg; \ - sErrorMsg = stream.str(); \ - m_SubConfigs.clear(); \ - m_ConfigEntries.clear(); \ - return false; \ -} while (0) +#define ERROR(arg) \ + do { \ + std::stringstream stream; \ + stream << "Error on line " << uLineNum << ": " << arg; \ + sErrorMsg = stream.str(); \ + m_SubConfigs.clear(); \ + m_ConfigEntries.clear(); \ + return false; \ + } while (0) // Remove all leading spaces and trailing line endings sLine.TrimLeft(); @@ -92,7 +84,8 @@ bool CConfig::Parse(CFile& file, CString& sErrorMsg) continue; } - if ((sLine.empty()) || (sLine.StartsWith("#")) || (sLine.StartsWith("//"))) { + if ((sLine.empty()) || (sLine.StartsWith("#")) || + (sLine.StartsWith("//"))) { continue; } @@ -109,7 +102,8 @@ bool CConfig::Parse(CFile& file, CString& sErrorMsg) if (sTag.TrimPrefix("/")) { if (!sValue.empty()) - ERROR("Malformated closing tag. Expected \"\"."); + ERROR("Malformated closing tag. Expected \"\"."); if (ConfigStack.empty()) ERROR("Closing tag \"" << sTag << "\" which is not open."); @@ -128,11 +122,12 @@ bool CConfig::Parse(CFile& file, CString& sErrorMsg) else pActiveConfig = &ConfigStack.top().Config; - SubConfig &conf = pActiveConfig->m_SubConfigs[sTag.AsLower()]; + SubConfig& conf = pActiveConfig->m_SubConfigs[sTag.AsLower()]; SubConfig::const_iterator it = conf.find(sName); if (it != conf.end()) - ERROR("Duplicate entry for tag \"" << sTag << "\" name \"" << sName << "\"."); + ERROR("Duplicate entry for tag \"" << sTag << "\" name \"" + << sName << "\"."); conf[sName] = CConfigEntry(myConfig); } else { @@ -157,19 +152,20 @@ bool CConfig::Parse(CFile& file, CString& sErrorMsg) // leading/trailing spaces. sName.Trim(); - if (sName.empty() || sValue.empty()) - ERROR("Malformed line"); + if (sName.empty() || sValue.empty()) ERROR("Malformed line"); CString sNameLower = sName.AsLower(); pActiveConfig->m_ConfigEntries[sNameLower].push_back(sValue); } - if (bCommented) - ERROR("Comment not closed at end of file."); + if (bCommented) ERROR("Comment not closed at end of file."); if (!ConfigStack.empty()) { const CString& sTag = ConfigStack.top().sTag; - ERROR("Not all tags are closed at the end of the file. Inner-most open tag is \"" << sTag << "\"."); + ERROR( + "Not all tags are closed at the end of the file. Inner-most open " + "tag is \"" + << sTag << "\"."); } return true; diff --git a/src/FileUtils.cpp b/src/FileUtils.cpp index 5406ec6e..55e37b8a 100644 --- a/src/FileUtils.cpp +++ b/src/FileUtils.cpp @@ -25,25 +25,27 @@ #include #ifndef HAVE_LSTAT -# define lstat(a, b) stat(a, b) +#define lstat(a, b) stat(a, b) #endif #ifndef O_BINARY -# define O_BINARY 0 +#define O_BINARY 0 #endif CString CFile::m_sHomePath; -CFile::CFile() : CFile("") { -} +CFile::CFile() : CFile("") {} -CFile::CFile(const CString& sLongName) : m_sBuffer(""), m_iFD(-1), m_bHadError(false), m_sLongName(""), m_sShortName("") { +CFile::CFile(const CString& sLongName) + : m_sBuffer(""), + m_iFD(-1), + m_bHadError(false), + m_sLongName(""), + m_sShortName("") { SetFileName(sLongName); } -CFile::~CFile() { - Close(); -} +CFile::~CFile() { Close(); } void CFile::SetFileName(const CString& sLongName) { if (sLongName.StartsWith("~/")) { @@ -56,7 +58,7 @@ void CFile::SetFileName(const CString& sLongName) { CString::size_type uPos = m_sShortName.rfind('/'); if (uPos != CString::npos) { - m_sShortName = m_sShortName.substr(uPos +1); + m_sShortName = m_sShortName.substr(uPos + 1); } } @@ -65,24 +67,49 @@ bool CFile::IsDir(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_DIRECTORY, bUseLstat); // Some OS don't like trailing slashes for directories - return CFile::FType(sLongName.TrimRight_n("/"), - FT_DIRECTORY, bUseLstat); + return CFile::FType(sLongName.TrimRight_n("/"), FT_DIRECTORY, bUseLstat); } -bool CFile::IsReg(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_REGULAR, bUseLstat); } -bool CFile::IsChr(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_CHARACTER, bUseLstat); } -bool CFile::IsBlk(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_BLOCK, bUseLstat); } -bool CFile::IsFifo(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_FIFO, bUseLstat); } -bool CFile::IsLnk(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_LINK, bUseLstat); } -bool CFile::IsSock(const CString& sLongName, bool bUseLstat) { return CFile::FType(sLongName, FT_SOCK, bUseLstat); } +bool CFile::IsReg(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_REGULAR, bUseLstat); +} +bool CFile::IsChr(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_CHARACTER, bUseLstat); +} +bool CFile::IsBlk(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_BLOCK, bUseLstat); +} +bool CFile::IsFifo(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_FIFO, bUseLstat); +} +bool CFile::IsLnk(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_LINK, bUseLstat); +} +bool CFile::IsSock(const CString& sLongName, bool bUseLstat) { + return CFile::FType(sLongName, FT_SOCK, bUseLstat); +} -bool CFile::IsReg(bool bUseLstat) const { return CFile::IsReg(m_sLongName, bUseLstat); } -bool CFile::IsDir(bool bUseLstat) const { return CFile::IsDir(m_sLongName, bUseLstat); } -bool CFile::IsChr(bool bUseLstat) const { return CFile::IsChr(m_sLongName, bUseLstat); } -bool CFile::IsBlk(bool bUseLstat) const { return CFile::IsBlk(m_sLongName, bUseLstat); } -bool CFile::IsFifo(bool bUseLstat) const { return CFile::IsFifo(m_sLongName, bUseLstat); } -bool CFile::IsLnk(bool bUseLstat) const { return CFile::IsLnk(m_sLongName, bUseLstat); } -bool CFile::IsSock(bool bUseLstat) const { return CFile::IsSock(m_sLongName, bUseLstat); } +bool CFile::IsReg(bool bUseLstat) const { + return CFile::IsReg(m_sLongName, bUseLstat); +} +bool CFile::IsDir(bool bUseLstat) const { + return CFile::IsDir(m_sLongName, bUseLstat); +} +bool CFile::IsChr(bool bUseLstat) const { + return CFile::IsChr(m_sLongName, bUseLstat); +} +bool CFile::IsBlk(bool bUseLstat) const { + return CFile::IsBlk(m_sLongName, bUseLstat); +} +bool CFile::IsFifo(bool bUseLstat) const { + return CFile::IsFifo(m_sLongName, bUseLstat); +} +bool CFile::IsLnk(bool bUseLstat) const { + return CFile::IsLnk(m_sLongName, bUseLstat); +} +bool CFile::IsSock(bool bUseLstat) const { + return CFile::IsSock(m_sLongName, bUseLstat); +} // for gettin file types, using fstat instead bool CFile::FType(const CString& sFileName, EFileTypes eType, bool bUseLstat) { @@ -160,12 +187,12 @@ time_t CFile::GetCTime(const CString& sFile) { uid_t CFile::GetUID(const CString& sFile) { struct stat st; - return (stat(sFile.c_str(), &st) != 0) ? -1 : (int) st.st_uid; + return (stat(sFile.c_str(), &st) != 0) ? -1 : (int)st.st_uid; } gid_t CFile::GetGID(const CString& sFile) { struct stat st; - return (stat(sFile.c_str(), &st) != 0) ? -1 : (int) st.st_gid; + return (stat(sFile.c_str(), &st) != 0) ? -1 : (int)st.st_gid; } int CFile::GetInfo(const CString& sFile, struct stat& st) { return stat(sFile.c_str(), &st); @@ -175,22 +202,19 @@ int CFile::GetInfo(const CString& sFile, struct stat& st) { // Functions to manipulate the file on the filesystem // bool CFile::Delete() { - if (CFile::Delete(m_sLongName)) - return true; + if (CFile::Delete(m_sLongName)) return true; m_bHadError = true; return false; } bool CFile::Move(const CString& sNewFileName, bool bOverwrite) { - if (CFile::Move(m_sLongName, sNewFileName, bOverwrite)) - return true; + if (CFile::Move(m_sLongName, sNewFileName, bOverwrite)) return true; m_bHadError = true; return false; } bool CFile::Copy(const CString& sNewFileName, bool bOverwrite) { - if (CFile::Copy(m_sLongName, sNewFileName, bOverwrite)) - return true; + if (CFile::Copy(m_sLongName, sNewFileName, bOverwrite)) return true; m_bHadError = true; return false; } @@ -199,7 +223,8 @@ bool CFile::Delete(const CString& sFileName) { return (unlink(sFileName.c_str()) == 0) ? true : false; } -bool CFile::Move(const CString& sOldFileName, const CString& sNewFileName, bool bOverwrite) { +bool CFile::Move(const CString& sOldFileName, const CString& sNewFileName, + bool bOverwrite) { if (CFile::Exists(sNewFileName)) { if (!bOverwrite) { errno = EEXIST; @@ -207,15 +232,18 @@ bool CFile::Move(const CString& sOldFileName, const CString& sNewFileName, bool } #ifdef _WIN32 // rename() never overwrites files on Windows. - DWORD dFlags = MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING; - return (::MoveFileExA(sOldFileName.c_str(), sNewFileName.c_str(), dFlags) != 0); + DWORD dFlags = MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED | + MOVEFILE_REPLACE_EXISTING; + return (::MoveFileExA(sOldFileName.c_str(), sNewFileName.c_str(), + dFlags) != 0); #endif } return (rename(sOldFileName.c_str(), sNewFileName.c_str()) == 0); } -bool CFile::Copy(const CString& sOldFileName, const CString& sNewFileName, bool bOverwrite) { +bool CFile::Copy(const CString& sOldFileName, const CString& sNewFileName, + bool bOverwrite) { if ((!bOverwrite) && (CFile::Exists(sNewFileName))) { errno = EEXIST; return false; @@ -306,8 +334,7 @@ bool CFile::Sync() { /* This sets errno in case m_iFD == -1 */ errno = EBADF; - if (m_iFD != -1 && fsync(m_iFD) == 0) - return true; + if (m_iFD != -1 && fsync(m_iFD) == 0) return true; m_bHadError = true; return false; } @@ -343,19 +370,18 @@ bool CFile::Open(int iFlags, mode_t iMode) { return true; } -ssize_t CFile::Read(char *pszBuffer, int iBytes) { +ssize_t CFile::Read(char* pszBuffer, int iBytes) { if (m_iFD == -1) { errno = EBADF; return -1; } ssize_t res = read(m_iFD, pszBuffer, iBytes); - if (res != iBytes) - m_bHadError = true; + if (res != iBytes) m_bHadError = true; return res; } -bool CFile::ReadLine(CString& sData, const CString & sDelimiter) { +bool CFile::ReadLine(CString& sData, const CString& sDelimiter) { char buff[4096]; ssize_t iBytes; @@ -418,27 +444,26 @@ bool CFile::ReadFile(CString& sData, size_t iMaxSize) { return false; } -ssize_t CFile::Write(const char *pszBuffer, size_t iBytes) { +ssize_t CFile::Write(const char* pszBuffer, size_t iBytes) { if (m_iFD == -1) { errno = EBADF; return -1; } ssize_t res = write(m_iFD, pszBuffer, iBytes); - if (-1 == res) - m_bHadError = true; + if (-1 == res) m_bHadError = true; return res; } -ssize_t CFile::Write(const CString & sData) { +ssize_t CFile::Write(const CString& sData) { return Write(sData.data(), sData.size()); } void CFile::Close() { if (m_iFD >= 0) { if (close(m_iFD) < 0) { m_bHadError = true; - DEBUG("CFile::Close(): close() failed with [" - << strerror(errno) << "]"); + DEBUG("CFile::Close(): close() failed with [" << strerror(errno) + << "]"); } } m_iFD = -1; @@ -451,17 +476,11 @@ bool CFile::TryExLock(const CString& sLockFile, int iFlags) { return TryExLock(); } -bool CFile::TryExLock() { - return Lock(F_WRLCK, false); -} +bool CFile::TryExLock() { return Lock(F_WRLCK, false); } -bool CFile::ExLock() { - return Lock(F_WRLCK, true); -} +bool CFile::ExLock() { return Lock(F_WRLCK, true); } -bool CFile::UnLock() { - return Lock(F_UNLCK, true); -} +bool CFile::UnLock() { return Lock(F_UNLCK, true); } bool CFile::Lock(short iType, bool bBlocking) { struct flock fl; @@ -470,10 +489,10 @@ bool CFile::Lock(short iType, bool bBlocking) { return false; } - fl.l_type = iType; + fl.l_type = iType; fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; + fl.l_start = 0; + fl.l_len = 0; return (fcntl(m_iFD, (bBlocking ? F_SETLKW : F_SETLK), &fl) != -1); } @@ -491,7 +510,7 @@ CString CFile::GetDir() const { } void CFile::InitHomePath(const CString& sFallback) { - const char *home = getenv("HOME"); + const char* home = getenv("HOME"); m_sHomePath.clear(); if (home) { @@ -511,7 +530,8 @@ void CFile::InitHomePath(const CString& sFallback) { } } -CString CDir::ChangeDir(const CString& sPath, const CString& sAdd, const CString& sHome) { +CString CDir::ChangeDir(const CString& sPath, const CString& sAdd, + const CString& sHome) { CString sHomeDir(sHome); if (sHomeDir.empty()) { @@ -555,12 +575,12 @@ CString CDir::ChangeDir(const CString& sPath, const CString& sAdd, const CString return (sRet.empty()) ? "/" : sRet; } -CString CDir::CheckPathPrefix(const CString& sPath, const CString& sAdd, const CString& sHomeDir) { +CString CDir::CheckPathPrefix(const CString& sPath, const CString& sAdd, + const CString& sHomeDir) { CString sPrefix = sPath.Replace_n("//", "/").TrimRight_n("/") + "/"; CString sAbsolutePath = ChangeDir(sPrefix, sAdd, sHomeDir); - if (!sAbsolutePath.StartsWith(sPrefix)) - return ""; + if (!sAbsolutePath.StartsWith(sPrefix)) return ""; return sAbsolutePath; } @@ -576,8 +596,7 @@ bool CDir::MakeDir(const CString& sPath, mode_t iMode) { } // If this is an absolute path, we need to handle this now! - if (sPath.StartsWith("/")) - sDir = "/"; + if (sPath.StartsWith("/")) sDir = "/"; // For every single subpath, do... sPath.Split("/", dirs, false); @@ -589,12 +608,10 @@ bool CDir::MakeDir(const CString& sPath, mode_t iMode) { if (i != 0) { // All errors except EEXIST are fatal - if (errno != EEXIST) - return false; + if (errno != EEXIST) return false; // If it's EEXIST we have to make sure it's a dir - if (!CFile::IsDir(sDir)) - return false; + if (!CFile::IsDir(sDir)) return false; } sDir += "/"; @@ -604,14 +621,13 @@ bool CDir::MakeDir(const CString& sPath, mode_t iMode) { return true; } -int CExecSock::popen2(int & iReadFD, int & iWriteFD, const CString & sCommand) { - int rpipes[2] = { -1, -1 }; - int wpipes[2] = { -1, -1 }; +int CExecSock::popen2(int& iReadFD, int& iWriteFD, const CString& sCommand) { + int rpipes[2] = {-1, -1}; + int wpipes[2] = {-1, -1}; iReadFD = -1; iWriteFD = -1; - if (pipe(rpipes) < 0) - return -1; + if (pipe(rpipes) < 0) return -1; if (pipe(wpipes) < 0) { close(rpipes[0]); @@ -637,14 +653,8 @@ int CExecSock::popen2(int & iReadFD, int & iWriteFD, const CString & sCommand) { dup2(rpipes[1], 2); close(wpipes[0]); close(rpipes[1]); - const char * pArgv[] = - { - "sh", - "-c", - sCommand.c_str(), - nullptr - }; - execvp("sh", (char * const *) pArgv); + const char* pArgv[] = {"sh", "-c", sCommand.c_str(), nullptr}; + execvp("sh", (char* const*)pArgv); // if execvp returns, there was an error perror("execvp"); exit(1); @@ -664,8 +674,7 @@ void CExecSock::close2(int iPid, int iReadFD, int iWriteFD) { close(iWriteFD); time_t iNow = time(nullptr); while (waitpid(iPid, nullptr, WNOHANG) == 0) { - if ((time(nullptr) - iNow) > 5) - break; // giveup + if ((time(nullptr) - iNow) > 5) break; // giveup usleep(100); } return; diff --git a/src/HTTPSock.cpp b/src/HTTPSock.cpp index d37c3cb0..c0e2129d 100644 --- a/src/HTTPSock.cpp +++ b/src/HTTPSock.cpp @@ -19,7 +19,6 @@ #include #include - #ifdef HAVE_ZLIB #include #endif @@ -27,38 +26,40 @@ using std::map; using std::set; -#define MAX_POST_SIZE 1024 * 1024 +#define MAX_POST_SIZE 1024 * 1024 -CHTTPSock::CHTTPSock(CModule *pMod, const CString& sURIPrefix) : CHTTPSock(pMod, sURIPrefix, "", 0) { +CHTTPSock::CHTTPSock(CModule* pMod, const CString& sURIPrefix) + : CHTTPSock(pMod, sURIPrefix, "", 0) { Init(); } -CHTTPSock::CHTTPSock(CModule *pMod, const CString& sURIPrefix, const CString& sHostname, unsigned short uPort, int iTimeout) - : CSocket(pMod, sHostname, uPort, iTimeout), - m_bSentHeader(false), - m_bGotHeader(false), - m_bLoggedIn(false), - m_bPost(false), - m_bDone(false), - m_bBasicAuth(false), - m_uPostLen(0), - m_sPostData(""), - m_sURI(""), - m_sUser(""), - m_sPass(""), - m_sContentType(""), - m_sDocRoot(""), - m_sForwardedIP(""), - m_msvsPOSTParams(), - m_msvsGETParams(), - m_msHeaders(), - m_bHTTP10Client(false), - m_sIfNoneMatch(""), - m_bAcceptGzip(false), - m_msRequestCookies(), - m_msResponseCookies(), - m_sURIPrefix(sURIPrefix) -{ +CHTTPSock::CHTTPSock(CModule* pMod, const CString& sURIPrefix, + const CString& sHostname, unsigned short uPort, + int iTimeout) + : CSocket(pMod, sHostname, uPort, iTimeout), + m_bSentHeader(false), + m_bGotHeader(false), + m_bLoggedIn(false), + m_bPost(false), + m_bDone(false), + m_bBasicAuth(false), + m_uPostLen(0), + m_sPostData(""), + m_sURI(""), + m_sUser(""), + m_sPass(""), + m_sContentType(""), + m_sDocRoot(""), + m_sForwardedIP(""), + m_msvsPOSTParams(), + m_msvsGETParams(), + m_msHeaders(), + m_bHTTP10Client(false), + m_sIfNoneMatch(""), + m_bAcceptGzip(false), + m_msRequestCookies(), + m_msResponseCookies(), + m_sURIPrefix(sURIPrefix) { Init(); } @@ -79,9 +80,9 @@ void CHTTPSock::ReadData(const char* data, size_t len) { bool CHTTPSock::SendCookie(const CString& sKey, const CString& sValue) { if (!sKey.empty() && !sValue.empty()) { if (m_msRequestCookies.find(sKey) == m_msRequestCookies.end() || - m_msRequestCookies[sKey].StrCmp(sValue) != 0) - { - // only queue a Set-Cookie to be sent if the client didn't send a Cookie header of the same name+value. + m_msRequestCookies[sKey].StrCmp(sValue) != 0) { + // only queue a Set-Cookie to be sent if the client didn't send a + // Cookie header of the same name+value. m_msResponseCookies[sKey] = sValue; } return true; @@ -130,8 +131,9 @@ void CHTTPSock::ReadLine(const CString& sData) { sLine.Token(1, true).Split(";", vsNV, false, "", "", true, true); for (const CString& s : vsNV) { - m_msRequestCookies[s.Token(0, false, "=").Escape_n(CString::EURL, CString::EASCII)] = - s.Token(1, true, "=").Escape_n(CString::EURL, CString::EASCII); + m_msRequestCookies[s.Token(0, false, "=") + .Escape_n(CString::EURL, CString::EASCII)] = + s.Token(1, true, "=").Escape_n(CString::EURL, CString::EASCII); } } else if (sName.Equals("Authorization:")) { CString sUnhashed; @@ -139,11 +141,14 @@ void CHTTPSock::ReadLine(const CString& sData) { m_sUser = sUnhashed.Token(0, false, ":"); m_sPass = sUnhashed.Token(1, true, ":"); m_bBasicAuth = true; - // Postpone authorization attempt until end of headers, because cookies should be read before that, otherwise session id will be overwritten in GetSession() + // Postpone authorization attempt until end of headers, because cookies + // should be read before that, otherwise session id will be overwritten + // in GetSession() } else if (sName.Equals("Content-Length:")) { m_uPostLen = sLine.Token(1).ToULong(); if (m_uPostLen > MAX_POST_SIZE) - PrintErrorPage(413, "Request Entity Too Large", "The request you sent was too large."); + PrintErrorPage(413, "Request Entity Too Large", + "The request you sent was too large."); } else if (sName.Equals("X-Forwarded-For:")) { // X-Forwarded-For: client, proxy1, proxy2 if (m_sForwardedIP.empty()) { @@ -172,7 +177,8 @@ void CHTTPSock::ReadLine(const CString& sData) { } } - // either sIP is not trusted proxy, or it's in the beginning of the X-Forwarded-For list + // either sIP is not trusted proxy, or it's in the beginning of the + // X-Forwarded-For list // in both cases use it as the endpoind m_sForwardedIP = sIP; } @@ -182,13 +188,16 @@ void CHTTPSock::ReadLine(const CString& sData) { } else if (sName.Equals("Accept-Encoding:") && !m_bHTTP10Client) { SCString ssEncodings; // trimming whitespace from the tokens is important: - sLine.Token(1, true).Split(",", ssEncodings, false, "", "", false, true); + sLine.Token(1, true) + .Split(",", ssEncodings, false, "", "", false, true); m_bAcceptGzip = (ssEncodings.find("gzip") != ssEncodings.end()); } else if (sLine.empty()) { if (m_bBasicAuth && !m_bLoggedIn) { m_bLoggedIn = OnLogin(m_sUser, m_sPass, true); - // After successful login ReadLine("") will be called again to trigger "else" block - // Failed login sends error and closes socket, so no infinite loop here + // After successful login ReadLine("") will be called again to + // trigger "else" block + // Failed login sends error and closes socket, so no infinite loop + // here } else { m_bGotHeader = true; @@ -215,12 +224,11 @@ CString CHTTPSock::GetRemoteIP() const { CString CHTTPSock::GetDate(time_t stamp) { struct tm tm; std::stringstream stream; - const char *wkday[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; - const char *month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + const char* wkday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + const char* month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - if (stamp == 0) - time(&stamp); + if (stamp == 0) time(&stamp); gmtime_r(&stamp, &tm); stream << wkday[tm.tm_wday] << ", "; @@ -239,18 +247,18 @@ void CHTTPSock::GetPage() { // Check that the requested path starts with the prefix. Strip it if so. if (!m_sURI.TrimPrefix(m_sURIPrefix)) { - DEBUG("INVALID path => Does not start with prefix [" + m_sURIPrefix + "]"); + DEBUG("INVALID path => Does not start with prefix [" + m_sURIPrefix + + "]"); DEBUG("Expected prefix: " << m_sURIPrefix); DEBUG("Requested path: " << m_sURI); Redirect("/"); } else { OnPageRequest(m_sURI); } - } #ifdef HAVE_ZLIB -static bool InitZlibStream(z_stream *zStrm, const char* buf) { +static bool InitZlibStream(z_stream* zStrm, const char* buf) { memset(zStrm, 0, sizeof(z_stream)); zStrm->next_in = (Bytef*)buf; @@ -259,8 +267,8 @@ static bool InitZlibStream(z_stream *zStrm, const char* buf) { const int WINDOW_BITS = 15 + 16; const int MEMLEVEL = 8; - return (deflateInit2(zStrm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, - WINDOW_BITS, MEMLEVEL, Z_DEFAULT_STRATEGY) == Z_OK); + return (deflateInit2(zStrm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, WINDOW_BITS, + MEMLEVEL, Z_DEFAULT_STRATEGY) == Z_OK); } #endif @@ -274,7 +282,7 @@ void CHTTPSock::PrintPage(const CString& sPage) { if (InitZlibStream(&zStrm, sPage.c_str())) { DEBUG("- Sending gzip-compressed."); AddHeader("Content-Encoding", "gzip"); - PrintHeader(0); // we do not know the compressed data's length + PrintHeader(0); // we do not know the compressed data's length zStrm.avail_in = sPage.size(); do { @@ -287,17 +295,18 @@ void CHTTPSock::PrintPage(const CString& sPage) { zStatus = deflate(&zStrm, zFlush); - if((zStatus == Z_OK || zStatus == Z_STREAM_END) && zStrm.avail_out < sizeof(szBuf)) { - Write(szBuf, sizeof(szBuf) - zStrm.avail_out); + if ((zStatus == Z_OK || zStatus == Z_STREAM_END) && + zStrm.avail_out < sizeof(szBuf)) { + Write(szBuf, sizeof(szBuf) - zStrm.avail_out); } - } while(zStatus == Z_OK); + } while (zStatus == Z_OK); Close(Csock::CLT_AFTERWRITE); deflateEnd(&zStrm); return; } - } // else: fall through + } // else: fall through #endif if (!SentHeader()) { PrintHeader(sPage.length()); @@ -318,7 +327,9 @@ bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) { sFilePath = CDir::CheckPathPrefix(m_sDocRoot, sFilePath, m_sDocRoot); if (sFilePath.empty()) { - PrintErrorPage(403, "Forbidden", "You don't have permission to access that file on this server."); + PrintErrorPage(403, "Forbidden", + "You don't have permission to access that file on " + "this server."); DEBUG("THIS FILE: [" << sFilePath << "] does not live in ..."); DEBUG("DOCUMENT ROOT: [" << m_sDocRoot << "]"); return false; @@ -359,7 +370,7 @@ bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) { CString sETag; if (iMTime > 0 && !m_bHTTP10Client) { - sETag = "-" + CString(iMTime); // lighttpd style ETag + sETag = "-" + CString(iMTime); // lighttpd style ETag AddHeader("Last-Modified", GetDate(iMTime)); AddHeader("ETag", "\"" + sETag + "\""); @@ -367,7 +378,8 @@ bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) { if (!m_sIfNoneMatch.empty()) { m_sIfNoneMatch.Trim("\\\"'"); - bNotModified = (m_sIfNoneMatch.Equals(sETag, CString::CaseSensitive)); + bNotModified = + (m_sIfNoneMatch.Equals(sETag, CString::CaseSensitive)); } } @@ -385,12 +397,15 @@ bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) { } #ifdef HAVE_ZLIB - bool bGzip = m_bAcceptGzip && (sContentType.StartsWith("text/") || sFileName.EndsWith(".js")); + bool bGzip = m_bAcceptGzip && (sContentType.StartsWith("text/") || + sFileName.EndsWith(".js")); if (bGzip) { DEBUG("- Sending gzip-compressed."); AddHeader("Content-Encoding", "gzip"); - PrintHeader(0, sContentType); // we do not know the compressed data's length + PrintHeader( + 0, + sContentType); // we do not know the compressed data's length WriteFileGzipped(File); } else #endif @@ -400,7 +415,8 @@ bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) { } } - DEBUG("- ETag: [" << sETag << "] / If-None-Match [" << m_sIfNoneMatch << "]"); + DEBUG("- ETag: [" << sETag << "] / If-None-Match [" << m_sIfNoneMatch + << "]"); Close(Csock::CLT_AFTERWRITE); @@ -468,7 +484,8 @@ void CHTTPSock::WriteFileGzipped(CFile& File) { zStatus = deflate(&zStrm, zFlush); - if ((zStatus == Z_OK || zStatus == Z_STREAM_END) && zStrm.avail_out < sizeof(szBufOut)) { + if ((zStatus == Z_OK || zStatus == Z_STREAM_END) && + zStrm.avail_out < sizeof(szBufOut)) { // there's data in the buffer: Write(szBufOut, sizeof(szBufOut) - zStrm.avail_out); } @@ -484,19 +501,20 @@ void CHTTPSock::ParseURI() { m_sURI = m_sURI.Token(0, false, "?"); } -CString CHTTPSock::GetPath() const { - return m_sURI.Token(0, false, "?"); -} +CString CHTTPSock::GetPath() const { return m_sURI.Token(0, false, "?"); } -void CHTTPSock::ParseParams(const CString& sParams, map &msvsParams) { +void CHTTPSock::ParseParams(const CString& sParams, + map& msvsParams) { msvsParams.clear(); VCString vsPairs; sParams.Split("&", vsPairs, true); for (const CString& sPair : vsPairs) { - CString sName = sPair.Token(0, false, "=").Escape_n(CString::EURL, CString::EASCII); - CString sValue = sPair.Token(1, true, "=").Escape_n(CString::EURL, CString::EASCII); + CString sName = + sPair.Token(0, false, "=").Escape_n(CString::EURL, CString::EASCII); + CString sValue = + sPair.Token(1, true, "=").Escape_n(CString::EURL, CString::EASCII); msvsParams[sName].push_back(sValue); } @@ -507,43 +525,30 @@ void CHTTPSock::SetDocRoot(const CString& s) { m_sDocRoot.Replace("//", "/"); } -const CString& CHTTPSock::GetDocRoot() const { - return m_sDocRoot; -} +const CString& CHTTPSock::GetDocRoot() const { return m_sDocRoot; } -const CString& CHTTPSock::GetUser() const { - return m_sUser; -} +const CString& CHTTPSock::GetUser() const { return m_sUser; } -const CString& CHTTPSock::GetPass() const { - return m_sPass; -} +const CString& CHTTPSock::GetPass() const { return m_sPass; } -const CString& CHTTPSock::GetContentType() const { - return m_sContentType; -} +const CString& CHTTPSock::GetContentType() const { return m_sContentType; } -const CString& CHTTPSock::GetParamString() const { - return m_sPostData; -} +const CString& CHTTPSock::GetParamString() const { return m_sPostData; } -const CString& CHTTPSock::GetURIPrefix() const { - return m_sURIPrefix; -} +const CString& CHTTPSock::GetURIPrefix() const { return m_sURIPrefix; } bool CHTTPSock::HasParam(const CString& sName, bool bPost) const { - if (bPost) - return (m_msvsPOSTParams.find(sName) != m_msvsPOSTParams.end()); + if (bPost) return (m_msvsPOSTParams.find(sName) != m_msvsPOSTParams.end()); return (m_msvsGETParams.find(sName) != m_msvsGETParams.end()); } CString CHTTPSock::GetRawParam(const CString& sName, bool bPost) const { - if (bPost) - return GetRawParam(sName, m_msvsPOSTParams); + if (bPost) return GetRawParam(sName, m_msvsPOSTParams); return GetRawParam(sName, m_msvsGETParams); } -CString CHTTPSock::GetRawParam(const CString& sName, const map& msvsParams) { +CString CHTTPSock::GetRawParam(const CString& sName, + const map& msvsParams) { CString sRet; map::const_iterator it = msvsParams.find(sName); @@ -555,13 +560,15 @@ CString CHTTPSock::GetRawParam(const CString& sName, const map& msvsParams, const CString& sFilter) { +CString CHTTPSock::GetParam(const CString& sName, + const map& msvsParams, + const CString& sFilter) { CString sRet = GetRawParam(sName, msvsParams); sRet.Trim(); @@ -572,13 +579,15 @@ CString CHTTPSock::GetParam(const CString& sName, const map& return sRet; } -size_t CHTTPSock::GetParamValues(const CString& sName, set& ssRet, bool bPost, const CString& sFilter) const { - if (bPost) - return GetParamValues(sName, ssRet, m_msvsPOSTParams, sFilter); +size_t CHTTPSock::GetParamValues(const CString& sName, set& ssRet, + bool bPost, const CString& sFilter) const { + if (bPost) return GetParamValues(sName, ssRet, m_msvsPOSTParams, sFilter); return GetParamValues(sName, ssRet, m_msvsGETParams, sFilter); } -size_t CHTTPSock::GetParamValues(const CString& sName, set& ssRet, const map& msvsParams, const CString& sFilter) { +size_t CHTTPSock::GetParamValues(const CString& sName, set& ssRet, + const map& msvsParams, + const CString& sFilter) { ssRet.clear(); map::const_iterator it = msvsParams.find(sName); @@ -597,13 +606,15 @@ size_t CHTTPSock::GetParamValues(const CString& sName, set& ssRet, cons return ssRet.size(); } -size_t CHTTPSock::GetParamValues(const CString& sName, VCString& vsRet, bool bPost, const CString& sFilter) const { - if (bPost) - return GetParamValues(sName, vsRet, m_msvsPOSTParams, sFilter); +size_t CHTTPSock::GetParamValues(const CString& sName, VCString& vsRet, + bool bPost, const CString& sFilter) const { + if (bPost) return GetParamValues(sName, vsRet, m_msvsPOSTParams, sFilter); return GetParamValues(sName, vsRet, m_msvsGETParams, sFilter); } -size_t CHTTPSock::GetParamValues(const CString& sName, VCString& vsRet, const map& msvsParams, const CString& sFilter) { +size_t CHTTPSock::GetParamValues(const CString& sName, VCString& vsRet, + const map& msvsParams, + const CString& sFilter) { vsRet.clear(); map::const_iterator it = msvsParams.find(sName); @@ -623,42 +634,52 @@ size_t CHTTPSock::GetParamValues(const CString& sName, VCString& vsRet, const ma } const map& CHTTPSock::GetParams(bool bPost) const { - if (bPost) - return m_msvsPOSTParams; + if (bPost) return m_msvsPOSTParams; return m_msvsGETParams; } -bool CHTTPSock::IsPost() const { - return m_bPost; -} +bool CHTTPSock::IsPost() const { return m_bPost; } bool CHTTPSock::PrintNotFound() { - return PrintErrorPage(404, "Not Found", "The requested URL was not found on this server."); + return PrintErrorPage(404, "Not Found", + "The requested URL was not found on this server."); } -bool CHTTPSock::PrintErrorPage(unsigned int uStatusId, const CString& sStatusMsg, const CString& sMessage) { +bool CHTTPSock::PrintErrorPage(unsigned int uStatusId, + const CString& sStatusMsg, + const CString& sMessage) { if (SentHeader()) { DEBUG("PrintErrorPage(): Header was already sent"); return false; } CString sPage = - "\r\n" - "\r\n" - "\r\n" - "\r\n" - "\r\n" - "" + CString(uStatusId) + " " + sStatusMsg.Escape_n(CString::EHTML) + "\r\n" - "\r\n" - "\r\n" - "

" + sStatusMsg.Escape_n(CString::EHTML) + "

\r\n" - "

" + sMessage.Escape_n(CString::EHTML) + "

\r\n" - "
\r\n" - "

" + CZNC::GetTag(false, /* bHTML = */ true) + "

\r\n" - "\r\n" - "\r\n"; + "\r\n" + "\r\n" + "\r\n" + "\r\n" + "\r\n" + "" + + CString(uStatusId) + " " + sStatusMsg.Escape_n(CString::EHTML) + + "\r\n" + "\r\n" + "\r\n" + "

" + + sStatusMsg.Escape_n(CString::EHTML) + + "

\r\n" + "

" + + sMessage.Escape_n(CString::EHTML) + + "

\r\n" + "
\r\n" + "

" + + CZNC::GetTag(false, /* bHTML = */ true) + + "

\r\n" + "\r\n" + "\r\n"; - PrintHeader(sPage.length(), "text/html; charset=utf-8", uStatusId, sStatusMsg); + PrintHeader(sPage.length(), "text/html; charset=utf-8", uStatusId, + sStatusMsg); Write(sPage); Close(Csock::CLT_AFTERWRITE); @@ -675,21 +696,22 @@ bool CHTTPSock::ForceLogin() { return false; } - AddHeader("WWW-Authenticate", "Basic realm=\"" + CZNC::GetTag(false) + "\""); + AddHeader("WWW-Authenticate", + "Basic realm=\"" + CZNC::GetTag(false) + "\""); PrintErrorPage(401, "Unauthorized", "You need to login to view this page."); return false; } -bool CHTTPSock::OnLogin(const CString& sUser, const CString& sPass, bool bBasic) { +bool CHTTPSock::OnLogin(const CString& sUser, const CString& sPass, + bool bBasic) { return false; } -bool CHTTPSock::SentHeader() const { - return m_bSentHeader; -} +bool CHTTPSock::SentHeader() const { return m_bSentHeader; } -bool CHTTPSock::PrintHeader(off_t uContentLength, const CString& sContentType, unsigned int uStatusId, const CString& sStatusMsg) { +bool CHTTPSock::PrintHeader(off_t uContentLength, const CString& sContentType, + unsigned int uStatusId, const CString& sStatusMsg) { if (SentHeader()) { DEBUG("PrintHeader(): Header was already sent!"); return false; @@ -703,9 +725,11 @@ bool CHTTPSock::PrintHeader(off_t uContentLength, const CString& sContentType, u m_sContentType = "text/html; charset=utf-8"; } - DEBUG("- " << uStatusId << " (" << sStatusMsg << ") [" << m_sContentType << "]"); + DEBUG("- " << uStatusId << " (" << sStatusMsg << ") [" << m_sContentType + << "]"); - Write("HTTP/" + CString(m_bHTTP10Client ? "1.0 " : "1.1 ") + CString(uStatusId) + " " + sStatusMsg + "\r\n"); + Write("HTTP/" + CString(m_bHTTP10Client ? "1.0 " : "1.1 ") + + CString(uStatusId) + " " + sStatusMsg + "\r\n"); Write("Date: " + GetDate() + "\r\n"); Write("Server: " + CZNC::GetTag(false) + "\r\n"); if (uContentLength > 0) { @@ -714,7 +738,9 @@ bool CHTTPSock::PrintHeader(off_t uContentLength, const CString& sContentType, u Write("Content-Type: " + m_sContentType + "\r\n"); for (const auto& it : m_msResponseCookies) { - Write("Set-Cookie: " + it.first.Escape_n(CString::EURL) + "=" + it.second.Escape_n(CString::EURL) + "; HttpOnly; path=/;" + (GetSSL() ? "Secure;" : "") + "\r\n"); + Write("Set-Cookie: " + it.first.Escape_n(CString::EURL) + "=" + + it.second.Escape_n(CString::EURL) + "; HttpOnly; path=/;" + + (GetSSL() ? "Secure;" : "") + "\r\n"); } for (const auto& it : m_msHeaders) { @@ -741,21 +767,22 @@ bool CHTTPSock::Redirect(const CString& sURL) { if (SentHeader()) { DEBUG("Redirect() - Header was already sent"); return false; - } else if(!sURL.StartsWith("/")) { + } else if (!sURL.StartsWith("/")) { // HTTP/1.1 only admits absolute URIs for the Location header. DEBUG("Redirect to relative URI [" + sURL + "] is not allowed."); return false; } else { CString location = m_sURIPrefix + sURL; - DEBUG("- Redirect to [" << location << "] with prefix [" + m_sURIPrefix + "]"); + DEBUG("- Redirect to [" << location + << "] with prefix [" + m_sURIPrefix + "]"); AddHeader("Location", location); - PrintErrorPage(302, "Found", "The document has moved here."); + PrintErrorPage(302, "Found", "The document has moved here."); return true; } } -void CHTTPSock::Connected() { - SetTimeout(120); -} +void CHTTPSock::Connected() { SetTimeout(120); } diff --git a/src/IRCNetwork.cpp b/src/IRCNetwork.cpp index 637ee85a..78d34465 100644 --- a/src/IRCNetwork.cpp +++ b/src/IRCNetwork.cpp @@ -30,9 +30,12 @@ using std::vector; using std::set; class CIRCNetworkPingTimer : public CCron { -public: - CIRCNetworkPingTimer(CIRCNetwork *pNetwork) : CCron(), m_pNetwork(pNetwork) { - SetName("CIRCNetworkPingTimer::" + m_pNetwork->GetUser()->GetUserName() + "::" + m_pNetwork->GetName()); + public: + CIRCNetworkPingTimer(CIRCNetwork* pNetwork) + : CCron(), m_pNetwork(pNetwork) { + SetName("CIRCNetworkPingTimer::" + + m_pNetwork->GetUser()->GetUserName() + "::" + + m_pNetwork->GetName()); Start(CIRCNetwork::PING_SLACK); } @@ -41,30 +44,36 @@ public: CIRCNetworkPingTimer(const CIRCNetworkPingTimer&) = delete; CIRCNetworkPingTimer& operator=(const CIRCNetworkPingTimer&) = delete; -protected: + protected: void RunJob() override { CIRCSock* pIRCSock = m_pNetwork->GetIRCSock(); - if (pIRCSock && pIRCSock->GetTimeSinceLastDataTransaction() >= CIRCNetwork::PING_FREQUENCY) { + if (pIRCSock && + pIRCSock->GetTimeSinceLastDataTransaction() >= + CIRCNetwork::PING_FREQUENCY) { pIRCSock->PutIRC("PING :ZNC"); } const vector& vClients = m_pNetwork->GetClients(); for (CClient* pClient : vClients) { - if (pClient->GetTimeSinceLastDataTransaction() >= CIRCNetwork::PING_FREQUENCY) { + if (pClient->GetTimeSinceLastDataTransaction() >= + CIRCNetwork::PING_FREQUENCY) { pClient->PutClient("PING :ZNC"); } } } -private: + private: CIRCNetwork* m_pNetwork; }; class CIRCNetworkJoinTimer : public CCron { -public: - CIRCNetworkJoinTimer(CIRCNetwork *pNetwork) : CCron(), m_bDelayed(false), m_pNetwork(pNetwork) { - SetName("CIRCNetworkJoinTimer::" + m_pNetwork->GetUser()->GetUserName() + "::" + m_pNetwork->GetName()); + public: + CIRCNetworkJoinTimer(CIRCNetwork* pNetwork) + : CCron(), m_bDelayed(false), m_pNetwork(pNetwork) { + SetName("CIRCNetworkJoinTimer::" + + m_pNetwork->GetUser()->GetUserName() + "::" + + m_pNetwork->GetName()); Start(CIRCNetwork::JOIN_FREQUENCY); } @@ -78,7 +87,7 @@ public: Start(uDelay); } -protected: + protected: void RunJob() override { if (m_bDelayed) { m_bDelayed = false; @@ -89,8 +98,8 @@ protected: } } -private: - bool m_bDelayed; + private: + bool m_bDelayed; CIRCNetwork* m_pNetwork; }; @@ -101,7 +110,7 @@ bool CIRCNetwork::IsValidNetwork(const CString& sNetwork) { return false; } - const char *p = sNetwork.c_str(); + const char* p = sNetwork.c_str(); while (*p) { if (*p != '_' && *p != '-' && !isalnum(*p)) { return false; @@ -113,44 +122,46 @@ bool CIRCNetwork::IsValidNetwork(const CString& sNetwork) { return true; } -CIRCNetwork::CIRCNetwork(CUser *pUser, const CString& sName) - : m_sName(sName), - m_pUser(nullptr), - m_sNick(""), - m_sAltNick(""), - m_sIdent(""), - m_sRealName(""), - m_sBindHost(""), - m_sEncoding(""), - m_sQuitMsg(""), - m_ssTrustedFingerprints(), - m_pModules(new CModules), - m_vClients(), - m_pIRCSock(nullptr), - m_vChans(), - m_vQueries(), - m_sChanPrefixes(""), - m_bIRCConnectEnabled(true), - m_sIRCServer(""), - m_vServers(), - m_uServerIdx(0), - m_IRCNick(), - m_bIRCAway(false), - m_fFloodRate(1), - m_uFloodBurst(4), - m_RawBuffer(), - m_MotdBuffer(), - m_NoticeBuffer(), - m_pPingTimer(nullptr), - m_pJoinTimer(nullptr), - m_uJoinDelay(0), - m_uBytesRead(0), - m_uBytesWritten(0) -{ +CIRCNetwork::CIRCNetwork(CUser* pUser, const CString& sName) + : m_sName(sName), + m_pUser(nullptr), + m_sNick(""), + m_sAltNick(""), + m_sIdent(""), + m_sRealName(""), + m_sBindHost(""), + m_sEncoding(""), + m_sQuitMsg(""), + m_ssTrustedFingerprints(), + m_pModules(new CModules), + m_vClients(), + m_pIRCSock(nullptr), + m_vChans(), + m_vQueries(), + m_sChanPrefixes(""), + m_bIRCConnectEnabled(true), + m_sIRCServer(""), + m_vServers(), + m_uServerIdx(0), + m_IRCNick(), + m_bIRCAway(false), + m_fFloodRate(1), + m_uFloodBurst(4), + m_RawBuffer(), + m_MotdBuffer(), + m_NoticeBuffer(), + m_pPingTimer(nullptr), + m_pJoinTimer(nullptr), + m_uJoinDelay(0), + m_uBytesRead(0), + m_uBytesWritten(0) { SetUser(pUser); - m_RawBuffer.SetLineCount(100, true); // This should be more than enough raws, especially since we are buffering the MOTD separately - m_MotdBuffer.SetLineCount(200, true); // This should be more than enough motd lines + m_RawBuffer.SetLineCount(100, true); // This should be more than enough + // raws, especially since we are + // buffering the MOTD separately + m_MotdBuffer.SetLineCount( + 200, true); // This should be more than enough motd lines m_NoticeBuffer.SetLineCount(250, true); m_pPingTimer = new CIRCNetworkPingTimer(this); @@ -162,7 +173,8 @@ CIRCNetwork::CIRCNetwork(CUser *pUser, const CString& sName) SetIRCConnectEnabled(true); } -CIRCNetwork::CIRCNetwork(CUser *pUser, const CIRCNetwork &Network) : CIRCNetwork(pUser, "") { +CIRCNetwork::CIRCNetwork(CUser* pUser, const CIRCNetwork& Network) + : CIRCNetwork(pUser, "") { Clone(Network); } @@ -196,7 +208,8 @@ void CIRCNetwork::Clone(const CIRCNetwork& Network, bool bCloneName) { DelServers(); for (CServer* pServer : vServers) { - AddServer(pServer->GetName(), pServer->GetPort(), pServer->GetPass(), pServer->IsSSL()); + AddServer(pServer->GetName(), pServer->GetPort(), pServer->GetPass(), + pServer->IsSSL()); } m_uServerIdx = 0; @@ -211,7 +224,8 @@ void CIRCNetwork::Clone(const CIRCNetwork& Network, bool bCloneName) { CIRCSock* pSock = GetIRCSock(); if (pSock) { - PutStatus("Jumping servers because this server is no longer in the list"); + PutStatus( + "Jumping servers because this server is no longer in the list"); pSock->Quit(); } } @@ -250,9 +264,12 @@ void CIRCNetwork::Clone(const CIRCNetwork& Network, bool bCloneName) { CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName()); if (!pCurMod) { - vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), CModInfo::NetworkModule, m_pUser, this, sModRet); + vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), + CModInfo::NetworkModule, m_pUser, this, + sModRet); } else if (pNewMod->GetArgs() != pCurMod->GetArgs()) { - vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), m_pUser, this, sModRet); + vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), + m_pUser, this, sModRet); } } @@ -338,34 +355,35 @@ CString CIRCNetwork::GetNetworkPath() const { return sNetworkPath; } -template +template struct TOption { - const char *name; + const char* name; void (CIRCNetwork::*pSetter)(T); }; -bool CIRCNetwork::ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade) { +bool CIRCNetwork::ParseConfig(CConfig* pConfig, CString& sError, + bool bUpgrade) { VCString vsList; if (!bUpgrade) { TOption StringOptions[] = { - { "nick", &CIRCNetwork::SetNick }, - { "altnick", &CIRCNetwork::SetAltNick }, - { "ident", &CIRCNetwork::SetIdent }, - { "realname", &CIRCNetwork::SetRealName }, - { "bindhost", &CIRCNetwork::SetBindHost }, - { "encoding", &CIRCNetwork::SetEncoding }, - { "quitmsg", &CIRCNetwork::SetQuitMsg }, + {"nick", &CIRCNetwork::SetNick}, + {"altnick", &CIRCNetwork::SetAltNick}, + {"ident", &CIRCNetwork::SetIdent}, + {"realname", &CIRCNetwork::SetRealName}, + {"bindhost", &CIRCNetwork::SetBindHost}, + {"encoding", &CIRCNetwork::SetEncoding}, + {"quitmsg", &CIRCNetwork::SetQuitMsg}, }; TOption BoolOptions[] = { - { "ircconnectenabled", &CIRCNetwork::SetIRCConnectEnabled }, + {"ircconnectenabled", &CIRCNetwork::SetIRCConnectEnabled}, }; TOption DoubleOptions[] = { - { "floodrate", &CIRCNetwork::SetFloodRate }, + {"floodrate", &CIRCNetwork::SetFloodRate}, }; TOption SUIntOptions[] = { - { "floodburst", &CIRCNetwork::SetFloodBurst }, - { "joindelay", &CIRCNetwork::SetJoinDelay }, + {"floodburst", &CIRCNetwork::SetFloodBurst}, + {"joindelay", &CIRCNetwork::SetJoinDelay}, }; for (const auto& Option : StringOptions) { @@ -400,19 +418,25 @@ bool CIRCNetwork::ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade) // XXX Legacy crap, added in ZNC 0.203, modified in 0.207 // Note that 0.203 == 0.207 if (sModName == "away") { - sNotice = "NOTICE: [away] was renamed, loading [awaystore] instead"; + sNotice = + "NOTICE: [away] was renamed, loading [awaystore] instead"; sModName = "awaystore"; } // XXX Legacy crap, added in ZNC 0.207 if (sModName == "autoaway") { - sNotice = "NOTICE: [autoaway] was renamed, loading [awaystore] instead"; + sNotice = + "NOTICE: [autoaway] was renamed, loading [awaystore] " + "instead"; sModName = "awaystore"; } - - // XXX Legacy crap, added in 1.1; fakeonline module was dropped in 1.0 and returned in 1.1 + + // XXX Legacy crap, added in 1.1; fakeonline module was dropped in + // 1.0 and returned in 1.1 if (sModName == "fakeonline") { - sNotice = "NOTICE: [fakeonline] was renamed, loading [modules_online] instead"; + sNotice = + "NOTICE: [fakeonline] was renamed, loading " + "[modules_online] instead"; sModName = "modules_online"; } @@ -422,7 +446,8 @@ bool CIRCNetwork::ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade) bool bModRet = LoadModule(sModName, sArgs, sNotice, sModRet); if (!bModRet) { - // XXX The awaynick module was retired in 1.6 (still available as external module) + // XXX The awaynick module was retired in 1.6 (still available + // as external module) if (sModName == "awaynick") { // load simple_away instead, unless it's already on the list bool bFound = false; @@ -432,7 +457,8 @@ bool CIRCNetwork::ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade) } } if (!bFound) { - sNotice = "Loading network module [simple_away] instead"; + sNotice = + "Loading network module [simple_away] instead"; sModName = "simple_away"; // not a fatal error if simple_away is not available LoadModule(sModName, sArgs, sNotice, sModRet); @@ -471,7 +497,9 @@ bool CIRCNetwork::ParseConfig(CConfig *pConfig, CString& sError, bool bUpgrade) CChan* pChan = new CChan(sChanName, this, true, pSubConf); if (!pSubConf->empty()) { - sError = "Unhandled lines in config for User [" + m_pUser->GetUserName() + "], Network [" + GetName() + "], Channel [" + sChanName + "]!"; + sError = "Unhandled lines in config for User [" + + m_pUser->GetUserName() + "], Network [" + GetName() + + "], Channel [" + sChanName + "]!"; CUtils::PrintError(sError); CZNC::DumpConfig(pSubConf); @@ -515,7 +543,8 @@ CConfig CIRCNetwork::ToConfig() const { config.AddKeyValuePair("BindHost", m_sBindHost); } - config.AddKeyValuePair("IRCConnectEnabled", CString(GetIRCConnectEnabled())); + config.AddKeyValuePair("IRCConnectEnabled", + CString(GetIRCConnectEnabled())); config.AddKeyValuePair("FloodRate", CString(GetFloodRate())); config.AddKeyValuePair("FloodBurst", CString(GetFloodBurst())); config.AddKeyValuePair("JoinDelay", CString(GetJoinDelay())); @@ -577,7 +606,7 @@ bool CIRCNetwork::IsUserOnline() const { return false; } -void CIRCNetwork::ClientConnected(CClient *pClient) { +void CIRCNetwork::ClientConnected(CClient* pClient) { if (!m_pUser->MultiClients()) { BounceAllClients(); } @@ -593,7 +622,8 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { pClient->SetPlaybackActive(true); if (m_RawBuffer.IsEmpty()) { - pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + " :- Welcome to ZNC -"); + pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + + " :- Welcome to ZNC -"); } else { const CString& sClientNick = pClient->GetNick(false); MCString msParams; @@ -605,9 +635,9 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { } const CNick& Nick = GetIRCNick(); - if (sClientNick != Nick.GetNick()) { // case-sensitive match - pClient->PutClient(":" + sClientNick + "!" + Nick.GetIdent() + - "@" + Nick.GetHost() + " NICK :" + Nick.GetNick()); + if (sClientNick != Nick.GetNick()) { // case-sensitive match + pClient->PutClient(":" + sClientNick + "!" + Nick.GetIdent() + "@" + + Nick.GetHost() + " NICK :" + Nick.GetNick()); pClient->SetNick(Nick.GetNick()); } } @@ -621,7 +651,7 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { for (uIdx = 0; uIdx < uSize; uIdx++) { pClient->PutClient(m_MotdBuffer.GetLine(uIdx, *pClient, msParams)); } - } + } if (GetIRCSock() != nullptr) { CString sUserMode(""); @@ -630,14 +660,16 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { sUserMode += cMode; } if (!sUserMode.empty()) { - pClient->PutClient(":" + GetIRCNick().GetNickMask() + " MODE " + GetIRCNick().GetNick() + " :+" + sUserMode); + pClient->PutClient(":" + GetIRCNick().GetNickMask() + " MODE " + + GetIRCNick().GetNick() + " :+" + sUserMode); } } if (m_bIRCAway) { // If they want to know their away reason they'll have to whois // themselves. At least we can tell them their away status... - pClient->PutClient(":irc.znc.in 306 " + GetIRCNick().GetNick() + " :You have been marked as being away"); + pClient->PutClient(":irc.znc.in 306 " + GetIRCNick().GetNick() + + " :You have been marked as being away"); } const vector& vChans = GetChans(); @@ -667,7 +699,8 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { Message.SetTime(BufLine.GetTime()); Message.SetTags(BufLine.GetTags()); bool bContinue = false; - NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), m_pUser, this, nullptr, &bContinue); + NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), m_pUser, this, + nullptr, &bContinue); if (bContinue) continue; pClient->PutClient(Message); } @@ -677,11 +710,12 @@ void CIRCNetwork::ClientConnected(CClient *pClient) { // Tell them why they won't connect if (!GetIRCConnectEnabled()) - pClient->PutStatus("You are currently disconnected from IRC. " - "Use 'connect' to reconnect."); + pClient->PutStatus( + "You are currently disconnected from IRC. " + "Use 'connect' to reconnect."); } -void CIRCNetwork::ClientDisconnected(CClient *pClient) { +void CIRCNetwork::ClientDisconnected(CClient* pClient) { auto it = std::find(m_vClients.begin(), m_vClients.end(), pClient); if (it != m_vClients.end()) { m_vClients.erase(it); @@ -689,15 +723,12 @@ void CIRCNetwork::ClientDisconnected(CClient *pClient) { pClient->ClearServerDependentCaps(); } -CUser* CIRCNetwork::GetUser() const { - return m_pUser; -} +CUser* CIRCNetwork::GetUser() const { return m_pUser; } -const CString& CIRCNetwork::GetName() const { - return m_sName; -} +const CString& CIRCNetwork::GetName() const { return m_sName; } -std::vector CIRCNetwork::FindClients(const CString& sIdentifier) const { +std::vector CIRCNetwork::FindClients( + const CString& sIdentifier) const { std::vector vClients; for (CClient* pClient : m_vClients) { if (pClient->GetIdentifier().Equals(sIdentifier)) { @@ -708,9 +739,10 @@ std::vector CIRCNetwork::FindClients(const CString& sIdentifier) const return vClients; } -void CIRCNetwork::SetUser(CUser *pUser) { +void CIRCNetwork::SetUser(CUser* pUser) { for (CClient* pClient : m_vClients) { - pClient->PutStatus("This network is being deleted or moved to another user."); + pClient->PutStatus( + "This network is being deleted or moved to another user."); pClient->SetNetwork(nullptr); } @@ -735,9 +767,11 @@ bool CIRCNetwork::SetName(const CString& sName) { return false; } -bool CIRCNetwork::PutUser(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CIRCNetwork::PutUser(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutClient(sLine); if (pClient) { @@ -749,9 +783,11 @@ bool CIRCNetwork::PutUser(const CString& sLine, CClient* pClient, CClient* pSkip return (pClient == nullptr); } -bool CIRCNetwork::PutUser(const CMessage& Message, CClient* pClient, CClient* pSkipClient) { +bool CIRCNetwork::PutUser(const CMessage& Message, CClient* pClient, + CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutClient(Message); if (pClient) { @@ -763,9 +799,11 @@ bool CIRCNetwork::PutUser(const CMessage& Message, CClient* pClient, CClient* pS return (pClient == nullptr); } -bool CIRCNetwork::PutStatus(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CIRCNetwork::PutStatus(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutStatus(sLine); if (pClient) { @@ -777,9 +815,11 @@ bool CIRCNetwork::PutStatus(const CString& sLine, CClient* pClient, CClient* pSk return (pClient == nullptr); } -bool CIRCNetwork::PutModule(const CString& sModule, const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CIRCNetwork::PutModule(const CString& sModule, const CString& sLine, + CClient* pClient, CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutModule(sModule, sLine); if (pClient) { @@ -797,7 +837,8 @@ const vector& CIRCNetwork::GetChans() const { return m_vChans; } CChan* CIRCNetwork::FindChan(CString sName) const { if (GetIRCSock()) { - // See https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.16 + // See + // https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.16 sName.TrimLeft(GetIRCSock()->GetISupport("STATUSMSG", "")); } @@ -815,8 +856,7 @@ std::vector CIRCNetwork::FindChans(const CString& sWild) const { vChans.reserve(m_vChans.size()); const CString sLower = sWild.AsLower(); for (CChan* pChan : m_vChans) { - if (pChan->GetName().AsLower().WildCmp(sLower)) - vChans.push_back(pChan); + if (pChan->GetName().AsLower().WildCmp(sLower)) vChans.push_back(pChan); } return vChans; } @@ -848,7 +888,8 @@ bool CIRCNetwork::AddChan(const CString& sName, bool bInConfig) { } bool CIRCNetwork::DelChan(const CString& sName) { - for (vector::iterator a = m_vChans.begin(); a != m_vChans.end(); ++a) { + for (vector::iterator a = m_vChans.begin(); a != m_vChans.end(); + ++a) { if (sName.Equals((*a)->GetName())) { delete *a; m_vChans.erase(a); @@ -861,8 +902,7 @@ bool CIRCNetwork::DelChan(const CString& sName) { void CIRCNetwork::JoinChans() { // Avoid divsion by zero, it's bad! - if (m_vChans.empty()) - return; + if (m_vChans.empty()) return; // We start at a random offset into the channel list so that if your // first 3 channels are invite-only and you got MaxJoins == 3, ZNC will @@ -874,8 +914,7 @@ void CIRCNetwork::JoinChans() { unsigned int idx = (start + a) % m_vChans.size(); CChan* pChan = m_vChans[idx]; if (!pChan->IsOn() && !pChan->IsDisabled()) { - if (!JoinChan(pChan)) - continue; + if (!JoinChan(pChan)) continue; sChans.insert(pChan); @@ -888,8 +927,7 @@ void CIRCNetwork::JoinChans() { } } - while (!sChans.empty()) - JoinChans(sChans); + while (!sChans.empty()) JoinChans(sChans); } void CIRCNetwork::JoinChans(set& sChans) { @@ -902,10 +940,9 @@ void CIRCNetwork::JoinChans(set& sChans) { const CString& sName = (*it)->GetName(); const CString& sKey = (*it)->GetKey(); size_t len = sName.length() + sKey.length(); - len += 2; // two comma + len += 2; // two comma - if (!sKeys.empty() && uiJoinLength + len >= 512) - break; + if (!sKeys.empty() && uiJoinLength + len >= 512) break; if (!sJoin.empty()) { sJoin += ","; @@ -930,16 +967,18 @@ bool CIRCNetwork::JoinChan(CChan* pChan) { bool bReturn = false; NETWORKMODULECALL(OnJoining(*pChan), m_pUser, this, nullptr, &bReturn); - if (bReturn) - return false; + if (bReturn) return false; - if (m_pUser->JoinTries() != 0 && pChan->GetJoinTries() >= m_pUser->JoinTries()) { - PutStatus("The channel " + pChan->GetName() + " could not be joined, disabling it."); + if (m_pUser->JoinTries() != 0 && + pChan->GetJoinTries() >= m_pUser->JoinTries()) { + PutStatus("The channel " + pChan->GetName() + + " could not be joined, disabling it."); pChan->Disable(); } else { pChan->IncJoinTries(); bool bFailed = false; - NETWORKMODULECALL(OnTimerAutoJoin(*pChan), m_pUser, this, nullptr, &bFailed); + NETWORKMODULECALL(OnTimerAutoJoin(*pChan), m_pUser, this, nullptr, + &bFailed); if (bFailed) return false; return true; } @@ -947,10 +986,9 @@ bool CIRCNetwork::JoinChan(CChan* pChan) { } bool CIRCNetwork::IsChan(const CString& sChan) const { - if (sChan.empty()) - return false; // There is no way this is a chan + if (sChan.empty()) return false; // There is no way this is a chan if (GetChanPrefixes().empty()) - return true; // We can't know, so we allow everything + return true; // We can't know, so we allow everything // Thanks to the above if (empty), we can do sChan[0] return GetChanPrefixes().find(sChan[0]) != CString::npos; } @@ -1002,7 +1040,8 @@ CQuery* CIRCNetwork::AddQuery(const CString& sName) { } bool CIRCNetwork::DelQuery(const CString& sName) { - for (vector::iterator a = m_vQueries.begin(); a != m_vQueries.end(); ++a) { + for (vector::iterator a = m_vQueries.begin(); + a != m_vQueries.end(); ++a) { if (sName.Equals((*a)->GetName())) { delete *a; m_vQueries.erase(a); @@ -1027,7 +1066,8 @@ CServer* CIRCNetwork::FindServer(const CString& sName) const { return nullptr; } -bool CIRCNetwork::DelServer(const CString& sName, unsigned short uPort, const CString& sPass) { +bool CIRCNetwork::DelServer(const CString& sName, unsigned short uPort, + const CString& sPass) { if (sName.empty()) { return false; } @@ -1036,20 +1076,17 @@ bool CIRCNetwork::DelServer(const CString& sName, unsigned short uPort, const CS bool bSawCurrentServer = false; CServer* pCurServer = GetCurrentServer(); - for (vector::iterator it = m_vServers.begin(); it != m_vServers.end(); ++it, a++) { + for (vector::iterator it = m_vServers.begin(); + it != m_vServers.end(); ++it, a++) { CServer* pServer = *it; - if (pServer == pCurServer) - bSawCurrentServer = true; + if (pServer == pCurServer) bSawCurrentServer = true; - if (!pServer->GetName().Equals(sName)) - continue; + if (!pServer->GetName().Equals(sName)) continue; - if (uPort != 0 && pServer->GetPort() != uPort) - continue; + if (uPort != 0 && pServer->GetPort() != uPort) continue; - if (!sPass.empty() && pServer->GetPass() != sPass) - continue; + if (!sPass.empty() && pServer->GetPass() != sPass) continue; m_vServers.erase(it); @@ -1102,7 +1139,8 @@ bool CIRCNetwork::AddServer(const CString& sName) { return AddServer(sHost, uPort, sPass, bSSL); } -bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) { +bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort, + const CString& sPass, bool bSSL) { #ifndef HAVE_LIBSSL if (bSSL) { return false; @@ -1119,17 +1157,13 @@ bool CIRCNetwork::AddServer(const CString& sName, unsigned short uPort, const CS // Check if server is already added for (CServer* pServer : m_vServers) { - if (!sName.Equals(pServer->GetName())) - continue; + if (!sName.Equals(pServer->GetName())) continue; - if (uPort != pServer->GetPort()) - continue; + if (uPort != pServer->GetPort()) continue; - if (sPass != pServer->GetPass()) - continue; + if (sPass != pServer->GetPass()) continue; - if (bSSL != pServer->IsSSL()) - continue; + if (bSSL != pServer->IsSSL()) continue; // Server is already added return false; @@ -1160,7 +1194,7 @@ CServer* CIRCNetwork::GetNextServer(bool bAdvance) { } CServer* CIRCNetwork::GetCurrentServer() const { - size_t uIdx = (m_uServerIdx) ? m_uServerIdx -1 : 0; + size_t uIdx = (m_uServerIdx) ? m_uServerIdx - 1 : 0; if (uIdx >= m_vServers.size()) { return nullptr; @@ -1212,12 +1246,10 @@ CString CIRCNetwork::GetCurNick() const { } bool CIRCNetwork::Connect() { - if (!GetIRCConnectEnabled() || m_pIRCSock || !HasServers()) - return false; + if (!GetIRCConnectEnabled() || m_pIRCSock || !HasServers()) return false; - CServer *pServer = GetNextServer(); - if (!pServer) - return false; + CServer* pServer = GetNextServer(); + if (!pServer) return false; if (CZNC::Get().GetServerThrottle(pServer->GetName())) { // Can't connect right now, schedule retry later @@ -1230,20 +1262,23 @@ bool CIRCNetwork::Connect() { bool bSSL = pServer->IsSSL(); #ifndef HAVE_LIBSSL if (bSSL) { - PutStatus("Cannot connect to [" + pServer->GetString(false) + "], ZNC is not compiled with SSL."); + PutStatus("Cannot connect to [" + pServer->GetString(false) + + "], ZNC is not compiled with SSL."); CZNC::Get().AddNetworkToQueue(this); return false; } #endif - CIRCSock *pIRCSock = new CIRCSock(this); + CIRCSock* pIRCSock = new CIRCSock(this); pIRCSock->SetPass(pServer->GetPass()); pIRCSock->SetSSLTrustedPeerFingerprints(m_ssTrustedFingerprints); - DEBUG("Connecting user/network [" << m_pUser->GetUserName() << "/" << m_sName << "]"); + DEBUG("Connecting user/network [" << m_pUser->GetUserName() << "/" + << m_sName << "]"); bool bAbort = false; - NETWORKMODULECALL(OnIRCConnecting(pIRCSock), m_pUser, this, nullptr, &bAbort); + NETWORKMODULECALL(OnIRCConnecting(pIRCSock), m_pUser, this, nullptr, + &bAbort); if (bAbort) { DEBUG("Some module aborted the connection attempt"); PutStatus("Some module aborted the connection attempt"); @@ -1253,7 +1288,9 @@ bool CIRCNetwork::Connect() { } CString sSockName = "IRC::" + m_pUser->GetUserName() + "::" + m_sName; - CZNC::Get().GetManager().Connect(pServer->GetName(), pServer->GetPort(), sSockName, 120, bSSL, GetBindHost(), pIRCSock); + CZNC::Get().GetManager().Connect(pServer->GetName(), pServer->GetPort(), + sSockName, 120, bSSL, GetBindHost(), + pIRCSock); return true; } @@ -1263,9 +1300,7 @@ bool CIRCNetwork::IsIRCConnected() const { return (pSock && pSock->IsAuthed()); } -void CIRCNetwork::SetIRCSocket(CIRCSock* pIRCSock) { - m_pIRCSock = pIRCSock; -} +void CIRCNetwork::SetIRCSocket(CIRCSock* pIRCSock) { m_pIRCSock = pIRCSock; } void CIRCNetwork::IRCConnected() { const SCString& ssCaps = m_pIRCSock->GetAcceptedCaps(); @@ -1324,7 +1359,8 @@ bool CIRCNetwork::PutIRC(const CString& sLine) { } void CIRCNetwork::ClearQueryBuffer() { - std::for_each(m_vQueries.begin(), m_vQueries.end(), std::default_delete()); + std::for_each(m_vQueries.begin(), m_vQueries.end(), + std::default_delete()); m_vQueries.clear(); } @@ -1368,9 +1404,7 @@ const CString& CIRCNetwork::GetBindHost() const { return m_sBindHost; } -const CString& CIRCNetwork::GetEncoding() const { - return m_sEncoding; -} +const CString& CIRCNetwork::GetEncoding() const { return m_sEncoding; } CString CIRCNetwork::GetQuitMsg() const { if (m_sQuitMsg.empty()) { @@ -1420,9 +1454,7 @@ void CIRCNetwork::SetBindHost(const CString& s) { } } -void CIRCNetwork::SetEncoding(const CString& s) { - m_sEncoding = s; -} +void CIRCNetwork::SetEncoding(const CString& s) { m_sEncoding = s; } void CIRCNetwork::SetQuitMsg(const CString& s) { if (m_pUser->GetQuitMsg().Equals(s)) { @@ -1451,12 +1483,13 @@ CString& CIRCNetwork::ExpandString(const CString& sStr, CString& sRet) const { return m_pUser->ExpandString(sRet, sRet); } -bool CIRCNetwork::LoadModule(const CString& sModName, const CString& sArgs, const CString& sNotice, CString& sError) -{ +bool CIRCNetwork::LoadModule(const CString& sModName, const CString& sArgs, + const CString& sNotice, CString& sError) { CUtils::PrintAction(sNotice); CString sModRet; - bool bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::NetworkModule, GetUser(), this, sModRet); + bool bModRet = GetModules().LoadModule( + sModName, sArgs, CModInfo::NetworkModule, GetUser(), this, sModRet); CUtils::PrintStatus(bModRet, sModRet); if (!bModRet) { diff --git a/src/IRCSock.cpp b/src/IRCSock.cpp index 4b666d23..9e2e809e 100644 --- a/src/IRCSock.cpp +++ b/src/IRCSock.cpp @@ -26,7 +26,9 @@ using std::set; using std::vector; using std::map; -#define IRCSOCKMODULECALL(macFUNC, macEXITER) NETWORKMODULECALL(macFUNC, m_pNetwork->GetUser(), m_pNetwork, nullptr, macEXITER) +#define IRCSOCKMODULECALL(macFUNC, macEXITER) \ + NETWORKMODULECALL(macFUNC, m_pNetwork->GetUser(), m_pNetwork, nullptr, \ + macEXITER) // These are used in OnGeneralCTCP() const time_t CIRCSock::m_uCTCPFloodTime = 5; const unsigned int CIRCSock::m_uCTCPFloodCount = 5; @@ -37,19 +39,20 @@ const unsigned int CIRCSock::m_uCTCPFloodCount = 5; static const double FLOOD_MINIMAL_RATE = 0.3; class CIRCFloodTimer : public CCron { - CIRCSock* m_pSock; - public: - CIRCFloodTimer(CIRCSock* pSock) : m_pSock(pSock) { - StartMaxCycles(m_pSock->m_fFloodRate, 0); - } - CIRCFloodTimer(const CIRCFloodTimer&) = delete; - CIRCFloodTimer& operator=(const CIRCFloodTimer&) = delete; - void RunJob() override { - if (m_pSock->m_iSendsAllowed < m_pSock->m_uFloodBurst) { - m_pSock->m_iSendsAllowed++; - } - m_pSock->TrySend(); + CIRCSock* m_pSock; + + public: + CIRCFloodTimer(CIRCSock* pSock) : m_pSock(pSock) { + StartMaxCycles(m_pSock->m_fFloodRate, 0); + } + CIRCFloodTimer(const CIRCFloodTimer&) = delete; + CIRCFloodTimer& operator=(const CIRCFloodTimer&) = delete; + void RunJob() override { + if (m_pSock->m_iSendsAllowed < m_pSock->m_uFloodBurst) { + m_pSock->m_iSendsAllowed++; } + m_pSock->TrySend(); + } }; bool CIRCSock::IsFloodProtected(double fRate) { @@ -57,35 +60,34 @@ bool CIRCSock::IsFloodProtected(double fRate) { } CIRCSock::CIRCSock(CIRCNetwork* pNetwork) - : CIRCSocket(), - m_bAuthed(false), - m_bNamesx(false), - m_bUHNames(false), - m_bAwayNotify(false), - m_bAccountNotify(false), - m_bExtendedJoin(false), - m_bServerTime(false), - m_sPerms("*!@%+"), - m_sPermModes("qaohv"), - m_scUserModes(), - m_mueChanModes(), - m_pNetwork(pNetwork), - m_Nick(), - m_sPass(""), - m_msChans(), - m_uMaxNickLen(9), - m_uCapPaused(0), - m_ssAcceptedCaps(), - m_ssPendingCaps(), - m_lastCTCP(0), - m_uNumCTCP(0), - m_mISupport(), - m_vsSendQueue(), - m_iSendsAllowed(pNetwork->GetFloodBurst()), - m_uFloodBurst(pNetwork->GetFloodBurst()), - m_fFloodRate(pNetwork->GetFloodRate()), - m_bFloodProtection(IsFloodProtected(pNetwork->GetFloodRate())) -{ + : CIRCSocket(), + m_bAuthed(false), + m_bNamesx(false), + m_bUHNames(false), + m_bAwayNotify(false), + m_bAccountNotify(false), + m_bExtendedJoin(false), + m_bServerTime(false), + m_sPerms("*!@%+"), + m_sPermModes("qaohv"), + m_scUserModes(), + m_mueChanModes(), + m_pNetwork(pNetwork), + m_Nick(), + m_sPass(""), + m_msChans(), + m_uMaxNickLen(9), + m_uCapPaused(0), + m_ssAcceptedCaps(), + m_ssPendingCaps(), + m_lastCTCP(0), + m_uNumCTCP(0), + m_mISupport(), + m_vsSendQueue(), + m_iSendsAllowed(pNetwork->GetFloodBurst()), + m_uFloodBurst(pNetwork->GetFloodBurst()), + m_fFloodRate(pNetwork->GetFloodRate()), + m_bFloodProtection(IsFloodProtected(pNetwork->GetFloodRate())) { EnableReadLine(); m_Nick.SetIdent(m_pNetwork->GetIdent()); m_Nick.SetHost(m_pNetwork->GetBindHost()); @@ -104,7 +106,8 @@ CIRCSock::CIRCSock(CIRCNetwork* pNetwork) pNetwork->SetIRCSocket(this); - // RFC says a line can have 512 chars max + 512 chars for message tags, but we don't care ;) + // RFC says a line can have 512 chars max + 512 chars for message tags, but + // we don't care ;) SetMaxBufferThreshold(2048); if (m_bFloodProtection) { AddCron(new CIRCFloodTimer(this)); @@ -151,7 +154,8 @@ void CIRCSock::ReadLine(const CString& sData) { sLine.TrimRight("\n\r"); - DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" << m_pNetwork->GetName() << ") IRC -> ZNC [" << sLine << "]"); + DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" + << m_pNetwork->GetName() << ") IRC -> ZNC [" << sLine << "]"); bool bReturn = false; IRCSOCKMODULECALL(OnRaw(sLine), &bReturn); @@ -245,9 +249,7 @@ void CIRCSock::SendNextCap() { } } -void CIRCSock::PauseCap() { - ++m_uCapPaused; -} +void CIRCSock::PauseCap() { ++m_uCapPaused; } void CIRCSock::ResumeCap() { --m_uCapPaused; @@ -295,7 +297,8 @@ bool CIRCSock::OnActionMessage(CActionMessage& Message) { IRCSOCKMODULECALL(OnPrivActionMessage(Message), &bResult); if (bResult) return true; - if (!m_pNetwork->IsUserOnline() || !m_pNetwork->GetUser()->AutoClearQueryBuffer()) { + if (!m_pNetwork->IsUserOnline() || + !m_pNetwork->GetUser()->AutoClearQueryBuffer()) { const CNick& Nick = Message.GetNick(); CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick()); if (pQuery) { @@ -317,7 +320,8 @@ bool CIRCSock::OnActionMessage(CActionMessage& Message) { IRCSOCKMODULECALL(OnChanActionMessage(Message), &bResult); if (bResult) return true; - if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || pChan->IsDetached()) { + if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || + pChan->IsDetached()) { CActionMessage Format; Format.Clone(Message); Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask())); @@ -363,13 +367,14 @@ bool CIRCSock::OnCapabilityMessage(CMessage& Message) { } std::map> mSupportedCaps = { - {"multi-prefix", [this](bool bVal) { m_bNamesx = bVal; }}, - {"userhost-in-names", [this](bool bVal) { m_bUHNames = bVal; }}, - {"away-notify", [this](bool bVal) { m_bAwayNotify = bVal; }}, - {"account-notify", [this](bool bVal) { m_bAccountNotify = bVal; }}, - {"extended-join", [this](bool bVal) { m_bExtendedJoin = bVal; }}, - {"server-time", [this](bool bVal) { m_bServerTime = bVal; }}, - {"znc.in/server-time-iso", [this](bool bVal) { m_bServerTime = bVal; }}, + {"multi-prefix", [this](bool bVal) { m_bNamesx = bVal; }}, + {"userhost-in-names", [this](bool bVal) { m_bUHNames = bVal; }}, + {"away-notify", [this](bool bVal) { m_bAwayNotify = bVal; }}, + {"account-notify", [this](bool bVal) { m_bAccountNotify = bVal; }}, + {"extended-join", [this](bool bVal) { m_bExtendedJoin = bVal; }}, + {"server-time", [this](bool bVal) { m_bServerTime = bVal; }}, + {"znc.in/server-time-iso", + [this](bool bVal) { m_bServerTime = bVal; }}, }; if (sSubCmd == "LS") { @@ -452,8 +457,7 @@ bool CIRCSock::OnCTCPMessage(CCTCPMessage& Message) { if (!sReply.empty()) { time_t now = time(nullptr); // If the last CTCP is older than m_uCTCPFloodTime, reset the counter - if (m_lastCTCP + m_uCTCPFloodTime < now) - m_uNumCTCP = 0; + if (m_lastCTCP + m_uCTCPFloodTime < now) m_uNumCTCP = 0; m_lastCTCP = now; // If we are over the limit, don't reply to this CTCP if (m_uNumCTCP >= m_uCTCPFloodCount) { @@ -462,7 +466,8 @@ bool CIRCSock::OnCTCPMessage(CCTCPMessage& Message) { } m_uNumCTCP++; - PutIRC("NOTICE " + Nick.GetNick() + " :\001" + sQuery + " " + sReply + "\001"); + PutIRC("NOTICE " + Nick.GetNick() + " :\001" + sQuery + " " + sReply + + "\001"); return true; } @@ -470,7 +475,7 @@ bool CIRCSock::OnCTCPMessage(CCTCPMessage& Message) { } bool CIRCSock::OnErrorMessage(CMessage& Message) { - //ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) + // ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) CString sError = Message.GetParam(0); m_pNetwork->PutStatus("Error from Server [" + sError + "]"); return true; @@ -478,7 +483,8 @@ bool CIRCSock::OnErrorMessage(CMessage& Message) { bool CIRCSock::OnInviteMessage(CMessage& Message) { bool bResult = false; - IRCSOCKMODULECALL(OnInvite(Message.GetNick(), Message.GetParam(1)), &bResult); + IRCSOCKMODULECALL(OnInvite(Message.GetNick(), Message.GetParam(1)), + &bResult); return bResult; } @@ -551,9 +557,10 @@ bool CIRCSock::OnModeMessage(CModeMessage& Message) { } else if (sTarget == m_Nick.GetNick()) { CString sModeArg = sModes.Token(0); bool bAdd = true; -/* no module call defined (yet?) - MODULECALL(OnRawUserMode(*pOpNick, *this, sModeArg, sArgs), m_pNetwork->GetUser(), nullptr, ); -*/ + /* no module call defined (yet?) + MODULECALL(OnRawUserMode(*pOpNick, *this, sModeArg, sArgs), + m_pNetwork->GetUser(), nullptr, ); + */ for (unsigned int a = 0; a < sModeArg.size(); a++) { const unsigned char& uMode = sModeArg[a]; @@ -630,7 +637,8 @@ bool CIRCSock::OnNoticeMessage(CNoticeMessage& Message) { IRCSOCKMODULECALL(OnChanNoticeMessage(Message), &bResult); if (bResult) return true; - if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || pChan->IsDetached()) { + if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || + pChan->IsDetached()) { CNoticeMessage Format; Format.Clone(Message); Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask())); @@ -666,16 +674,21 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { if (bResult) return true; switch (uRaw) { - case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay Network nick + case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay + // Network nick if (m_bAuthed && sServer == "irc.znc.in") { - // m_bAuthed == true => we already received another 001 => we might be in a traffic loop - m_pNetwork->PutStatus("ZNC seems to be connected to itself, disconnecting..."); + // m_bAuthed == true => we already received another 001 => we + // might be in a traffic loop + m_pNetwork->PutStatus( + "ZNC seems to be connected to itself, disconnecting..."); Quit(); return true; } m_pNetwork->SetIRCServer(sServer); - SetTimeout(CIRCNetwork::NO_TRAFFIC_TIMEOUT, TMO_READ); // Now that we are connected, let nature take its course + SetTimeout(CIRCNetwork::NO_TRAFFIC_TIMEOUT, + TMO_READ); // Now that we are connected, let nature take + // its course PutIRC("WHO " + sNick); m_bAuthed = true; @@ -687,8 +700,11 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { CString sClientNick = pClient->GetNick(false); if (!sClientNick.Equals(sNick)) { - // If they connected with a nick that doesn't match the one we got on irc, then we need to update them - pClient->PutClient(":" + sClientNick + "!" + m_Nick.GetIdent() + "@" + m_Nick.GetHost() + " NICK :" + sNick); + // If they connected with a nick that doesn't match the one + // we got on irc, then we need to update them + pClient->PutClient(":" + sClientNick + "!" + + m_Nick.GetIdent() + "@" + + m_Nick.GetHost() + " NICK :" + sNick); } } @@ -707,13 +723,16 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { ParseISupport(Message); m_pNetwork->UpdateExactRawBuffer(BufferMessage(Message)); break; - case 10: { // :irc.server.com 010 nick : + case 10: { // :irc.server.com 010 nick : CString sHost = Message.GetParam(1); CString sPort = Message.GetParam(2); CString sInfo = Message.GetParam(3); - m_pNetwork->PutStatus("Server [" + m_pNetwork->GetCurrentServer()->GetString(false) + - "] redirects us to [" + sHost + ":" + sPort + "] with reason [" + sInfo + "]"); - m_pNetwork->PutStatus("Perhaps you want to add it as a new server."); + m_pNetwork->PutStatus( + "Server [" + m_pNetwork->GetCurrentServer()->GetString(false) + + "] redirects us to [" + sHost + ":" + sPort + + "] with reason [" + sInfo + "]"); + m_pNetwork->PutStatus( + "Perhaps you want to add it as a new server."); // Don't send server redirects to the client return true; } @@ -754,8 +773,7 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { return true; } } - } - break; + } break; case 329: { // :irc.server.com 329 nick #chan 1234567890 CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1)); @@ -775,8 +793,7 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { return true; } } - } - break; + } break; case 331: { // :irc.server.com 331 yournick #chan :No topic is set. CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1)); @@ -823,7 +840,8 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { break; } case 352: { // WHO - // :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name + // :irc.yourserver.com 352 yournick #chan ident theirhost.com + // irc.theirserver.com theirnick H :0 Real Name sNick = Message.GetParam(5); CString sChan = Message.GetParam(1); CString sIdent = Message.GetParam(2); @@ -877,7 +895,8 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { CString sModes = pChan->GetDefaultModes(); if (sModes.empty()) { - sModes = m_pNetwork->GetUser()->GetDefaultChanModes(); + sModes = + m_pNetwork->GetUser()->GetDefaultChanModes(); } if (!sModes.empty()) { @@ -905,12 +924,15 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { } break; case 437: - // :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable - // :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable - // :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel - if (m_pNetwork->IsChan(Message.GetParam(1)) || sNick != "*") - break; - case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal characters + // :irc.server.net 437 * badnick :Nick/channel is temporarily + // unavailable + // :irc.server.net 437 mynick badnick :Nick/channel is temporarily + // unavailable + // :irc.server.net 437 mynick badnick :Cannot change nickname while + // banned on channel + if (m_pNetwork->IsChan(Message.GetParam(1)) || sNick != "*") break; + case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal + // characters case 433: { CString sBadNick = Message.GetParam(1); @@ -922,12 +944,14 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { } case 451: // :irc.server.com 451 CAP :You have not registered - // Servers that dont support CAP will give us this error, dont send it to the client - if (sNick.Equals("CAP")) - return true; + // Servers that dont support CAP will give us this error, dont send + // it to the client + if (sNick.Equals("CAP")) return true; case 470: { - // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2 - // :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel + // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you + // are automatically being transferred to the linked channel #chan2 + // :mccaffrey.freenode.net 470 mynick #electronics ##electronics + // :Forwarding to another channel // freenode style numeric CChan* pChan = m_pNetwork->FindChan(Message.GetParam(1)); @@ -937,14 +961,17 @@ bool CIRCSock::OnNumericMessage(CNumericMessage& Message) { } if (pChan) { pChan->Disable(); - m_pNetwork->PutStatus("Channel [" + pChan->GetName() + "] is linked to " - "another channel and was thus disabled."); + m_pNetwork->PutStatus("Channel [" + pChan->GetName() + + "] is linked to " + "another channel and was thus disabled."); } break; } case 670: - // :hydra.sector5d.org 670 kylef :STARTTLS successful, go ahead with TLS handshake - // 670 is a response to `STARTTLS` telling the client to switch to TLS + // :hydra.sector5d.org 670 kylef :STARTTLS successful, go ahead with + // TLS handshake + // 670 is a response to `STARTTLS` telling the client to switch to + // TLS if (!GetSSL()) { StartTLS(); @@ -968,8 +995,7 @@ bool CIRCSock::OnPartMessage(CPartMessage& Message) { Message.SetChan(pChan); IRCSOCKMODULECALL(OnPartMessage(Message), NOTHING); - if (pChan->IsDetached()) - bDetached = true; + if (pChan->IsDetached()) bDetached = true; } if (Nick.NickEquals(GetNick())) { @@ -1036,7 +1062,8 @@ bool CIRCSock::OnTextMessage(CTextMessage& Message) { IRCSOCKMODULECALL(OnPrivMessage(Message), &bResult); if (bResult) return true; - if (!m_pNetwork->IsUserOnline() || !m_pNetwork->GetUser()->AutoClearQueryBuffer()) { + if (!m_pNetwork->IsUserOnline() || + !m_pNetwork->GetUser()->AutoClearQueryBuffer()) { const CNick& Nick = Message.GetNick(); CQuery* pQuery = m_pNetwork->AddQuery(Nick.GetNick()); if (pQuery) { @@ -1056,7 +1083,8 @@ bool CIRCSock::OnTextMessage(CTextMessage& Message) { IRCSOCKMODULECALL(OnChanMessage(Message), &bResult); if (bResult) return true; - if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || pChan->IsDetached()) { + if (!pChan->AutoClearChanBuffer() || !m_pNetwork->IsUserOnline() || + pChan->IsDetached()) { CTextMessage Format; Format.Clone(Message); Format.SetNick(_NAMEDFMT(Message.GetNick().GetNickMask())); @@ -1081,7 +1109,7 @@ bool CIRCSock::OnTopicMessage(CTopicMessage& Message) { if (bReturn) return true; pChan->SetTopicOwner(Nick.GetNick()); - pChan->SetTopicDate((unsigned long) time(nullptr)); + pChan->SetTopicDate((unsigned long)time(nullptr)); pChan->SetTopic(Message.GetTopic()); } @@ -1102,18 +1130,24 @@ bool CIRCSock::OnWallopsMessage(CMessage& Message) { } void CIRCSock::PutIRC(const CString& sLine) { - // Only print if the line won't get sent immediately (same condition as in TrySend()!) + // Only print if the line won't get sent immediately (same condition as in + // TrySend()!) if (m_bFloodProtection && m_iSendsAllowed <= 0) { - DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine << "] (queued)"); + DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" + << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine + << "] (queued)"); } m_vsSendQueue.push_back(sLine); TrySend(); } void CIRCSock::PutIRCQuick(const CString& sLine) { - // Only print if the line won't get sent immediately (same condition as in TrySend()!) + // Only print if the line won't get sent immediately (same condition as in + // TrySend()!) if (m_bFloodProtection && m_iSendsAllowed <= 0) { - DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine << "] (queued to front)"); + DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" + << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine + << "] (queued to front)"); } m_vsSendQueue.push_front(sLine); TrySend(); @@ -1121,13 +1155,17 @@ void CIRCSock::PutIRCQuick(const CString& sLine) { void CIRCSock::TrySend() { // This condition must be the same as in PutIRC() and PutIRCQuick()! - while (!m_vsSendQueue.empty() && (!m_bFloodProtection || m_iSendsAllowed > 0)) { + while (!m_vsSendQueue.empty() && + (!m_bFloodProtection || m_iSendsAllowed > 0)) { m_iSendsAllowed--; bool bSkip = false; CString& sLine = m_vsSendQueue.front(); IRCSOCKMODULECALL(OnSendToIRC(sLine), &bSkip); - if (!bSkip) {; - DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine << "]"); + if (!bSkip) { + ; + DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" + << m_pNetwork->GetName() << ") ZNC -> IRC [" << sLine + << "]"); Write(sLine + "\r\n"); } m_vsSendQueue.pop_front(); @@ -1148,7 +1186,8 @@ void CIRCSock::Connected() { CString sRealName = m_pNetwork->GetRealName(); bool bReturn = false; - IRCSOCKMODULECALL(OnIRCRegistration(sPass, sNick, sIdent, sRealName), &bReturn); + IRCSOCKMODULECALL(OnIRCRegistration(sPass, sNick, sIdent, sRealName), + &bReturn); if (bReturn) return; PutIRC("CAP LS"); @@ -1158,7 +1197,8 @@ void CIRCSock::Connected() { } PutIRC("NICK " + sNick); - PutIRC("USER " + sIdent + " \"" + sIdent + "\" \"" + sIdent + "\" :" + sRealName); + PutIRC("USER " + sIdent + " \"" + sIdent + "\" \"" + sIdent + "\" :" + + sRealName); // SendAltNick() needs this m_Nick.SetNick(sNick); @@ -1168,8 +1208,9 @@ void CIRCSock::Disconnected() { IRCSOCKMODULECALL(OnIRCDisconnected(), NOTHING); DEBUG(GetSockName() << " == Disconnected()"); - if (!m_pNetwork->GetUser()->IsBeingDeleted() && m_pNetwork->GetIRCConnectEnabled() && - m_pNetwork->GetServers().size() != 0) { + if (!m_pNetwork->GetUser()->IsBeingDeleted() && + m_pNetwork->GetIRCConnectEnabled() && + m_pNetwork->GetServers().size() != 0) { m_pNetwork->PutStatus("Disconnected from IRC. Reconnecting..."); } m_pNetwork->ClearRawBuffer(); @@ -1177,9 +1218,11 @@ void CIRCSock::Disconnected() { CString sPrefix = m_pNetwork->GetUser()->GetStatusPrefix(); for (CChan* pChan : m_pNetwork->GetChans()) { - if(pChan->IsOn()) { - m_pNetwork->PutUser(":" + sPrefix + "status!znc@znc.in KICK " + pChan->GetName() + " " + GetNick() - + " :You have been disconnected from the IRC server"); + if (pChan->IsOn()) { + m_pNetwork->PutUser( + ":" + sPrefix + "status!znc@znc.in KICK " + pChan->GetName() + + " " + GetNick() + + " :You have been disconnected from the IRC server"); } } @@ -1193,7 +1236,9 @@ void CIRCSock::Disconnected() { sUserMode += cMode; } if (!sUserMode.empty()) { - m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " MODE " + m_pNetwork->GetIRCNick().GetNick() + " :-" + sUserMode); + m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + + " MODE " + m_pNetwork->GetIRCNick().GetNick() + + " :-" + sUserMode); } // also clear the user modes in our space: @@ -1203,13 +1248,14 @@ void CIRCSock::Disconnected() { void CIRCSock::SockError(int iErrno, const CString& sDescription) { CString sError = sDescription; - DEBUG(GetSockName() << " == SockError(" << iErrno << " " - << sError << ")"); + DEBUG(GetSockName() << " == SockError(" << iErrno << " " << sError << ")"); if (!m_pNetwork->GetUser()->IsBeingDeleted()) { if (GetConState() != CST_OK) { - m_pNetwork->PutStatus("Cannot connect to IRC (" + sError + "). Retrying..."); + m_pNetwork->PutStatus("Cannot connect to IRC (" + sError + + "). Retrying..."); } else { - m_pNetwork->PutStatus("Disconnected from IRC (" + sError + "). Reconnecting..."); + m_pNetwork->PutStatus("Disconnected from IRC (" + sError + + "). Reconnecting..."); } #ifdef HAVE_LIBSSL if (iErrno == errnoBadSSLCert) { @@ -1227,15 +1273,21 @@ void CIRCSock::SockError(int iErrno, const CString& sDescription) { VCString vsCert; sCert.Split("\n", vsCert); for (const CString& s : vsCert) { - // It shouldn't contain any bad characters, but let's be safe... + // It shouldn't contain any bad characters, but let's be + // safe... m_pNetwork->PutStatus("|" + s.Escape_n(CString::EDEBUG)); } CString sSHA1; if (GetPeerFingerprint(sSHA1)) - m_pNetwork->PutStatus("SHA1: " + sSHA1.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON)); + m_pNetwork->PutStatus( + "SHA1: " + + sSHA1.Escape_n(CString::EHEXCOLON, CString::EHEXCOLON)); CString sSHA256 = GetSSLPeerFingerprint(); m_pNetwork->PutStatus("SHA-256: " + sSHA256); - m_pNetwork->PutStatus("If you trust this certificate, do /znc AddTrustedServerFingerprint " + sSHA256); + m_pNetwork->PutStatus( + "If you trust this certificate, do /znc " + "AddTrustedServerFingerprint " + + sSHA256); } } #endif @@ -1313,25 +1365,24 @@ void CIRCSock::ParseISupport(const CMessage& Message) { CString sModes = sValue.Token(a, false, ","); for (unsigned int b = 0; b < sModes.size(); b++) { - m_mueChanModes[sModes[b]] = (EChanModeArgs) a; + m_mueChanModes[sModes[b]] = (EChanModeArgs)a; } } } } else if (sName.Equals("NAMESX")) { - if (m_bNamesx) - continue; + if (m_bNamesx) continue; m_bNamesx = true; PutIRC("PROTOCTL NAMESX"); } else if (sName.Equals("UHNAMES")) { - if (m_bUHNames) - continue; + if (m_bUHNames) continue; m_bUHNames = true; PutIRC("PROTOCTL UHNAMES"); } } } -CString CIRCSock::GetISupport(const CString& sKey, const CString& sDefault) const { +CString CIRCSock::GetISupport(const CString& sKey, + const CString& sDefault) const { MCString::const_iterator i = m_mISupport.find(sKey.AsUpper()); if (i == m_mISupport.end()) { return sDefault; @@ -1352,7 +1403,7 @@ void CIRCSock::SendAltNick(const CString& sBadNick) { unsigned int uMax = m_uMaxNickLen; const CString& sConfNick = m_pNetwork->GetNick(); - const CString& sAltNick = m_pNetwork->GetAltNick(); + const CString& sAltNick = m_pNetwork->GetAltNick(); CString sNewNick = sConfNick.Left(uMax - 1); if (sLastNick.Equals(sConfNick)) { @@ -1363,11 +1414,14 @@ void CIRCSock::SendAltNick(const CString& sBadNick) { } } else if (sLastNick.Equals(sAltNick) && !sAltNick.Equals(sNewNick + "-")) { sNewNick += "-"; - } else if (sLastNick.Equals(sNewNick + "-") && !sAltNick.Equals(sNewNick + "|")) { + } else if (sLastNick.Equals(sNewNick + "-") && + !sAltNick.Equals(sNewNick + "|")) { sNewNick += "|"; - } else if (sLastNick.Equals(sNewNick + "|") && !sAltNick.Equals(sNewNick + "^")) { + } else if (sLastNick.Equals(sNewNick + "|") && + !sAltNick.Equals(sNewNick + "^")) { sNewNick += "^"; - } else if (sLastNick.Equals(sNewNick + "^") && !sAltNick.Equals(sNewNick + "a")) { + } else if (sLastNick.Equals(sNewNick + "^") && + !sAltNick.Equals(sNewNick + "a")) { sNewNick += "a"; } else { char cLetter = 0; @@ -1385,9 +1439,9 @@ void CIRCSock::SendAltNick(const CString& sBadNick) { return; } - sNewNick = sConfNick.Left(uMax -1) + ++cLetter; + sNewNick = sConfNick.Left(uMax - 1) + ++cLetter; if (sNewNick.Equals(sAltNick)) - sNewNick = sConfNick.Left(uMax -1) + ++cLetter; + sNewNick = sConfNick.Left(uMax - 1) + ++cLetter; } PutIRC("NICK " + sNewNick); m_Nick.SetNick(sNewNick); @@ -1406,7 +1460,8 @@ unsigned char CIRCSock::GetPermFromMode(unsigned char uMode) const { } CIRCSock::EChanModeArgs CIRCSock::GetModeType(unsigned char uMode) const { - map::const_iterator it = m_mueChanModes.find(uMode); + map::const_iterator it = + m_mueChanModes.find(uMode); if (it == m_mueChanModes.end()) { return NoArg; @@ -1420,4 +1475,3 @@ void CIRCSock::ResetChans() { it.second->Reset(); } } - diff --git a/src/Listener.cpp b/src/Listener.cpp index b55916ec..3f18d73c 100644 --- a/src/Listener.cpp +++ b/src/Listener.cpp @@ -18,8 +18,7 @@ #include CListener::~CListener() { - if (m_pListener) - CZNC::Get().GetManager().DelSockByAddr(m_pListener); + if (m_pListener) CZNC::Get().GetManager().DelSockByAddr(m_pListener); } bool CListener::Listen() { @@ -44,32 +43,32 @@ bool CListener::Listen() { // Make sure there is a consistent error message, not something random // which might even be "Error: Success". errno = EINVAL; - return CZNC::Get().GetManager().ListenHost(m_uPort, "_LISTENER", m_sBindHost, bSSL, SOMAXCONN, - m_pListener, 0, m_eAddr); + return CZNC::Get().GetManager().ListenHost(m_uPort, "_LISTENER", + m_sBindHost, bSSL, SOMAXCONN, + m_pListener, 0, m_eAddr); } -void CListener::ResetRealListener() { - m_pListener = nullptr; -} +void CListener::ResetRealListener() { m_pListener = nullptr; } -CRealListener::~CRealListener() { - m_Listener.ResetRealListener(); -} +CRealListener::~CRealListener() { m_Listener.ResetRealListener(); } bool CRealListener::ConnectionFrom(const CString& sHost, unsigned short uPort) { bool bHostAllowed = CZNC::Get().IsHostAllowed(sHost); - DEBUG(GetSockName() << " == ConnectionFrom(" << sHost << ", " << uPort << ") [" << (bHostAllowed ? "Allowed" : "Not allowed") << "]"); + DEBUG(GetSockName() << " == ConnectionFrom(" << sHost << ", " << uPort + << ") [" << (bHostAllowed ? "Allowed" : "Not allowed") + << "]"); return bHostAllowed; } Csock* CRealListener::GetSockObj(const CString& sHost, unsigned short uPort) { - CIncomingConnection *pClient = new CIncomingConnection(sHost, uPort, - m_Listener.GetAcceptType(), - m_Listener.GetURIPrefix()); + CIncomingConnection* pClient = new CIncomingConnection( + sHost, uPort, m_Listener.GetAcceptType(), m_Listener.GetURIPrefix()); if (CZNC::Get().AllowConnectionFrom(sHost)) { GLOBALMODULECALL(OnClientConnect(pClient, sHost, uPort), NOTHING); } else { - pClient->Write(":irc.znc.in 464 unknown-nick :Too many anonymous connections from your IP\r\n"); + pClient->Write( + ":irc.znc.in 464 unknown-nick :Too many anonymous connections from " + "your IP\r\n"); pClient->Close(Csock::CLT_AFTERWRITE); GLOBALMODULECALL(OnFailedLogin("", sHost), NOTHING); } @@ -77,18 +76,28 @@ Csock* CRealListener::GetSockObj(const CString& sHost, unsigned short uPort) { } void CRealListener::SockError(int iErrno, const CString& sDescription) { - DEBUG(GetSockName() << " == SockError(" << sDescription << ", " << strerror(iErrno) << ")"); + DEBUG(GetSockName() << " == SockError(" << sDescription << ", " + << strerror(iErrno) << ")"); if (iErrno == EMFILE) { - // We have too many open fds, let's close this listening port to be able to continue + // We have too many open fds, let's close this listening port to be able + // to continue // to work, next rehash will (try to) reopen it. - CZNC::Get().Broadcast("We hit the FD limit, closing listening socket on [" - + GetLocalIP() + " : " + CString(GetLocalPort()) + "]"); - CZNC::Get().Broadcast("An admin has to rehash to reopen the listening port"); + CZNC::Get().Broadcast( + "We hit the FD limit, closing listening socket on [" + + GetLocalIP() + " : " + CString(GetLocalPort()) + "]"); + CZNC::Get().Broadcast( + "An admin has to rehash to reopen the listening port"); Close(); } } -CIncomingConnection::CIncomingConnection(const CString& sHostname, unsigned short uPort, CListener::EAcceptType eAcceptType, const CString& sURIPrefix) : CZNCSock(sHostname, uPort), m_eAcceptType(eAcceptType), m_sURIPrefix(sURIPrefix) { +CIncomingConnection::CIncomingConnection(const CString& sHostname, + unsigned short uPort, + CListener::EAcceptType eAcceptType, + const CString& sURIPrefix) + : CZNCSock(sHostname, uPort), + m_eAcceptType(eAcceptType), + m_sURIPrefix(sURIPrefix) { // The socket will time out in 120 secs, no matter what. // This has to be fixed up later, if desired. SetTimeout(120, 0); @@ -98,25 +107,24 @@ CIncomingConnection::CIncomingConnection(const CString& sHostname, unsigned shor } void CIncomingConnection::ReachedMaxBuffer() { - if (GetCloseType() != CLT_DONT) - return; // Already closing + if (GetCloseType() != CLT_DONT) return; // Already closing // We don't actually SetMaxBufferThreshold() because that would be // inherited by sockets after SwapSockByAddr(). - if (GetInternalReadBuffer().length() <= 4096) - return; + if (GetInternalReadBuffer().length() <= 4096) return; // We should never get here with legitimate requests :/ Close(); } void CIncomingConnection::ReadLine(const CString& sLine) { - bool bIsHTTP = (sLine.WildCmp("GET * HTTP/1.?\r\n") || sLine.WildCmp("POST * HTTP/1.?\r\n")); - bool bAcceptHTTP = (m_eAcceptType == CListener::ACCEPT_ALL) - || (m_eAcceptType == CListener::ACCEPT_HTTP); - bool bAcceptIRC = (m_eAcceptType == CListener::ACCEPT_ALL) - || (m_eAcceptType == CListener::ACCEPT_IRC); - Csock *pSock = nullptr; + bool bIsHTTP = (sLine.WildCmp("GET * HTTP/1.?\r\n") || + sLine.WildCmp("POST * HTTP/1.?\r\n")); + bool bAcceptHTTP = (m_eAcceptType == CListener::ACCEPT_ALL) || + (m_eAcceptType == CListener::ACCEPT_HTTP); + bool bAcceptIRC = (m_eAcceptType == CListener::ACCEPT_ALL) || + (m_eAcceptType == CListener::ACCEPT_IRC); + Csock* pSock = nullptr; if (!bIsHTTP) { // Let's assume it's an IRC connection @@ -138,7 +146,9 @@ void CIncomingConnection::ReadLine(const CString& sLine) { // This is a HTTP request, let the webmods handle it if (!bAcceptHTTP) { - Write("HTTP/1.0 403 Access Denied\r\n\r\nWeb Access is not enabled.\r\n"); + Write( + "HTTP/1.0 403 Access Denied\r\n\r\nWeb Access is not " + "enabled.\r\n"); Close(CLT_AFTERWRITE); DEBUG("Refused HTTP connection to non HTTP port"); diff --git a/src/MD5.cpp b/src/MD5.cpp index a3e1c414..dd740c54 100644 --- a/src/MD5.cpp +++ b/src/MD5.cpp @@ -23,35 +23,29 @@ #include #include -CMD5::CMD5() { - *m_szMD5 = '\0'; -} +CMD5::CMD5() { *m_szMD5 = '\0'; } -CMD5::CMD5(const string& sText) { - MakeHash(sText.c_str(), sText.length()); -} +CMD5::CMD5(const string& sText) { MakeHash(sText.c_str(), sText.length()); } -CMD5::CMD5(const char* szText, uint32 nTextLen) { - MakeHash(szText, nTextLen); -} +CMD5::CMD5(const char* szText, uint32 nTextLen) { MakeHash(szText, nTextLen); } CMD5::~CMD5() {} -#define GET_UINT32(n,b,i) { \ - (n) = ((uint32) (b)[(i) ] ) \ - | ((uint32) (b)[(i) + 1] << 8) \ - | ((uint32) (b)[(i) + 2] << 16) \ - | ((uint32) (b)[(i) + 3] << 24); \ -} +#define GET_UINT32(n, b, i) \ + { \ + (n) = ((uint32)(b)[(i)]) | ((uint32)(b)[(i)+1] << 8) | \ + ((uint32)(b)[(i)+2] << 16) | ((uint32)(b)[(i)+3] << 24); \ + } -#define PUT_UINT32(n,b,i) { \ - (b)[(i) ] = (uint8) ((n) ); \ - (b)[(i) + 1] = (uint8) ((n) >> 8); \ - (b)[(i) + 2] = (uint8) ((n) >> 16); \ - (b)[(i) + 3] = (uint8) ((n) >> 24); \ -} +#define PUT_UINT32(n, b, i) \ + { \ + (b)[(i)] = (uint8)((n)); \ + (b)[(i)+1] = (uint8)((n) >> 8); \ + (b)[(i)+2] = (uint8)((n) >> 16); \ + (b)[(i)+3] = (uint8)((n) >> 24); \ + } -void CMD5::md5_starts(md5_context *ctx) const { +void CMD5::md5_starts(md5_context* ctx) const { ctx->total[0] = 0; ctx->total[1] = 0; @@ -61,19 +55,19 @@ void CMD5::md5_starts(md5_context *ctx) const { ctx->state[3] = 0x10325476; } -void CMD5::md5_process(md5_context *ctx, const uint8 data[64]) const { +void CMD5::md5_process(md5_context* ctx, const uint8 data[64]) const { uint32 X[16], A, B, C, D; - GET_UINT32(X[0], data, 0); - GET_UINT32(X[1], data, 4); - GET_UINT32(X[2], data, 8); - GET_UINT32(X[3], data, 12); - GET_UINT32(X[4], data, 16); - GET_UINT32(X[5], data, 20); - GET_UINT32(X[6], data, 24); - GET_UINT32(X[7], data, 28); - GET_UINT32(X[8], data, 32); - GET_UINT32(X[9], data, 36); + GET_UINT32(X[0], data, 0); + GET_UINT32(X[1], data, 4); + GET_UINT32(X[2], data, 8); + GET_UINT32(X[3], data, 12); + GET_UINT32(X[4], data, 16); + GET_UINT32(X[5], data, 20); + GET_UINT32(X[6], data, 24); + GET_UINT32(X[7], data, 28); + GET_UINT32(X[8], data, 32); + GET_UINT32(X[9], data, 36); GET_UINT32(X[10], data, 40); GET_UINT32(X[11], data, 44); GET_UINT32(X[12], data, 48); @@ -81,96 +75,98 @@ void CMD5::md5_process(md5_context *ctx, const uint8 data[64]) const { GET_UINT32(X[14], data, 56); GET_UINT32(X[15], data, 60); -#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) +#define S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) -#define P(a,b,c,d,k,s,t) a += F(b,c,d) + X[k] + t; a = S(a,s) + b; +#define P(a, b, c, d, k, s, t) \ + a += F(b, c, d) + X[k] + t; \ + a = S(a, s) + b; A = ctx->state[0]; B = ctx->state[1]; C = ctx->state[2]; D = ctx->state[3]; -#define F(x,y,z) (z ^ (x & (y ^ z))) +#define F(x, y, z) (z ^ (x & (y ^ z))) - P(A, B, C, D, 0, 7, 0xD76AA478); - P(D, A, B, C, 1, 12, 0xE8C7B756); - P(C, D, A, B, 2, 17, 0x242070DB); - P(B, C, D, A, 3, 22, 0xC1BDCEEE); - P(A, B, C, D, 4, 7, 0xF57C0FAF); - P(D, A, B, C, 5, 12, 0x4787C62A); - P(C, D, A, B, 6, 17, 0xA8304613); - P(B, C, D, A, 7, 22, 0xFD469501); - P(A, B, C, D, 8, 7, 0x698098D8); - P(D, A, B, C, 9, 12, 0x8B44F7AF); + P(A, B, C, D, 0, 7, 0xD76AA478); + P(D, A, B, C, 1, 12, 0xE8C7B756); + P(C, D, A, B, 2, 17, 0x242070DB); + P(B, C, D, A, 3, 22, 0xC1BDCEEE); + P(A, B, C, D, 4, 7, 0xF57C0FAF); + P(D, A, B, C, 5, 12, 0x4787C62A); + P(C, D, A, B, 6, 17, 0xA8304613); + P(B, C, D, A, 7, 22, 0xFD469501); + P(A, B, C, D, 8, 7, 0x698098D8); + P(D, A, B, C, 9, 12, 0x8B44F7AF); P(C, D, A, B, 10, 17, 0xFFFF5BB1); P(B, C, D, A, 11, 22, 0x895CD7BE); - P(A, B, C, D, 12, 7, 0x6B901122); + P(A, B, C, D, 12, 7, 0x6B901122); P(D, A, B, C, 13, 12, 0xFD987193); P(C, D, A, B, 14, 17, 0xA679438E); P(B, C, D, A, 15, 22, 0x49B40821); #undef F -#define F(x,y,z) (y ^ (z & (x ^ y))) +#define F(x, y, z) (y ^ (z & (x ^ y))) - P(A, B, C, D, 1, 5, 0xF61E2562); - P(D, A, B, C, 6, 9, 0xC040B340); + P(A, B, C, D, 1, 5, 0xF61E2562); + P(D, A, B, C, 6, 9, 0xC040B340); P(C, D, A, B, 11, 14, 0x265E5A51); - P(B, C, D, A, 0, 20, 0xE9B6C7AA); - P(A, B, C, D, 5, 5, 0xD62F105D); - P(D, A, B, C, 10, 9, 0x02441453); + P(B, C, D, A, 0, 20, 0xE9B6C7AA); + P(A, B, C, D, 5, 5, 0xD62F105D); + P(D, A, B, C, 10, 9, 0x02441453); P(C, D, A, B, 15, 14, 0xD8A1E681); - P(B, C, D, A, 4, 20, 0xE7D3FBC8); - P(A, B, C, D, 9, 5, 0x21E1CDE6); - P(D, A, B, C, 14, 9, 0xC33707D6); - P(C, D, A, B, 3, 14, 0xF4D50D87); - P(B, C, D, A, 8, 20, 0x455A14ED); - P(A, B, C, D, 13, 5, 0xA9E3E905); - P(D, A, B, C, 2, 9, 0xFCEFA3F8); - P(C, D, A, B, 7, 14, 0x676F02D9); + P(B, C, D, A, 4, 20, 0xE7D3FBC8); + P(A, B, C, D, 9, 5, 0x21E1CDE6); + P(D, A, B, C, 14, 9, 0xC33707D6); + P(C, D, A, B, 3, 14, 0xF4D50D87); + P(B, C, D, A, 8, 20, 0x455A14ED); + P(A, B, C, D, 13, 5, 0xA9E3E905); + P(D, A, B, C, 2, 9, 0xFCEFA3F8); + P(C, D, A, B, 7, 14, 0x676F02D9); P(B, C, D, A, 12, 20, 0x8D2A4C8A); #undef F -#define F(x,y,z) (x ^ y ^ z) +#define F(x, y, z) (x ^ y ^ z) - P(A, B, C, D, 5, 4, 0xFFFA3942); - P(D, A, B, C, 8, 11, 0x8771F681); + P(A, B, C, D, 5, 4, 0xFFFA3942); + P(D, A, B, C, 8, 11, 0x8771F681); P(C, D, A, B, 11, 16, 0x6D9D6122); P(B, C, D, A, 14, 23, 0xFDE5380C); - P(A, B, C, D, 1, 4, 0xA4BEEA44); - P(D, A, B, C, 4, 11, 0x4BDECFA9); - P(C, D, A, B, 7, 16, 0xF6BB4B60); + P(A, B, C, D, 1, 4, 0xA4BEEA44); + P(D, A, B, C, 4, 11, 0x4BDECFA9); + P(C, D, A, B, 7, 16, 0xF6BB4B60); P(B, C, D, A, 10, 23, 0xBEBFBC70); - P(A, B, C, D, 13, 4, 0x289B7EC6); - P(D, A, B, C, 0, 11, 0xEAA127FA); - P(C, D, A, B, 3, 16, 0xD4EF3085); - P(B, C, D, A, 6, 23, 0x04881D05); - P(A, B, C, D, 9, 4, 0xD9D4D039); + P(A, B, C, D, 13, 4, 0x289B7EC6); + P(D, A, B, C, 0, 11, 0xEAA127FA); + P(C, D, A, B, 3, 16, 0xD4EF3085); + P(B, C, D, A, 6, 23, 0x04881D05); + P(A, B, C, D, 9, 4, 0xD9D4D039); P(D, A, B, C, 12, 11, 0xE6DB99E5); P(C, D, A, B, 15, 16, 0x1FA27CF8); - P(B, C, D, A, 2, 23, 0xC4AC5665); + P(B, C, D, A, 2, 23, 0xC4AC5665); #undef F -#define F(x,y,z) (y ^ (x | ~z)) +#define F(x, y, z) (y ^ (x | ~z)) - P(A, B, C, D, 0, 6, 0xF4292244); - P(D, A, B, C, 7, 10, 0x432AFF97); + P(A, B, C, D, 0, 6, 0xF4292244); + P(D, A, B, C, 7, 10, 0x432AFF97); P(C, D, A, B, 14, 15, 0xAB9423A7); - P(B, C, D, A, 5, 21, 0xFC93A039); - P(A, B, C, D, 12, 6, 0x655B59C3); - P(D, A, B, C, 3, 10, 0x8F0CCC92); + P(B, C, D, A, 5, 21, 0xFC93A039); + P(A, B, C, D, 12, 6, 0x655B59C3); + P(D, A, B, C, 3, 10, 0x8F0CCC92); P(C, D, A, B, 10, 15, 0xFFEFF47D); - P(B, C, D, A, 1, 21, 0x85845DD1); - P(A, B, C, D, 8, 6, 0x6FA87E4F); + P(B, C, D, A, 1, 21, 0x85845DD1); + P(A, B, C, D, 8, 6, 0x6FA87E4F); P(D, A, B, C, 15, 10, 0xFE2CE6E0); - P(C, D, A, B, 6, 15, 0xA3014314); + P(C, D, A, B, 6, 15, 0xA3014314); P(B, C, D, A, 13, 21, 0x4E0811A1); - P(A, B, C, D, 4, 6, 0xF7537E82); + P(A, B, C, D, 4, 6, 0xF7537E82); P(D, A, B, C, 11, 10, 0xBD3AF235); - P(C, D, A, B, 2, 15, 0x2AD7D2BB); - P(B, C, D, A, 9, 21, 0xEB86D391); + P(C, D, A, B, 2, 15, 0x2AD7D2BB); + P(B, C, D, A, 9, 21, 0xEB86D391); #undef F @@ -180,7 +176,8 @@ void CMD5::md5_process(md5_context *ctx, const uint8 data[64]) const { ctx->state[3] += D; } -void CMD5::md5_update(md5_context *ctx, const uint8 *input, uint32 length) const { +void CMD5::md5_update(md5_context* ctx, const uint8* input, + uint32 length) const { uint32 left, fill; if (!length) return; @@ -191,47 +188,41 @@ void CMD5::md5_update(md5_context *ctx, const uint8 *input, uint32 length) const ctx->total[0] += length; ctx->total[0] &= 0xFFFFFFFF; - if (ctx->total[0] < length) - ctx->total[1]++; + if (ctx->total[0] < length) ctx->total[1]++; if (left && length >= fill) { - memcpy((void *) (ctx->buffer + left), - (void *) input, fill); + memcpy((void*)(ctx->buffer + left), (void*)input, fill); md5_process(ctx, ctx->buffer); length -= fill; - input += fill; + input += fill; left = 0; } while (length >= 64) { md5_process(ctx, input); length -= 64; - input += 64; + input += 64; } if (length) { - memcpy((void *) (ctx->buffer + left), - (void *) input, length); + memcpy((void*)(ctx->buffer + left), (void*)input, length); } } static const uint8 md5_padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -void CMD5::md5_finish(md5_context *ctx, uint8 digest[16]) const { +void CMD5::md5_finish(md5_context* ctx, uint8 digest[16]) const { uint32 last, padn; uint32 high, low; uint8 msglen[8]; - high = (ctx->total[0] >> 29) - | (ctx->total[1] << 3); - low = (ctx->total[0] << 3); + high = (ctx->total[0] >> 29) | (ctx->total[1] << 3); + low = (ctx->total[0] << 3); - PUT_UINT32(low, msglen, 0); + PUT_UINT32(low, msglen, 0); PUT_UINT32(high, msglen, 4); last = ctx->total[0] & 0x3F; @@ -240,9 +231,9 @@ void CMD5::md5_finish(md5_context *ctx, uint8 digest[16]) const { md5_update(ctx, md5_padding, padn); md5_update(ctx, msglen, 8); - PUT_UINT32(ctx->state[0], digest, 0); - PUT_UINT32(ctx->state[1], digest, 4); - PUT_UINT32(ctx->state[2], digest, 8); + PUT_UINT32(ctx->state[0], digest, 0); + PUT_UINT32(ctx->state[1], digest, 4); + PUT_UINT32(ctx->state[2], digest, 8); PUT_UINT32(ctx->state[3], digest, 12); } @@ -254,10 +245,11 @@ char* CMD5::MakeHash(const char* szText, uint32 nTextLen) { md5_update(&ctx, (uint8*)szText, nTextLen); md5_finish(&ctx, md5sum); - sprintf(m_szMD5, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - md5sum[0], md5sum[1], md5sum[2], md5sum[3], md5sum[4], md5sum[5], - md5sum[6], md5sum[7], md5sum[8], md5sum[9], md5sum[10], md5sum[11], - md5sum[12], md5sum[13], md5sum[14], md5sum[15]); + sprintf(m_szMD5, + "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + md5sum[0], md5sum[1], md5sum[2], md5sum[3], md5sum[4], md5sum[5], + md5sum[6], md5sum[7], md5sum[8], md5sum[9], md5sum[10], md5sum[11], + md5sum[12], md5sum[13], md5sum[14], md5sum[15]); return m_szMD5; } diff --git a/src/Message.cpp b/src/Message.cpp index b8e5410d..dac57564 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -17,40 +17,38 @@ #include #include -CMessage::CMessage(const CString& sMessage) -{ +CMessage::CMessage(const CString& sMessage) { Parse(sMessage); InitTime(); } -CMessage::CMessage(const CNick& Nick, const CString& sCommand, const VCString& vsParams, const MCString& mssTags) - : m_Nick(Nick), m_sCommand(sCommand), m_vsParams(vsParams), m_mssTags(mssTags) -{ +CMessage::CMessage(const CNick& Nick, const CString& sCommand, + const VCString& vsParams, const MCString& mssTags) + : m_Nick(Nick), + m_sCommand(sCommand), + m_vsParams(vsParams), + m_mssTags(mssTags) { InitTime(); } -bool CMessage::Equals(const CMessage& Other) const -{ +bool CMessage::Equals(const CMessage& Other) const { return m_Nick.NickEquals(Other.GetNick().GetNick()) && m_sCommand.Equals(Other.GetCommand()) && m_vsParams == Other.GetParams(); } -void CMessage::Clone(const CMessage& Message) -{ +void CMessage::Clone(const CMessage& Message) { if (&Message != this) { *this = Message; } } -void CMessage::SetCommand(const CString& sCommand) -{ +void CMessage::SetCommand(const CString& sCommand) { m_sCommand = sCommand; InitType(); } -CString CMessage::GetParams(unsigned int uIdx, unsigned int uLen) const -{ +CString CMessage::GetParams(unsigned int uIdx, unsigned int uLen) const { if (m_vsParams.empty() || uLen == 0) { return ""; } @@ -61,7 +59,9 @@ CString CMessage::GetParams(unsigned int uIdx, unsigned int uLen) const unsigned uParams = m_vsParams.size(); for (unsigned int i = uIdx; i < uIdx + uLen; ++i) { CString sParam = m_vsParams[i]; - if (i == uParams - 1 && (m_bColon || sParam.empty() || sParam.StartsWith(":") || sParam.Contains(" "))) { + if (i == uParams - 1 && + (m_bColon || sParam.empty() || sParam.StartsWith(":") || + sParam.Contains(" "))) { sParam = ":" + sParam; } vsParams.push_back(sParam); @@ -69,38 +69,36 @@ CString CMessage::GetParams(unsigned int uIdx, unsigned int uLen) const return CString(" ").Join(vsParams.begin(), vsParams.end()); } -void CMessage::SetParams(const VCString& vsParams) -{ +void CMessage::SetParams(const VCString& vsParams) { m_vsParams = vsParams; m_bColon = false; - if (m_eType == Type::Text || m_eType == Type::Notice || m_eType == Type::Action || m_eType == Type::CTCP) { + if (m_eType == Type::Text || m_eType == Type::Notice || + m_eType == Type::Action || m_eType == Type::CTCP) { InitType(); } } -CString CMessage::GetParam(unsigned int uIdx) const -{ +CString CMessage::GetParam(unsigned int uIdx) const { if (uIdx >= m_vsParams.size()) { return ""; } return m_vsParams[uIdx]; } -void CMessage::SetParam(unsigned int uIdx, const CString& sParam) -{ +void CMessage::SetParam(unsigned int uIdx, const CString& sParam) { if (uIdx >= m_vsParams.size()) { m_vsParams.resize(uIdx + 1); } m_vsParams[uIdx] = sParam; - if (uIdx == 1 && (m_eType == Type::Text || m_eType == Type::Notice || m_eType == Type::Action || m_eType == Type::CTCP)) { + if (uIdx == 1 && (m_eType == Type::Text || m_eType == Type::Notice || + m_eType == Type::Action || m_eType == Type::CTCP)) { InitType(); } } -CString CMessage::GetTag(const CString& sKey) const -{ +CString CMessage::GetTag(const CString& sKey) const { MCString::const_iterator it = m_mssTags.find(sKey); if (it != m_mssTags.end()) { return it->second; @@ -108,13 +106,11 @@ CString CMessage::GetTag(const CString& sKey) const return ""; } -void CMessage::SetTag(const CString& sKey, const CString& sValue) -{ +void CMessage::SetTag(const CString& sKey, const CString& sValue) { m_mssTags[sKey] = sValue; } -CString CMessage::ToString(unsigned int uFlags) const -{ +CString CMessage::ToString(unsigned int uFlags) const { CString sMessage; // @@ -161,8 +157,7 @@ CString CMessage::ToString(unsigned int uFlags) const return sMessage; } -void CMessage::Parse(CString sMessage) -{ +void CMessage::Parse(CString sMessage) { // m_mssTags.clear(); if (sMessage.StartsWith("@")) { @@ -171,7 +166,8 @@ void CMessage::Parse(CString sMessage) for (const CString& sTag : vsTags) { CString sKey = sTag.Token(0, false, "=", true); CString sValue = sTag.Token(1, true, "=", true); - m_mssTags[sKey] = sValue.Escape(CString::EMSGTAG, CString::CString::EASCII); + m_mssTags[sKey] = + sValue.Escape(CString::EMSGTAG, CString::CString::EASCII); } sMessage = sMessage.Token(1, true); } @@ -213,8 +209,7 @@ void CMessage::Parse(CString sMessage) InitType(); } -void CMessage::InitTime() -{ +void CMessage::InitTime() { auto it = m_mssTags.find("time"); if (it != m_mssTags.end()) { m_time = CUtils::ParseServerTime(it->second); @@ -236,9 +231,9 @@ void CMessage::InitTime() } } -void CMessage::InitType() -{ - if (m_sCommand.length() == 3 && isdigit(m_sCommand[0]) && isdigit(m_sCommand[1]) && isdigit(m_sCommand[2])) { +void CMessage::InitType() { + if (m_sCommand.length() == 3 && isdigit(m_sCommand[0]) && + isdigit(m_sCommand[1]) && isdigit(m_sCommand[2])) { m_eType = Type::Numeric; } else if (m_sCommand.Equals("PRIVMSG")) { CString sParam = GetParam(1); @@ -260,21 +255,21 @@ void CMessage::InitType() } } else { std::map mTypes = { - {"ACCOUNT", Type::Account}, - {"AWAY", Type::Away}, - {"CAP", Type::Capability}, - {"ERROR", Type::Error}, - {"INVITE", Type::Invite}, - {"JOIN", Type::Join}, - {"KICK", Type::Kick}, - {"MODE", Type::Mode}, - {"NICK", Type::Nick}, - {"PART", Type::Part}, - {"PING", Type::Ping}, - {"PONG", Type::Pong}, - {"QUIT", Type::Quit}, - {"TOPIC", Type::Topic}, - {"WALLOPS", Type::Wallops}, + {"ACCOUNT", Type::Account}, + {"AWAY", Type::Away}, + {"CAP", Type::Capability}, + {"ERROR", Type::Error}, + {"INVITE", Type::Invite}, + {"JOIN", Type::Join}, + {"KICK", Type::Kick}, + {"MODE", Type::Mode}, + {"NICK", Type::Nick}, + {"PART", Type::Part}, + {"PING", Type::Ping}, + {"PONG", Type::Pong}, + {"QUIT", Type::Quit}, + {"TOPIC", Type::Topic}, + {"WALLOPS", Type::Wallops}, }; auto it = mTypes.find(m_sCommand.AsUpper()); if (it != mTypes.end()) { diff --git a/src/Modules.cpp b/src/Modules.cpp index 2762934f..bcaf612d 100644 --- a/src/Modules.cpp +++ b/src/Modules.cpp @@ -30,80 +30,77 @@ using std::vector; bool ZNC_NO_NEED_TO_DO_ANYTHING_ON_MODULE_CALL_EXITER; #ifndef RTLD_LOCAL -# define RTLD_LOCAL 0 -# warning "your crap box doesnt define RTLD_LOCAL !?" +#define RTLD_LOCAL 0 +#warning "your crap box doesnt define RTLD_LOCAL !?" #endif -#define MODUNLOADCHK(func) \ - for (CModule* pMod : *this) { \ - try { \ - CClient* pOldClient = pMod->GetClient(); \ - pMod->SetClient(m_pClient); \ - CUser* pOldUser = nullptr; \ - if (m_pUser) { \ - pOldUser = pMod->GetUser(); \ - pMod->SetUser(m_pUser); \ - } \ - CIRCNetwork* pNetwork = nullptr; \ - if (m_pNetwork) { \ - pNetwork = pMod->GetNetwork(); \ - pMod->SetNetwork(m_pNetwork); \ - } \ - pMod->func; \ - if (m_pUser) \ - pMod->SetUser(pOldUser); \ - if (m_pNetwork) \ - pMod->SetNetwork(pNetwork); \ - pMod->SetClient(pOldClient); \ - } catch (const CModule::EModException& e) { \ - if (e == CModule::UNLOAD) { \ - UnloadModule(pMod->GetModName()); \ - } \ - } \ +#define MODUNLOADCHK(func) \ + for (CModule * pMod : *this) { \ + try { \ + CClient* pOldClient = pMod->GetClient(); \ + pMod->SetClient(m_pClient); \ + CUser* pOldUser = nullptr; \ + if (m_pUser) { \ + pOldUser = pMod->GetUser(); \ + pMod->SetUser(m_pUser); \ + } \ + CIRCNetwork* pNetwork = nullptr; \ + if (m_pNetwork) { \ + pNetwork = pMod->GetNetwork(); \ + pMod->SetNetwork(m_pNetwork); \ + } \ + pMod->func; \ + if (m_pUser) pMod->SetUser(pOldUser); \ + if (m_pNetwork) pMod->SetNetwork(pNetwork); \ + pMod->SetClient(pOldClient); \ + } catch (const CModule::EModException& e) { \ + if (e == CModule::UNLOAD) { \ + UnloadModule(pMod->GetModName()); \ + } \ + } \ } - -#define MODHALTCHK(func) \ - bool bHaltCore = false; \ - for (CModule* pMod : *this) { \ - try { \ - CModule::EModRet e = CModule::CONTINUE; \ - CClient* pOldClient = pMod->GetClient(); \ - pMod->SetClient(m_pClient); \ - CUser* pOldUser = nullptr; \ - if (m_pUser) { \ - pOldUser = pMod->GetUser(); \ - pMod->SetUser(m_pUser); \ - } \ - CIRCNetwork* pNetwork = nullptr; \ - if (m_pNetwork) { \ - pNetwork = pMod->GetNetwork(); \ - pMod->SetNetwork(m_pNetwork); \ - } \ - e = pMod->func; \ - if (m_pUser) \ - pMod->SetUser(pOldUser); \ - if (m_pNetwork) \ - pMod->SetNetwork(pNetwork); \ - pMod->SetClient(pOldClient); \ - if (e == CModule::HALTMODS) { \ - break; \ - } else if (e == CModule::HALTCORE) { \ - bHaltCore = true; \ - } else if (e == CModule::HALT) { \ - bHaltCore = true; \ - break; \ - } \ - } catch (const CModule::EModException& e) { \ - if (e == CModule::UNLOAD) { \ - UnloadModule(pMod->GetModName()); \ - } \ - } \ - } \ +#define MODHALTCHK(func) \ + bool bHaltCore = false; \ + for (CModule * pMod : *this) { \ + try { \ + CModule::EModRet e = CModule::CONTINUE; \ + CClient* pOldClient = pMod->GetClient(); \ + pMod->SetClient(m_pClient); \ + CUser* pOldUser = nullptr; \ + if (m_pUser) { \ + pOldUser = pMod->GetUser(); \ + pMod->SetUser(m_pUser); \ + } \ + CIRCNetwork* pNetwork = nullptr; \ + if (m_pNetwork) { \ + pNetwork = pMod->GetNetwork(); \ + pMod->SetNetwork(m_pNetwork); \ + } \ + e = pMod->func; \ + if (m_pUser) pMod->SetUser(pOldUser); \ + if (m_pNetwork) pMod->SetNetwork(pNetwork); \ + pMod->SetClient(pOldClient); \ + if (e == CModule::HALTMODS) { \ + break; \ + } else if (e == CModule::HALTCORE) { \ + bHaltCore = true; \ + } else if (e == CModule::HALT) { \ + bHaltCore = true; \ + break; \ + } \ + } catch (const CModule::EModException& e) { \ + if (e == CModule::UNLOAD) { \ + UnloadModule(pMod->GetModName()); \ + } \ + } \ + } \ return bHaltCore; /////////////////// Timer /////////////////// -CTimer::CTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CCron(), m_pModule(pModule), m_sDescription(sDescription) { +CTimer::CTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, + const CString& sLabel, const CString& sDescription) + : CCron(), m_pModule(pModule), m_sDescription(sDescription) { SetName(sLabel); if (uCycles) { @@ -113,9 +110,7 @@ CTimer::CTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, c } } -CTimer::~CTimer() { - m_pModule->UnlinkTimer(this); -} +CTimer::~CTimer() { m_pModule->UnlinkTimer(this); } void CTimer::SetModule(CModule* p) { m_pModule = p; } void CTimer::SetDescription(const CString& s) { m_sDescription = s; } @@ -123,29 +118,29 @@ CModule* CTimer::GetModule() const { return m_pModule; } const CString& CTimer::GetDescription() const { return m_sDescription; } /////////////////// !Timer /////////////////// - -CModule::CModule(ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, const CString& sModName, const CString& sDataDir, CModInfo::EModuleType eType) - : m_eType(eType), - m_sDescription(""), - m_sTimers(), - m_sSockets(), +CModule::CModule(ModHandle pDLL, CUser* pUser, CIRCNetwork* pNetwork, + const CString& sModName, const CString& sDataDir, + CModInfo::EModuleType eType) + : m_eType(eType), + m_sDescription(""), + m_sTimers(), + m_sSockets(), #ifdef HAVE_PTHREAD - m_sJobs(), + m_sJobs(), #endif - m_pDLL(pDLL), - m_pManager(&(CZNC::Get().GetManager())), - m_pUser(pUser), - m_pNetwork(pNetwork), - m_pClient(nullptr), - m_sModName(sModName), - m_sDataDir(sDataDir), - m_sSavePath(""), - m_sArgs(""), - m_sModPath(""), - m_mssRegistry(), - m_vSubPages(), - m_mCommands() -{ + m_pDLL(pDLL), + m_pManager(&(CZNC::Get().GetManager())), + m_pUser(pUser), + m_pNetwork(pNetwork), + m_pClient(nullptr), + m_sModName(sModName), + m_sDataDir(sDataDir), + m_sSavePath(""), + m_sArgs(""), + m_sModPath(""), + m_mssRegistry(), + m_vSubPages(), + m_mCommands() { if (m_pNetwork) { m_sSavePath = m_pNetwork->GetNetworkPath() + "/moddata/" + m_sModName; } else if (m_pUser) { @@ -204,30 +199,42 @@ const CString& CModule::GetSavePath() const { CString CModule::GetWebPath() { switch (m_eType) { - case CModInfo::GlobalModule: return "/mods/global/" + GetModName() + "/"; - case CModInfo::UserModule: return "/mods/user/" + GetModName() + "/"; - case CModInfo::NetworkModule: return "/mods/network/" + m_pNetwork->GetName() + "/" + GetModName() + "/"; - default: return "/"; + case CModInfo::GlobalModule: + return "/mods/global/" + GetModName() + "/"; + case CModInfo::UserModule: + return "/mods/user/" + GetModName() + "/"; + case CModInfo::NetworkModule: + return "/mods/network/" + m_pNetwork->GetName() + "/" + + GetModName() + "/"; + default: + return "/"; } } CString CModule::GetWebFilesPath() { switch (m_eType) { - case CModInfo::GlobalModule: return "/modfiles/global/" + GetModName() + "/"; - case CModInfo::UserModule: return "/modfiles/user/" + GetModName() + "/"; - case CModInfo::NetworkModule: return "/modfiles/network/" + m_pNetwork->GetName() + "/" + GetModName() + "/"; - default: return "/"; + case CModInfo::GlobalModule: + return "/modfiles/global/" + GetModName() + "/"; + case CModInfo::UserModule: + return "/modfiles/user/" + GetModName() + "/"; + case CModInfo::NetworkModule: + return "/modfiles/network/" + m_pNetwork->GetName() + "/" + + GetModName() + "/"; + default: + return "/"; } } bool CModule::LoadRegistry() { - //CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global"; - return (m_mssRegistry.ReadFromDisk(GetSavePath() + "/.registry") == MCString::MCS_SUCCESS); + // CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global"; + return (m_mssRegistry.ReadFromDisk(GetSavePath() + "/.registry") == + MCString::MCS_SUCCESS); } bool CModule::SaveRegistry() const { - //CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global"; - return (m_mssRegistry.WriteToDisk(GetSavePath() + "/.registry", 0600) == MCString::MCS_SUCCESS); + // CString sPrefix = (m_pUser) ? m_pUser->GetUserName() : ".global"; + return (m_mssRegistry.WriteToDisk(GetSavePath() + "/.registry", 0600) == + MCString::MCS_SUCCESS); } bool CModule::MoveRegistry(const CString& sPath) { @@ -246,7 +253,8 @@ bool CModule::MoveRegistry(const CString& sPath) { return false; } -bool CModule::SetNV(const CString & sName, const CString & sValue, bool bWriteToDisk) { +bool CModule::SetNV(const CString& sName, const CString& sValue, + bool bWriteToDisk) { m_mssRegistry[sName] = sValue; if (bWriteToDisk) { return SaveRegistry(); @@ -255,7 +263,7 @@ bool CModule::SetNV(const CString & sName, const CString & sValue, bool bWriteTo return true; } -CString CModule::GetNV(const CString & sName) const { +CString CModule::GetNV(const CString& sName) const { MCString::const_iterator it = m_mssRegistry.find(sName); if (it != m_mssRegistry.end()) { @@ -265,7 +273,7 @@ CString CModule::GetNV(const CString & sName) const { return ""; } -bool CModule::DelNV(const CString & sName, bool bWriteToDisk) { +bool CModule::DelNV(const CString& sName, bool bWriteToDisk) { MCString::iterator it = m_mssRegistry.find(sName); if (it != m_mssRegistry.end()) { @@ -291,7 +299,8 @@ bool CModule::ClearNV(bool bWriteToDisk) { } bool CModule::AddTimer(CTimer* pTimer) { - if ((!pTimer) || (!pTimer->GetName().empty() && FindTimer(pTimer->GetName()))) { + if ((!pTimer) || + (!pTimer->GetName().empty() && FindTimer(pTimer->GetName()))) { delete pTimer; return false; } @@ -304,30 +313,29 @@ bool CModule::AddTimer(CTimer* pTimer) { return true; } -bool CModule::AddTimer(FPTimer_t pFBCallback, const CString& sLabel, u_int uInterval, u_int uCycles, const CString& sDescription) { - CFPTimer *pTimer = new CFPTimer(this, uInterval, uCycles, sLabel, sDescription); +bool CModule::AddTimer(FPTimer_t pFBCallback, const CString& sLabel, + u_int uInterval, u_int uCycles, + const CString& sDescription) { + CFPTimer* pTimer = + new CFPTimer(this, uInterval, uCycles, sLabel, sDescription); pTimer->SetFPCallback(pFBCallback); return AddTimer(pTimer); } bool CModule::RemTimer(CTimer* pTimer) { - if (m_sTimers.erase(pTimer) == 0) - return false; + if (m_sTimers.erase(pTimer) == 0) return false; m_pManager->DelCronByAddr(pTimer); return true; } bool CModule::RemTimer(const CString& sLabel) { - CTimer *pTimer = FindTimer(sLabel); - if (!pTimer) - return false; + CTimer* pTimer = FindTimer(sLabel); + if (!pTimer) return false; return RemTimer(pTimer); } -bool CModule::UnlinkTimer(CTimer* pTimer) { - return m_sTimers.erase(pTimer); -} +bool CModule::UnlinkTimer(CTimer* pTimer) { return m_sTimers.erase(pTimer); } CTimer* CModule::FindTimer(const CString& sLabel) { if (sLabel.empty()) { @@ -361,7 +369,11 @@ void CModule::ListTimers() { Table.AddRow(); Table.SetCell("Name", pTimer->GetName()); - Table.SetCell("Secs", CString(Interval.tv_sec) + "seconds" + (Interval.tv_usec ? " " + CString(Interval.tv_usec) + " microseconds" : "")); + Table.SetCell( + "Secs", CString(Interval.tv_sec) + "seconds" + + (Interval.tv_usec + ? " " + CString(Interval.tv_usec) + " microseconds" + : "")); Table.SetCell("Cycles", ((uCycles) ? CString(uCycles) : "INF")); Table.SetCell("Description", pTimer->GetDescription()); } @@ -440,34 +452,29 @@ void CModule::ListSockets() { Table.SetCell("LocalPort", CString(pSocket->GetLocalPort())); Table.SetCell("SSL", (pSocket->GetSSL() ? "yes" : "no")); Table.SetCell("RemoteIP", pSocket->GetRemoteIP()); - Table.SetCell("RemotePort", (pSocket->GetRemotePort()) ? CString(pSocket->GetRemotePort()) : CString("")); + Table.SetCell("RemotePort", (pSocket->GetRemotePort()) + ? CString(pSocket->GetRemotePort()) + : CString("")); } PutModule(Table); } #ifdef HAVE_PTHREAD -CModuleJob::~CModuleJob() -{ - m_pModule->UnlinkJob(this); -} +CModuleJob::~CModuleJob() { m_pModule->UnlinkJob(this); } -void CModule::AddJob(CModuleJob *pJob) -{ +void CModule::AddJob(CModuleJob* pJob) { CThreadPool::Get().addJob(pJob); m_sJobs.insert(pJob); } -void CModule::CancelJob(CModuleJob *pJob) -{ - if (pJob == nullptr) - return; +void CModule::CancelJob(CModuleJob* pJob) { + if (pJob == nullptr) return; // Destructor calls UnlinkJob and removes the job from m_sJobs CThreadPool::Get().cancelJob(pJob); } -bool CModule::CancelJob(const CString& sJobName) -{ +bool CModule::CancelJob(const CString& sJobName) { for (CModuleJob* pJob : m_sJobs) { if (pJob->GetName().Equals(sJobName)) { CancelJob(pJob); @@ -477,59 +484,50 @@ bool CModule::CancelJob(const CString& sJobName) return false; } -void CModule::CancelJobs(const std::set& sJobs) -{ +void CModule::CancelJobs(const std::set& sJobs) { set sPlainJobs(sJobs.begin(), sJobs.end()); // Destructor calls UnlinkJob and removes the jobs from m_sJobs CThreadPool::Get().cancelJobs(sPlainJobs); } -bool CModule::UnlinkJob(CModuleJob *pJob) -{ - return 0 != m_sJobs.erase(pJob); -} +bool CModule::UnlinkJob(CModuleJob* pJob) { return 0 != m_sJobs.erase(pJob); } #endif -bool CModule::AddCommand(const CModCommand& Command) -{ - if (Command.GetFunction() == nullptr) - return false; - if (Command.GetCommand().Contains(" ")) - return false; - if (FindCommand(Command.GetCommand()) != nullptr) - return false; +bool CModule::AddCommand(const CModCommand& Command) { + if (Command.GetFunction() == nullptr) return false; + if (Command.GetCommand().Contains(" ")) return false; + if (FindCommand(Command.GetCommand()) != nullptr) return false; m_mCommands[Command.GetCommand()] = Command; return true; } -bool CModule::AddCommand(const CString& sCmd, CModCommand::ModCmdFunc func, const CString& sArgs, const CString& sDesc) -{ +bool CModule::AddCommand(const CString& sCmd, CModCommand::ModCmdFunc func, + const CString& sArgs, const CString& sDesc) { CModCommand cmd(sCmd, this, func, sArgs, sDesc); return AddCommand(cmd); } -bool CModule::AddCommand(const CString& sCmd, const CString& sArgs, const CString& sDesc, std::function func) { +bool CModule::AddCommand(const CString& sCmd, const CString& sArgs, + const CString& sDesc, + std::function func) { CModCommand cmd(sCmd, std::move(func), sArgs, sDesc); return AddCommand(std::move(cmd)); } -void CModule::AddHelpCommand() -{ - AddCommand("Help", &CModule::HandleHelpCommand, "search", "Generate this output"); +void CModule::AddHelpCommand() { + AddCommand("Help", &CModule::HandleHelpCommand, "search", + "Generate this output"); } -bool CModule::RemCommand(const CString& sCmd) -{ +bool CModule::RemCommand(const CString& sCmd) { return m_mCommands.erase(sCmd) > 0; } -const CModCommand* CModule::FindCommand(const CString& sCmd) const -{ +const CModCommand* CModule::FindCommand(const CString& sCmd) const { for (const auto& it : m_mCommands) { - if (!it.first.Equals(sCmd)) - continue; + if (!it.first.Equals(sCmd)) continue; return &it.second; } return nullptr; @@ -556,7 +554,9 @@ void CModule::HandleHelpCommand(const CString& sLine) { CModCommand::InitHelp(Table); for (const auto& it : m_mCommands) { CString sCmd = it.second.GetCommand().AsLower(); - if (sFilter.empty() || (sCmd.StartsWith(sFilter, CString::CaseSensitive)) || sCmd.WildCmp(sFilter)) { + if (sFilter.empty() || + (sCmd.StartsWith(sFilter, CString::CaseSensitive)) || + sCmd.WildCmp(sFilter)) { it.second.AddHelp(Table); } } @@ -567,66 +567,104 @@ void CModule::HandleHelpCommand(const CString& sLine) { } } -CString CModule::GetModNick() const { return ((m_pUser) ? m_pUser->GetStatusPrefix() : "*") + m_sModName; } +CString CModule::GetModNick() const { + return ((m_pUser) ? m_pUser->GetStatusPrefix() : "*") + m_sModName; +} // Webmods -bool CModule::OnWebPreRequest(CWebSock& WebSock, const CString& sPageName) { return false; } -bool CModule::OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { return false; } -bool CModule::OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { return false; } +bool CModule::OnWebPreRequest(CWebSock& WebSock, const CString& sPageName) { + return false; +} +bool CModule::OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) { + return false; +} +bool CModule::OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) { + return false; +} // !Webmods -bool CModule::OnLoad(const CString& sArgs, CString& sMessage) { sMessage = ""; return true; } +bool CModule::OnLoad(const CString& sArgs, CString& sMessage) { + sMessage = ""; + return true; +} bool CModule::OnBoot() { return true; } void CModule::OnPreRehash() {} void CModule::OnPostRehash() {} void CModule::OnIRCDisconnected() {} void CModule::OnIRCConnected() {} -CModule::EModRet CModule::OnIRCConnecting(CIRCSock *IRCSock) { return CONTINUE; } -void CModule::OnIRCConnectionError(CIRCSock *IRCSock) {} -CModule::EModRet CModule::OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName) { return CONTINUE; } +CModule::EModRet CModule::OnIRCConnecting(CIRCSock* IRCSock) { + return CONTINUE; +} +void CModule::OnIRCConnectionError(CIRCSock* IRCSock) {} +CModule::EModRet CModule::OnIRCRegistration(CString& sPass, CString& sNick, + CString& sIdent, + CString& sRealName) { + return CONTINUE; +} CModule::EModRet CModule::OnBroadcast(CString& sMessage) { return CONTINUE; } -void CModule::OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) { - if (pOpNick) OnChanPermission(*pOpNick, Nick, Channel, uMode, bAdded, bNoChange); +void CModule::OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, + bool bAdded, bool bNoChange) { + if (pOpNick) + OnChanPermission(*pOpNick, Nick, Channel, uMode, bAdded, bNoChange); } -void CModule::OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { +void CModule::OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { if (pOpNick) OnOp(*pOpNick, Nick, Channel, bNoChange); } -void CModule::OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { +void CModule::OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { if (pOpNick) OnDeop(*pOpNick, Nick, Channel, bNoChange); } -void CModule::OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { +void CModule::OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { if (pOpNick) OnVoice(*pOpNick, Nick, Channel, bNoChange); } -void CModule::OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { +void CModule::OnDevoice2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, bool bNoChange) { if (pOpNick) OnDevoice(*pOpNick, Nick, Channel, bNoChange); } -void CModule::OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) { +void CModule::OnRawMode2(const CNick* pOpNick, CChan& Channel, + const CString& sModes, const CString& sArgs) { if (pOpNick) OnRawMode(*pOpNick, Channel, sModes, sArgs); } -void CModule::OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) { +void CModule::OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) { if (pOpNick) OnMode(*pOpNick, Channel, uMode, sArg, bAdded, bNoChange); } -void CModule::OnChanPermission(const CNick& pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) {} -void CModule::OnOp(const CNick& pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) {} -void CModule::OnDeop(const CNick& pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) {} -void CModule::OnVoice(const CNick& pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) {} -void CModule::OnDevoice(const CNick& pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) {} -void CModule::OnRawMode(const CNick& pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) {} -void CModule::OnMode(const CNick& pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) {} +void CModule::OnChanPermission(const CNick& pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, bool bAdded, + bool bNoChange) {} +void CModule::OnOp(const CNick& pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) {} +void CModule::OnDeop(const CNick& pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) {} +void CModule::OnVoice(const CNick& pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) {} +void CModule::OnDevoice(const CNick& pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) {} +void CModule::OnRawMode(const CNick& pOpNick, CChan& Channel, + const CString& sModes, const CString& sArgs) {} +void CModule::OnMode(const CNick& pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) {} CModule::EModRet CModule::OnRaw(CString& sLine) { return CONTINUE; } CModule::EModRet CModule::OnRawMessage(CMessage& Message) { return CONTINUE; } -CModule::EModRet CModule::OnNumericMessage(CNumericMessage& Message) { return CONTINUE; } +CModule::EModRet CModule::OnNumericMessage(CNumericMessage& Message) { + return CONTINUE; +} -CModule::EModRet CModule::OnStatusCommand(CString& sCommand) { return CONTINUE; } +CModule::EModRet CModule::OnStatusCommand(CString& sCommand) { + return CONTINUE; +} void CModule::OnModNotice(const CString& sMessage) {} void CModule::OnModCTCP(const CString& sMessage) {} -void CModule::OnModCommand(const CString& sCommand) { - HandleCommand(sCommand); -} +void CModule::OnModCommand(const CString& sCommand) { HandleCommand(sCommand); } void CModule::OnUnknownModCommand(const CString& sLine) { if (m_mCommands.empty()) // This function is only called if OnModCommand wasn't @@ -637,35 +675,68 @@ void CModule::OnUnknownModCommand(const CString& sLine) { PutModule("Unknown command!"); } -void CModule::OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) {} -void CModule::OnQuitMessage(CQuitMessage& Message, const vector& vChans) { OnQuit(Message.GetNick(), Message.GetReason(), vChans); } -void CModule::OnNick(const CNick& Nick, const CString& sNewNick, const vector& vChans) {} -void CModule::OnNickMessage(CNickMessage& Message, const vector& vChans) { OnNick(Message.GetNick(), Message.GetNewNick(), vChans); } -void CModule::OnKick(const CNick& Nick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) {} -void CModule::OnKickMessage(CKickMessage& Message) { OnKick(Message.GetNick(), Message.GetKickedNick(), *Message.GetChan(), Message.GetReason()); } +void CModule::OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) {} +void CModule::OnQuitMessage(CQuitMessage& Message, + const vector& vChans) { + OnQuit(Message.GetNick(), Message.GetReason(), vChans); +} +void CModule::OnNick(const CNick& Nick, const CString& sNewNick, + const vector& vChans) {} +void CModule::OnNickMessage(CNickMessage& Message, + const vector& vChans) { + OnNick(Message.GetNick(), Message.GetNewNick(), vChans); +} +void CModule::OnKick(const CNick& Nick, const CString& sKickedNick, + CChan& Channel, const CString& sMessage) {} +void CModule::OnKickMessage(CKickMessage& Message) { + OnKick(Message.GetNick(), Message.GetKickedNick(), *Message.GetChan(), + Message.GetReason()); +} CModule::EModRet CModule::OnJoining(CChan& Channel) { return CONTINUE; } void CModule::OnJoin(const CNick& Nick, CChan& Channel) {} -void CModule::OnJoinMessage(CJoinMessage& Message) { OnJoin(Message.GetNick(), *Message.GetChan()); } -void CModule::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) {} -void CModule::OnPartMessage(CPartMessage& Message) { OnPart(Message.GetNick(), *Message.GetChan(), Message.GetReason()); } -CModule::EModRet CModule::OnInvite(const CNick& Nick, const CString& sChan) { return CONTINUE; } +void CModule::OnJoinMessage(CJoinMessage& Message) { + OnJoin(Message.GetNick(), *Message.GetChan()); +} +void CModule::OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) {} +void CModule::OnPartMessage(CPartMessage& Message) { + OnPart(Message.GetNick(), *Message.GetChan(), Message.GetReason()); +} +CModule::EModRet CModule::OnInvite(const CNick& Nick, const CString& sChan) { + return CONTINUE; +} -CModule::EModRet CModule::OnChanBufferStarting(CChan& Chan, CClient& Client) { return CONTINUE; } -CModule::EModRet CModule::OnChanBufferEnding(CChan& Chan, CClient& Client) { return CONTINUE; } -CModule::EModRet CModule::OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine) { return CONTINUE; } -CModule::EModRet CModule::OnPrivBufferPlayLine(CClient& Client, CString& sLine) { return CONTINUE; } +CModule::EModRet CModule::OnChanBufferStarting(CChan& Chan, CClient& Client) { + return CONTINUE; +} +CModule::EModRet CModule::OnChanBufferEnding(CChan& Chan, CClient& Client) { + return CONTINUE; +} +CModule::EModRet CModule::OnChanBufferPlayLine(CChan& Chan, CClient& Client, + CString& sLine) { + return CONTINUE; +} +CModule::EModRet CModule::OnPrivBufferPlayLine(CClient& Client, + CString& sLine) { + return CONTINUE; +} -CModule::EModRet CModule::OnChanBufferPlayLine2(CChan& Chan, CClient& Client, CString& sLine, const timeval& tv) { +CModule::EModRet CModule::OnChanBufferPlayLine2(CChan& Chan, CClient& Client, + CString& sLine, + const timeval& tv) { return OnChanBufferPlayLine(Chan, Client, sLine); } -CModule::EModRet CModule::OnPrivBufferPlayLine2(CClient& Client, CString& sLine, const timeval& tv) { +CModule::EModRet CModule::OnPrivBufferPlayLine2(CClient& Client, CString& sLine, + const timeval& tv) { return OnPrivBufferPlayLine(Client, sLine); } CModule::EModRet CModule::OnChanBufferPlayMessage(CMessage& Message) { CString sOriginal, sModified; sOriginal = sModified = Message.ToString(CMessage::ExcludeTags); - EModRet ret = OnChanBufferPlayLine2(*Message.GetChan(), *Message.GetClient(), sModified, Message.GetTime()); + EModRet ret = OnChanBufferPlayLine2( + *Message.GetChan(), *Message.GetClient(), sModified, Message.GetTime()); if (sOriginal != sModified) { Message.Parse(sModified); } @@ -674,7 +745,8 @@ CModule::EModRet CModule::OnChanBufferPlayMessage(CMessage& Message) { CModule::EModRet CModule::OnPrivBufferPlayMessage(CMessage& Message) { CString sOriginal, sModified; sOriginal = sModified = Message.ToString(CMessage::ExcludeTags); - EModRet ret = OnPrivBufferPlayLine2(*Message.GetClient(), sModified, Message.GetTime()); + EModRet ret = OnPrivBufferPlayLine2(*Message.GetClient(), sModified, + Message.GetTime()); if (sOriginal != sModified) { Message.Parse(sModified); } @@ -684,8 +756,12 @@ CModule::EModRet CModule::OnPrivBufferPlayMessage(CMessage& Message) { void CModule::OnClientLogin() {} void CModule::OnClientDisconnect() {} CModule::EModRet CModule::OnUserRaw(CString& sLine) { return CONTINUE; } -CModule::EModRet CModule::OnUserRawMessage(CMessage& Message) { return CONTINUE; } -CModule::EModRet CModule::OnUserCTCPReply(CString& sTarget, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserRawMessage(CMessage& Message) { + return CONTINUE; +} +CModule::EModRet CModule::OnUserCTCPReply(CString& sTarget, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserCTCPReplyMessage(CCTCPMessage& Message) { CString sTarget = Message.GetTarget(); CString sText = Message.GetText(); @@ -694,7 +770,9 @@ CModule::EModRet CModule::OnUserCTCPReplyMessage(CCTCPMessage& Message) { Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnUserCTCP(CString& sTarget, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserCTCP(CString& sTarget, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserCTCPMessage(CCTCPMessage& Message) { CString sTarget = Message.GetTarget(); CString sText = Message.GetText(); @@ -703,7 +781,9 @@ CModule::EModRet CModule::OnUserCTCPMessage(CCTCPMessage& Message) { Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnUserAction(CString& sTarget, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserAction(CString& sTarget, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserActionMessage(CActionMessage& Message) { CString sTarget = Message.GetTarget(); CString sText = Message.GetText(); @@ -712,7 +792,9 @@ CModule::EModRet CModule::OnUserActionMessage(CActionMessage& Message) { Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnUserMsg(CString& sTarget, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserMsg(CString& sTarget, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserTextMessage(CTextMessage& Message) { CString sTarget = Message.GetTarget(); CString sText = Message.GetText(); @@ -721,7 +803,9 @@ CModule::EModRet CModule::OnUserTextMessage(CTextMessage& Message) { Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnUserNotice(CString& sTarget, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserNotice(CString& sTarget, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserNoticeMessage(CNoticeMessage& Message) { CString sTarget = Message.GetTarget(); CString sText = Message.GetText(); @@ -730,7 +814,9 @@ CModule::EModRet CModule::OnUserNoticeMessage(CNoticeMessage& Message) { Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnUserJoin(CString& sChannel, CString& sKey) { return CONTINUE; } +CModule::EModRet CModule::OnUserJoin(CString& sChannel, CString& sKey) { + return CONTINUE; +} CModule::EModRet CModule::OnUserJoinMessage(CJoinMessage& Message) { CString sChan = Message.GetTarget(); CString sKey = Message.GetKey(); @@ -739,7 +825,9 @@ CModule::EModRet CModule::OnUserJoinMessage(CJoinMessage& Message) { Message.SetKey(sKey); return ret; } -CModule::EModRet CModule::OnUserPart(CString& sChannel, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnUserPart(CString& sChannel, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnUserPartMessage(CPartMessage& Message) { CString sChan = Message.GetTarget(); CString sReason = Message.GetReason(); @@ -748,7 +836,9 @@ CModule::EModRet CModule::OnUserPartMessage(CPartMessage& Message) { Message.SetReason(sReason); return ret; } -CModule::EModRet CModule::OnUserTopic(CString& sChannel, CString& sTopic) { return CONTINUE; } +CModule::EModRet CModule::OnUserTopic(CString& sChannel, CString& sTopic) { + return CONTINUE; +} CModule::EModRet CModule::OnUserTopicMessage(CTopicMessage& Message) { CString sChan = Message.GetTarget(); CString sTopic = Message.GetTopic(); @@ -757,7 +847,9 @@ CModule::EModRet CModule::OnUserTopicMessage(CTopicMessage& Message) { Message.SetTopic(sTopic); return ret; } -CModule::EModRet CModule::OnUserTopicRequest(CString& sChannel) { return CONTINUE; } +CModule::EModRet CModule::OnUserTopicRequest(CString& sChannel) { + return CONTINUE; +} CModule::EModRet CModule::OnUserQuit(CString& sMessage) { return CONTINUE; } CModule::EModRet CModule::OnUserQuitMessage(CQuitMessage& Message) { CString sReason = Message.GetReason(); @@ -766,70 +858,95 @@ CModule::EModRet CModule::OnUserQuitMessage(CQuitMessage& Message) { return ret; } -CModule::EModRet CModule::OnCTCPReply(CNick& Nick, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnCTCPReply(CNick& Nick, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnCTCPReplyMessage(CCTCPMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnCTCPReply(Message.GetNick(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnPrivCTCP(CNick& Nick, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnPrivCTCP(CNick& Nick, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnPrivCTCPMessage(CCTCPMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnPrivCTCP(Message.GetNick(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnChanCTCPMessage(CCTCPMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnChanCTCP(Message.GetNick(), *Message.GetChan(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnPrivAction(CNick& Nick, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnPrivAction(CNick& Nick, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnPrivActionMessage(CActionMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnPrivAction(Message.GetNick(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnChanActionMessage(CActionMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnChanAction(Message.GetNick(), *Message.GetChan(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnPrivMsg(CNick& Nick, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnPrivMsg(CNick& Nick, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnPrivMessage(CTextMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnPrivMsg(Message.GetNick(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnChanMsg(CNick& Nick, CChan& Channel, + CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnChanMessage(CTextMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnChanMsg(Message.GetNick(), *Message.GetChan(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnPrivNotice(CNick& Nick, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnPrivNotice(CNick& Nick, CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnPrivNoticeMessage(CNoticeMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnPrivNotice(Message.GetNick(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { return CONTINUE; } +CModule::EModRet CModule::OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) { + return CONTINUE; +} CModule::EModRet CModule::OnChanNoticeMessage(CNoticeMessage& Message) { CString sText = Message.GetText(); EModRet ret = OnChanNotice(Message.GetNick(), *Message.GetChan(), sText); Message.SetText(sText); return ret; } -CModule::EModRet CModule::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) { return CONTINUE; } +CModule::EModRet CModule::OnTopic(CNick& Nick, CChan& Channel, + CString& sTopic) { + return CONTINUE; +} CModule::EModRet CModule::OnTopicMessage(CTopicMessage& Message) { CString sTopic = Message.GetTopic(); EModRet ret = OnTopic(Message.GetNick(), *Message.GetChan(), sTopic); @@ -837,10 +954,17 @@ CModule::EModRet CModule::OnTopicMessage(CTopicMessage& Message) { return ret; } CModule::EModRet CModule::OnTimerAutoJoin(CChan& Channel) { return CONTINUE; } -CModule::EModRet CModule::OnAddNetwork(CIRCNetwork& Network, CString& sErrorRet) { return CONTINUE; } -CModule::EModRet CModule::OnDeleteNetwork(CIRCNetwork& Network) { return CONTINUE; } +CModule::EModRet CModule::OnAddNetwork(CIRCNetwork& Network, + CString& sErrorRet) { + return CONTINUE; +} +CModule::EModRet CModule::OnDeleteNetwork(CIRCNetwork& Network) { + return CONTINUE; +} -CModule::EModRet CModule::OnSendToClient(CString& sLine, CClient& Client) { return CONTINUE; } +CModule::EModRet CModule::OnSendToClient(CString& sLine, CClient& Client) { + return CONTINUE; +} CModule::EModRet CModule::OnSendToIRC(CString& sLine) { return CONTINUE; } bool CModule::OnServerCapAvailable(const CString& sCap) { return false; } @@ -856,13 +980,11 @@ bool CModule::PutStatus(const CString& sLine) { return (m_pNetwork) ? m_pNetwork->PutStatus(sLine, m_pClient) : false; } unsigned int CModule::PutModule(const CTable& table) { - if (!m_pUser) - return 0; + if (!m_pUser) return 0; unsigned int idx = 0; CString sLine; - while (table.GetLine(idx++, sLine)) - PutModule(sLine); + while (table.GetLine(idx++, sLine)) PutModule(sLine); return idx - 1; } bool CModule::PutModule(const CString& sLine) { @@ -882,8 +1004,7 @@ bool CModule::PutModule(const CString& sLine) { return false; } bool CModule::PutModNotice(const CString& sLine) { - if (!m_pUser) - return false; + if (!m_pUser) return false; if (m_pClient) { m_pClient->PutModNotice(GetModName(), sLine); @@ -896,32 +1017,52 @@ bool CModule::PutModNotice(const CString& sLine) { /////////////////// // Global Module // /////////////////// -CModule::EModRet CModule::OnAddUser(CUser& User, CString& sErrorRet) { return CONTINUE; } -CModule::EModRet CModule::OnDeleteUser(CUser& User) { return CONTINUE; } -void CModule::OnClientConnect(CZNCSock* pClient, const CString& sHost, unsigned short uPort) {} -CModule::EModRet CModule::OnLoginAttempt(std::shared_ptr Auth) { return CONTINUE; } -void CModule::OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) {} -CModule::EModRet CModule::OnUnknownUserRaw(CClient* pClient, CString& sLine) { return CONTINUE; } -CModule::EModRet CModule::OnUnknownUserRawMessage(CMessage& Message) { return CONTINUE; } -void CModule::OnClientCapLs(CClient* pClient, SCString& ssCaps) {} -bool CModule::IsClientCapSupported(CClient* pClient, const CString& sCap, bool bState) { return false; } -void CModule::OnClientCapRequest(CClient* pClient, const CString& sCap, bool bState) {} -CModule::EModRet CModule::OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg) { return CONTINUE; } -CModule::EModRet CModule::OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg) { +CModule::EModRet CModule::OnAddUser(CUser& User, CString& sErrorRet) { return CONTINUE; } -CModule::EModRet CModule::OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg) { return CONTINUE; } -void CModule::OnGetAvailableMods(set& ssMods, CModInfo::EModuleType eType) {} - - -CModules::CModules() : m_pUser(nullptr), m_pNetwork(nullptr), m_pClient(nullptr) { +CModule::EModRet CModule::OnDeleteUser(CUser& User) { return CONTINUE; } +void CModule::OnClientConnect(CZNCSock* pClient, const CString& sHost, + unsigned short uPort) {} +CModule::EModRet CModule::OnLoginAttempt(std::shared_ptr Auth) { + return CONTINUE; } - -CModules::~CModules() { - UnloadAll(); +void CModule::OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP) {} +CModule::EModRet CModule::OnUnknownUserRaw(CClient* pClient, CString& sLine) { + return CONTINUE; } +CModule::EModRet CModule::OnUnknownUserRawMessage(CMessage& Message) { + return CONTINUE; +} +void CModule::OnClientCapLs(CClient* pClient, SCString& ssCaps) {} +bool CModule::IsClientCapSupported(CClient* pClient, const CString& sCap, + bool bState) { + return false; +} +void CModule::OnClientCapRequest(CClient* pClient, const CString& sCap, + bool bState) {} +CModule::EModRet CModule::OnModuleLoading(const CString& sModName, + const CString& sArgs, + CModInfo::EModuleType eType, + bool& bSuccess, CString& sRetMsg) { + return CONTINUE; +} +CModule::EModRet CModule::OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg) { + return CONTINUE; +} +CModule::EModRet CModule::OnGetModInfo(CModInfo& ModInfo, + const CString& sModule, bool& bSuccess, + CString& sRetMsg) { + return CONTINUE; +} +void CModule::OnGetAvailableMods(set& ssMods, + CModInfo::EModuleType eType) {} + +CModules::CModules() + : m_pUser(nullptr), m_pNetwork(nullptr), m_pClient(nullptr) {} + +CModules::~CModules() { UnloadAll(); } void CModules::UnloadAll() { while (size()) { @@ -947,106 +1088,354 @@ bool CModules::OnBoot() { return false; } -bool CModules::OnPreRehash() { MODUNLOADCHK(OnPreRehash()); return false; } -bool CModules::OnPostRehash() { MODUNLOADCHK(OnPostRehash()); return false; } -bool CModules::OnIRCConnected() { MODUNLOADCHK(OnIRCConnected()); return false; } -bool CModules::OnIRCConnecting(CIRCSock *pIRCSock) { MODHALTCHK(OnIRCConnecting(pIRCSock)); } -bool CModules::OnIRCConnectionError(CIRCSock *pIRCSock) { MODUNLOADCHK(OnIRCConnectionError(pIRCSock)); return false; } -bool CModules::OnIRCRegistration(CString& sPass, CString& sNick, CString& sIdent, CString& sRealName) { MODHALTCHK(OnIRCRegistration(sPass, sNick, sIdent, sRealName)); } -bool CModules::OnBroadcast(CString& sMessage) { MODHALTCHK(OnBroadcast(sMessage)); } -bool CModules::OnIRCDisconnected() { MODUNLOADCHK(OnIRCDisconnected()); return false; } +bool CModules::OnPreRehash() { + MODUNLOADCHK(OnPreRehash()); + return false; +} +bool CModules::OnPostRehash() { + MODUNLOADCHK(OnPostRehash()); + return false; +} +bool CModules::OnIRCConnected() { + MODUNLOADCHK(OnIRCConnected()); + return false; +} +bool CModules::OnIRCConnecting(CIRCSock* pIRCSock) { + MODHALTCHK(OnIRCConnecting(pIRCSock)); +} +bool CModules::OnIRCConnectionError(CIRCSock* pIRCSock) { + MODUNLOADCHK(OnIRCConnectionError(pIRCSock)); + return false; +} +bool CModules::OnIRCRegistration(CString& sPass, CString& sNick, + CString& sIdent, CString& sRealName) { + MODHALTCHK(OnIRCRegistration(sPass, sNick, sIdent, sRealName)); +} +bool CModules::OnBroadcast(CString& sMessage) { + MODHALTCHK(OnBroadcast(sMessage)); +} +bool CModules::OnIRCDisconnected() { + MODUNLOADCHK(OnIRCDisconnected()); + return false; +} -bool CModules::OnChanPermission2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) { MODUNLOADCHK(OnChanPermission2(pOpNick, Nick, Channel, uMode, bAdded, bNoChange)); return false; } -bool CModules::OnChanPermission(const CNick& OpNick, const CNick& Nick, CChan& Channel, unsigned char uMode, bool bAdded, bool bNoChange) { MODUNLOADCHK(OnChanPermission(OpNick, Nick, Channel, uMode, bAdded, bNoChange)); return false; } -bool CModules::OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnOp2(pOpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnOp(OpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnDeop2(pOpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnDeop(OpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnVoice2(pOpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnVoice(OpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnDevoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnDevoice2(pOpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, bool bNoChange) { MODUNLOADCHK(OnDevoice(OpNick, Nick, Channel, bNoChange)); return false; } -bool CModules::OnRawMode2(const CNick* pOpNick, CChan& Channel, const CString& sModes, const CString& sArgs) { MODUNLOADCHK(OnRawMode2(pOpNick, Channel, sModes, sArgs)); return false; } -bool CModules::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs) { MODUNLOADCHK(OnRawMode(OpNick, Channel, sModes, sArgs)); return false; } -bool CModules::OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) { MODUNLOADCHK(OnMode2(pOpNick, Channel, uMode, sArg, bAdded, bNoChange)); return false; } -bool CModules::OnMode(const CNick& OpNick, CChan& Channel, char uMode, const CString& sArg, bool bAdded, bool bNoChange) { MODUNLOADCHK(OnMode(OpNick, Channel, uMode, sArg, bAdded, bNoChange)); return false; } +bool CModules::OnChanPermission2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, + bool bAdded, bool bNoChange) { + MODUNLOADCHK( + OnChanPermission2(pOpNick, Nick, Channel, uMode, bAdded, bNoChange)); + return false; +} +bool CModules::OnChanPermission(const CNick& OpNick, const CNick& Nick, + CChan& Channel, unsigned char uMode, + bool bAdded, bool bNoChange) { + MODUNLOADCHK( + OnChanPermission(OpNick, Nick, Channel, uMode, bAdded, bNoChange)); + return false; +} +bool CModules::OnOp2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnOp2(pOpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnOp(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnOp(OpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnDeop2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnDeop2(pOpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnDeop(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnDeop(OpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnVoice2(const CNick* pOpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnVoice2(pOpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnVoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnVoice(OpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnDevoice2(const CNick* pOpNick, const CNick& Nick, + CChan& Channel, bool bNoChange) { + MODUNLOADCHK(OnDevoice2(pOpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnDevoice(const CNick& OpNick, const CNick& Nick, CChan& Channel, + bool bNoChange) { + MODUNLOADCHK(OnDevoice(OpNick, Nick, Channel, bNoChange)); + return false; +} +bool CModules::OnRawMode2(const CNick* pOpNick, CChan& Channel, + const CString& sModes, const CString& sArgs) { + MODUNLOADCHK(OnRawMode2(pOpNick, Channel, sModes, sArgs)); + return false; +} +bool CModules::OnRawMode(const CNick& OpNick, CChan& Channel, + const CString& sModes, const CString& sArgs) { + MODUNLOADCHK(OnRawMode(OpNick, Channel, sModes, sArgs)); + return false; +} +bool CModules::OnMode2(const CNick* pOpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) { + MODUNLOADCHK(OnMode2(pOpNick, Channel, uMode, sArg, bAdded, bNoChange)); + return false; +} +bool CModules::OnMode(const CNick& OpNick, CChan& Channel, char uMode, + const CString& sArg, bool bAdded, bool bNoChange) { + MODUNLOADCHK(OnMode(OpNick, Channel, uMode, sArg, bAdded, bNoChange)); + return false; +} bool CModules::OnRaw(CString& sLine) { MODHALTCHK(OnRaw(sLine)); } -bool CModules::OnRawMessage(CMessage& Message) { MODHALTCHK(OnRawMessage(Message)); } -bool CModules::OnNumericMessage(CNumericMessage& Message) { MODHALTCHK(OnNumericMessage(Message)); } +bool CModules::OnRawMessage(CMessage& Message) { + MODHALTCHK(OnRawMessage(Message)); +} +bool CModules::OnNumericMessage(CNumericMessage& Message) { + MODHALTCHK(OnNumericMessage(Message)); +} -bool CModules::OnClientLogin() { MODUNLOADCHK(OnClientLogin()); return false; } -bool CModules::OnClientDisconnect() { MODUNLOADCHK(OnClientDisconnect()); return false; } +bool CModules::OnClientLogin() { + MODUNLOADCHK(OnClientLogin()); + return false; +} +bool CModules::OnClientDisconnect() { + MODUNLOADCHK(OnClientDisconnect()); + return false; +} bool CModules::OnUserRaw(CString& sLine) { MODHALTCHK(OnUserRaw(sLine)); } -bool CModules::OnUserRawMessage(CMessage& Message) { MODHALTCHK(OnUserRawMessage(Message)); } -bool CModules::OnUserCTCPReply(CString& sTarget, CString& sMessage) { MODHALTCHK(OnUserCTCPReply(sTarget, sMessage)); } -bool CModules::OnUserCTCPReplyMessage(CCTCPMessage& Message) { MODHALTCHK(OnUserCTCPReplyMessage(Message)); } -bool CModules::OnUserCTCP(CString& sTarget, CString& sMessage) { MODHALTCHK(OnUserCTCP(sTarget, sMessage)); } -bool CModules::OnUserCTCPMessage(CCTCPMessage& Message) { MODHALTCHK(OnUserCTCPMessage(Message)); } -bool CModules::OnUserAction(CString& sTarget, CString& sMessage) { MODHALTCHK(OnUserAction(sTarget, sMessage)); } -bool CModules::OnUserActionMessage(CActionMessage& Message) { MODHALTCHK(OnUserActionMessage(Message)); } -bool CModules::OnUserMsg(CString& sTarget, CString& sMessage) { MODHALTCHK(OnUserMsg(sTarget, sMessage)); } -bool CModules::OnUserTextMessage(CTextMessage& Message) { MODHALTCHK(OnUserTextMessage(Message)); } -bool CModules::OnUserNotice(CString& sTarget, CString& sMessage) { MODHALTCHK(OnUserNotice(sTarget, sMessage)); } -bool CModules::OnUserNoticeMessage(CNoticeMessage& Message) { MODHALTCHK(OnUserNoticeMessage(Message)); } -bool CModules::OnUserJoin(CString& sChannel, CString& sKey) { MODHALTCHK(OnUserJoin(sChannel, sKey)); } -bool CModules::OnUserJoinMessage(CJoinMessage& Message) { MODHALTCHK(OnUserJoinMessage(Message)); } -bool CModules::OnUserPart(CString& sChannel, CString& sMessage) { MODHALTCHK(OnUserPart(sChannel, sMessage)); } -bool CModules::OnUserPartMessage(CPartMessage& Message) { MODHALTCHK(OnUserPartMessage(Message)); } -bool CModules::OnUserTopic(CString& sChannel, CString& sTopic) { MODHALTCHK(OnUserTopic(sChannel, sTopic)); } -bool CModules::OnUserTopicMessage(CTopicMessage& Message) { MODHALTCHK(OnUserTopicMessage(Message)); } -bool CModules::OnUserTopicRequest(CString& sChannel) { MODHALTCHK(OnUserTopicRequest(sChannel)); } -bool CModules::OnUserQuit(CString& sMessage) { MODHALTCHK(OnUserQuit(sMessage)); } -bool CModules::OnUserQuitMessage(CQuitMessage& Message) { MODHALTCHK(OnUserQuitMessage(Message)); } +bool CModules::OnUserRawMessage(CMessage& Message) { + MODHALTCHK(OnUserRawMessage(Message)); +} +bool CModules::OnUserCTCPReply(CString& sTarget, CString& sMessage) { + MODHALTCHK(OnUserCTCPReply(sTarget, sMessage)); +} +bool CModules::OnUserCTCPReplyMessage(CCTCPMessage& Message) { + MODHALTCHK(OnUserCTCPReplyMessage(Message)); +} +bool CModules::OnUserCTCP(CString& sTarget, CString& sMessage) { + MODHALTCHK(OnUserCTCP(sTarget, sMessage)); +} +bool CModules::OnUserCTCPMessage(CCTCPMessage& Message) { + MODHALTCHK(OnUserCTCPMessage(Message)); +} +bool CModules::OnUserAction(CString& sTarget, CString& sMessage) { + MODHALTCHK(OnUserAction(sTarget, sMessage)); +} +bool CModules::OnUserActionMessage(CActionMessage& Message) { + MODHALTCHK(OnUserActionMessage(Message)); +} +bool CModules::OnUserMsg(CString& sTarget, CString& sMessage) { + MODHALTCHK(OnUserMsg(sTarget, sMessage)); +} +bool CModules::OnUserTextMessage(CTextMessage& Message) { + MODHALTCHK(OnUserTextMessage(Message)); +} +bool CModules::OnUserNotice(CString& sTarget, CString& sMessage) { + MODHALTCHK(OnUserNotice(sTarget, sMessage)); +} +bool CModules::OnUserNoticeMessage(CNoticeMessage& Message) { + MODHALTCHK(OnUserNoticeMessage(Message)); +} +bool CModules::OnUserJoin(CString& sChannel, CString& sKey) { + MODHALTCHK(OnUserJoin(sChannel, sKey)); +} +bool CModules::OnUserJoinMessage(CJoinMessage& Message) { + MODHALTCHK(OnUserJoinMessage(Message)); +} +bool CModules::OnUserPart(CString& sChannel, CString& sMessage) { + MODHALTCHK(OnUserPart(sChannel, sMessage)); +} +bool CModules::OnUserPartMessage(CPartMessage& Message) { + MODHALTCHK(OnUserPartMessage(Message)); +} +bool CModules::OnUserTopic(CString& sChannel, CString& sTopic) { + MODHALTCHK(OnUserTopic(sChannel, sTopic)); +} +bool CModules::OnUserTopicMessage(CTopicMessage& Message) { + MODHALTCHK(OnUserTopicMessage(Message)); +} +bool CModules::OnUserTopicRequest(CString& sChannel) { + MODHALTCHK(OnUserTopicRequest(sChannel)); +} +bool CModules::OnUserQuit(CString& sMessage) { + MODHALTCHK(OnUserQuit(sMessage)); +} +bool CModules::OnUserQuitMessage(CQuitMessage& Message) { + MODHALTCHK(OnUserQuitMessage(Message)); +} -bool CModules::OnQuit(const CNick& Nick, const CString& sMessage, const vector& vChans) { MODUNLOADCHK(OnQuit(Nick, sMessage, vChans)); return false; } -bool CModules::OnQuitMessage(CQuitMessage& Message, const vector& vChans) { MODUNLOADCHK(OnQuitMessage(Message, vChans)); return false; } -bool CModules::OnNick(const CNick& Nick, const CString& sNewNick, const vector& vChans) { MODUNLOADCHK(OnNick(Nick, sNewNick, vChans)); return false; } -bool CModules::OnNickMessage(CNickMessage& Message, const vector& vChans) { MODUNLOADCHK(OnNickMessage(Message, vChans)); return false; } -bool CModules::OnKick(const CNick& Nick, const CString& sKickedNick, CChan& Channel, const CString& sMessage) { MODUNLOADCHK(OnKick(Nick, sKickedNick, Channel, sMessage)); return false; } -bool CModules::OnKickMessage(CKickMessage& Message) { MODUNLOADCHK(OnKickMessage(Message)); return false; } +bool CModules::OnQuit(const CNick& Nick, const CString& sMessage, + const vector& vChans) { + MODUNLOADCHK(OnQuit(Nick, sMessage, vChans)); + return false; +} +bool CModules::OnQuitMessage(CQuitMessage& Message, + const vector& vChans) { + MODUNLOADCHK(OnQuitMessage(Message, vChans)); + return false; +} +bool CModules::OnNick(const CNick& Nick, const CString& sNewNick, + const vector& vChans) { + MODUNLOADCHK(OnNick(Nick, sNewNick, vChans)); + return false; +} +bool CModules::OnNickMessage(CNickMessage& Message, + const vector& vChans) { + MODUNLOADCHK(OnNickMessage(Message, vChans)); + return false; +} +bool CModules::OnKick(const CNick& Nick, const CString& sKickedNick, + CChan& Channel, const CString& sMessage) { + MODUNLOADCHK(OnKick(Nick, sKickedNick, Channel, sMessage)); + return false; +} +bool CModules::OnKickMessage(CKickMessage& Message) { + MODUNLOADCHK(OnKickMessage(Message)); + return false; +} bool CModules::OnJoining(CChan& Channel) { MODHALTCHK(OnJoining(Channel)); } -bool CModules::OnJoin(const CNick& Nick, CChan& Channel) { MODUNLOADCHK(OnJoin(Nick, Channel)); return false; } -bool CModules::OnJoinMessage(CJoinMessage& Message) { MODUNLOADCHK(OnJoinMessage(Message)); return false; } -bool CModules::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage) { MODUNLOADCHK(OnPart(Nick, Channel, sMessage)); return false; } -bool CModules::OnPartMessage(CPartMessage& Message) { MODUNLOADCHK(OnPartMessage(Message)); return false; } -bool CModules::OnInvite(const CNick& Nick, const CString& sChan) { MODHALTCHK(OnInvite(Nick, sChan)); } -bool CModules::OnChanBufferStarting(CChan& Chan, CClient& Client) { MODHALTCHK(OnChanBufferStarting(Chan, Client)); } -bool CModules::OnChanBufferEnding(CChan& Chan, CClient& Client) { MODHALTCHK(OnChanBufferEnding(Chan, Client)); } -bool CModules::OnChanBufferPlayLine2(CChan& Chan, CClient& Client, CString& sLine, const timeval& tv) { MODHALTCHK(OnChanBufferPlayLine2(Chan, Client, sLine, tv)); } -bool CModules::OnChanBufferPlayLine(CChan& Chan, CClient& Client, CString& sLine) { MODHALTCHK(OnChanBufferPlayLine(Chan, Client, sLine)); } -bool CModules::OnPrivBufferPlayLine2(CClient& Client, CString& sLine, const timeval& tv) { MODHALTCHK(OnPrivBufferPlayLine2(Client, sLine, tv)); } -bool CModules::OnPrivBufferPlayLine(CClient& Client, CString& sLine) { MODHALTCHK(OnPrivBufferPlayLine(Client, sLine)); } -bool CModules::OnChanBufferPlayMessage(CMessage& Message) { MODHALTCHK(OnChanBufferPlayMessage(Message)); } -bool CModules::OnPrivBufferPlayMessage(CMessage& Message) { MODHALTCHK(OnPrivBufferPlayMessage(Message)); } -bool CModules::OnCTCPReply(CNick& Nick, CString& sMessage) { MODHALTCHK(OnCTCPReply(Nick, sMessage)); } -bool CModules::OnCTCPReplyMessage(CCTCPMessage& Message) { MODHALTCHK(OnCTCPReplyMessage(Message)); } -bool CModules::OnPrivCTCP(CNick& Nick, CString& sMessage) { MODHALTCHK(OnPrivCTCP(Nick, sMessage)); } -bool CModules::OnPrivCTCPMessage(CCTCPMessage& Message) { MODHALTCHK(OnPrivCTCPMessage(Message)); } -bool CModules::OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) { MODHALTCHK(OnChanCTCP(Nick, Channel, sMessage)); } -bool CModules::OnChanCTCPMessage(CCTCPMessage& Message) { MODHALTCHK(OnChanCTCPMessage(Message)); } -bool CModules::OnPrivAction(CNick& Nick, CString& sMessage) { MODHALTCHK(OnPrivAction(Nick, sMessage)); } -bool CModules::OnPrivActionMessage(CActionMessage& Message) { MODHALTCHK(OnPrivActionMessage(Message)); } -bool CModules::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { MODHALTCHK(OnChanAction(Nick, Channel, sMessage)); } -bool CModules::OnChanActionMessage(CActionMessage& Message) { MODHALTCHK(OnChanActionMessage(Message)); } -bool CModules::OnPrivMsg(CNick& Nick, CString& sMessage) { MODHALTCHK(OnPrivMsg(Nick, sMessage)); } -bool CModules::OnPrivMessage(CTextMessage& Message) { MODHALTCHK(OnPrivMessage(Message)); } -bool CModules::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { MODHALTCHK(OnChanMsg(Nick, Channel, sMessage)); } -bool CModules::OnChanMessage(CTextMessage& Message) { MODHALTCHK(OnChanMessage(Message)); } -bool CModules::OnPrivNotice(CNick& Nick, CString& sMessage) { MODHALTCHK(OnPrivNotice(Nick, sMessage)); } -bool CModules::OnPrivNoticeMessage(CNoticeMessage& Message) { MODHALTCHK(OnPrivNoticeMessage(Message)); } -bool CModules::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { MODHALTCHK(OnChanNotice(Nick, Channel, sMessage)); } -bool CModules::OnChanNoticeMessage(CNoticeMessage& Message) { MODHALTCHK(OnChanNoticeMessage(Message)); } -bool CModules::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) { MODHALTCHK(OnTopic(Nick, Channel, sTopic)); } -bool CModules::OnTopicMessage(CTopicMessage& Message) { MODHALTCHK(OnTopicMessage(Message)); } -bool CModules::OnTimerAutoJoin(CChan& Channel) { MODHALTCHK(OnTimerAutoJoin(Channel)); } -bool CModules::OnAddNetwork(CIRCNetwork& Network, CString& sErrorRet) { MODHALTCHK(OnAddNetwork(Network, sErrorRet)); } -bool CModules::OnDeleteNetwork(CIRCNetwork& Network) { MODHALTCHK(OnDeleteNetwork(Network)); } -bool CModules::OnSendToClient(CString& sLine, CClient& Client) { MODHALTCHK(OnSendToClient(sLine, Client)); } +bool CModules::OnJoin(const CNick& Nick, CChan& Channel) { + MODUNLOADCHK(OnJoin(Nick, Channel)); + return false; +} +bool CModules::OnJoinMessage(CJoinMessage& Message) { + MODUNLOADCHK(OnJoinMessage(Message)); + return false; +} +bool CModules::OnPart(const CNick& Nick, CChan& Channel, + const CString& sMessage) { + MODUNLOADCHK(OnPart(Nick, Channel, sMessage)); + return false; +} +bool CModules::OnPartMessage(CPartMessage& Message) { + MODUNLOADCHK(OnPartMessage(Message)); + return false; +} +bool CModules::OnInvite(const CNick& Nick, const CString& sChan) { + MODHALTCHK(OnInvite(Nick, sChan)); +} +bool CModules::OnChanBufferStarting(CChan& Chan, CClient& Client) { + MODHALTCHK(OnChanBufferStarting(Chan, Client)); +} +bool CModules::OnChanBufferEnding(CChan& Chan, CClient& Client) { + MODHALTCHK(OnChanBufferEnding(Chan, Client)); +} +bool CModules::OnChanBufferPlayLine2(CChan& Chan, CClient& Client, + CString& sLine, const timeval& tv) { + MODHALTCHK(OnChanBufferPlayLine2(Chan, Client, sLine, tv)); +} +bool CModules::OnChanBufferPlayLine(CChan& Chan, CClient& Client, + CString& sLine) { + MODHALTCHK(OnChanBufferPlayLine(Chan, Client, sLine)); +} +bool CModules::OnPrivBufferPlayLine2(CClient& Client, CString& sLine, + const timeval& tv) { + MODHALTCHK(OnPrivBufferPlayLine2(Client, sLine, tv)); +} +bool CModules::OnPrivBufferPlayLine(CClient& Client, CString& sLine) { + MODHALTCHK(OnPrivBufferPlayLine(Client, sLine)); +} +bool CModules::OnChanBufferPlayMessage(CMessage& Message) { + MODHALTCHK(OnChanBufferPlayMessage(Message)); +} +bool CModules::OnPrivBufferPlayMessage(CMessage& Message) { + MODHALTCHK(OnPrivBufferPlayMessage(Message)); +} +bool CModules::OnCTCPReply(CNick& Nick, CString& sMessage) { + MODHALTCHK(OnCTCPReply(Nick, sMessage)); +} +bool CModules::OnCTCPReplyMessage(CCTCPMessage& Message) { + MODHALTCHK(OnCTCPReplyMessage(Message)); +} +bool CModules::OnPrivCTCP(CNick& Nick, CString& sMessage) { + MODHALTCHK(OnPrivCTCP(Nick, sMessage)); +} +bool CModules::OnPrivCTCPMessage(CCTCPMessage& Message) { + MODHALTCHK(OnPrivCTCPMessage(Message)); +} +bool CModules::OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) { + MODHALTCHK(OnChanCTCP(Nick, Channel, sMessage)); +} +bool CModules::OnChanCTCPMessage(CCTCPMessage& Message) { + MODHALTCHK(OnChanCTCPMessage(Message)); +} +bool CModules::OnPrivAction(CNick& Nick, CString& sMessage) { + MODHALTCHK(OnPrivAction(Nick, sMessage)); +} +bool CModules::OnPrivActionMessage(CActionMessage& Message) { + MODHALTCHK(OnPrivActionMessage(Message)); +} +bool CModules::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) { + MODHALTCHK(OnChanAction(Nick, Channel, sMessage)); +} +bool CModules::OnChanActionMessage(CActionMessage& Message) { + MODHALTCHK(OnChanActionMessage(Message)); +} +bool CModules::OnPrivMsg(CNick& Nick, CString& sMessage) { + MODHALTCHK(OnPrivMsg(Nick, sMessage)); +} +bool CModules::OnPrivMessage(CTextMessage& Message) { + MODHALTCHK(OnPrivMessage(Message)); +} +bool CModules::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) { + MODHALTCHK(OnChanMsg(Nick, Channel, sMessage)); +} +bool CModules::OnChanMessage(CTextMessage& Message) { + MODHALTCHK(OnChanMessage(Message)); +} +bool CModules::OnPrivNotice(CNick& Nick, CString& sMessage) { + MODHALTCHK(OnPrivNotice(Nick, sMessage)); +} +bool CModules::OnPrivNoticeMessage(CNoticeMessage& Message) { + MODHALTCHK(OnPrivNoticeMessage(Message)); +} +bool CModules::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) { + MODHALTCHK(OnChanNotice(Nick, Channel, sMessage)); +} +bool CModules::OnChanNoticeMessage(CNoticeMessage& Message) { + MODHALTCHK(OnChanNoticeMessage(Message)); +} +bool CModules::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) { + MODHALTCHK(OnTopic(Nick, Channel, sTopic)); +} +bool CModules::OnTopicMessage(CTopicMessage& Message) { + MODHALTCHK(OnTopicMessage(Message)); +} +bool CModules::OnTimerAutoJoin(CChan& Channel) { + MODHALTCHK(OnTimerAutoJoin(Channel)); +} +bool CModules::OnAddNetwork(CIRCNetwork& Network, CString& sErrorRet) { + MODHALTCHK(OnAddNetwork(Network, sErrorRet)); +} +bool CModules::OnDeleteNetwork(CIRCNetwork& Network) { + MODHALTCHK(OnDeleteNetwork(Network)); +} +bool CModules::OnSendToClient(CString& sLine, CClient& Client) { + MODHALTCHK(OnSendToClient(sLine, Client)); +} bool CModules::OnSendToIRC(CString& sLine) { MODHALTCHK(OnSendToIRC(sLine)); } -bool CModules::OnStatusCommand(CString& sCommand) { MODHALTCHK(OnStatusCommand(sCommand)); } -bool CModules::OnModCommand(const CString& sCommand) { MODUNLOADCHK(OnModCommand(sCommand)); return false; } -bool CModules::OnModNotice(const CString& sMessage) { MODUNLOADCHK(OnModNotice(sMessage)); return false; } -bool CModules::OnModCTCP(const CString& sMessage) { MODUNLOADCHK(OnModCTCP(sMessage)); return false; } +bool CModules::OnStatusCommand(CString& sCommand) { + MODHALTCHK(OnStatusCommand(sCommand)); +} +bool CModules::OnModCommand(const CString& sCommand) { + MODUNLOADCHK(OnModCommand(sCommand)); + return false; +} +bool CModules::OnModNotice(const CString& sMessage) { + MODUNLOADCHK(OnModNotice(sMessage)); + return false; +} +bool CModules::OnModCTCP(const CString& sMessage) { + MODUNLOADCHK(OnModCTCP(sMessage)); + return false; +} // Why MODHALTCHK works only with functions returning EModRet ? :( bool CModules::OnServerCapAvailable(const CString& sCap) { @@ -1074,7 +1463,10 @@ bool CModules::OnServerCapAvailable(const CString& sCap) { return bResult; } -bool CModules::OnServerCapResult(const CString& sCap, bool bSuccess) { MODUNLOADCHK(OnServerCapResult(sCap, bSuccess)); return false; } +bool CModules::OnServerCapResult(const CString& sCap, bool bSuccess) { + MODUNLOADCHK(OnServerCapResult(sCap, bSuccess)); + return false; +} //////////////////// // Global Modules // @@ -1083,11 +1475,10 @@ bool CModules::OnAddUser(CUser& User, CString& sErrorRet) { MODHALTCHK(OnAddUser(User, sErrorRet)); } -bool CModules::OnDeleteUser(CUser& User) { - MODHALTCHK(OnDeleteUser(User)); -} +bool CModules::OnDeleteUser(CUser& User) { MODHALTCHK(OnDeleteUser(User)); } -bool CModules::OnClientConnect(CZNCSock* pClient, const CString& sHost, unsigned short uPort) { +bool CModules::OnClientConnect(CZNCSock* pClient, const CString& sHost, + unsigned short uPort) { MODUNLOADCHK(OnClientConnect(pClient, sHost, uPort)); return false; } @@ -1096,7 +1487,8 @@ bool CModules::OnLoginAttempt(std::shared_ptr Auth) { MODHALTCHK(OnLoginAttempt(Auth)); } -bool CModules::OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) { +bool CModules::OnFailedLogin(const CString& sUsername, + const CString& sRemoteIP) { MODUNLOADCHK(OnFailedLogin(sUsername, sRemoteIP)); return false; } @@ -1115,7 +1507,8 @@ bool CModules::OnClientCapLs(CClient* pClient, SCString& ssCaps) { } // Maybe create new macro for this? -bool CModules::IsClientCapSupported(CClient* pClient, const CString& sCap, bool bState) { +bool CModules::IsClientCapSupported(CClient* pClient, const CString& sCap, + bool bState) { bool bResult = false; for (CModule* pMod : *this) { try { @@ -1140,31 +1533,34 @@ bool CModules::IsClientCapSupported(CClient* pClient, const CString& sCap, bool return bResult; } -bool CModules::OnClientCapRequest(CClient* pClient, const CString& sCap, bool bState) { +bool CModules::OnClientCapRequest(CClient* pClient, const CString& sCap, + bool bState) { MODUNLOADCHK(OnClientCapRequest(pClient, sCap, bState)); return false; } bool CModules::OnModuleLoading(const CString& sModName, const CString& sArgs, - CModInfo::EModuleType eType, bool& bSuccess, CString& sRetMsg) { + CModInfo::EModuleType eType, bool& bSuccess, + CString& sRetMsg) { MODHALTCHK(OnModuleLoading(sModName, sArgs, eType, bSuccess, sRetMsg)); } -bool CModules::OnModuleUnloading(CModule* pModule, bool& bSuccess, CString& sRetMsg) { +bool CModules::OnModuleUnloading(CModule* pModule, bool& bSuccess, + CString& sRetMsg) { MODHALTCHK(OnModuleUnloading(pModule, bSuccess, sRetMsg)); } bool CModules::OnGetModInfo(CModInfo& ModInfo, const CString& sModule, - bool& bSuccess, CString& sRetMsg) { + bool& bSuccess, CString& sRetMsg) { MODHALTCHK(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg)); } -bool CModules::OnGetAvailableMods(set& ssMods, CModInfo::EModuleType eType) { +bool CModules::OnGetAvailableMods(set& ssMods, + CModInfo::EModuleType eType) { MODUNLOADCHK(OnGetAvailableMods(ssMods, eType)); return false; } - CModule* CModules::FindModule(const CString& sModule) const { for (CModule* pMod : *this) { if (sModule.Equals(pMod->GetModName())) { @@ -1175,7 +1571,9 @@ CModule* CModules::FindModule(const CString& sModule) const { return nullptr; } -bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo::EModuleType eType, CUser* pUser, CIRCNetwork *pNetwork, CString& sRetMsg) { +bool CModules::LoadModule(const CString& sModule, const CString& sArgs, + CModInfo::EModuleType eType, CUser* pUser, + CIRCNetwork* pNetwork, CString& sRetMsg) { sRetMsg = ""; if (FindModule(sModule) != nullptr) { @@ -1185,7 +1583,8 @@ bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo bool bSuccess; bool bHandled = false; - _GLOBALMODULECALL(OnModuleLoading(sModule, sArgs, eType, bSuccess, sRetMsg), pUser, pNetwork, nullptr, &bHandled); + _GLOBALMODULECALL(OnModuleLoading(sModule, sArgs, eType, bSuccess, sRetMsg), + pUser, pNetwork, nullptr, &bHandled); if (bHandled) return bSuccess; CString sModPath, sDataPath; @@ -1197,10 +1596,10 @@ bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo return false; } - ModHandle p = OpenModule(sModule, sModPath, bVersionMismatch, Info, sRetMsg); + ModHandle p = + OpenModule(sModule, sModPath, bVersionMismatch, Info, sRetMsg); - if (!p) - return false; + if (!p) return false; if (bVersionMismatch) { dlclose(p); @@ -1210,8 +1609,8 @@ bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo if (!Info.SupportsType(eType)) { dlclose(p); - sRetMsg = "Module [" + sModule + "] does not support module type [" - + CModInfo::ModuleTypeToString(eType) + "]."; + sRetMsg = "Module [" + sModule + "] does not support module type [" + + CModInfo::ModuleTypeToString(eType) + "]."; return false; } @@ -1227,7 +1626,8 @@ bool CModules::LoadModule(const CString& sModule, const CString& sArgs, CModInfo return false; } - CModule* pModule = Info.GetLoader()(p, pUser, pNetwork, sModule, sDataPath, eType); + CModule* pModule = + Info.GetLoader()(p, pUser, pNetwork, sModule, sDataPath, eType); pModule->SetDescription(Info.GetDescription()); pModule->SetArgs(sArgs); pModule->SetModPath(CDir::ChangeDir(CZNC::Get().GetCurPath(), sModPath)); @@ -1263,7 +1663,8 @@ bool CModules::UnloadModule(const CString& sModule) { } bool CModules::UnloadModule(const CString& sModule, CString& sRetMsg) { - CString sMod = sModule; // Make a copy incase the reference passed in is from CModule::GetModName() + CString sMod = sModule; // Make a copy incase the reference passed in is + // from CModule::GetModName() CModule* pModule = FindModule(sMod); sRetMsg = ""; @@ -1274,7 +1675,9 @@ bool CModules::UnloadModule(const CString& sModule, CString& sRetMsg) { bool bSuccess; bool bHandled = false; - _GLOBALMODULECALL(OnModuleUnloading(pModule, bSuccess, sRetMsg), pModule->GetUser(), pModule->GetNetwork(), nullptr, &bHandled); + _GLOBALMODULECALL(OnModuleUnloading(pModule, bSuccess, sRetMsg), + pModule->GetUser(), pModule->GetNetwork(), nullptr, + &bHandled); if (bHandled) return bSuccess; ModHandle p = pModule->GetDLL(); @@ -1299,9 +1702,12 @@ bool CModules::UnloadModule(const CString& sModule, CString& sRetMsg) { return false; } -bool CModules::ReloadModule(const CString& sModule, const CString& sArgs, CUser* pUser, CIRCNetwork* pNetwork, CString& sRetMsg) { - CString sMod = sModule; // Make a copy incase the reference passed in is from CModule::GetModName() - CModule *pModule = FindModule(sMod); +bool CModules::ReloadModule(const CString& sModule, const CString& sArgs, + CUser* pUser, CIRCNetwork* pNetwork, + CString& sRetMsg) { + CString sMod = sModule; // Make a copy incase the reference passed in is + // from CModule::GetModName() + CModule* pModule = FindModule(sMod); if (!pModule) { sRetMsg = "Module [" + sMod + "] not loaded"; @@ -1324,12 +1730,14 @@ bool CModules::ReloadModule(const CString& sModule, const CString& sArgs, CUser* return true; } -bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule, CString& sRetMsg) { +bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule, + CString& sRetMsg) { CString sModPath, sTmp; bool bSuccess; bool bHandled = false; - GLOBALMODULECALL(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg), &bHandled); + GLOBALMODULECALL(OnGetModInfo(ModInfo, sModule, bSuccess, sRetMsg), + &bHandled); if (bHandled) return bSuccess; if (!FindModPath(sModule, sModPath, sTmp)) { @@ -1340,19 +1748,21 @@ bool CModules::GetModInfo(CModInfo& ModInfo, const CString& sModule, CString& sR return GetModPathInfo(ModInfo, sModule, sModPath, sRetMsg); } -bool CModules::GetModPathInfo(CModInfo& ModInfo, const CString& sModule, const CString& sModPath, CString& sRetMsg) { +bool CModules::GetModPathInfo(CModInfo& ModInfo, const CString& sModule, + const CString& sModPath, CString& sRetMsg) { bool bVersionMismatch; - ModHandle p = OpenModule(sModule, sModPath, bVersionMismatch, ModInfo, sRetMsg); + ModHandle p = + OpenModule(sModule, sModPath, bVersionMismatch, ModInfo, sRetMsg); - if (!p) - return false; + if (!p) return false; ModInfo.SetName(sModule); ModInfo.SetPath(sModPath); if (bVersionMismatch) { - ModInfo.SetDescription("--- Version mismatch, recompile this module. ---"); + ModInfo.SetDescription( + "--- Version mismatch, recompile this module. ---"); } dlclose(p); @@ -1360,7 +1770,8 @@ bool CModules::GetModPathInfo(CModInfo& ModInfo, const CString& sModule, const C return true; } -void CModules::GetAvailableMods(set& ssMods, CModInfo::EModuleType eType) { +void CModules::GetAvailableMods(set& ssMods, + CModInfo::EModuleType eType) { ssMods.clear(); unsigned int a = 0; @@ -1391,16 +1802,15 @@ void CModules::GetAvailableMods(set& ssMods, CModInfo::EModuleType eTy GLOBALMODULECALL(OnGetAvailableMods(ssMods, eType), NOTHING); } -void CModules::GetDefaultMods(set& ssMods, CModInfo::EModuleType eType) { - +void CModules::GetDefaultMods(set& ssMods, + CModInfo::EModuleType eType) { GetAvailableMods(ssMods, eType); const map ns = { - { "chansaver", CModInfo::UserModule }, - { "controlpanel", CModInfo::UserModule }, - { "simple_away", CModInfo::NetworkModule }, - { "webadmin", CModInfo::GlobalModule } - }; + {"chansaver", CModInfo::UserModule}, + {"controlpanel", CModInfo::UserModule}, + {"simple_away", CModInfo::NetworkModule}, + {"webadmin", CModInfo::GlobalModule}}; auto it = ssMods.begin(); while (it != ssMods.end()) { @@ -1414,11 +1824,10 @@ void CModules::GetDefaultMods(set& ssMods, CModInfo::EModuleType eType } bool CModules::FindModPath(const CString& sModule, CString& sModPath, - CString& sDataPath) { + CString& sDataPath) { CString sMod = sModule; CString sDir = sMod; - if (!sModule.Contains(".")) - sMod += ".so"; + if (!sModule.Contains(".")) sMod += ".so"; ModDirList dirs = GetModDirs(); @@ -1451,20 +1860,27 @@ CModules::ModDirList CModules::GetModDirs() { ret.push(std::make_pair(sDir, sDir)); // and (/lib/znc) - ret.push(std::make_pair(_MODDIR_ + CString("/"), _DATADIR_ + CString("/modules/"))); + ret.push(std::make_pair(_MODDIR_ + CString("/"), + _DATADIR_ + CString("/modules/"))); return ret; } -ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, bool &bVersionMismatch, - CModInfo& Info, CString& sRetMsg) { +ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, + bool& bVersionMismatch, CModInfo& Info, + CString& sRetMsg) { // Some sane defaults in case anything errors out below bVersionMismatch = false; sRetMsg.clear(); for (unsigned int a = 0; a < sModule.length(); a++) { - if (((sModule[a] < '0') || (sModule[a] > '9')) && ((sModule[a] < 'a') || (sModule[a] > 'z')) && ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) { - sRetMsg = "Module names can only contain letters, numbers and underscores, [" + sModule + "] is invalid."; + if (((sModule[a] < '0') || (sModule[a] > '9')) && + ((sModule[a] < 'a') || (sModule[a] > 'z')) && + ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) { + sRetMsg = + "Module names can only contain letters, numbers and " + "underscores, [" + + sModule + "] is invalid."; return nullptr; } } @@ -1477,14 +1893,17 @@ ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, // failed symbol lookups later on. Doesn't really seem to have much of a // performance impact. // - // RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later on - // loads own modules (which it apparently does with RTLD_LAZY), we will die in a + // RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later + // on + // loads own modules (which it apparently does with RTLD_LAZY), we will die + // in a // name lookup since one of perl's symbols isn't found. That's worse // than any theoretical issue with RTLD_GLOBAL. ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_GLOBAL); if (!p) { - // dlerror() returns pointer to static buffer, which may be overwritten very soon with another dl call + // dlerror() returns pointer to static buffer, which may be overwritten + // very soon with another dl call // also it may just return null. const char* cDlError = dlerror(); CString sDlError = cDlError ? cDlError : "Unknown error"; @@ -1493,7 +1912,7 @@ ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, } typedef bool (*InfoFP)(double, CModInfo&); - InfoFP ZNCModInfo = (InfoFP) dlsym(p, "ZNCModInfo"); + InfoFP ZNCModInfo = (InfoFP)dlsym(p, "ZNCModInfo"); if (!ZNCModInfo) { dlclose(p); @@ -1512,24 +1931,26 @@ ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, return p; } -CModCommand::CModCommand() - : m_sCmd(), m_pFunc(nullptr), m_sArgs(), m_sDesc() -{ -} +CModCommand::CModCommand() : m_sCmd(), m_pFunc(nullptr), m_sArgs(), m_sDesc() {} -CModCommand::CModCommand(const CString& sCmd, CModule* pMod, ModCmdFunc func, const CString& sArgs, const CString& sDesc) - : m_sCmd(sCmd), m_pFunc([pMod, func](const CString& sLine) { (pMod->*func)(sLine); }), m_sArgs(sArgs), m_sDesc(sDesc) {} +CModCommand::CModCommand(const CString& sCmd, CModule* pMod, ModCmdFunc func, + const CString& sArgs, const CString& sDesc) + : m_sCmd(sCmd), + m_pFunc([pMod, func](const CString& sLine) { (pMod->*func)(sLine); }), + m_sArgs(sArgs), + m_sDesc(sDesc) {} -CModCommand::CModCommand(const CString& sCmd, CmdFunc func, const CString& sArgs, const CString& sDesc) - : m_sCmd(sCmd), m_pFunc(std::move(func)), m_sArgs(sArgs), m_sDesc(sDesc) {} +CModCommand::CModCommand(const CString& sCmd, CmdFunc func, + const CString& sArgs, const CString& sDesc) + : m_sCmd(sCmd), m_pFunc(std::move(func)), m_sArgs(sArgs), m_sDesc(sDesc) {} CModCommand::CModCommand(const CModCommand& other) - : m_sCmd(other.m_sCmd), m_pFunc(other.m_pFunc), m_sArgs(other.m_sArgs), m_sDesc(other.m_sDesc) -{ -} + : m_sCmd(other.m_sCmd), + m_pFunc(other.m_pFunc), + m_sArgs(other.m_sArgs), + m_sDesc(other.m_sDesc) {} -CModCommand& CModCommand::operator=(const CModCommand& other) -{ +CModCommand& CModCommand::operator=(const CModCommand& other) { m_sCmd = other.m_sCmd; m_pFunc = other.m_pFunc; m_sArgs = other.m_sArgs; diff --git a/src/Nick.cpp b/src/Nick.cpp index bcdd114b..5d380852 100644 --- a/src/Nick.cpp +++ b/src/Nick.cpp @@ -22,12 +22,14 @@ using std::vector; using std::map; -CNick::CNick() : m_sChanPerms(""), m_pNetwork(nullptr), m_sNick(""), m_sIdent(""), m_sHost("") { -} +CNick::CNick() + : m_sChanPerms(""), + m_pNetwork(nullptr), + m_sNick(""), + m_sIdent(""), + m_sHost("") {} -CNick::CNick(const CString& sNick) : CNick() { - Parse(sNick); -} +CNick::CNick(const CString& sNick) : CNick() { Parse(sNick); } CNick::~CNick() {} @@ -48,22 +50,24 @@ void CNick::Parse(const CString& sNickMask) { return; } - m_sNick = sNickMask.substr((sNickMask[0] == ':'), uPos - (sNickMask[0] == ':')); - m_sHost = sNickMask.substr(uPos +1); + m_sNick = + sNickMask.substr((sNickMask[0] == ':'), uPos - (sNickMask[0] == ':')); + m_sHost = sNickMask.substr(uPos + 1); if ((uPos = m_sHost.find('@')) != CString::npos) { m_sIdent = m_sHost.substr(0, uPos); - m_sHost = m_sHost.substr(uPos +1); + m_sHost = m_sHost.substr(uPos + 1); } } -size_t CNick::GetCommonChans(vector& vRetChans, CIRCNetwork* pNetwork) const { +size_t CNick::GetCommonChans(vector& vRetChans, + CIRCNetwork* pNetwork) const { vRetChans.clear(); const vector& vChans = pNetwork->GetChans(); for (CChan* pChan : vChans) { - const map& msNicks = pChan->GetNicks(); + const map& msNicks = pChan->GetNicks(); for (const auto& it : msNicks) { if (it.first.Equals(m_sNick)) { @@ -77,8 +81,8 @@ size_t CNick::GetCommonChans(vector& vRetChans, CIRCNetwork* pNetwork) c } bool CNick::NickEquals(const CString& nickname) const { - //TODO add proper IRC case mapping here - //https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.1 + // TODO add proper IRC case mapping here + // https://tools.ietf.org/html/draft-brocklesby-irc-isupport-03#section-3.1 return m_sNick.Equals(nickname); } @@ -148,8 +152,7 @@ CString CNick::GetNickMask() const { CString sRet = m_sNick; if (!m_sHost.empty()) { - if (!m_sIdent.empty()) - sRet += "!" + m_sIdent; + if (!m_sIdent.empty()) sRet += "!" + m_sIdent; sRet += "@" + m_sHost; } diff --git a/src/Query.cpp b/src/Query.cpp index ca4043d9..07b68bf2 100644 --- a/src/Query.cpp +++ b/src/Query.cpp @@ -21,24 +21,22 @@ using std::vector; -CQuery::CQuery(const CString& sName, CIRCNetwork* pNetwork) : m_sName(sName), m_pNetwork(pNetwork), m_Buffer() { +CQuery::CQuery(const CString& sName, CIRCNetwork* pNetwork) + : m_sName(sName), m_pNetwork(pNetwork), m_Buffer() { SetBufferCount(m_pNetwork->GetUser()->GetQueryBufferSize(), true); } -CQuery::~CQuery() { -} +CQuery::~CQuery() {} -void CQuery::SendBuffer(CClient* pClient) { - SendBuffer(pClient, m_Buffer); -} +void CQuery::SendBuffer(CClient* pClient) { SendBuffer(pClient, m_Buffer); } void CQuery::SendBuffer(CClient* pClient, const CBuffer& Buffer) { if (m_pNetwork && m_pNetwork->IsUserAttached()) { // Based on CChan::SendBuffer() if (!Buffer.IsEmpty()) { - const vector & vClients = m_pNetwork->GetClients(); + const vector& vClients = m_pNetwork->GetClients(); for (CClient* pEachClient : vClients) { - CClient * pUseClient = (pClient ? pClient : pEachClient); + CClient* pUseClient = (pClient ? pClient : pEachClient); MCString msParams; msParams["target"] = pUseClient->GetNick(); @@ -50,15 +48,19 @@ void CQuery::SendBuffer(CClient* pClient, const CBuffer& Buffer) { CString sBatchName = m_sName.MD5(); if (bBatch) { - m_pNetwork->PutUser(":znc.in BATCH +" + sBatchName + " znc.in/playback " + m_sName, pUseClient); + m_pNetwork->PutUser(":znc.in BATCH +" + sBatchName + + " znc.in/playback " + m_sName, + pUseClient); } size_t uSize = Buffer.Size(); for (size_t uIdx = 0; uIdx < uSize; uIdx++) { const CBufLine& BufLine = Buffer.GetBufLine(uIdx); CMessage Message = BufLine.ToMessage(*pUseClient, msParams); - if (!pUseClient->HasEchoMessage() && !pUseClient->HasSelfMessage()) { - if (Message.GetNick().NickEquals(pUseClient->GetNick())) { + if (!pUseClient->HasEchoMessage() && + !pUseClient->HasSelfMessage()) { + if (Message.GetNick().NickEquals( + pUseClient->GetNick())) { continue; } } @@ -68,19 +70,21 @@ void CQuery::SendBuffer(CClient* pClient, const CBuffer& Buffer) { Message.SetTag("batch", sBatchName); } bool bContinue = false; - NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), m_pNetwork->GetUser(), m_pNetwork, nullptr, &bContinue); + NETWORKMODULECALL(OnPrivBufferPlayMessage(Message), + m_pNetwork->GetUser(), m_pNetwork, + nullptr, &bContinue); if (bContinue) continue; m_pNetwork->PutUser(Message, pUseClient); } if (bBatch) { - m_pNetwork->PutUser(":znc.in BATCH -" + sBatchName, pUseClient); + m_pNetwork->PutUser(":znc.in BATCH -" + sBatchName, + pUseClient); } pUseClient->SetPlaybackActive(bWasPlaybackActive); - if (pClient) - break; + if (pClient) break; } } } diff --git a/src/SHA256.cpp b/src/SHA256.cpp index e4853863..25083f8c 100644 --- a/src/SHA256.cpp +++ b/src/SHA256.cpp @@ -35,195 +35,180 @@ #include -#define SHFR(x, n) (x >> n) -#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define CH(x, y, z) ((x & y) ^ (~x & z)) +#define SHFR(x, n) (x >> n) +#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) +#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) +#define CH(x, y, z) ((x & y) ^ (~x & z)) #define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) -#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) -#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) +#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) +#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) +#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3)) #define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10)) -#define UNPACK32(x, str) \ -{ \ - *((str) + 3) = (uint8_t) ((x) ); \ - *((str) + 2) = (uint8_t) ((x) >> 8); \ - *((str) + 1) = (uint8_t) ((x) >> 16); \ - *((str) + 0) = (uint8_t) ((x) >> 24); \ -} +#define UNPACK32(x, str) \ + { \ + *((str)+3) = (uint8_t)((x)); \ + *((str)+2) = (uint8_t)((x) >> 8); \ + *((str)+1) = (uint8_t)((x) >> 16); \ + *((str)+0) = (uint8_t)((x) >> 24); \ + } -#define PACK32(str, x) \ -{ \ - *(x) = ((uint32_t) *((str) + 3) ) \ - | ((uint32_t) *((str) + 2) << 8) \ - | ((uint32_t) *((str) + 1) << 16) \ - | ((uint32_t) *((str) + 0) << 24); \ -} +#define PACK32(str, x) \ + { \ + *(x) = ((uint32_t) * ((str)+3)) | ((uint32_t) * ((str)+2) << 8) | \ + ((uint32_t) * ((str)+1) << 16) | \ + ((uint32_t) * ((str)+0) << 24); \ + } /* Macros used for loops unrolling */ -#define SHA256_SCR(i) \ -{ \ - w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \ - + SHA256_F3(w[i - 15]) + w[i - 16]; \ -} +#define SHA256_SCR(i) \ + { \ + w[i] = \ + SHA256_F4(w[i - 2]) + w[i - 7] + SHA256_F3(w[i - 15]) + w[i - 16]; \ + } -#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ -{ \ - t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \ - + sha256_k[j] + w[j]; \ - t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ - wv[d] += t1; \ - wv[h] = t1 + t2; \ -} +#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \ + { \ + t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) + \ + sha256_k[j] + w[j]; \ + t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \ + wv[d] += t1; \ + wv[h] = t1 + t2; \ + } -uint32_t sha256_h0[8] = - {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; +uint32_t sha256_h0[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; -uint32_t sha256_k[64] = - {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; +uint32_t sha256_k[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; /* SHA-256 functions */ -static void sha256_transf(sha256_ctx *ctx, const unsigned char *message, - size_t block_nb) -{ - uint32_t w[64]; - uint32_t wv[8]; - uint32_t t1, t2; - const unsigned char *sub_block; - int i; +static void sha256_transf(sha256_ctx* ctx, const unsigned char* message, + size_t block_nb) { + uint32_t w[64]; + uint32_t wv[8]; + uint32_t t1, t2; + const unsigned char* sub_block; + int i; - int j; + int j; - for (i = 0; i < (int) block_nb; i++) { - sub_block = message + (i << 6); + for (i = 0; i < (int)block_nb; i++) { + sub_block = message + (i << 6); - for (j = 0; j < 16; j++) { - PACK32(&sub_block[j << 2], &w[j]); - } + for (j = 0; j < 16; j++) { + PACK32(&sub_block[j << 2], &w[j]); + } - for (j = 16; j < 64; j++) { - SHA256_SCR(j); - } + for (j = 16; j < 64; j++) { + SHA256_SCR(j); + } - for (j = 0; j < 8; j++) { - wv[j] = ctx->h[j]; - } + for (j = 0; j < 8; j++) { + wv[j] = ctx->h[j]; + } - for (j = 0; j < 64; j++) { - t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) - + sha256_k[j] + w[j]; - t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } + for (j = 0; j < 64; j++) { + t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6]) + + sha256_k[j] + w[j]; + t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]); + wv[7] = wv[6]; + wv[6] = wv[5]; + wv[5] = wv[4]; + wv[4] = wv[3] + t1; + wv[3] = wv[2]; + wv[2] = wv[1]; + wv[1] = wv[0]; + wv[0] = t1 + t2; + } - for (j = 0; j < 8; j++) { - ctx->h[j] += wv[j]; - } - } + for (j = 0; j < 8; j++) { + ctx->h[j] += wv[j]; + } + } } -void sha256(const unsigned char *message, size_t len, unsigned char *digest) -{ - sha256_ctx ctx; +void sha256(const unsigned char* message, size_t len, unsigned char* digest) { + sha256_ctx ctx; - sha256_init(&ctx); - sha256_update(&ctx, message, len); - sha256_final(&ctx, digest); + sha256_init(&ctx); + sha256_update(&ctx, message, len); + sha256_final(&ctx, digest); } -void sha256_init(sha256_ctx *ctx) -{ - int i; - for (i = 0; i < 8; i++) { - ctx->h[i] = sha256_h0[i]; - } +void sha256_init(sha256_ctx* ctx) { + int i; + for (i = 0; i < 8; i++) { + ctx->h[i] = sha256_h0[i]; + } - ctx->len = 0; - ctx->tot_len = 0; + ctx->len = 0; + ctx->tot_len = 0; } -void sha256_update(sha256_ctx *ctx, const unsigned char *message, - size_t len) -{ - size_t block_nb; - size_t new_len, rem_len, tmp_len; - const unsigned char *shifted_message; +void sha256_update(sha256_ctx* ctx, const unsigned char* message, size_t len) { + size_t block_nb; + size_t new_len, rem_len, tmp_len; + const unsigned char* shifted_message; - tmp_len = SHA256_BLOCK_SIZE - ctx->len; - rem_len = len < tmp_len ? len : tmp_len; + tmp_len = SHA256_BLOCK_SIZE - ctx->len; + rem_len = len < tmp_len ? len : tmp_len; - memcpy(&ctx->block[ctx->len], message, rem_len); + memcpy(&ctx->block[ctx->len], message, rem_len); - if (ctx->len + len < SHA256_BLOCK_SIZE) { - ctx->len += len; - return; - } + if (ctx->len + len < SHA256_BLOCK_SIZE) { + ctx->len += len; + return; + } - new_len = len - rem_len; - block_nb = new_len / SHA256_BLOCK_SIZE; + new_len = len - rem_len; + block_nb = new_len / SHA256_BLOCK_SIZE; - shifted_message = message + rem_len; + shifted_message = message + rem_len; - sha256_transf(ctx, ctx->block, 1); - sha256_transf(ctx, shifted_message, block_nb); + sha256_transf(ctx, ctx->block, 1); + sha256_transf(ctx, shifted_message, block_nb); - rem_len = new_len % SHA256_BLOCK_SIZE; + rem_len = new_len % SHA256_BLOCK_SIZE; - memcpy(ctx->block, &shifted_message[block_nb << 6], - rem_len); + memcpy(ctx->block, &shifted_message[block_nb << 6], rem_len); - ctx->len = rem_len; - ctx->tot_len += (block_nb + 1) << 6; + ctx->len = rem_len; + ctx->tot_len += (block_nb + 1) << 6; } -void sha256_final(sha256_ctx *ctx, unsigned char *digest) -{ - unsigned int block_nb; - unsigned int pm_len; - size_t len_b; +void sha256_final(sha256_ctx* ctx, unsigned char* digest) { + unsigned int block_nb; + unsigned int pm_len; + size_t len_b; - int i; + int i; - block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) - < (ctx->len % SHA256_BLOCK_SIZE))); + block_nb = (1 + ((SHA256_BLOCK_SIZE - 9) < (ctx->len % SHA256_BLOCK_SIZE))); - len_b = (ctx->tot_len + ctx->len) << 3; - pm_len = block_nb << 6; + len_b = (ctx->tot_len + ctx->len) << 3; + pm_len = block_nb << 6; - memset(ctx->block + ctx->len, 0, pm_len - ctx->len); - ctx->block[ctx->len] = 0x80; - UNPACK32(len_b, ctx->block + pm_len - 4); + memset(ctx->block + ctx->len, 0, pm_len - ctx->len); + ctx->block[ctx->len] = 0x80; + UNPACK32(len_b, ctx->block + pm_len - 4); - sha256_transf(ctx, ctx->block, block_nb); + sha256_transf(ctx, ctx->block, block_nb); - for (i = 0 ; i < 8; i++) { - UNPACK32(ctx->h[i], &digest[i << 2]); - } + for (i = 0; i < 8; i++) { + UNPACK32(ctx->h[i], &digest[i << 2]); + } } diff --git a/src/SSLVerifyHost.cpp b/src/SSLVerifyHost.cpp index a5830add..5de1e309 100644 --- a/src/SSLVerifyHost.cpp +++ b/src/SSLVerifyHost.cpp @@ -51,8 +51,7 @@ namespace ZNC_Curl { /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because its behavior is altered by the current locale. */ -inline char Curl_raw_toupper(char in) -{ +inline char Curl_raw_toupper(char in) { switch (in) { case 'a': return 'A'; @@ -119,32 +118,30 @@ inline char Curl_raw_toupper(char in) * The function is capable of comparing a-z case insensitively even for * non-ascii. */ -static int Curl_raw_equal(const char *first, const char *second) -{ - while(*first && *second) { - if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) +static int Curl_raw_equal(const char* first, const char* second) { + while (*first && *second) { + if (Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) /* get out of the loop as soon as they don't match */ break; first++; second++; } /* we do the comparison here (possibly again), just to make sure that if the - loop above is skipped because one of the strings reached zero, we must not + loop above is skipped because one of the strings reached zero, we must + not return this as a successful match */ return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second)); } -static int Curl_raw_nequal(const char *first, const char *second, size_t max) -{ - while(*first && *second && max) { - if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) { +static int Curl_raw_nequal(const char* first, const char* second, size_t max) { + while (*first && *second && max) { + if (Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) { break; } max--; first++; second++; } - if(0 == max) - return 1; /* they are equal this far */ + if (0 == max) return 1; /* they are equal this far */ return Curl_raw_toupper(*first) == Curl_raw_toupper(*second); } @@ -171,91 +168,88 @@ static const int CURL_HOST_MATCH = 1; * contents at will. */ -static int hostmatch(char *hostname, char *pattern) -{ - const char *pattern_label_end, *pattern_wildcard, *hostname_label_end; - int wildcard_enabled; - size_t prefixlen, suffixlen; - struct in_addr ignored; +static int hostmatch(char* hostname, char* pattern) { + const char* pattern_label_end, *pattern_wildcard, *hostname_label_end; + int wildcard_enabled; + size_t prefixlen, suffixlen; + struct in_addr ignored; #ifdef ENABLE_IPV6 - struct sockaddr_in6 si6; + struct sockaddr_in6 si6; #endif - /* normalize pattern and hostname by stripping off trailing dots */ - size_t len = strlen(hostname); - if(hostname[len-1]=='.') - hostname[len-1]=0; - len = strlen(pattern); - if(pattern[len-1]=='.') - pattern[len-1]=0; + /* normalize pattern and hostname by stripping off trailing dots */ + size_t len = strlen(hostname); + if (hostname[len - 1] == '.') hostname[len - 1] = 0; + len = strlen(pattern); + if (pattern[len - 1] == '.') pattern[len - 1] = 0; - pattern_wildcard = strchr(pattern, '*'); - if(pattern_wildcard == nullptr) - return Curl_raw_equal(pattern, hostname) ? - CURL_HOST_MATCH : CURL_HOST_NOMATCH; + pattern_wildcard = strchr(pattern, '*'); + if (pattern_wildcard == nullptr) + return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH + : CURL_HOST_NOMATCH; - /* detect IP address as hostname and fail the match if so */ - if(inet_pton(AF_INET, hostname, &ignored) > 0) - return CURL_HOST_NOMATCH; + /* detect IP address as hostname and fail the match if so */ + if (inet_pton(AF_INET, hostname, &ignored) > 0) return CURL_HOST_NOMATCH; #ifdef ENABLE_IPV6 - else if(Curl_inet_pton(AF_INET6, hostname, &si6.sin6_addr) > 0) - return CURL_HOST_NOMATCH; + else if (Curl_inet_pton(AF_INET6, hostname, &si6.sin6_addr) > 0) + return CURL_HOST_NOMATCH; #endif - /* We require at least 2 dots in pattern to avoid too wide wildcard - match. */ - wildcard_enabled = 1; - pattern_label_end = strchr(pattern, '.'); - if(pattern_label_end == nullptr || strchr(pattern_label_end+1, '.') == nullptr || - pattern_wildcard > pattern_label_end || - Curl_raw_nequal(pattern, "xn--", 4)) { - wildcard_enabled = 0; - } - if(!wildcard_enabled) - return Curl_raw_equal(pattern, hostname) ? - CURL_HOST_MATCH : CURL_HOST_NOMATCH; + /* We require at least 2 dots in pattern to avoid too wide wildcard + match. */ + wildcard_enabled = 1; + pattern_label_end = strchr(pattern, '.'); + if (pattern_label_end == nullptr || + strchr(pattern_label_end + 1, '.') == nullptr || + pattern_wildcard > pattern_label_end || + Curl_raw_nequal(pattern, "xn--", 4)) { + wildcard_enabled = 0; + } + if (!wildcard_enabled) + return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH + : CURL_HOST_NOMATCH; - hostname_label_end = strchr(hostname, '.'); - if(hostname_label_end == nullptr || - !Curl_raw_equal(pattern_label_end, hostname_label_end)) - return CURL_HOST_NOMATCH; + hostname_label_end = strchr(hostname, '.'); + if (hostname_label_end == nullptr || + !Curl_raw_equal(pattern_label_end, hostname_label_end)) + return CURL_HOST_NOMATCH; - /* The wildcard must match at least one character, so the left-most - label of the hostname is at least as large as the left-most label - of the pattern. */ - if(hostname_label_end - hostname < pattern_label_end - pattern) - return CURL_HOST_NOMATCH; + /* The wildcard must match at least one character, so the left-most + label of the hostname is at least as large as the left-most label + of the pattern. */ + if (hostname_label_end - hostname < pattern_label_end - pattern) + return CURL_HOST_NOMATCH; - prefixlen = pattern_wildcard - pattern; - suffixlen = pattern_label_end - (pattern_wildcard+1); - return Curl_raw_nequal(pattern, hostname, prefixlen) && - Curl_raw_nequal(pattern_wildcard+1, hostname_label_end - suffixlen, - suffixlen) ? - CURL_HOST_MATCH : CURL_HOST_NOMATCH; + prefixlen = pattern_wildcard - pattern; + suffixlen = pattern_label_end - (pattern_wildcard + 1); + return Curl_raw_nequal(pattern, hostname, prefixlen) && + Curl_raw_nequal(pattern_wildcard + 1, + hostname_label_end - suffixlen, suffixlen) + ? CURL_HOST_MATCH + : CURL_HOST_NOMATCH; } -static int Curl_cert_hostcheck(const char *match_pattern, const char *hostname) -{ - char *matchp; - char *hostp; - int res = 0; - if(!match_pattern || !*match_pattern || - !hostname || !*hostname) /* sanity check */ - ; - else { - matchp = strdup(match_pattern); - if(matchp) { - hostp = strdup(hostname); - if(hostp) { - if(hostmatch(hostp, matchp) == CURL_HOST_MATCH) - res= 1; - free(hostp); - } - free(matchp); - } - } +static int Curl_cert_hostcheck(const char* match_pattern, + const char* hostname) { + char* matchp; + char* hostp; + int res = 0; + if (!match_pattern || !*match_pattern || !hostname || + !*hostname) /* sanity check */ + ; + else { + matchp = strdup(match_pattern); + if (matchp) { + hostp = strdup(hostname); + if (hostp) { + if (hostmatch(hostp, matchp) == CURL_HOST_MATCH) res = 1; + free(hostp); + } + free(matchp); + } + } - return res; + return res; } // @@ -275,14 +269,14 @@ namespace ZNC_iSECPartners { * Helper functions to perform basic hostname validation using OpenSSL. * * Please read "everything-you-wanted-to-know-about-openssl.pdf" before - * attempting to use this code. This whitepaper describes how the code works, + * attempting to use this code. This whitepaper describes how the code works, * how it should be used, and what its limitations are. * * Author: Alban Diquet * License: See LICENSE * */ - + typedef enum { MatchFound, MatchNotFound, @@ -301,20 +295,23 @@ typedef enum { * Returns MalformedCertificate if the Common Name had a NUL character embedded in it. * Returns Error if the Common Name could not be extracted. */ -static HostnameValidationResult matches_common_name(const char *hostname, const X509 *server_cert) { +static HostnameValidationResult matches_common_name(const char* hostname, + const X509* server_cert) { int common_name_loc = -1; - X509_NAME_ENTRY *common_name_entry = nullptr; - ASN1_STRING *common_name_asn1 = nullptr; - char *common_name_str = nullptr; + X509_NAME_ENTRY* common_name_entry = nullptr; + ASN1_STRING* common_name_asn1 = nullptr; + char* common_name_str = nullptr; // Find the position of the CN field in the Subject field of the certificate - common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1); + common_name_loc = X509_NAME_get_index_by_NID( + X509_get_subject_name((X509*)server_cert), NID_commonName, -1); if (common_name_loc < 0) { return Error; } // Extract the CN field - common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc); + common_name_entry = X509_NAME_get_entry( + X509_get_subject_name((X509*)server_cert), common_name_loc); if (common_name_entry == nullptr) { return Error; } @@ -323,11 +320,12 @@ static HostnameValidationResult matches_common_name(const char *hostname, const common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry); if (common_name_asn1 == nullptr) { return Error; - } - common_name_str = (char *) ASN1_STRING_data(common_name_asn1); + } + common_name_str = (char*)ASN1_STRING_data(common_name_asn1); // Make sure there isn't an embedded NUL character in the CN - if (ASN1_STRING_length(common_name_asn1) != static_cast(strlen(common_name_str))) { + if (ASN1_STRING_length(common_name_asn1) != + static_cast(strlen(common_name_str))) { return MalformedCertificate; } @@ -335,13 +333,11 @@ static HostnameValidationResult matches_common_name(const char *hostname, const // Compare expected hostname with the CN if (ZNC_Curl::Curl_cert_hostcheck(common_name_str, hostname)) { return MatchFound; - } - else { + } else { return MatchNotFound; } } - /** * Tries to find a match for hostname in the certificate's Subject Alternative Name extension. * @@ -350,33 +346,35 @@ static HostnameValidationResult matches_common_name(const char *hostname, const * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it. * Returns NoSANPresent if the SAN extension was not present in the certificate. */ -static HostnameValidationResult matches_subject_alternative_name(const char *hostname, const X509 *server_cert) { +static HostnameValidationResult matches_subject_alternative_name( + const char* hostname, const X509* server_cert) { HostnameValidationResult result = MatchNotFound; int i; int san_names_nb = -1; - STACK_OF(GENERAL_NAME) *san_names = nullptr; + STACK_OF(GENERAL_NAME)* san_names = nullptr; // Try to extract the names within the SAN extension from the certificate - san_names = reinterpret_cast(X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, nullptr, nullptr)); + san_names = reinterpret_cast(X509_get_ext_d2i( + (X509*)server_cert, NID_subject_alt_name, nullptr, nullptr)); if (san_names == nullptr) { return NoSANPresent; } san_names_nb = sk_GENERAL_NAME_num(san_names); // Check each name within the extension - for (i=0; itype == GEN_DNS) { // Current name is a DNS name, let's check it - char *dns_name = (char *) ASN1_STRING_data(current_name->d.dNSName); + char* dns_name = (char*)ASN1_STRING_data(current_name->d.dNSName); // Make sure there isn't an embedded NUL character in the DNS name - if (ASN1_STRING_length(current_name->d.dNSName) != static_cast(strlen(dns_name))) { + if (ASN1_STRING_length(current_name->d.dNSName) != + static_cast(strlen(dns_name))) { result = MalformedCertificate; break; - } - else { // Compare expected hostname with the DNS name + } else { // Compare expected hostname with the DNS name DEBUG("SSLVerifyHost: Found SAN " << dns_name); if (ZNC_Curl::Curl_cert_hostcheck(dns_name, hostname)) { result = MatchFound; @@ -390,7 +388,6 @@ static HostnameValidationResult matches_subject_alternative_name(const char *hos return result; } - /** * Validates the server's identity by looking for the expected hostname in the * server's certificate. As described in RFC 6125, it first tries to find a match @@ -402,11 +399,11 @@ static HostnameValidationResult matches_subject_alternative_name(const char *hos * Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it. * Returns Error if there was an error. */ -static HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert) { +static HostnameValidationResult validate_hostname(const char* hostname, + const X509* server_cert) { HostnameValidationResult result; - if((hostname == nullptr) || (server_cert == nullptr)) - return Error; + if ((hostname == nullptr) || (server_cert == nullptr)) return Error; // First try the Subject Alternative Names extension result = matches_subject_alternative_name(hostname, server_cert); @@ -424,9 +421,11 @@ static HostnameValidationResult validate_hostname(const char *hostname, const X5 /////////////////////////////////////////////////////////////////////////// } // namespace ZNC_iSECPartners -bool ZNC_SSLVerifyHost(const CString& sHost, const X509* pCert, CString& sError) { +bool ZNC_SSLVerifyHost(const CString& sHost, const X509* pCert, + CString& sError) { DEBUG("SSLVerifyHost: checking " << sHost); - ZNC_iSECPartners::HostnameValidationResult eResult = ZNC_iSECPartners::validate_hostname(sHost.c_str(), pCert); + ZNC_iSECPartners::HostnameValidationResult eResult = + ZNC_iSECPartners::validate_hostname(sHost.c_str(), pCert); switch (eResult) { case ZNC_iSECPartners::MatchFound: DEBUG("SSLVerifyHost: verified"); @@ -446,5 +445,4 @@ bool ZNC_SSLVerifyHost(const CString& sHost, const X509* pCert, CString& sError) } } - #endif /* HAVE_LIBSSL */ diff --git a/src/Server.cpp b/src/Server.cpp index 82e49a92..93c0c09c 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -16,13 +16,12 @@ #include -CServer::CServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) - : m_sName(sName), - m_uPort((uPort) ? uPort : (unsigned short)6667), - m_sPass(sPass), - m_bSSL(bSSL) -{ -} +CServer::CServer(const CString& sName, unsigned short uPort, + const CString& sPass, bool bSSL) + : m_sName(sName), + m_uPort((uPort) ? uPort : (unsigned short)6667), + m_sPass(sPass), + m_bSSL(bSSL) {} CServer::~CServer() {} @@ -37,5 +36,6 @@ bool CServer::IsSSL() const { return m_bSSL; } CString CServer::GetString(bool bIncludePassword) const { return m_sName + " " + CString(m_bSSL ? "+" : "") + CString(m_uPort) + - CString(bIncludePassword ? (m_sPass.empty() ? "" : " " + m_sPass) : ""); + CString(bIncludePassword ? (m_sPass.empty() ? "" : " " + m_sPass) + : ""); } diff --git a/src/Socket.cpp b/src/Socket.cpp index d316bcdc..678f8d86 100644 --- a/src/Socket.cpp +++ b/src/Socket.cpp @@ -28,19 +28,31 @@ #endif #ifdef HAVE_LIBSSL -// Copypasted from https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28default.29 at 22 Dec 2014 +// Copypasted from +// https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28default.29 +// at 22 Dec 2014 static CString ZNC_DefaultCipher() { - return - "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" - "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:" - "ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:" - "ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" - "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:" - "AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"; + return "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-" + "RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" + "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" + "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:" + "ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-" + "SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:" + "ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:" + "DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" + "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-" + "SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:" + "AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!" + "RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!" + "KRB5-DES-CBC3-SHA"; } #endif -CZNCSock::CZNCSock(int timeout) : Csock(timeout), m_sHostToVerifySSL(""), m_ssTrustedFingerprints(), m_ssCertVerificationErrors() { +CZNCSock::CZNCSock(int timeout) + : Csock(timeout), + m_sHostToVerifySSL(""), + m_ssTrustedFingerprints(), + m_ssCertVerificationErrors() { #ifdef HAVE_LIBSSL DisableSSLCompression(); FollowSSLCipherServerPreference(); @@ -53,7 +65,11 @@ CZNCSock::CZNCSock(int timeout) : Csock(timeout), m_sHostToVerifySSL(""), m_ssTr #endif } -CZNCSock::CZNCSock(const CString& sHost, u_short port, int timeout) : Csock(sHost, port, timeout), m_sHostToVerifySSL(""), m_ssTrustedFingerprints(), m_ssCertVerificationErrors() { +CZNCSock::CZNCSock(const CString& sHost, u_short port, int timeout) + : Csock(sHost, port, timeout), + m_sHostToVerifySSL(""), + m_ssTrustedFingerprints(), + m_ssCertVerificationErrors() { #ifdef HAVE_LIBSSL DisableSSLCompression(); FollowSSLCipherServerPreference(); @@ -61,15 +77,15 @@ CZNCSock::CZNCSock(const CString& sHost, u_short port, int timeout) : Csock(sHos #endif } -unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const { +unsigned int CSockManager::GetAnonConnectionCount(const CString& sIP) const { const_iterator it; unsigned int ret = 0; for (it = begin(); it != end(); ++it) { - Csock *pSock = *it; + Csock* pSock = *it; // Logged in CClients have "USR::" as their sockname - if (pSock->GetType() == Csock::INBOUND && pSock->GetRemoteIP() == sIP - && !pSock->GetSockName().StartsWith("USR::")) { + if (pSock->GetType() == Csock::INBOUND && pSock->GetRemoteIP() == sIP && + !pSock->GetSockName().StartsWith("USR::")) { ret++; } } @@ -79,17 +95,19 @@ unsigned int CSockManager::GetAnonConnectionCount(const CString &sIP) const { return ret; } -int CZNCSock::ConvertAddress(const struct sockaddr_storage* pAddr, socklen_t iAddrLen, CString& sIP, u_short* piPort) const { +int CZNCSock::ConvertAddress(const struct sockaddr_storage* pAddr, + socklen_t iAddrLen, CString& sIP, + u_short* piPort) const { int ret = Csock::ConvertAddress(pAddr, iAddrLen, sIP, piPort); - if (ret == 0) - sIP.TrimPrefix("::ffff:"); + if (ret == 0) sIP.TrimPrefix("::ffff:"); return ret; } #ifdef HAVE_LIBSSL -int CZNCSock::VerifyPeerCertificate(int iPreVerify, X509_STORE_CTX * pStoreCTX) { +int CZNCSock::VerifyPeerCertificate(int iPreVerify, X509_STORE_CTX* pStoreCTX) { if (iPreVerify == 0) { - m_ssCertVerificationErrors.insert(X509_verify_cert_error_string(X509_STORE_CTX_get_error(pStoreCTX))); + m_ssCertVerificationErrors.insert( + X509_verify_cert_error_string(X509_STORE_CTX_get_error(pStoreCTX))); } return 1; } @@ -122,7 +140,8 @@ void CZNCSock::SSLHandShakeFinished() { } DEBUG(GetSockName() + ": Bad cert"); CString sErrorMsg = "Invalid SSL certificate: "; - sErrorMsg += CString(", ").Join(begin(m_ssCertVerificationErrors), end(m_ssCertVerificationErrors)); + sErrorMsg += CString(", ").Join(begin(m_ssCertVerificationErrors), + end(m_ssCertVerificationErrors)); CallSockError(errnoBadSSLCert, sErrorMsg); Close(); } @@ -143,15 +162,16 @@ CString CZNCSock::GetSSLPeerFingerprint() const { DEBUG(GetSockName() + ": GetSSLPeerFingerprint: Anonymous cert"); return ""; } - unsigned char buf[256/8]; - unsigned int _32 = 256/8; + unsigned char buf[256 / 8]; + unsigned int _32 = 256 / 8; int iSuccess = X509_digest(pCert, evp, buf, &_32); X509_free(pCert); if (!iSuccess) { DEBUG(GetSockName() + ": GetSSLPeerFingerprint: Couldn't find digest"); return ""; } - return CString(reinterpret_cast(buf), sizeof buf).Escape_n(CString::EASCII, CString::EHEXCOLON); + return CString(reinterpret_cast(buf), sizeof buf) + .Escape_n(CString::EASCII, CString::EHEXCOLON); #else return ""; #endif @@ -159,10 +179,8 @@ CString CZNCSock::GetSSLPeerFingerprint() const { #ifdef HAVE_PTHREAD class CSockManager::CThreadMonitorFD : public CSMonitorFD { -public: - CThreadMonitorFD() { - Add(CThreadPool::Get().getReadFD(), ECT_Read); - } + public: + CThreadMonitorFD() { Add(CThreadPool::Get().getReadFD(), ECT_Read); } bool FDsThatTriggered(const std::map& miiReadyFds) override { if (miiReadyFds.find(CThreadPool::Get().getReadFD())->second) { @@ -193,7 +211,7 @@ void CSockManager::CDNSJob::runThread() { iRes = ETIMEDOUT; break; } - sleep(5); // wait 5 seconds before next try + sleep(5); // wait 5 seconds before next try } } @@ -203,7 +221,8 @@ void CSockManager::CDNSJob::runMain() { if (this->aiResult) { DEBUG("And aiResult is not nullptr..."); } - this->aiResult = nullptr; // just for case. Maybe to call freeaddrinfo()? + this->aiResult = + nullptr; // just for case. Maybe to call freeaddrinfo()? } pManager->SetTDNSThreadFinished(this->task, this->bBind, this->aiResult); } @@ -212,22 +231,25 @@ void CSockManager::StartTDNSThread(TDNSTask* task, bool bBind) { CString sHostname = bBind ? task->sBindhost : task->sHostname; CDNSJob* arg = new CDNSJob; arg->sHostname = sHostname; - arg->task = task; - arg->bBind = bBind; - arg->pManager = this; + arg->task = task; + arg->bBind = bBind; + arg->pManager = this; CThreadPool::Get().addJob(arg); } -static CString RandomFromSet(const SCString& sSet, std::default_random_engine& gen) { +static CString RandomFromSet(const SCString& sSet, + std::default_random_engine& gen) { std::uniform_int_distribution<> distr(0, sSet.size() - 1); auto it = sSet.cbegin(); std::advance(it, distr(gen)); return *it; } -static std::tuple RandomFrom2SetsWithBias(const SCString& ss4, const SCString& ss6, std::default_random_engine& gen) { - // It's not quite what RFC says how to choose between IPv4 and IPv6, but proper way is harder to implement. +static std::tuple RandomFrom2SetsWithBias( + const SCString& ss4, const SCString& ss6, std::default_random_engine& gen) { + // It's not quite what RFC says how to choose between IPv4 and IPv6, but + // proper way is harder to implement. // It would require to maintain some state between Csock objects. bool bUseIPv6; if (ss4.empty()) { @@ -243,7 +265,8 @@ static std::tuple RandomFrom2SetsWithBias(const SCString& ss4, co return std::make_tuple(RandomFromSet(sSet, gen), bUseIPv6); } -void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult) { +void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, + addrinfo* aiResult) { if (bBind) { task->aiBind = aiResult; task->bDoneBind = true; @@ -262,7 +285,8 @@ void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* a SCString ssTargets6; for (addrinfo* ai = task->aiTarget; ai; ai = ai->ai_next) { char s[INET6_ADDRSTRLEN] = {}; - getnameinfo(ai->ai_addr, ai->ai_addrlen, s, sizeof(s), nullptr, 0, NI_NUMERICHOST); + getnameinfo(ai->ai_addr, ai->ai_addrlen, s, sizeof(s), nullptr, 0, + NI_NUMERICHOST); switch (ai->ai_family) { case AF_INET: ssTargets4.insert(s); @@ -278,7 +302,8 @@ void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* a SCString ssBinds6; for (addrinfo* ai = task->aiBind; ai; ai = ai->ai_next) { char s[INET6_ADDRSTRLEN] = {}; - getnameinfo(ai->ai_addr, ai->ai_addrlen, s, sizeof(s), nullptr, 0, NI_NUMERICHOST); + getnameinfo(ai->ai_addr, ai->ai_addrlen, s, sizeof(s), nullptr, 0, + NI_NUMERICHOST); switch (ai->ai_family) { case AF_INET: ssBinds4.insert(s); @@ -303,7 +328,8 @@ void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* a throw "Can't resolve server hostname"; } else if (task->sBindhost.empty()) { // Choose random target - std::tie(sTargetHost, std::ignore) = RandomFrom2SetsWithBias(ssTargets4, ssTargets6, gen); + std::tie(sTargetHost, std::ignore) = + RandomFrom2SetsWithBias(ssTargets4, ssTargets6, gen); } else if (ssBinds4.empty() && ssBinds6.empty()) { throw "Can't resolve bind hostname. Try /znc ClearBindHost and /znc ClearUserBindHost"; } else if (ssBinds4.empty()) { @@ -325,14 +351,17 @@ void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* a } else { // Choose random target bool bUseIPv6; - std::tie(sTargetHost, bUseIPv6) = RandomFrom2SetsWithBias(ssTargets4, ssTargets6, gen); + std::tie(sTargetHost, bUseIPv6) = + RandomFrom2SetsWithBias(ssTargets4, ssTargets6, gen); // Choose random bindhost matching chosen target const SCString& ssBinds = bUseIPv6 ? ssBinds6 : ssBinds4; sBindhost = RandomFromSet(ssBinds, gen); } - DEBUG("TDNS: " << task->sSockName << ", connecting to [" << sTargetHost << "] using bindhost [" << sBindhost << "]"); - FinishConnect(sTargetHost, task->iPort, task->sSockName, task->iTimeout, task->bSSL, sBindhost, task->pcSock); + DEBUG("TDNS: " << task->sSockName << ", connecting to [" << sTargetHost + << "] using bindhost [" << sBindhost << "]"); + FinishConnect(sTargetHost, task->iPort, task->sSockName, task->iTimeout, + task->bSSL, sBindhost, task->pcSock); } catch (const char* s) { DEBUG(task->sSockName << ", dns resolving error: " << s); task->pcSock->SetSockName(task->sSockName); @@ -350,23 +379,25 @@ CSockManager::CSockManager() { #endif } -CSockManager::~CSockManager() { -} +CSockManager::~CSockManager() {} -void CSockManager::Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) { +void CSockManager::Connect(const CString& sHostname, u_short iPort, + const CString& sSockName, int iTimeout, bool bSSL, + const CString& sBindHost, CZNCSock* pcSock) { if (pcSock) { pcSock->SetHostToVerifySSL(sHostname); } #ifdef HAVE_THREADED_DNS - DEBUG("TDNS: initiating resolving of [" << sHostname << "] and bindhost [" << sBindHost << "]"); + DEBUG("TDNS: initiating resolving of [" << sHostname << "] and bindhost [" + << sBindHost << "]"); TDNSTask* task = new TDNSTask; - task->sHostname = sHostname; - task->iPort = iPort; - task->sSockName = sSockName; - task->iTimeout = iTimeout; - task->bSSL = bSSL; - task->sBindhost = sBindHost; - task->pcSock = pcSock; + task->sHostname = sHostname; + task->iPort = iPort; + task->sSockName = sSockName; + task->iTimeout = iTimeout; + task->bSSL = bSSL; + task->sBindhost = sBindHost; + task->pcSock = pcSock; if (sBindHost.empty()) { task->bDoneBind = true; } else { @@ -375,11 +406,15 @@ void CSockManager::Connect(const CString& sHostname, u_short iPort, const CStrin StartTDNSThread(task, false); #else /* HAVE_THREADED_DNS */ // Just let Csocket handle DNS itself - FinishConnect(sHostname, iPort, sSockName, iTimeout, bSSL, sBindHost, pcSock); + FinishConnect(sHostname, iPort, sSockName, iTimeout, bSSL, sBindHost, + pcSock); #endif } -void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) { +void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, + const CString& sSockName, int iTimeout, + bool bSSL, const CString& sBindHost, + CZNCSock* pcSock) { CSConnection C(sHostname, iPort, iTimeout); C.SetSockName(sSockName); @@ -396,7 +431,6 @@ void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, const TSocketManager::Connect(C, pcSock); } - /////////////////// CSocket /////////////////// CSocket::CSocket(CModule* pModule) : CZNCSock(), m_pModule(pModule) { if (m_pModule) m_pModule->AddSocket(this); @@ -404,14 +438,16 @@ CSocket::CSocket(CModule* pModule) : CZNCSock(), m_pModule(pModule) { SetMaxBufferThreshold(10240); } -CSocket::CSocket(CModule* pModule, const CString& sHostname, unsigned short uPort, int iTimeout) : CZNCSock(sHostname, uPort, iTimeout), m_pModule(pModule) { +CSocket::CSocket(CModule* pModule, const CString& sHostname, + unsigned short uPort, int iTimeout) + : CZNCSock(sHostname, uPort, iTimeout), m_pModule(pModule) { if (m_pModule) m_pModule->AddSocket(this); EnableReadLine(); SetMaxBufferThreshold(10240); } CSocket::~CSocket() { - CUser *pUser = nullptr; + CUser* pUser = nullptr; CIRCNetwork* pNetwork = nullptr; // CWebSock could cause us to have a nullptr pointer here @@ -421,10 +457,12 @@ CSocket::~CSocket() { m_pModule->UnlinkSocket(this); } - if (pNetwork && m_pModule && (m_pModule->GetType() == CModInfo::NetworkModule)) { + if (pNetwork && m_pModule && + (m_pModule->GetType() == CModInfo::NetworkModule)) { pNetwork->AddBytesWritten(GetBytesWritten()); pNetwork->AddBytesRead(GetBytesRead()); - } else if (pUser && m_pModule && (m_pModule->GetType() == CModInfo::UserModule)) { + } else if (pUser && m_pModule && + (m_pModule->GetType() == CModInfo::UserModule)) { pUser->AddBytesWritten(GetBytesWritten()); pUser->AddBytesRead(GetBytesRead()); } else { @@ -435,12 +473,15 @@ CSocket::~CSocket() { void CSocket::ReachedMaxBuffer() { DEBUG(GetSockName() << " == ReachedMaxBuffer()"); - if (m_pModule) m_pModule->PutModule("Some socket reached its max buffer limit and was closed!"); + if (m_pModule) + m_pModule->PutModule( + "Some socket reached its max buffer limit and was closed!"); Close(); } void CSocket::SockError(int iErrno, const CString& sDescription) { - DEBUG(GetSockName() << " == SockError(" << sDescription << ", " << strerror(iErrno) << ")"); + DEBUG(GetSockName() << " == SockError(" << sDescription << ", " + << strerror(iErrno) << ")"); if (iErrno == EMFILE) { // We have too many open fds, this can cause a busy loop. Close(); @@ -451,9 +492,12 @@ bool CSocket::ConnectionFrom(const CString& sHost, unsigned short uPort) { return CZNC::Get().AllowConnectionFrom(sHost); } -bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, unsigned int uTimeout) { +bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, + unsigned int uTimeout) { if (!m_pModule) { - DEBUG("ERROR: CSocket::Connect called on instance without m_pModule handle!"); + DEBUG( + "ERROR: CSocket::Connect called on instance without m_pModule " + "handle!"); return false; } @@ -476,13 +520,16 @@ bool CSocket::Connect(const CString& sHostname, unsigned short uPort, bool bSSL, sSockName = GetSockName(); } - m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, bSSL, sBindHost, this); + m_pModule->GetManager()->Connect(sHostname, uPort, sSockName, uTimeout, + bSSL, sBindHost, this); return true; } bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) { if (!m_pModule) { - DEBUG("ERROR: CSocket::Listen called on instance without m_pModule handle!"); + DEBUG( + "ERROR: CSocket::Listen called on instance without m_pModule " + "handle!"); return false; } @@ -497,22 +544,22 @@ bool CSocket::Listen(unsigned short uPort, bool bSSL, unsigned int uTimeout) { sSockName = GetSockName(); } - return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, this); + return m_pModule->GetManager()->ListenAll(uPort, sSockName, bSSL, SOMAXCONN, + this); } CModule* CSocket::GetModule() const { return m_pModule; } /////////////////// !CSocket /////////////////// #ifdef HAVE_ICU -void CIRCSocket::IcuExtToUCallback( - UConverterToUnicodeArgs* toArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode* err) { +void CIRCSocket::IcuExtToUCallback(UConverterToUnicodeArgs* toArgs, + const char* codeUnits, int32_t length, + UConverterCallbackReason reason, + UErrorCode* err) { // From http://www.mirc.com/colors.html // The Control+O key combination in mIRC inserts ascii character 15, - // which turns off all previous attributes, including color, bold, underline, and italics. + // which turns off all previous attributes, including color, bold, + // underline, and italics. // // \x02 bold // \x03 mIRC-compatible color @@ -525,8 +572,10 @@ void CIRCSocket::IcuExtToUCallback( // Also see http://www.visualirc.net/tech-attrs.php // // Keep in sync with CUser::AddTimestamp and CIRCSocket::IcuExtFromUCallback - static const std::set scAllowedChars = {'\x02', '\x03', '\x04', '\x0F', '\x12', '\x16', '\x1D', '\x1F'}; - if (reason == UCNV_ILLEGAL && length == 1 && scAllowedChars.count(*codeUnits)) { + static const std::set scAllowedChars = { + '\x02', '\x03', '\x04', '\x0F', '\x12', '\x16', '\x1D', '\x1F'}; + if (reason == UCNV_ILLEGAL && length == 1 && + scAllowedChars.count(*codeUnits)) { *err = U_ZERO_ERROR; UChar c = *codeUnits; ucnv_cbToUWriteUChars(toArgs, &c, 1, 0, err); @@ -535,21 +584,21 @@ void CIRCSocket::IcuExtToUCallback( Csock::IcuExtToUCallback(toArgs, codeUnits, length, reason, err); } -void CIRCSocket::IcuExtFromUCallback( - UConverterFromUnicodeArgs* fromArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode* err) { +void CIRCSocket::IcuExtFromUCallback(UConverterFromUnicodeArgs* fromArgs, + const UChar* codeUnits, int32_t length, + UChar32 codePoint, + UConverterCallbackReason reason, + UErrorCode* err) { // See comment in CIRCSocket::IcuExtToUCallback - static const std::set scAllowedChars = {0x02, 0x03, 0x04, 0x0F, 0x12, 0x16, 0x1D, 0x1F}; + static const std::set scAllowedChars = {0x02, 0x03, 0x04, 0x0F, + 0x12, 0x16, 0x1D, 0x1F}; if (reason == UCNV_ILLEGAL && scAllowedChars.count(codePoint)) { *err = U_ZERO_ERROR; char c = codePoint; ucnv_cbFromUWriteBytes(fromArgs, &c, 1, 0, err); return; } - Csock::IcuExtFromUCallback(fromArgs, codeUnits, length, codePoint, reason, err); + Csock::IcuExtFromUCallback(fromArgs, codeUnits, length, codePoint, reason, + err); } #endif diff --git a/src/Template.cpp b/src/Template.cpp index a8f39138..1849598e 100644 --- a/src/Template.cpp +++ b/src/Template.cpp @@ -42,7 +42,7 @@ CTemplate* CTemplateLoopContext::GetRow(unsigned int uIndex) { if (uIndex < uSize) { if (m_bReverse) { - return (*m_pvRows)[uSize - uIndex -1]; + return (*m_pvRows)[uSize - uIndex - 1]; } else { return (*m_pvRows)[uIndex]; } @@ -55,26 +55,31 @@ CString CTemplateLoopContext::GetValue(const CString& sName, bool bFromIf) { CTemplate* pTemplate = GetCurRow(); if (!pTemplate) { - DEBUG("Loop [" + GetName() + "] has no row index [" + CString(GetRowIndex()) + "]"); + DEBUG("Loop [" + GetName() + "] has no row index [" + + CString(GetRowIndex()) + "]"); return ""; } if (sName.Equals("__ID__")) { - return CString(GetRowIndex() +1); + return CString(GetRowIndex() + 1); } else if (sName.Equals("__COUNT__")) { return CString(GetRowCount()); } else if (sName.Equals("__ODD__")) { - return ((GetRowIndex() %2) ? "" : "1"); + return ((GetRowIndex() % 2) ? "" : "1"); } else if (sName.Equals("__EVEN__")) { - return ((GetRowIndex() %2) ? "1" : ""); + return ((GetRowIndex() % 2) ? "1" : ""); } else if (sName.Equals("__FIRST__")) { return ((GetRowIndex() == 0) ? "1" : ""); } else if (sName.Equals("__LAST__")) { - return ((GetRowIndex() == m_pvRows->size() -1) ? "1" : ""); + return ((GetRowIndex() == m_pvRows->size() - 1) ? "1" : ""); } else if (sName.Equals("__OUTER__")) { - return ((GetRowIndex() == 0 || GetRowIndex() == m_pvRows->size() -1) ? "1" : ""); + return ((GetRowIndex() == 0 || GetRowIndex() == m_pvRows->size() - 1) + ? "1" + : ""); } else if (sName.Equals("__INNER__")) { - return ((GetRowIndex() == 0 || GetRowIndex() == m_pvRows->size() -1) ? "" : "1"); + return ((GetRowIndex() == 0 || GetRowIndex() == m_pvRows->size() - 1) + ? "" + : "1"); } return pTemplate->GetValue(sName, bFromIf); @@ -99,7 +104,7 @@ void CTemplate::Init() { CString sPath(CConfig::GetValue("WebFilesPath")); if (!sPath.empty()) { - SetPath(sPath); + SetPath(sPath); } */ @@ -109,7 +114,7 @@ void CTemplate::Init() { CString CTemplate::ExpandFile(const CString& sFilename, bool bFromInc) { /*if (sFilename.StartsWith("/") || sFilename.StartsWith("./")) { - return sFilename; + return sFilename; }*/ CString sFile(ResolveLiteral(sFilename).TrimLeft_n("/")); @@ -118,7 +123,8 @@ CString CTemplate::ExpandFile(const CString& sFilename, bool bFromInc) { CString& sRoot = it.first; CString sFilePath(CDir::ChangeDir(sRoot, sFile)); - // Make sure path ends with a slash because "/foo/pub*" matches "/foo/public_keep_out/" but "/foo/pub/*" doesn't + // Make sure path ends with a slash because "/foo/pub*" matches + // "/foo/public_keep_out/" but "/foo/pub/*" doesn't if (!sRoot.empty() && !sRoot.EndsWith("/")) { sRoot += "/"; } @@ -133,7 +139,8 @@ CString CTemplate::ExpandFile(const CString& sFilename, bool bFromInc) { DEBUG(" Found [" + sFilePath + "]"); return sFilePath; } else { - DEBUG("\t\tOutside of root [" + sFilePath + "] !~ [" + sRoot + "]"); + DEBUG("\t\tOutside of root [" + sFilePath + "] !~ [" + sRoot + + "]"); } } } @@ -143,10 +150,12 @@ CString CTemplate::ExpandFile(const CString& sFilename, bool bFromInc) { DEBUG("Unable to find [" + sFile + "] using the current directory"); break; case 1: - DEBUG("Unable to find [" + sFile + "] in the defined path [" + m_lsbPaths.begin()->first + "]"); + DEBUG("Unable to find [" + sFile + "] in the defined path [" + + m_lsbPaths.begin()->first + "]"); break; default: - DEBUG("Unable to find [" + sFile + "] in any of the " + CString(m_lsbPaths.size()) + " defined paths"); + DEBUG("Unable to find [" + sFile + "] in any of the " + + CString(m_lsbPaths.size()) + " defined paths"); } return ""; @@ -182,20 +191,20 @@ void CTemplate::AppendPath(const CString& sPath, bool bIncludesOnly) { } void CTemplate::RemovePath(const CString& sPath) { - DEBUG("CTemplate::RemovePath(" + sPath + ") == [" + CDir::ChangeDir("./", sPath + "/") + "]"); + DEBUG("CTemplate::RemovePath(" + sPath + ") == [" + + CDir::ChangeDir("./", sPath + "/") + "]"); for (const auto& it : m_lsbPaths) { if (it.first == sPath) { m_lsbPaths.remove(it); - RemovePath(sPath); // @todo probably shouldn't use recursion, being lazy + RemovePath( + sPath); // @todo probably shouldn't use recursion, being lazy return; } } } -void CTemplate::ClearPaths() { - m_lsbPaths.clear(); -} +void CTemplate::ClearPaths() { m_lsbPaths.clear(); } bool CTemplate::SetFile(const CString& sFileName) { m_sFileName = ExpandFile(sFileName, false); @@ -218,10 +227,12 @@ bool CTemplate::SetFile(const CString& sFileName) { class CLoopSorter { CString m_sType; -public: + + public: CLoopSorter(const CString& sType) : m_sType(sType) {} bool operator()(CTemplate* pTemplate1, CTemplate* pTemplate2) { - return (pTemplate1->GetValue(m_sType, false) < pTemplate2->GetValue(m_sType, false)); + return (pTemplate1->GetValue(m_sType, false) < + pTemplate2->GetValue(m_sType, false)); } }; @@ -255,7 +266,7 @@ vector* CTemplate::GetLoop(const CString& sName) { } } - map >::iterator it = m_mvLoops.find(sName); + map>::iterator it = m_mvLoops.find(sName); if (it != m_mvLoops.end()) { return &(it->second); @@ -274,9 +285,7 @@ bool CTemplate::PrintString(CString& sRet) { return bRet; } -bool CTemplate::Print(ostream& oOut) { - return Print(m_sFileName, oOut); -} +bool CTemplate::Print(ostream& oOut) { return Print(m_sFileName, oOut); } bool CTemplate::Print(const CString& sFileName, ostream& oOut) { if (sFileName.empty()) { @@ -328,28 +337,30 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { sOutput += sLine.substr(0, iPos); } - sLine = sLine.substr(iPos +2); + sLine = sLine.substr(iPos + 2); CString::size_type iPos2 = sLine.find("?>"); // Make sure our tmpl tag is ended properly if (iPos2 == CString::npos) { - DEBUG("Template tag not ended properly in file [" + sFileName + "] [ 1) { @@ -390,7 +401,8 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { for (const CString& sArg : vsArgs) { if (sArg.StartsWith("ESC=")) { - eEscape = CString::ToEscape(sArg.LeftChomp_n(4)); + eEscape = + CString::ToEscape(sArg.LeftChomp_n(4)); } else { CString sValue = GetValue(sArg); @@ -425,7 +437,10 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { break; } else { - DEBUG("[" + sFileName + ":" + CString(uCurPos - iPos2 -4) + "] must be used inside of a loop!"); + DEBUG("[" + sFileName + ":" + + CString(uCurPos - iPos2 - 4) + + "] must be used inside of a " + "loop!"); } } else if (sAction.Equals("BREAK")) { // break from loop @@ -437,44 +452,62 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { break; } else { - DEBUG("[" + sFileName + ":" + CString(uCurPos - iPos2 -4) + "] must be used inside of a loop!"); + DEBUG( + "[" + sFileName + ":" + + CString(uCurPos - iPos2 - 4) + + "] must be used inside of a loop!"); } } else if (sAction.Equals("EXIT")) { bExit = true; } else if (sAction.Equals("DEBUG")) { - DEBUG("CTemplate DEBUG [" + sFileName + "@" + CString(uCurPos - iPos2 -4) + "b] -> [" + sArgs + "]"); + DEBUG("CTemplate DEBUG [" + sFileName + "@" + + CString(uCurPos - iPos2 - 4) + "b] -> [" + sArgs + + "]"); } else if (sAction.Equals("LOOP")) { CTemplateLoopContext* pContext = GetCurLoopContext(); - if (!pContext || pContext->GetFilePosition() != uCurPos) { - // we are at a brand new loop (be it new or a first pass at an inner loop) + if (!pContext || + pContext->GetFilePosition() != uCurPos) { + // we are at a brand new loop (be it new or a first + // pass at an inner loop) CString sLoopName = sArgs.Token(0); bool bReverse = (sArgs.Token(1).Equals("REVERSE")); bool bSort = (sArgs.Token(1).StartsWith("SORT")); vector* pvLoop = GetLoop(sLoopName); - if (bSort && pvLoop != nullptr && pvLoop->size() > 1) { + if (bSort && pvLoop != nullptr && + pvLoop->size() > 1) { CString sKey; - if(sArgs.Token(1).TrimPrefix_n("SORT").StartsWith("ASC=")) { - sKey = sArgs.Token(1).TrimPrefix_n("SORTASC="); - } else if(sArgs.Token(1).TrimPrefix_n("SORT").StartsWith("DESC=")) { - sKey = sArgs.Token(1).TrimPrefix_n("SORTDESC="); + if (sArgs.Token(1) + .TrimPrefix_n("SORT") + .StartsWith("ASC=")) { + sKey = + sArgs.Token(1).TrimPrefix_n("SORTASC="); + } else if (sArgs.Token(1) + .TrimPrefix_n("SORT") + .StartsWith("DESC=")) { + sKey = sArgs.Token(1) + .TrimPrefix_n("SORTDESC="); bReverse = true; } if (!sKey.empty()) { - std::sort(pvLoop->begin(), pvLoop->end(), CLoopSorter(sKey)); + std::sort(pvLoop->begin(), pvLoop->end(), + CLoopSorter(sKey)); } } if (pvLoop) { - // If we found data for this loop, add it to our context vector - //unsigned long uBeforeLoopTag = uCurPos - iPos2 - 4; + // If we found data for this loop, add it to our + // context vector + // unsigned long uBeforeLoopTag = uCurPos - + // iPos2 - 4; unsigned long uAfterLoopTag = uCurPos; - for (CString::size_type t = 0; t < sLine.size(); t++) { + for (CString::size_type t = 0; t < sLine.size(); + t++) { char c = sLine[t]; if (c == '\r' || c == '\n') { uAfterLoopTag++; @@ -483,8 +516,12 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { } } - m_vLoopContexts.push_back(new CTemplateLoopContext(uAfterLoopTag, sLoopName, bReverse, pvLoop)); - } else { // If we don't have data, just skip this loop and everything inside + m_vLoopContexts.push_back( + new CTemplateLoopContext(uAfterLoopTag, + sLoopName, + bReverse, pvLoop)); + } else { // If we don't have data, just skip this + // loop and everything inside uSkip++; } } @@ -535,13 +572,15 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { if (uSkip) { uSkip--; } else { - // We are at the end of the loop so we need to inc the index + // We are at the end of the loop so we need to inc the + // index CTemplateLoopContext* pContext = GetCurLoopContext(); if (pContext) { pContext->IncRowIndex(); - // If we didn't go out of bounds we need to seek back to the top of our loop + // If we didn't go out of bounds we need to seek + // back to the top of our loop if (!bLoopBreak && pContext->GetCurRow()) { uCurPos = pContext->GetFilePosition(); uFilePos = uCurPos; @@ -570,7 +609,8 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { if (!bValidLastIf && uSkip == 1) { CString sArg = sArgs.Token(0); - if (sArg.empty() || (sArg.Equals("IF") && ValidIf(sArgs.Token(1, true)))) { + if (sArg.empty() || (sArg.Equals("IF") && + ValidIf(sArgs.Token(1, true)))) { uSkip = 0; bValidLastIf = true; } @@ -579,14 +619,18 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { } } else if (bNotFound) { // Unknown tag that isn't being skipped... - vector >& vspTagHandlers = GetTagHandlers(); + vector>& + vspTagHandlers = GetTagHandlers(); - if (!vspTagHandlers.empty()) { // @todo this should go up to the top to grab handlers + if (!vspTagHandlers.empty()) { // @todo this should go up + // to the top to grab + // handlers CTemplate* pTmpl = GetCurTemplate(); CString sCustomOutput; for (const auto& spTagHandler : vspTagHandlers) { - if (spTagHandler->HandleTag(*pTmpl, sAction, sArgs, sCustomOutput)) { + if (spTagHandler->HandleTag(*pTmpl, sAction, sArgs, + sCustomOutput)) { sOutput += sCustomOutput; bNotFound = false; break; @@ -602,7 +646,8 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { continue; } - DEBUG("Malformed tag on line " + CString(uLineNum) + " of [" << File.GetLongName() + "]"); + DEBUG("Malformed tag on line " + CString(uLineNum) + " of [" + << File.GetLongName() + "]"); DEBUG("--------------- [" + sLine + "]"); } @@ -614,10 +659,11 @@ bool CTemplate::Print(const CString& sFileName, ostream& oOut) { } } - if (!bFoundATag || bTmplLoopHasData || sOutput.find_first_not_of(" \t\r\n") != CString::npos) { + if (!bFoundATag || bTmplLoopHasData || + sOutput.find_first_not_of(" \t\r\n") != CString::npos) { if (bInSetBlock) { CString sName = sSetBlockVar.Token(0); - //CString sValue = sSetBlockVar.Token(1, true); + // CString sValue = sSetBlockVar.Token(1, true); (*this)[sName] += sOutput; } else { oOut << sOutput; @@ -653,7 +699,7 @@ CTemplateLoopContext* CTemplate::GetCurLoopContext() { bool CTemplate::ValidIf(const CString& sArgs) { CString sArgStr = sArgs; - //sArgStr.Replace(" ", "", "\"", "\"", true); + // sArgStr.Replace(" ", "", "\"", "\"", true); sArgStr.Replace(" &&", "&&", "\"", "\"", false); sArgStr.Replace("&& ", "&&", "\"", "\"", false); sArgStr.Replace(" ||", "||", "\"", "\"", false); @@ -662,7 +708,8 @@ bool CTemplate::ValidIf(const CString& sArgs) { CString::size_type uOrPos = sArgStr.find("||"); CString::size_type uAndPos = sArgStr.find("&&"); - while (uOrPos != CString::npos || uAndPos != CString::npos || !sArgStr.empty()) { + while (uOrPos != CString::npos || uAndPos != CString::npos || + !sArgStr.empty()) { bool bAnd = false; if (uAndPos < uOrPos) { @@ -783,12 +830,14 @@ CString CTemplate::GetValue(const CString& sArgs, bool bFromIf) { CString sRest = sArgs.Token(1, true); CString sRet; - while (sRest.Replace(" =", "=", "\"", "\"")) {} - while (sRest.Replace("= ", "=", "\"", "\"")) {} + while (sRest.Replace(" =", "=", "\"", "\"")) { + } + while (sRest.Replace("= ", "=", "\"", "\"")) { + } VCString vArgs; MCString msArgs; - //sRest.Split(" ", vArgs, false, "\"", "\""); + // sRest.Split(" ", vArgs, false, "\"", "\""); sRest.QuoteSplit(vArgs); for (const CString& sArg : vArgs) { @@ -818,19 +867,27 @@ CString CTemplate::GetValue(const CString& sArgs, bool bFromIf) { sRet = (it != end()) ? it->second : ""; } - vector >& vspTagHandlers = GetTagHandlers(); + vector>& vspTagHandlers = + GetTagHandlers(); - if (!vspTagHandlers.empty()) { // @todo this should go up to the top to grab handlers + if (!vspTagHandlers + .empty()) { // @todo this should go up to the top to grab handlers CTemplate* pTmpl = GetCurTemplate(); if (sRet.empty()) { for (const auto& spTagHandler : vspTagHandlers) { CString sCustomOutput; - if (!bFromIf && spTagHandler->HandleVar(*pTmpl, sArgs.Token(0), sArgs.Token(1, true), sCustomOutput)) { + if (!bFromIf && + spTagHandler->HandleVar(*pTmpl, sArgs.Token(0), + sArgs.Token(1, true), + sCustomOutput)) { sRet = sCustomOutput; break; - } else if (bFromIf && spTagHandler->HandleIf(*pTmpl, sArgs.Token(0), sArgs.Token(1, true), sCustomOutput)) { + } else if (bFromIf && + spTagHandler->HandleIf(*pTmpl, sArgs.Token(0), + sArgs.Token(1, true), + sCustomOutput)) { sRet = sCustomOutput; break; } @@ -859,7 +916,8 @@ CString CTemplate::GetValue(const CString& sArgs, bool bFromIf) { sRet.Escape(CString::ToEscape(sEsc)); } } else { - sRet.Escape(m_spOptions->GetEscapeFrom(), m_spOptions->GetEscapeTo()); + sRet.Escape(m_spOptions->GetEscapeFrom(), + m_spOptions->GetEscapeTo()); } } diff --git a/src/Threads.cpp b/src/Threads.cpp index 1f15f518..677e03e5 100644 --- a/src/Threads.cpp +++ b/src/Threads.cpp @@ -35,7 +35,16 @@ CThreadPool& CThreadPool::Get() { return pool; } -CThreadPool::CThreadPool() : m_mutex(), m_cond(), m_cancellationCond(), m_exit_cond(), m_done(false), m_num_threads(0), m_num_idle(0), m_iJobPipe{0,0}, m_jobs() { +CThreadPool::CThreadPool() + : m_mutex(), + m_cond(), + m_cancellationCond(), + m_exit_cond(), + m_done(false), + m_num_threads(0), + m_num_idle(0), + m_iJobPipe{0, 0}, + m_jobs() { if (pipe(m_iJobPipe)) { DEBUG("Ouch, can't open pipe for thread pool: " << strerror(errno)); exit(1); @@ -59,27 +68,30 @@ void CThreadPool::jobDone(CJob* job) { // (Yes, this really wants to write a pointer(!) to the pipe. size_t w = write(m_iJobPipe[1], &job, sizeof(job)); if (w != sizeof(job)) { - DEBUG("Something bad happened during write() to a pipe for thread pool, wrote " << w << " bytes: " << strerror(errno)); + DEBUG( + "Something bad happened during write() to a pipe for thread pool, " + "wrote " + << w << " bytes: " << strerror(errno)); exit(1); } } -void CThreadPool::handlePipeReadable() const { - finishJob(getJobFromPipe()); -} +void CThreadPool::handlePipeReadable() const { finishJob(getJobFromPipe()); } -CJob *CThreadPool::getJobFromPipe() const { +CJob* CThreadPool::getJobFromPipe() const { CJob* a = nullptr; ssize_t need = sizeof(a); ssize_t r = read(m_iJobPipe[0], &a, need); if (r != need) { - DEBUG("Something bad happened during read() from a pipe for thread pool: " << strerror(errno)); + DEBUG( + "Something bad happened during read() from a pipe for thread pool: " + << strerror(errno)); exit(1); } return a; } -void CThreadPool::finishJob(CJob *job) const { +void CThreadPool::finishJob(CJob* job) const { job->runMain(); delete job; } @@ -95,8 +107,7 @@ CThreadPool::~CThreadPool() { } bool CThreadPool::threadNeeded() const { - if (m_num_idle > MAX_IDLE_THREADS) - return false; + if (m_num_idle > MAX_IDLE_THREADS) return false; return !m_done; } @@ -107,15 +118,13 @@ void CThreadPool::threadFunc() { while (true) { while (m_jobs.empty()) { - if (!threadNeeded()) - break; + if (!threadNeeded()) break; m_cond.wait(m_mutex); } - if (!threadNeeded()) - break; + if (!threadNeeded()) break; // Figure out a job to do - CJob *job = m_jobs.front(); + CJob* job = m_jobs.front(); m_jobs.pop_front(); // Now do the actual job @@ -133,11 +142,10 @@ void CThreadPool::threadFunc() { m_num_threads--; m_num_idle--; - if (m_num_threads == 0 && m_done) - m_exit_cond.notify_one(); + if (m_num_threads == 0 && m_done) m_exit_cond.notify_one(); } -void CThreadPool::addJob(CJob *job) { +void CThreadPool::addJob(CJob* job) { CMutexLocker guard(m_mutex); m_jobs.push_back(job); @@ -154,18 +162,16 @@ void CThreadPool::addJob(CJob *job) { // Start a new thread for our pool m_num_threads++; - std::thread([this]() { - threadFunc(); - }).detach(); + std::thread([this]() { threadFunc(); }).detach(); } -void CThreadPool::cancelJob(CJob *job) { - std::set jobs; +void CThreadPool::cancelJob(CJob* job) { + std::set jobs; jobs.insert(job); cancelJobs(jobs); } -void CThreadPool::cancelJobs(const std::set &jobs) { +void CThreadPool::cancelJobs(const std::set& jobs) { // Thanks to the mutex, jobs cannot change state anymore. There are // three different states which can occur: // @@ -184,36 +190,37 @@ void CThreadPool::cancelJobs(const std::set &jobs) { // cancellation is done by changing the job's status to DONE. CMutexLocker guard(m_mutex); - std::set wait, finished, deleteLater; - std::set::const_iterator it; + std::set wait, finished, deleteLater; + std::set::const_iterator it; // Start cancelling all jobs for (it = jobs.begin(); it != jobs.end(); ++it) { switch ((*it)->m_eState) { - case CJob::READY: { - (*it)->m_eState = CJob::CANCELLED; + case CJob::READY: { + (*it)->m_eState = CJob::CANCELLED; - // Job wasn't started yet, must be in the queue - std::list::iterator it2 = std::find(m_jobs.begin(), m_jobs.end(), *it); - assert(it2 != m_jobs.end()); - m_jobs.erase(it2); - deleteLater.insert(*it); - continue; - } + // Job wasn't started yet, must be in the queue + std::list::iterator it2 = + std::find(m_jobs.begin(), m_jobs.end(), *it); + assert(it2 != m_jobs.end()); + m_jobs.erase(it2); + deleteLater.insert(*it); + continue; + } - case CJob::RUNNING: - (*it)->m_eState = CJob::CANCELLED; - wait.insert(*it); - continue; + case CJob::RUNNING: + (*it)->m_eState = CJob::CANCELLED; + wait.insert(*it); + continue; - case CJob::DONE: - (*it)->m_eState = CJob::CANCELLED; - finished.insert(*it); - continue; + case CJob::DONE: + (*it)->m_eState = CJob::CANCELLED; + finished.insert(*it); + continue; - case CJob::CANCELLED: - default: - assert(0); + case CJob::CANCELLED: + default: + assert(0); } } @@ -234,19 +241,19 @@ void CThreadPool::cancelJobs(const std::set &jobs) { it++; } - if (wait.empty()) - break; + if (wait.empty()) break; // Then wait for more to be done m_cancellationCond.wait(m_mutex); } - // We must call destructors with m_mutex unlocked so that they can call wasCancelled() + // We must call destructors with m_mutex unlocked so that they can call + // wasCancelled() guard.unlock(); // Handle finished jobs. They must already be in the pipe. while (!finished.empty()) { - CJob *job = getJobFromPipe(); + CJob* job = getJobFromPipe(); if (finished.erase(job) > 0) { assert(job->m_eState == CJob::CANCELLED); delete job; @@ -266,4 +273,4 @@ bool CJob::wasCancelled() const { return m_eState == CANCELLED; } -#endif // HAVE_PTHREAD +#endif // HAVE_PTHREAD diff --git a/src/User.cpp b/src/User.cpp index 67bb6b4d..db7cb661 100644 --- a/src/User.cpp +++ b/src/User.cpp @@ -29,7 +29,7 @@ using std::vector; using std::set; class CUserTimer : public CCron { -public: + public: CUserTimer(CUser* pUser) : CCron(), m_pUser(pUser) { SetName("CUserTimer::" + m_pUser->GetUserName()); Start(CIRCNetwork::PING_SLACK); @@ -39,13 +39,14 @@ public: CUserTimer(const CUserTimer&) = delete; CUserTimer& operator=(const CUserTimer&) = delete; -private: -protected: + private: + protected: void RunJob() override { const vector& vUserClients = m_pUser->GetUserClients(); for (CClient* pUserClient : vUserClients) { - if (pUserClient->GetTimeSinceLastDataTransaction() >= CIRCNetwork::PING_FREQUENCY) { + if (pUserClient->GetTimeSinceLastDataTransaction() >= + CIRCNetwork::PING_FREQUENCY) { pUserClient->PutClient("PING :ZNC"); } } @@ -55,49 +56,48 @@ protected: }; CUser::CUser(const CString& sUserName) - : m_sUserName(sUserName), - m_sCleanUserName(MakeCleanUserName(sUserName)), - m_sNick(m_sCleanUserName), - m_sAltNick(""), - m_sIdent(m_sCleanUserName), - m_sRealName(""), - m_sBindHost(""), - m_sDCCBindHost(""), - m_sPass(""), - m_sPassSalt(""), - m_sStatusPrefix("*"), - m_sDefaultChanModes(""), - m_sClientEncoding(""), - m_sQuitMsg(""), - m_mssCTCPReplies(), - m_sTimestampFormat("[%H:%M:%S]"), - m_sTimezone(""), - m_eHashType(HASH_NONE), - m_sUserPath(CZNC::Get().GetUserPath() + "/" + sUserName), - m_bMultiClients(true), - m_bDenyLoadMod(false), - m_bAdmin(false), - m_bDenySetBindHost(false), - m_bAutoClearChanBuffer(true), - m_bAutoClearQueryBuffer(true), - m_bBeingDeleted(false), - m_bAppendTimestamp(false), - m_bPrependTimestamp(true), - m_pUserTimer(nullptr), - m_vIRCNetworks(), - m_vClients(), - m_ssAllowedHosts(), - m_uChanBufferSize(50), - m_uQueryBufferSize(50), - m_uBytesRead(0), - m_uBytesWritten(0), - m_uMaxJoinTries(10), - m_uMaxNetworks(1), - m_uMaxQueryBuffers(50), - m_uMaxJoins(0), - m_sSkinName(""), - m_pModules(new CModules) -{ + : m_sUserName(sUserName), + m_sCleanUserName(MakeCleanUserName(sUserName)), + m_sNick(m_sCleanUserName), + m_sAltNick(""), + m_sIdent(m_sCleanUserName), + m_sRealName(""), + m_sBindHost(""), + m_sDCCBindHost(""), + m_sPass(""), + m_sPassSalt(""), + m_sStatusPrefix("*"), + m_sDefaultChanModes(""), + m_sClientEncoding(""), + m_sQuitMsg(""), + m_mssCTCPReplies(), + m_sTimestampFormat("[%H:%M:%S]"), + m_sTimezone(""), + m_eHashType(HASH_NONE), + m_sUserPath(CZNC::Get().GetUserPath() + "/" + sUserName), + m_bMultiClients(true), + m_bDenyLoadMod(false), + m_bAdmin(false), + m_bDenySetBindHost(false), + m_bAutoClearChanBuffer(true), + m_bAutoClearQueryBuffer(true), + m_bBeingDeleted(false), + m_bAppendTimestamp(false), + m_bPrependTimestamp(true), + m_pUserTimer(nullptr), + m_vIRCNetworks(), + m_vClients(), + m_ssAllowedHosts(), + m_uChanBufferSize(50), + m_uQueryBufferSize(50), + m_uBytesRead(0), + m_uBytesWritten(0), + m_uMaxJoinTries(10), + m_uMaxNetworks(1), + m_uMaxQueryBuffers(50), + m_uMaxJoins(0), + m_sSkinName(""), + m_pModules(new CModules) { m_pUserTimer = new CUserTimer(this); CZNC::Get().GetManager().AddCron(m_pUserTimer); } @@ -124,45 +124,46 @@ CUser::~CUser() { CZNC::Get().AddBytesWritten(m_uBytesWritten); } -template +template struct TOption { - const char *name; + const char* name; void (CUser::*pSetter)(T); }; bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { TOption StringOptions[] = { - { "nick", &CUser::SetNick }, - { "quitmsg", &CUser::SetQuitMsg }, - { "altnick", &CUser::SetAltNick }, - { "ident", &CUser::SetIdent }, - { "realname", &CUser::SetRealName }, - { "chanmodes", &CUser::SetDefaultChanModes }, - { "bindhost", &CUser::SetBindHost }, - { "vhost", &CUser::SetBindHost }, - { "dccbindhost", &CUser::SetDCCBindHost }, - { "dccvhost", &CUser::SetDCCBindHost }, - { "timestampformat", &CUser::SetTimestampFormat }, - { "skin", &CUser::SetSkinName }, - { "clientencoding", &CUser::SetClientEncoding }, + {"nick", &CUser::SetNick}, + {"quitmsg", &CUser::SetQuitMsg}, + {"altnick", &CUser::SetAltNick}, + {"ident", &CUser::SetIdent}, + {"realname", &CUser::SetRealName}, + {"chanmodes", &CUser::SetDefaultChanModes}, + {"bindhost", &CUser::SetBindHost}, + {"vhost", &CUser::SetBindHost}, + {"dccbindhost", &CUser::SetDCCBindHost}, + {"dccvhost", &CUser::SetDCCBindHost}, + {"timestampformat", &CUser::SetTimestampFormat}, + {"skin", &CUser::SetSkinName}, + {"clientencoding", &CUser::SetClientEncoding}, }; TOption UIntOptions[] = { - { "jointries", &CUser::SetJoinTries }, - { "maxnetworks", &CUser::SetMaxNetworks }, - { "maxquerybuffers", &CUser::SetMaxQueryBuffers }, - { "maxjoins", &CUser::SetMaxJoins }, + {"jointries", &CUser::SetJoinTries}, + {"maxnetworks", &CUser::SetMaxNetworks}, + {"maxquerybuffers", &CUser::SetMaxQueryBuffers}, + {"maxjoins", &CUser::SetMaxJoins}, }; TOption BoolOptions[] = { - { "keepbuffer", &CUser::SetKeepBuffer }, // XXX compatibility crap from pre-0.207 - { "autoclearchanbuffer", &CUser::SetAutoClearChanBuffer }, - { "autoclearquerybuffer", &CUser::SetAutoClearQueryBuffer }, - { "multiclients", &CUser::SetMultiClients }, - { "denyloadmod", &CUser::SetDenyLoadMod }, - { "admin", &CUser::SetAdmin }, - { "denysetbindhost", &CUser::SetDenySetBindHost }, - { "denysetvhost", &CUser::SetDenySetBindHost }, - { "appendtimestamp", &CUser::SetTimestampAppend }, - { "prependtimestamp", &CUser::SetTimestampPrepend }, + {"keepbuffer", + &CUser::SetKeepBuffer}, // XXX compatibility crap from pre-0.207 + {"autoclearchanbuffer", &CUser::SetAutoClearChanBuffer}, + {"autoclearquerybuffer", &CUser::SetAutoClearQueryBuffer}, + {"multiclients", &CUser::SetMultiClients}, + {"denyloadmod", &CUser::SetDenyLoadMod}, + {"admin", &CUser::SetAdmin}, + {"denysetbindhost", &CUser::SetDenySetBindHost}, + {"denysetvhost", &CUser::SetDenySetBindHost}, + {"appendtimestamp", &CUser::SetTimestampAppend}, + {"prependtimestamp", &CUser::SetTimestampPrepend}, }; for (const auto& Option : StringOptions) { @@ -195,11 +196,12 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { CString sDCCLookupValue; pConfig->FindStringEntry("dcclookupmethod", sDCCLookupValue); - if (pConfig->FindStringEntry("bouncedccs", sValue)) { + if (pConfig->FindStringEntry("bouncedccs", sValue)) { if (sValue.ToBool()) { CUtils::PrintAction("Loading Module [bouncedcc]"); CString sModRet; - bool bModRet = GetModules().LoadModule("bouncedcc", "", CModInfo::UserModule, this, nullptr, sModRet); + bool bModRet = GetModules().LoadModule( + "bouncedcc", "", CModInfo::UserModule, this, nullptr, sModRet); CUtils::PrintStatus(bModRet, sModRet); if (!bModRet) { @@ -219,19 +221,27 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { if (pConfig->FindStringEntry("querybuffersize", sValue)) SetQueryBufferSize(sValue.ToUInt(), true); if (pConfig->FindStringEntry("awaysuffix", sValue)) { - CUtils::PrintMessage("WARNING: AwaySuffix has been deprecated, instead try -> LoadModule = awaynick %nick%_" + sValue); + CUtils::PrintMessage( + "WARNING: AwaySuffix has been deprecated, instead try -> " + "LoadModule = awaynick %nick%_" + + sValue); } if (pConfig->FindStringEntry("autocycle", sValue)) { if (sValue.Equals("true")) - CUtils::PrintError("WARNING: AutoCycle has been removed, instead try -> LoadModule = autocycle"); + CUtils::PrintError( + "WARNING: AutoCycle has been removed, instead try -> " + "LoadModule = autocycle"); } if (pConfig->FindStringEntry("keepnick", sValue)) { if (sValue.Equals("true")) - CUtils::PrintError("WARNING: KeepNick has been deprecated, instead try -> LoadModule = keepnick"); + CUtils::PrintError( + "WARNING: KeepNick has been deprecated, instead try -> " + "LoadModule = keepnick"); } if (pConfig->FindStringEntry("statusprefix", sValue)) { if (!SetStatusPrefix(sValue)) { - sError = "Invalid StatusPrefix [" + sValue + "] Must be 1-5 chars, no spaces."; + sError = "Invalid StatusPrefix [" + sValue + + "] Must be 1-5 chars, no spaces."; CUtils::PrintError(sError); return false; } @@ -241,7 +251,9 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { } if (pConfig->FindStringEntry("timezoneoffset", sValue)) { if (fabs(sValue.ToDouble()) > 0.1) { - CUtils::PrintError("WARNING: TimezoneOffset has been deprecated, now you can set your timezone by name"); + CUtils::PrintError( + "WARNING: TimezoneOffset has been deprecated, now you can set " + "your timezone by name"); } } if (pConfig->FindStringEntry("timestamp", sValue)) { @@ -276,8 +288,7 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { CString sPass = sValue.Token(1, true, "#"); if (sMethod == "md5" || sMethod == "sha256") { CUser::eHashType type = CUser::HASH_MD5; - if (sMethod == "sha256") - type = CUser::HASH_SHA256; + if (sMethod == "sha256") type = CUser::HASH_SHA256; CString sSalt = sPass.Token(1, false, "#"); sPass = sPass.Token(0, false, "#"); @@ -340,7 +351,7 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { CUtils::PrintMessage("Loading network [" + sNetworkName + "]"); - CIRCNetwork *pNetwork = FindNetwork(sNetworkName); + CIRCNetwork* pNetwork = FindNetwork(sNetworkName); if (!pNetwork) { pNetwork = new CIRCNetwork(this, sNetworkName); @@ -351,15 +362,18 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { } } - if (pConfig->FindStringVector("server", vsList, false) || pConfig->FindStringVector("chan", vsList, false) || pConfig->FindSubConfig("chan", subConf, false)) { - CIRCNetwork *pNetwork = FindNetwork("default"); + if (pConfig->FindStringVector("server", vsList, false) || + pConfig->FindStringVector("chan", vsList, false) || + pConfig->FindSubConfig("chan", subConf, false)) { + CIRCNetwork* pNetwork = FindNetwork("default"); if (!pNetwork) { CString sErrorDummy; pNetwork = AddNetwork("default", sErrorDummy); } if (pNetwork) { - CUtils::PrintMessage("NOTICE: Found deprecated config, upgrading to a network"); + CUtils::PrintMessage( + "NOTICE: Found deprecated config, upgrading to a network"); if (!pNetwork->ParseConfig(pConfig, sError, true)) { return false; @@ -374,38 +388,50 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { // XXX Legacy crap, added in ZNC 0.089 if (sModName == "discon_kick") { - sNotice = "NOTICE: [discon_kick] was renamed, loading [disconkick] instead"; + sNotice = + "NOTICE: [discon_kick] was renamed, loading [disconkick] " + "instead"; sModName = "disconkick"; } // XXX Legacy crap, added in ZNC 0.099 if (sModName == "fixfreenode") { - sNotice = "NOTICE: [fixfreenode] doesn't do anything useful anymore, ignoring it"; + sNotice = + "NOTICE: [fixfreenode] doesn't do anything useful anymore, " + "ignoring it"; CUtils::PrintMessage(sNotice); continue; } // XXX Legacy crap, added in ZNC 0.207 if (sModName == "admin") { - sNotice = "NOTICE: [admin] module was renamed, loading [controlpanel] instead"; + sNotice = + "NOTICE: [admin] module was renamed, loading [controlpanel] " + "instead"; sModName = "controlpanel"; } - - // XXX Legacy crap, should have been added ZNC 0.207, but added only in 1.1 :( + + // XXX Legacy crap, should have been added ZNC 0.207, but added only in + // 1.1 :( if (sModName == "away") { sNotice = "NOTICE: [away] was renamed, loading [awaystore] instead"; sModName = "awaystore"; } - // XXX Legacy crap, added in 1.1; fakeonline module was dropped in 1.0 and returned in 1.1 + // XXX Legacy crap, added in 1.1; fakeonline module was dropped in 1.0 + // and returned in 1.1 if (sModName == "fakeonline") { - sNotice = "NOTICE: [fakeonline] was renamed, loading [modules_online] instead"; + sNotice = + "NOTICE: [fakeonline] was renamed, loading [modules_online] " + "instead"; sModName = "modules_online"; } // XXX Legacy crap, added in 1.3 if (sModName == "charset") { - CUtils::PrintAction("NOTICE: Charset support was moved to core, importing old charset module settings"); + CUtils::PrintAction( + "NOTICE: Charset support was moved to core, importing old " + "charset module settings"); size_t uIndex = 1; if (sMod.Token(uIndex).Equals("-force")) { uIndex++; @@ -414,20 +440,24 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { sMod.Token(uIndex).Split(",", vsClient); sMod.Token(uIndex + 1).Split(",", vsServer); if (vsClient.empty() || vsServer.empty()) { - CUtils::PrintStatus(false, "charset module was loaded with wrong parameters."); + CUtils::PrintStatus( + false, "charset module was loaded with wrong parameters."); continue; } SetClientEncoding(vsClient[0]); for (CIRCNetwork* pNetwork : m_vIRCNetworks) { pNetwork->SetEncoding(vsServer[0]); } - CUtils::PrintStatus(true, "Using [" + vsClient[0] + "] for clients, and [" + vsServer[0] + "] for servers"); + CUtils::PrintStatus(true, "Using [" + vsClient[0] + + "] for clients, and [" + vsServer[0] + + "] for servers"); continue; } // XXX Legacy crap, added in 1.7 if (sModName == "disconkick") { - sNotice = "NOTICE: [disconkick] is integrated to core now, ignoring it"; + sNotice = + "NOTICE: [disconkick] is integrated to core now, ignoring it"; CUtils::PrintMessage(sNotice); continue; } @@ -439,10 +469,12 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { CUtils::PrintStatus(bModRet, sModRet); if (!bModRet) { - // XXX The awaynick module was retired in 1.6 (still available as external module) + // XXX The awaynick module was retired in 1.6 (still available as + // external module) if (sModName == "awaynick") { // load simple_away instead, unless it's already on the list - if (std::find(vsList.begin(), vsList.end(), "simple_away") == vsList.end()) { + if (std::find(vsList.begin(), vsList.end(), "simple_away") == + vsList.end()) { sNotice = "Loading [simple_away] module instead"; sModName = "simple_away"; // not a fatal error if simple_away is not available @@ -466,9 +498,11 @@ bool CUser::ParseConfig(CConfig* pConfig, CString& sError) { return true; } -CIRCNetwork* CUser::AddNetwork(const CString &sNetwork, CString& sErrorRet) { +CIRCNetwork* CUser::AddNetwork(const CString& sNetwork, CString& sErrorRet) { if (!CIRCNetwork::IsValidNetwork(sNetwork)) { - sErrorRet = "Invalid network name. It should be alphanumeric. Not to be confused with server name"; + sErrorRet = + "Invalid network name. It should be alphanumeric. Not to be " + "confused with server name"; return nullptr; } else if (FindNetwork(sNetwork)) { sErrorRet = "Network [" + sNetwork.Token(0) + "] already exists"; @@ -479,7 +513,7 @@ CIRCNetwork* CUser::AddNetwork(const CString &sNetwork, CString& sErrorRet) { bool bCancel = false; USERMODULECALL(OnAddNetwork(*pNetwork, sErrorRet), this, nullptr, &bCancel); - if(bCancel) { + if (bCancel) { RemoveNetwork(pNetwork); delete pNetwork; return nullptr; @@ -488,7 +522,7 @@ CIRCNetwork* CUser::AddNetwork(const CString &sNetwork, CString& sErrorRet) { return pNetwork; } -bool CUser::AddNetwork(CIRCNetwork *pNetwork) { +bool CUser::AddNetwork(CIRCNetwork* pNetwork) { if (FindNetwork(pNetwork->GetName())) { return false; } @@ -498,7 +532,7 @@ bool CUser::AddNetwork(CIRCNetwork *pNetwork) { return true; } -void CUser::RemoveNetwork(CIRCNetwork *pNetwork) { +void CUser::RemoveNetwork(CIRCNetwork* pNetwork) { auto it = std::find(m_vIRCNetworks.begin(), m_vIRCNetworks.end(), pNetwork); if (it != m_vIRCNetworks.end()) { m_vIRCNetworks.erase(it); @@ -506,7 +540,7 @@ void CUser::RemoveNetwork(CIRCNetwork *pNetwork) { } bool CUser::DeleteNetwork(const CString& sNetwork) { - CIRCNetwork *pNetwork = FindNetwork(sNetwork); + CIRCNetwork* pNetwork = FindNetwork(sNetwork); if (pNetwork) { bool bCancel = false; @@ -574,8 +608,10 @@ CString CUser::AddTimestamp(const CString& sStr) const { CString CUser::AddTimestamp(time_t tm, const CString& sStr) const { CString sRet = sStr; - if (!GetTimestampFormat().empty() && (m_bAppendTimestamp || m_bPrependTimestamp)) { - CString sTimestamp = CUtils::FormatTime(tm, GetTimestampFormat(), m_sTimezone); + if (!GetTimestampFormat().empty() && + (m_bAppendTimestamp || m_bPrependTimestamp)) { + CString sTimestamp = + CUtils::FormatTime(tm, GetTimestampFormat(), m_sTimezone); if (sTimestamp.empty()) { return sRet; } @@ -587,7 +623,8 @@ CString CUser::AddTimestamp(time_t tm, const CString& sStr) const { if (m_bAppendTimestamp) { // From http://www.mirc.com/colors.html // The Control+O key combination in mIRC inserts ascii character 15, - // which turns off all previous attributes, including color, bold, underline, and italics. + // which turns off all previous attributes, including color, bold, + // underline, and italics. // // \x02 bold // \x03 mIRC-compatible color @@ -600,7 +637,8 @@ CString CUser::AddTimestamp(time_t tm, const CString& sStr) const { // Also see http://www.visualirc.net/tech-attrs.php // // Keep in sync with CIRCSocket::IcuExt__UCallback - if (CString::npos != sRet.find_first_of("\x02\x03\x04\x0F\x12\x16\x1D\x1F")) { + if (CString::npos != + sRet.find_first_of("\x02\x03\x04\x0F\x12\x16\x1D\x1F")) { sRet += "\x0F"; } @@ -624,7 +662,8 @@ void CUser::UserConnected(CClient* pClient) { BounceAllClients(); } - pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + " :- Welcome to ZNC -"); + pClient->PutClient(":irc.znc.in 001 " + pClient->GetNick() + + " :- Welcome to ZNC -"); m_vClients.push_back(pClient); } @@ -639,7 +678,7 @@ void CUser::UserDisconnected(CClient* pClient) { void CUser::CloneNetworks(const CUser& User) { const vector& vNetworks = User.GetNetworks(); for (CIRCNetwork* pUserNetwork : vNetworks) { - CIRCNetwork *pNetwork = FindNetwork(pUserNetwork->GetName()); + CIRCNetwork* pNetwork = FindNetwork(pUserNetwork->GetName()); if (pNetwork) { pNetwork->Clone(*pUserNetwork); @@ -664,7 +703,7 @@ void CUser::CloneNetworks(const CUser& User) { const vector& vClients = FindNetwork(sNetwork)->GetClients(); while (vClients.begin() != vClients.end()) { - CClient *pClient = vClients.front(); + CClient* pClient = vClients.front(); // This line will remove pClient from vClients, // because it's a reference to the internal Network's vector. pClient->SetNetwork(nullptr); @@ -684,8 +723,9 @@ bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) { // user names can only specified for the constructor, changing it later // on breaks too much stuff (e.g. lots of paths depend on the user name) if (GetUserName() != User.GetUserName()) { - DEBUG("Ignoring username in CUser::Clone(), old username [" << GetUserName() - << "]; New username [" << User.GetUserName() << "]"); + DEBUG("Ignoring username in CUser::Clone(), old username [" + << GetUserName() << "]; New username [" << User.GetUserName() + << "]"); } if (!User.GetPass().empty()) { @@ -719,7 +759,9 @@ bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) { for (CClient* pSock : m_vClients) { if (!IsHostAllowed(pSock->GetRemoteIP())) { - pSock->PutStatusNotice("You are being disconnected because your IP is no longer allowed to connect to this user"); + pSock->PutStatusNotice( + "You are being disconnected because your IP is no longer " + "allowed to connect to this user"); pSock->Close(); } } @@ -763,9 +805,11 @@ bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) { CModule* pCurMod = vCurMods.FindModule(pNewMod->GetModName()); if (!pCurMod) { - vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), CModInfo::UserModule, this, nullptr, sModRet); + vCurMods.LoadModule(pNewMod->GetModName(), pNewMod->GetArgs(), + CModInfo::UserModule, this, nullptr, sModRet); } else if (pNewMod->GetArgs() != pCurMod->GetArgs()) { - vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), this, nullptr, sModRet); + vCurMods.ReloadModule(pNewMod->GetModName(), pNewMod->GetArgs(), + this, nullptr, sModRet); } } @@ -787,7 +831,8 @@ bool CUser::Clone(const CUser& User, CString& sErrorRet, bool bCloneNetworks) { const set& CUser::GetAllowedHosts() const { return m_ssAllowedHosts; } bool CUser::AddAllowedHost(const CString& sHostMask) { - if (sHostMask.empty() || m_ssAllowedHosts.find(sHostMask) != m_ssAllowedHosts.end()) { + if (sHostMask.empty() || + m_ssAllowedHosts.find(sHostMask) != m_ssAllowedHosts.end()) { return false; } @@ -797,9 +842,7 @@ bool CUser::AddAllowedHost(const CString& sHostMask) { bool CUser::RemAllowedHost(const CString& sHostMask) { return m_ssAllowedHosts.erase(sHostMask) > 0; } -void CUser::ClearAllowedHosts() { - m_ssAllowedHosts.clear(); -} +void CUser::ClearAllowedHosts() { m_ssAllowedHosts.clear(); } bool CUser::IsHostAllowed(const CString& sHostMask) const { if (m_ssAllowedHosts.empty()) { @@ -869,15 +912,15 @@ CConfig CUser::ToConfig() const { CString sHash; switch (m_eHashType) { - case HASH_NONE: - sHash = "Plain"; - break; - case HASH_MD5: - sHash = "MD5"; - break; - case HASH_SHA256: - sHash = "SHA256"; - break; + case HASH_NONE: + sHash = "Plain"; + break; + case HASH_MD5: + sHash = "MD5"; + break; + case HASH_SHA256: + sHash = "SHA256"; + break; } passConfig.AddKeyValuePair("Salt", m_sPassSalt); passConfig.AddKeyValuePair("Method", sHash); @@ -899,8 +942,10 @@ CConfig CUser::ToConfig() const { config.AddKeyValuePair("ChanModes", GetDefaultChanModes()); config.AddKeyValuePair("ChanBufferSize", CString(GetChanBufferSize())); config.AddKeyValuePair("QueryBufferSize", CString(GetQueryBufferSize())); - config.AddKeyValuePair("AutoClearChanBuffer", CString(AutoClearChanBuffer())); - config.AddKeyValuePair("AutoClearQueryBuffer", CString(AutoClearQueryBuffer())); + config.AddKeyValuePair("AutoClearChanBuffer", + CString(AutoClearChanBuffer())); + config.AddKeyValuePair("AutoClearQueryBuffer", + CString(AutoClearQueryBuffer())); config.AddKeyValuePair("MultiClients", CString(MultiClients())); config.AddKeyValuePair("DenyLoadMod", CString(DenyLoadMod())); config.AddKeyValuePair("Admin", CString(IsAdmin())); @@ -925,7 +970,8 @@ CConfig CUser::ToConfig() const { // CTCP Replies if (!m_mssCTCPReplies.empty()) { for (const auto& itb : m_mssCTCPReplies) { - config.AddKeyValuePair("CTCPReply", itb.first.AsUpper() + " " + itb.second); + config.AddKeyValuePair("CTCPReply", + itb.first.AsUpper() + " " + itb.second); } } @@ -945,46 +991,45 @@ CConfig CUser::ToConfig() const { } // Networks - for (CIRCNetwork *pNetwork : m_vIRCNetworks) { - config.AddSubConfig("Network", pNetwork->GetName(), pNetwork->ToConfig()); + for (CIRCNetwork* pNetwork : m_vIRCNetworks) { + config.AddSubConfig("Network", pNetwork->GetName(), + pNetwork->ToConfig()); } return config; } bool CUser::CheckPass(const CString& sPass) const { - switch (m_eHashType) - { - case HASH_MD5: - return m_sPass.Equals(CUtils::SaltedMD5Hash(sPass, m_sPassSalt)); - case HASH_SHA256: - return m_sPass.Equals(CUtils::SaltedSHA256Hash(sPass, m_sPassSalt)); - case HASH_NONE: - default: - return (sPass == m_sPass); + switch (m_eHashType) { + case HASH_MD5: + return m_sPass.Equals(CUtils::SaltedMD5Hash(sPass, m_sPassSalt)); + case HASH_SHA256: + return m_sPass.Equals(CUtils::SaltedSHA256Hash(sPass, m_sPassSalt)); + case HASH_NONE: + default: + return (sPass == m_sPass); } } /*CClient* CUser::GetClient() { - // Todo: optimize this by saving a pointer to the sock - CSockManager& Manager = CZNC::Get().GetManager(); - CString sSockName = "USR::" + m_sUserName; + // Todo: optimize this by saving a pointer to the sock + CSockManager& Manager = CZNC::Get().GetManager(); + CString sSockName = "USR::" + m_sUserName; - for (unsigned int a = 0; a < Manager.size(); a++) { - Csock* pSock = Manager[a]; - if (pSock->GetSockName().Equals(sSockName)) { - if (!pSock->IsClosed()) { - return (CClient*) pSock; - } - } - } + for (unsigned int a = 0; a < Manager.size(); a++) { + Csock* pSock = Manager[a]; + if (pSock->GetSockName().Equals(sSockName)) { + if (!pSock->IsClosed()) { + return (CClient*) pSock; + } + } + } - return (CClient*) CZNC::Get().GetManager().FindSockByName(sSockName); + return (CClient*) CZNC::Get().GetManager().FindSockByName(sSockName); }*/ CString CUser::GetLocalDCCIP() const { - if (!GetDCCBindHost().empty()) - return GetDCCBindHost(); + if (!GetDCCBindHost().empty()) return GetDCCBindHost(); for (CIRCNetwork* pNetwork : m_vIRCNetworks) { CIRCSock* pIRCSock = pNetwork->GetIRCSock(); @@ -1000,9 +1045,11 @@ CString CUser::GetLocalDCCIP() const { return ""; } -bool CUser::PutUser(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutUser(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutClient(sLine); if (pClient) { @@ -1014,7 +1061,8 @@ bool CUser::PutUser(const CString& sLine, CClient* pClient, CClient* pSkipClient return (pClient == nullptr); } -bool CUser::PutAllUser(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutAllUser(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { PutUser(sLine, pClient, pSkipClient); for (CIRCNetwork* pNetwork : m_vIRCNetworks) { @@ -1026,10 +1074,12 @@ bool CUser::PutAllUser(const CString& sLine, CClient* pClient, CClient* pSkipCli return (pClient == nullptr); } -bool CUser::PutStatus(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutStatus(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { vector vClients = GetAllClients(); for (CClient* pEachClient : vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutStatus(sLine); if (pClient) { @@ -1041,10 +1091,12 @@ bool CUser::PutStatus(const CString& sLine, CClient* pClient, CClient* pSkipClie return (pClient == nullptr); } -bool CUser::PutStatusNotice(const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutStatusNotice(const CString& sLine, CClient* pClient, + CClient* pSkipClient) { vector vClients = GetAllClients(); for (CClient* pEachClient : vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutStatusNotice(sLine); if (pClient) { @@ -1056,9 +1108,11 @@ bool CUser::PutStatusNotice(const CString& sLine, CClient* pClient, CClient* pSk return (pClient == nullptr); } -bool CUser::PutModule(const CString& sModule, const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutModule(const CString& sModule, const CString& sLine, + CClient* pClient, CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutModule(sModule, sLine); if (pClient) { @@ -1070,9 +1124,11 @@ bool CUser::PutModule(const CString& sModule, const CString& sLine, CClient* pCl return (pClient == nullptr); } -bool CUser::PutModNotice(const CString& sModule, const CString& sLine, CClient* pClient, CClient* pSkipClient) { +bool CUser::PutModNotice(const CString& sModule, const CString& sLine, + CClient* pClient, CClient* pSkipClient) { for (CClient* pEachClient : m_vClients) { - if ((!pClient || pClient == pEachClient) && pSkipClient != pEachClient) { + if ((!pClient || pClient == pEachClient) && + pSkipClient != pEachClient) { pEachClient->PutModNotice(sModule, sLine); if (pClient) { @@ -1102,8 +1158,8 @@ bool CUser::IsUserAttached() const { return false; } -bool CUser::LoadModule(const CString& sModName, const CString& sArgs, const CString& sNotice, CString& sError) -{ +bool CUser::LoadModule(const CString& sModName, const CString& sArgs, + const CString& sNotice, CString& sError) { bool bModRet = true; CString sModRet; @@ -1115,11 +1171,15 @@ bool CUser::LoadModule(const CString& sModName, const CString& sArgs, const CStr CUtils::PrintAction(sNotice); - if (!ModInfo.SupportsType(CModInfo::UserModule) && ModInfo.SupportsType(CModInfo::NetworkModule)) { - CUtils::PrintMessage("NOTICE: Module [" + sModName + "] is a network module, loading module for all networks in user."); + if (!ModInfo.SupportsType(CModInfo::UserModule) && + ModInfo.SupportsType(CModInfo::NetworkModule)) { + CUtils::PrintMessage( + "NOTICE: Module [" + sModName + + "] is a network module, loading module for all networks in user."); // Do they have old NV? - CFile fNVFile = CFile(GetUserPath() + "/moddata/" + sModName + "/.registry"); + CFile fNVFile = + CFile(GetUserPath() + "/moddata/" + sModName + "/.registry"); for (CIRCNetwork* pNetwork : m_vIRCNetworks) { // Check whether the network already has this module loaded (#954) @@ -1128,7 +1188,8 @@ bool CUser::LoadModule(const CString& sModName, const CString& sArgs, const CStr } if (fNVFile.Exists()) { - CString sNetworkModPath = pNetwork->GetNetworkPath() + "/moddata/" + sModName; + CString sNetworkModPath = + pNetwork->GetNetworkPath() + "/moddata/" + sModName; if (!CFile::Exists(sNetworkModPath)) { CDir::MakeDir(sNetworkModPath); } @@ -1136,13 +1197,16 @@ bool CUser::LoadModule(const CString& sModName, const CString& sArgs, const CStr fNVFile.Copy(sNetworkModPath + "/.registry"); } - bModRet = pNetwork->GetModules().LoadModule(sModName, sArgs, CModInfo::NetworkModule, this, pNetwork, sModRet); + bModRet = pNetwork->GetModules().LoadModule( + sModName, sArgs, CModInfo::NetworkModule, this, pNetwork, + sModRet); if (!bModRet) { break; } } } else { - bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule, this, nullptr, sModRet); + bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::UserModule, + this, nullptr, sModRet); } if (!bModRet) { @@ -1185,8 +1249,7 @@ bool CUser::SetBufferCount(unsigned int u, bool bForce) { } bool CUser::SetChanBufferSize(unsigned int u, bool bForce) { - if (!bForce && u > CZNC::Get().GetMaxBufferSize()) - return false; + if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false; for (CIRCNetwork* pNetwork : m_vIRCNetworks) { for (CChan* pChan : pNetwork->GetChans()) { pChan->InheritBufferCount(u, bForce); @@ -1197,8 +1260,7 @@ bool CUser::SetChanBufferSize(unsigned int u, bool bForce) { } bool CUser::SetQueryBufferSize(unsigned int u, bool bForce) { - if (!bForce && u > CZNC::Get().GetMaxBufferSize()) - return false; + if (!bForce && u > CZNC::Get().GetMaxBufferSize()) return false; for (CIRCNetwork* pNetwork : m_vIRCNetworks) { for (CQuery* pQuery : pNetwork->GetQueries()) { pQuery->SetBufferCount(u, bForce); @@ -1252,13 +1314,21 @@ vector CUser::GetAllClients() const { return vClients; } - const CString& CUser::GetUserName() const { return m_sUserName; } const CString& CUser::GetCleanUserName() const { return m_sCleanUserName; } -const CString& CUser::GetNick(bool bAllowDefault) const { return (bAllowDefault && m_sNick.empty()) ? GetCleanUserName() : m_sNick; } -const CString& CUser::GetAltNick(bool bAllowDefault) const { return (bAllowDefault && m_sAltNick.empty()) ? GetCleanUserName() : m_sAltNick; } -const CString& CUser::GetIdent(bool bAllowDefault) const { return (bAllowDefault && m_sIdent.empty()) ? GetCleanUserName() : m_sIdent; } -CString CUser::GetRealName() const { return (!m_sRealName.Trim_n().empty()) ? m_sRealName : CZNC::GetTag(false); } +const CString& CUser::GetNick(bool bAllowDefault) const { + return (bAllowDefault && m_sNick.empty()) ? GetCleanUserName() : m_sNick; +} +const CString& CUser::GetAltNick(bool bAllowDefault) const { + return (bAllowDefault && m_sAltNick.empty()) ? GetCleanUserName() + : m_sAltNick; +} +const CString& CUser::GetIdent(bool bAllowDefault) const { + return (bAllowDefault && m_sIdent.empty()) ? GetCleanUserName() : m_sIdent; +} +CString CUser::GetRealName() const { + return (!m_sRealName.Trim_n().empty()) ? m_sRealName : CZNC::GetTag(false); +} const CString& CUser::GetBindHost() const { return m_sBindHost; } const CString& CUser::GetDCCBindHost() const { return m_sDCCBindHost; } const CString& CUser::GetPass() const { return m_sPass; } @@ -1269,20 +1339,32 @@ bool CUser::IsAdmin() const { return m_bAdmin; } bool CUser::DenySetBindHost() const { return m_bDenySetBindHost; } bool CUser::MultiClients() const { return m_bMultiClients; } const CString& CUser::GetStatusPrefix() const { return m_sStatusPrefix; } -const CString& CUser::GetDefaultChanModes() const { return m_sDefaultChanModes; } +const CString& CUser::GetDefaultChanModes() const { + return m_sDefaultChanModes; +} const CString& CUser::GetClientEncoding() const { return m_sClientEncoding; } -bool CUser::HasSpaceForNewNetwork() const { return GetNetworks().size() < MaxNetworks(); } +bool CUser::HasSpaceForNewNetwork() const { + return GetNetworks().size() < MaxNetworks(); +} -CString CUser::GetQuitMsg() const { return (!m_sQuitMsg.Trim_n().empty()) ? m_sQuitMsg : CZNC::GetTag(false); } +CString CUser::GetQuitMsg() const { + return (!m_sQuitMsg.Trim_n().empty()) ? m_sQuitMsg : CZNC::GetTag(false); +} const MCString& CUser::GetCTCPReplies() const { return m_mssCTCPReplies; } unsigned int CUser::GetBufferCount() const { return GetChanBufferSize(); } unsigned int CUser::GetChanBufferSize() const { return m_uChanBufferSize; } unsigned int CUser::GetQueryBufferSize() const { return m_uQueryBufferSize; } bool CUser::AutoClearChanBuffer() const { return m_bAutoClearChanBuffer; } bool CUser::AutoClearQueryBuffer() const { return m_bAutoClearQueryBuffer; } -//CString CUser::GetSkinName() const { return (!m_sSkinName.empty()) ? m_sSkinName : CZNC::Get().GetSkinName(); } +// CString CUser::GetSkinName() const { return (!m_sSkinName.empty()) ? +// m_sSkinName : CZNC::Get().GetSkinName(); } CString CUser::GetSkinName() const { return m_sSkinName; } -const CString& CUser::GetUserPath() const { if (!CFile::Exists(m_sUserPath)) { CDir::MakeDir(m_sUserPath); } return m_sUserPath; } +const CString& CUser::GetUserPath() const { + if (!CFile::Exists(m_sUserPath)) { + CDir::MakeDir(m_sUserPath); + } + return m_sUserPath; +} // !Getters unsigned long long CUser::BytesRead() const { diff --git a/src/Utils.cpp b/src/Utils.cpp index 8005b305..ba7f1f5f 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -46,33 +46,34 @@ CUtils::~CUtils() {} #ifdef HAVE_LIBSSL // Generated by "openssl dhparam 2048" constexpr const char* szDefaultDH2048 = - "-----BEGIN DH PARAMETERS-----\n" - "MIIBCAKCAQEAtS/K3TMY8IHzcCATQSjUF3rDidjDDQmT+mLxyxRORmzMPjFIFkKH\n" - "MOmxZvyCBArdaoCCEBBOzrldl/bBLn5TOeZb+MW7mpBLANTuQSOu97DDM7EzbnqC\n" - "b6z3QgixZ2+UqxdmQAu4nBPLFwym6W/XPFEHpz6iHISSvjzzo4cfI0xwWTcoAvFQ\n" - "r/ZU5BXSXp7XuDxSyyAqaaKUxquElf+x56QWrpNJypjzPpslg5ViAKwWQS0TnCrU\n" - "sVuhFtbNlZjqW1tMSBxiWFltS1HoEaaI79MEpf1Ps25OrQl8xqqCGKkZcHlNo4oF\n" - "cvUyzAEcCQYHmiYjp2hoZbSa8b690TQaAwIBAg==\n" - "-----END DH PARAMETERS-----\n"; + "-----BEGIN DH PARAMETERS-----\n" + "MIIBCAKCAQEAtS/K3TMY8IHzcCATQSjUF3rDidjDDQmT+mLxyxRORmzMPjFIFkKH\n" + "MOmxZvyCBArdaoCCEBBOzrldl/bBLn5TOeZb+MW7mpBLANTuQSOu97DDM7EzbnqC\n" + "b6z3QgixZ2+UqxdmQAu4nBPLFwym6W/XPFEHpz6iHISSvjzzo4cfI0xwWTcoAvFQ\n" + "r/ZU5BXSXp7XuDxSyyAqaaKUxquElf+x56QWrpNJypjzPpslg5ViAKwWQS0TnCrU\n" + "sVuhFtbNlZjqW1tMSBxiWFltS1HoEaaI79MEpf1Ps25OrQl8xqqCGKkZcHlNo4oF\n" + "cvUyzAEcCQYHmiYjp2hoZbSa8b690TQaAwIBAg==\n" + "-----END DH PARAMETERS-----\n"; -void CUtils::GenerateCert(FILE *pOut, const CString& sHost) { - EVP_PKEY *pKey = nullptr; - X509 *pCert = nullptr; - X509_NAME *pName = nullptr; +void CUtils::GenerateCert(FILE* pOut, const CString& sHost) { + EVP_PKEY* pKey = nullptr; + X509* pCert = nullptr; + X509_NAME* pName = nullptr; const int days = 365; const int years = 10; unsigned int uSeed = (unsigned int)time(nullptr); int serial = (rand_r(&uSeed) % 9999); - RSA *pRSA = RSA_generate_key(2048, 0x10001, nullptr, nullptr); + RSA* pRSA = RSA_generate_key(2048, 0x10001, nullptr, nullptr); if ((pKey = EVP_PKEY_new())) { if (!EVP_PKEY_assign_RSA(pKey, pRSA)) { EVP_PKEY_free(pKey); return; } - PEM_write_RSAPrivateKey(pOut, pRSA, nullptr, nullptr, 0, nullptr, nullptr); + PEM_write_RSAPrivateKey(pOut, pRSA, nullptr, nullptr, 0, nullptr, + nullptr); if (!(pCert = X509_new())) { EVP_PKEY_free(pKey); @@ -82,13 +83,14 @@ void CUtils::GenerateCert(FILE *pOut, const CString& sHost) { X509_set_version(pCert, 2); ASN1_INTEGER_set(X509_get_serialNumber(pCert), serial); X509_gmtime_adj(X509_get_notBefore(pCert), 0); - X509_gmtime_adj(X509_get_notAfter(pCert), (long)60*60*24*days*years); + X509_gmtime_adj(X509_get_notAfter(pCert), + (long)60 * 60 * 24 * days * years); X509_set_pubkey(pCert, pKey); pName = X509_get_subject_name(pCert); - const char *pLogName = getenv("LOGNAME"); - const char *pHostName = nullptr; + const char* pLogName = getenv("LOGNAME"); + const char* pHostName = nullptr; if (!sHost.empty()) { pHostName = sHost.c_str(); @@ -110,9 +112,13 @@ void CUtils::GenerateCert(FILE *pOut, const CString& sHost) { sEmailAddr += "@"; sEmailAddr += pHostName; - X509_NAME_add_entry_by_txt(pName, "OU", MBSTRING_ASC, (unsigned char *)pLogName, -1, -1, 0); - X509_NAME_add_entry_by_txt(pName, "CN", MBSTRING_ASC, (unsigned char *)pHostName, -1, -1, 0); - X509_NAME_add_entry_by_txt(pName, "emailAddress", MBSTRING_ASC, (unsigned char *)sEmailAddr.c_str(), -1, -1, 0); + X509_NAME_add_entry_by_txt(pName, "OU", MBSTRING_ASC, + (unsigned char*)pLogName, -1, -1, 0); + X509_NAME_add_entry_by_txt(pName, "CN", MBSTRING_ASC, + (unsigned char*)pHostName, -1, -1, 0); + X509_NAME_add_entry_by_txt(pName, "emailAddress", MBSTRING_ASC, + (unsigned char*)sEmailAddr.c_str(), -1, -1, + 0); X509_set_subject_name(pCert, pName); X509_set_issuer_name(pCert, pName); @@ -134,14 +140,14 @@ void CUtils::GenerateCert(FILE *pOut, const CString& sHost) { CString CUtils::GetIP(unsigned long addr) { char szBuf[16]; - memset((char*) szBuf, 0, 16); + memset((char*)szBuf, 0, 16); if (addr >= (1 << 24)) { unsigned long ip[4]; ip[0] = addr >> 24 & 255; ip[1] = addr >> 16 & 255; - ip[2] = addr >> 8 & 255; - ip[3] = addr & 255; + ip[2] = addr >> 8 & 255; + ip[3] = addr & 255; sprintf(szBuf, "%lu.%lu.%lu.%lu", ip[0], ip[1], ip[2], ip[3]); } @@ -153,13 +159,12 @@ unsigned long CUtils::GetLongIP(const CString& sIP) { char ip[4][4]; unsigned int i; - i = sscanf(sIP.c_str(), "%3[0-9].%3[0-9].%3[0-9].%3[0-9]", - ip[0], ip[1], ip[2], ip[3]); - if (i != 4) - return 0; + i = sscanf(sIP.c_str(), "%3[0-9].%3[0-9].%3[0-9].%3[0-9]", ip[0], ip[1], + ip[2], ip[3]); + if (i != 4) return 0; // Beware that atoi("200") << 24 would overflow and turn negative! - ret = atol(ip[0]) << 24; + ret = atol(ip[0]) << 24; ret += atol(ip[1]) << 16; ret += atol(ip[2]) << 8; ret += atol(ip[3]) << 0; @@ -191,9 +196,7 @@ CString CUtils::GetSaltedHashPass(CString& sSalt) { } } -CString CUtils::GetSalt() { - return CString::RandomString(20); -} +CString CUtils::GetSalt() { return CString::RandomString(20); } CString CUtils::SaltedMD5Hash(const CString& sPass, const CString& sSalt) { return CString(sPass + sSalt).MD5(); @@ -233,7 +236,7 @@ bool CUtils::GetBoolInput(const CString& sPrompt, bool bDefault) { return CUtils::GetBoolInput(sPrompt, &bDefault); } -bool CUtils::GetBoolInput(const CString& sPrompt, bool *pbDefault) { +bool CUtils::GetBoolInput(const CString& sPrompt, bool* pbDefault) { CString sRet, sDefault; if (pbDefault) { @@ -251,15 +254,17 @@ bool CUtils::GetBoolInput(const CString& sPrompt, bool *pbDefault) { } } -bool CUtils::GetNumInput(const CString& sPrompt, unsigned int& uRet, unsigned int uMin, unsigned int uMax, unsigned int uDefault) { +bool CUtils::GetNumInput(const CString& sPrompt, unsigned int& uRet, + unsigned int uMin, unsigned int uMax, + unsigned int uDefault) { if (uMin > uMax) { return false; } - CString sDefault = (uDefault != (unsigned int) ~0) ? CString(uDefault) : ""; + CString sDefault = (uDefault != (unsigned int)~0) ? CString(uDefault) : ""; CString sNum, sHint; - if (uMax != (unsigned int) ~0) { + if (uMax != (unsigned int)~0) { sHint = CString(uMin) + " to " + CString(uMax); } else if (uMin > 0) { sHint = CString(uMin) + " and up"; @@ -283,7 +288,8 @@ bool CUtils::GetNumInput(const CString& sPrompt, unsigned int& uRet, unsigned in return true; } -bool CUtils::GetInput(const CString& sPrompt, CString& sRet, const CString& sDefault, const CString& sHint) { +bool CUtils::GetInput(const CString& sPrompt, CString& sRet, + const CString& sDefault, const CString& sHint) { CString sExtra; CString sInput; sExtra += (!sHint.empty()) ? (" (" + sHint + ")") : ""; @@ -321,7 +327,8 @@ bool CUtils::GetInput(const CString& sPrompt, CString& sRet, const CString& sDef void CUtils::PrintError(const CString& sMessage) { if (CDebug::StdoutIsTTY()) - fprintf(stdout, BOLD BLU "[" RED " ** " BLU "]" DFL NORM" %s\n", sMessage.c_str()); + fprintf(stdout, BOLD BLU "[" RED " ** " BLU "]" DFL NORM " %s\n", + sMessage.c_str()); else fprintf(stdout, "%s\n", sMessage.c_str()); fflush(stdout); @@ -329,7 +336,8 @@ void CUtils::PrintError(const CString& sMessage) { void CUtils::PrintPrompt(const CString& sMessage) { if (CDebug::StdoutIsTTY()) - fprintf(stdout, BOLD BLU "[" YEL " ?? " BLU "]" DFL NORM " %s: ", sMessage.c_str()); + fprintf(stdout, BOLD BLU "[" YEL " ?? " BLU "]" DFL NORM " %s: ", + sMessage.c_str()); else fprintf(stdout, "[ ?? ] %s: ", sMessage.c_str()); fflush(stdout); @@ -338,11 +346,12 @@ void CUtils::PrintPrompt(const CString& sMessage) { void CUtils::PrintMessage(const CString& sMessage, bool bStrong) { if (CDebug::StdoutIsTTY()) { if (bStrong) - fprintf(stdout, BOLD BLU "[" YEL " ** " BLU "]" DFL BOLD " %s" NORM "\n", - sMessage.c_str()); + fprintf(stdout, + BOLD BLU "[" YEL " ** " BLU "]" DFL BOLD " %s" NORM "\n", + sMessage.c_str()); else fprintf(stdout, BOLD BLU "[" YEL " ** " BLU "]" DFL NORM " %s\n", - sMessage.c_str()); + sMessage.c_str()); } else fprintf(stdout, "%s\n", sMessage.c_str()); @@ -351,7 +360,8 @@ void CUtils::PrintMessage(const CString& sMessage, bool bStrong) { void CUtils::PrintAction(const CString& sMessage) { if (CDebug::StdoutIsTTY()) - fprintf(stdout, BOLD BLU "[ .. " BLU "]" DFL NORM " %s...\n", sMessage.c_str()); + fprintf(stdout, BOLD BLU "[ .. " BLU "]" DFL NORM " %s...\n", + sMessage.c_str()); else fprintf(stdout, "%s... ", sMessage.c_str()); fflush(stdout); @@ -360,10 +370,15 @@ void CUtils::PrintAction(const CString& sMessage) { void CUtils::PrintStatus(bool bSuccess, const CString& sMessage) { if (CDebug::StdoutIsTTY()) { if (bSuccess) { - if (!sMessage.empty()) - fprintf(stdout, BOLD BLU "[" GRN " >> " BLU "]" DFL NORM " %s\n", sMessage.c_str()); + if (!sMessage.empty()) + fprintf(stdout, + BOLD BLU "[" GRN " >> " BLU "]" DFL NORM " %s\n", + sMessage.c_str()); } else { - fprintf(stdout, sMessage.empty() ? " failed\n" : BOLD BLU "[" RED " !! " BLU "]" DFL NORM BOLD RED " %s" DFL NORM "\n", sMessage.c_str()); + fprintf(stdout, sMessage.empty() ? " failed\n" : BOLD BLU + "[" RED " !! " BLU "]" DFL NORM BOLD RED + " %s" DFL NORM "\n", + sMessage.c_str()); } } else { if (bSuccess) { @@ -381,30 +396,30 @@ void CUtils::PrintStatus(bool bSuccess, const CString& sMessage) { } namespace { - /* Switch GMT-X and GMT+X - * - * See https://en.wikipedia.org/wiki/Tz_database#Area - * - * "In order to conform with the POSIX style, those zone names beginning - * with "Etc/GMT" have their sign reversed from what most people expect. - * In this style, zones west of GMT have a positive sign and those east - * have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours - * ahead/east of GMT.)" - */ - inline CString FixGMT(CString sTZ) { - if (sTZ.length() >= 4 && sTZ.StartsWith("GMT")) { - if (sTZ[3] == '+') { - sTZ[3] = '-'; - } else if (sTZ[3] == '-') { - sTZ[3] = '+'; - } +/* Switch GMT-X and GMT+X + * + * See https://en.wikipedia.org/wiki/Tz_database#Area + * + * "In order to conform with the POSIX style, those zone names beginning + * with "Etc/GMT" have their sign reversed from what most people expect. + * In this style, zones west of GMT have a positive sign and those east + * have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours + * ahead/east of GMT.)" + */ +inline CString FixGMT(CString sTZ) { + if (sTZ.length() >= 4 && sTZ.StartsWith("GMT")) { + if (sTZ[3] == '+') { + sTZ[3] = '-'; + } else if (sTZ[3] == '-') { + sTZ[3] = '+'; } - return sTZ; } + return sTZ; +} } CString CUtils::CTime(time_t t, const CString& sTimezone) { - char s[30] = {}; // should have at least 26 bytes + char s[30] = {}; // should have at least 26 bytes if (sTimezone.empty()) { ctime_r(&t, s); // ctime() adds a trailing newline @@ -432,7 +447,8 @@ CString CUtils::CTime(time_t t, const CString& sTimezone) { return CString(s).Trim_n(); } -CString CUtils::FormatTime(time_t t, const CString& sFormat, const CString& sTimezone) { +CString CUtils::FormatTime(time_t t, const CString& sFormat, + const CString& sTimezone) { char s[1024] = {}; tm m; if (sTimezone.empty()) { @@ -472,7 +488,9 @@ CString CUtils::FormatServerTime(const timeval& tv) { // TODO support message-tags properly struct tm stm; memset(&stm, 0, sizeof(stm)); - const time_t secs = tv.tv_sec; // OpenBSD has tv_sec as int, so explicitly convert it to time_t to make gmtime_r() happy + const time_t secs = tv.tv_sec; // OpenBSD has tv_sec as int, so explicitly + // convert it to time_t to make gmtime_r() + // happy gmtime_r(&secs, &stm); char sTime[20] = {}; strftime(sTime, sizeof(sTime), "%Y-%m-%dT%H:%M:%S", &stm); @@ -496,26 +514,30 @@ timeval CUtils::ParseServerTime(const CString& sTime) { } namespace { - void FillTimezones(const CString& sPath, SCString& result, const CString& sPrefix) { - CDir Dir; - Dir.Fill(sPath); - for (CFile* pFile : Dir) { - CString sName = pFile->GetShortName(); - CString sFile = pFile->GetLongName(); - if (sName == "posix" || sName == "right") continue; // these 2 dirs contain the same filenames - if (sName.EndsWith(".tab") || sName == "posixrules" || sName == "localtime") continue; - if (pFile->IsDir()) { - if (sName == "Etc") { - FillTimezones(sFile, result, sPrefix); - } else { - FillTimezones(sFile, result, sPrefix + sName + "/"); - } +void FillTimezones(const CString& sPath, SCString& result, + const CString& sPrefix) { + CDir Dir; + Dir.Fill(sPath); + for (CFile* pFile : Dir) { + CString sName = pFile->GetShortName(); + CString sFile = pFile->GetLongName(); + if (sName == "posix" || sName == "right") + continue; // these 2 dirs contain the same filenames + if (sName.EndsWith(".tab") || sName == "posixrules" || + sName == "localtime") + continue; + if (pFile->IsDir()) { + if (sName == "Etc") { + FillTimezones(sFile, result, sPrefix); } else { - result.insert(sPrefix + sName); + FillTimezones(sFile, result, sPrefix + sName + "/"); } + } else { + result.insert(sPrefix + sName); } } } +} SCString CUtils::GetTimezones() { static SCString result; @@ -535,8 +557,10 @@ SCString CUtils::GetEncodings() { icu::ErrorCode e; for (int st = 0; st < ucnv_countStandards(); ++st) { const char* pStdName = ucnv_getStandard(st, e); - icu::LocalUEnumerationPointer ue(ucnv_openStandardNames(pConvName, pStdName, e)); - while (const char* pStdConvNameEnum = uenum_next(ue.getAlias(), nullptr, e)) { + icu::LocalUEnumerationPointer ue( + ucnv_openStandardNames(pConvName, pStdName, e)); + while (const char* pStdConvNameEnum = + uenum_next(ue.getAlias(), nullptr, e)) { ssResult.insert(pStdConvNameEnum); } } @@ -574,7 +598,7 @@ bool CTable::AddColumn(const CString& sName) { CTable::size_type CTable::AddRow() { // Don't add a row if no headers are defined if (m_vsHeaders.empty()) { - return (size_type) -1; + return (size_type)-1; } // Add a vector with enough space for each column @@ -582,19 +606,19 @@ CTable::size_type CTable::AddRow() { return size() - 1; } -bool CTable::SetCell(const CString& sColumn, const CString& sValue, size_type uRowIdx) { - if (uRowIdx == (size_type) ~0) { +bool CTable::SetCell(const CString& sColumn, const CString& sValue, + size_type uRowIdx) { + if (uRowIdx == (size_type)~0) { if (empty()) { return false; } - uRowIdx = size() -1; + uRowIdx = size() - 1; } unsigned int uColIdx = GetColumnIndex(sColumn); - if (uColIdx == (unsigned int) -1) - return false; + if (uColIdx == (unsigned int)-1) return false; (*this)[uRowIdx][uColIdx] = sValue; @@ -632,13 +656,12 @@ VCString CTable::Render() const { unsigned int CTable::GetColumnIndex(const CString& sName) const { for (unsigned int i = 0; i < m_vsHeaders.size(); i++) { - if (m_vsHeaders[i] == sName) - return i; + if (m_vsHeaders[i] == sName) return i; } DEBUG("CTable::GetColumnIndex(" + sName + ") failed"); - return (unsigned int) -1; + return (unsigned int)-1; } void CTable::Clear() { @@ -648,38 +671,37 @@ void CTable::Clear() { } #ifdef HAVE_LIBSSL -CBlowfish::CBlowfish(const CString & sPassword, int iEncrypt, const CString & sIvec) - : m_ivec((unsigned char *)calloc(sizeof(unsigned char), 8)), - m_bkey(), - m_iEncrypt(iEncrypt), - m_num(0) -{ - +CBlowfish::CBlowfish(const CString& sPassword, int iEncrypt, + const CString& sIvec) + : m_ivec((unsigned char*)calloc(sizeof(unsigned char), 8)), + m_bkey(), + m_iEncrypt(iEncrypt), + m_num(0) { if (sIvec.length() >= 8) { memcpy(m_ivec, sIvec.data(), 8); } - BF_set_key(&m_bkey, (unsigned int)sPassword.length(), (unsigned char *)sPassword.data()); + BF_set_key(&m_bkey, (unsigned int)sPassword.length(), + (unsigned char*)sPassword.data()); } -CBlowfish::~CBlowfish() { - free(m_ivec); -} +CBlowfish::~CBlowfish() { free(m_ivec); } //! output must be freed -unsigned char *CBlowfish::MD5(const unsigned char *input, u_int ilen) { - unsigned char *output = (unsigned char *)malloc(MD5_DIGEST_LENGTH); +unsigned char* CBlowfish::MD5(const unsigned char* input, u_int ilen) { + unsigned char* output = (unsigned char*)malloc(MD5_DIGEST_LENGTH); ::MD5(input, ilen, output); return output; } //! returns an md5 of the CString (not hex encoded) -CString CBlowfish::MD5(const CString & sInput, bool bHexEncode) { +CString CBlowfish::MD5(const CString& sInput, bool bHexEncode) { CString sRet; - unsigned char *data = MD5((const unsigned char *)sInput.data(), (unsigned int)sInput.length()); + unsigned char* data = + MD5((const unsigned char*)sInput.data(), (unsigned int)sInput.length()); if (!bHexEncode) { - sRet.append((const char *)data, MD5_DIGEST_LENGTH); + sRet.append((const char*)data, MD5_DIGEST_LENGTH); } else { for (int a = 0; a < MD5_DIGEST_LENGTH; a++) { sRet += g_HexDigits[data[a] >> 4]; @@ -692,23 +714,26 @@ CString CBlowfish::MD5(const CString & sInput, bool bHexEncode) { } //! output must be the same size as input -void CBlowfish::Crypt(unsigned char *input, unsigned char *output, u_int uBytes) { - BF_cfb64_encrypt(input, output, uBytes, &m_bkey, m_ivec, &m_num, m_iEncrypt); +void CBlowfish::Crypt(unsigned char* input, unsigned char* output, + u_int uBytes) { + BF_cfb64_encrypt(input, output, uBytes, &m_bkey, m_ivec, &m_num, + m_iEncrypt); } //! must free result -unsigned char * CBlowfish::Crypt(unsigned char *input, u_int uBytes) { - unsigned char *buff = (unsigned char *)malloc(uBytes); +unsigned char* CBlowfish::Crypt(unsigned char* input, u_int uBytes) { + unsigned char* buff = (unsigned char*)malloc(uBytes); Crypt(input, buff, uBytes); return buff; } -CString CBlowfish::Crypt(const CString & sData) { - unsigned char *buff = Crypt((unsigned char *)sData.data(), (unsigned int)sData.length()); +CString CBlowfish::Crypt(const CString& sData) { + unsigned char* buff = + Crypt((unsigned char*)sData.data(), (unsigned int)sData.length()); CString sOutput; - sOutput.append((const char *)buff, sData.length()); + sOutput.append((const char*)buff, sData.length()); free(buff); return sOutput; } -#endif // HAVE_LIBSSL +#endif // HAVE_LIBSSL diff --git a/src/WebModules.cpp b/src/WebModules.cpp index 211be4b8..01bcebd6 100644 --- a/src/WebModules.cpp +++ b/src/WebModules.cpp @@ -50,8 +50,9 @@ typedef std::multimap::iterator mIPSessionsIterator; static CSessionManager Sessions; class CWebAuth : public CAuthBase { -public: - CWebAuth(CWebSock* pWebSock, const CString& sUsername, const CString& sPassword, bool bBasic); + public: + CWebAuth(CWebSock* pWebSock, const CString& sUsername, + const CString& sPassword, bool bBasic); virtual ~CWebAuth() {} CWebAuth(const CWebAuth&) = delete; @@ -61,9 +62,10 @@ public: void AcceptedLogin(CUser& User) override; void RefusedLogin(const CString& sReason) override; void Invalidate() override; -private: -protected: - CWebSock* m_pWebSock; + + private: + protected: + CWebSock* m_pWebSock; bool m_bBasic; }; @@ -74,7 +76,7 @@ void CWebSock::FinishUserSessions(const CUser& User) { CWebSession::~CWebSession() { // Find our entry in mIPSessions pair p = - Sessions.m_mIPSessions.equal_range(m_sIP); + Sessions.m_mIPSessions.equal_range(m_sIP); mIPSessionsIterator it = p.first; mIPSessionsIterator end = p.second; @@ -87,12 +89,13 @@ CWebSession::~CWebSession() { } } -CZNCTagHandler::CZNCTagHandler(CWebSock& WebSock) : CTemplateTagHandler(), m_WebSock(WebSock) { -} +CZNCTagHandler::CZNCTagHandler(CWebSock& WebSock) + : CTemplateTagHandler(), m_WebSock(WebSock) {} -bool CZNCTagHandler::HandleTag(CTemplate& Tmpl, const CString& sName, const CString& sArgs, CString& sOutput) { +bool CZNCTagHandler::HandleTag(CTemplate& Tmpl, const CString& sName, + const CString& sArgs, CString& sOutput) { if (sName.Equals("URLPARAM")) { - //sOutput = CZNC::Get() + // sOutput = CZNC::Get() sOutput = m_WebSock.GetParam(sArgs.Token(0), false); return true; } @@ -100,20 +103,26 @@ bool CZNCTagHandler::HandleTag(CTemplate& Tmpl, const CString& sName, const CStr return false; } -CWebSession::CWebSession(const CString& sId, const CString& sIP) : m_sId(sId), m_sIP(sIP), m_pUser(nullptr), m_vsErrorMsgs(), m_vsSuccessMsgs(), m_tmLastActive() { +CWebSession::CWebSession(const CString& sId, const CString& sIP) + : m_sId(sId), + m_sIP(sIP), + m_pUser(nullptr), + m_vsErrorMsgs(), + m_vsSuccessMsgs(), + m_tmLastActive() { Sessions.m_mIPSessions.insert(make_pair(sIP, this)); UpdateLastActive(); } -void CWebSession::UpdateLastActive() { - time(&m_tmLastActive); -} +void CWebSession::UpdateLastActive() { time(&m_tmLastActive); } bool CWebSession::IsAdmin() const { return IsLoggedIn() && m_pUser->IsAdmin(); } -CWebAuth::CWebAuth(CWebSock* pWebSock, const CString& sUsername, const CString& sPassword, bool bBasic) - : CAuthBase(sUsername, sPassword, pWebSock), m_pWebSock(pWebSock), m_bBasic(bBasic) { -} +CWebAuth::CWebAuth(CWebSock* pWebSock, const CString& sUsername, + const CString& sPassword, bool bBasic) + : CAuthBase(sUsername, sPassword, pWebSock), + m_pWebSock(pWebSock), + m_bBasic(bBasic) {} void CWebSession::ClearMessageLoops() { m_vsErrorMsgs.clear(); @@ -168,7 +177,8 @@ void CWebAuth::AcceptedLogin(CUser& User) { m_pWebSock->Redirect("/?cookie_check=true"); } - DEBUG("Successful login attempt ==> USER [" + User.GetUserName() + "] ==> SESSION [" + spSession->GetId() + "]"); + DEBUG("Successful login attempt ==> USER [" + User.GetUserName() + + "] ==> SESSION [" + spSession->GetId() + "]"); } } @@ -183,13 +193,16 @@ void CWebAuth::RefusedLogin(const CString& sReason) { m_pWebSock->UnPauseRead(); if (m_bBasic) { m_pWebSock->AddHeader("WWW-Authenticate", "Basic realm=\"ZNC\""); - m_pWebSock->CHTTPSock::PrintErrorPage(401, "Unauthorized", "HTTP Basic authentication attemped with invalid credentials"); + m_pWebSock->CHTTPSock::PrintErrorPage( + 401, "Unauthorized", + "HTTP Basic authentication attemped with invalid credentials"); // Why CWebSock makes this function protected?.. } else { m_pWebSock->Redirect("/?cookie_check=true"); } - DEBUG("UNSUCCESSFUL login attempt ==> REASON [" + sReason + "] ==> SESSION [" + spSession->GetId() + "]"); + DEBUG("UNSUCCESSFUL login attempt ==> REASON [" + sReason + + "] ==> SESSION [" + spSession->GetId() + "]"); } } @@ -198,9 +211,15 @@ void CWebAuth::Invalidate() { m_pWebSock = nullptr; } -CWebSock::CWebSock(const CString& sURIPrefix) : CHTTPSock(nullptr, sURIPrefix), - m_bPathsSet(false), m_Template(), m_spAuth(), m_sModName(""), m_sPath(""), m_sPage(""), m_spSession() -{ +CWebSock::CWebSock(const CString& sURIPrefix) + : CHTTPSock(nullptr, sURIPrefix), + m_bPathsSet(false), + m_Template(), + m_spAuth(), + m_sModName(""), + m_sPath(""), + m_sPage(""), + m_spSession() { m_Template.AddTagHandler(std::make_shared(*this)); } @@ -211,7 +230,7 @@ CWebSock::~CWebSock() { // we have to account for traffic here because CSocket does // not have a valid CModule* pointer. - CUser *pUser = GetSession()->GetUser(); + CUser* pUser = GetSession()->GetUser(); if (pUser) { pUser->AddBytesWritten(GetBytesWritten()); pUser->AddBytesRead(GetBytesRead()); @@ -249,7 +268,8 @@ void CWebSock::GetAvailSkins(VCString& vRet) const { } for (const CFile* pSubDir : Dir) { - if (pSubDir->IsDir() && pSubDir->GetShortName() != "_default_" && pSubDir->GetShortName() != ".svn") { + if (pSubDir->IsDir() && pSubDir->GetShortName() != "_default_" && + pSubDir->GetShortName() != ".svn") { vRet.push_back(pSubDir->GetShortName()); } } @@ -269,12 +289,14 @@ VCString CWebSock::GetDirs(CModule* pModule, bool bIsTemplate) { // 1. ~/.znc/webskins//mods// // if (!sSkinName.empty()) { - vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName + "/"); + vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName + + "/"); } // 2. ~/.znc/webskins/_default_/mods// // - vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName + "/"); + vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName + + "/"); // 3. ./modules//tmpl/ // @@ -283,23 +305,27 @@ VCString CWebSock::GetDirs(CModule* pModule, bool bIsTemplate) { // 4. ~/.znc/webskins//mods// // if (!sSkinName.empty()) { - vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName + "/"); + vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName + + "/"); } // 5. ~/.znc/webskins/_default_/mods// // - vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName + "/"); + vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName + + "/"); } // 6. ~/.znc/webskins// // if (!sSkinName.empty()) { - vsResult.push_back(GetSkinPath(sSkinName) + CString(bIsTemplate ? "/tmpl/" : "/")); + vsResult.push_back(GetSkinPath(sSkinName) + + CString(bIsTemplate ? "/tmpl/" : "/")); } // 7. ~/.znc/webskins/_default_/ // - vsResult.push_back(GetSkinPath("_default_") + CString(bIsTemplate ? "/tmpl/" : "/")); + vsResult.push_back(GetSkinPath("_default_") + + CString(bIsTemplate ? "/tmpl/" : "/")); return vsResult; } @@ -375,14 +401,17 @@ void CWebSock::SetVars() { } } -bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, CTemplate *pTemplate) { +bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, + CTemplate* pTemplate) { if (!pTemplate) { pTemplate = &m_Template; } CString sTitle(Module.GetWebMenuTitle()); - if (!sTitle.empty() && (IsLoggedIn() || (!Module.WebRequiresLogin() && !Module.WebRequiresAdmin())) && (GetSession()->IsAdmin() || !Module.WebRequiresAdmin())) { + if (!sTitle.empty() && (IsLoggedIn() || (!Module.WebRequiresLogin() && + !Module.WebRequiresAdmin())) && + (GetSession()->IsAdmin() || !Module.WebRequiresAdmin())) { CTemplate& Row = pTemplate->AddRow(sLoopName); bool bActiveModule = false; @@ -392,12 +421,15 @@ bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, CTemplate * if (m_sModName == Module.GetModName()) { CString sModuleType = GetPath().Token(1, false, "/"); - if (sModuleType == "global" && Module.GetType() == CModInfo::GlobalModule) { + if (sModuleType == "global" && + Module.GetType() == CModInfo::GlobalModule) { bActiveModule = true; - } else if (sModuleType == "user" && Module.GetType() == CModInfo::UserModule) { + } else if (sModuleType == "user" && + Module.GetType() == CModInfo::UserModule) { bActiveModule = true; - } else if (sModuleType == "network" && Module.GetType() == CModInfo::NetworkModule) { - CIRCNetwork *Network = Module.GetNetwork(); + } else if (sModuleType == "network" && + Module.GetType() == CModInfo::NetworkModule) { + CIRCNetwork* Network = Module.GetNetwork(); if (Network) { CString sNetworkName = GetPath().Token(2, false, "/"); if (sNetworkName == Network->GetName()) { @@ -420,11 +452,14 @@ bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, CTemplate * VWebSubPages& vSubPages = Module.GetSubPages(); for (TWebSubPage& SubPage : vSubPages) { - // bActive is whether or not the current url matches this subpage (params will be checked below) - bool bActive = (m_sModName == Module.GetModName() && m_sPage == SubPage->GetName() && bActiveModule); + // bActive is whether or not the current url matches this subpage + // (params will be checked below) + bool bActive = (m_sModName == Module.GetModName() && + m_sPage == SubPage->GetName() && bActiveModule); if (SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) { - continue; // Don't add admin-only subpages to requests from non-admin users + continue; // Don't add admin-only subpages to requests from + // non-admin users } CTemplate& SubRow = Row.AddRow("SubPageLoop"); @@ -432,7 +467,8 @@ bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, CTemplate * SubRow["ModName"] = Module.GetModName(); SubRow["ModPath"] = Module.GetWebPath(); SubRow["PageName"] = SubPage->GetName(); - SubRow["Title"] = SubPage->GetTitle().empty() ? SubPage->GetName() : SubPage->GetTitle(); + SubRow["Title"] = SubPage->GetTitle().empty() ? SubPage->GetName() + : SubPage->GetTitle(); CString& sParams = SubRow["Params"]; @@ -466,17 +502,21 @@ bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module, CTemplate * return false; } -CWebSock::EPageReqResult CWebSock::PrintStaticFile(const CString& sPath, CString& sPageRet, CModule* pModule) { +CWebSock::EPageReqResult CWebSock::PrintStaticFile(const CString& sPath, + CString& sPageRet, + CModule* pModule) { SetPaths(pModule); CString sFile = m_Template.ExpandFile(sPath.TrimLeft_n("/")); - DEBUG("About to print [" + sFile+ "]"); + DEBUG("About to print [" + sFile + "]"); // Either PrintFile() fails and sends an error page or it suceeds and // sends a result. In both cases we don't have anything more to do. PrintFile(sFile); return PAGE_DONE; } -CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName, CString& sPageRet, CModule* pModule) { +CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName, + CString& sPageRet, + CModule* pModule) { SetVars(); m_Template["PageName"] = sPageName; @@ -488,8 +528,10 @@ CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName, CStri m_Template["Title"] = pModule->GetWebMenuTitle(); } - std::vector* breadcrumbs = m_Template.GetLoop("BreadCrumbs"); - if (breadcrumbs->size() == 1 && m_Template["Title"] != pModule->GetModName()) { + std::vector* breadcrumbs = + m_Template.GetLoop("BreadCrumbs"); + if (breadcrumbs->size() == 1 && + m_Template["Title"] != pModule->GetModName()) { // Module didn't add its own breadcrumbs, so add a generic one... // But it'll be useless if it's the same as module name CTemplate& bread = m_Template.AddRow("BreadCrumbs"); @@ -501,7 +543,8 @@ CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName, CStri SetPaths(pModule, true); } - if (m_Template.GetFileName().empty() && !m_Template.SetFile(sPageName + ".tmpl")) { + if (m_Template.GetFileName().empty() && + !m_Template.SetFile(sPageName + ".tmpl")) { return PAGE_NOTFOUND; } @@ -541,7 +584,8 @@ CString CWebSock::GetRequestCookie(const CString& sKey) { CString sRet; if (!m_sModName.empty()) { - sRet = CHTTPSock::GetRequestCookie("Mod-" + m_sModName + "-" + sPrefixedKey); + sRet = CHTTPSock::GetRequestCookie("Mod-" + m_sModName + "-" + + sPrefixedKey); } if (sRet.empty()) { @@ -555,7 +599,8 @@ bool CWebSock::SendCookie(const CString& sKey, const CString& sValue) { const CString sPrefixedKey = CString(GetLocalPort()) + "-" + sKey; if (!m_sModName.empty()) { - return CHTTPSock::SendCookie("Mod-" + m_sModName + "-" + sPrefixedKey, sValue); + return CHTTPSock::SendCookie("Mod-" + m_sModName + "-" + sPrefixedKey, + sValue); } return CHTTPSock::SendCookie(sPrefixedKey, sValue); @@ -565,36 +610,39 @@ void CWebSock::OnPageRequest(const CString& sURI) { CString sPageRet; EPageReqResult eRet = OnPageRequestInternal(sURI, sPageRet); switch (eRet) { - case PAGE_PRINT: - PrintPage(sPageRet); - break; - case PAGE_DEFERRED: - // Something else will later call Close() - break; - case PAGE_DONE: - // Redirect or something like that, it's done, just make sure - // the connection will be closed - Close(CLT_AFTERWRITE); - break; - case PAGE_NOTFOUND: - default: - PrintNotFound(); - break; + case PAGE_PRINT: + PrintPage(sPageRet); + break; + case PAGE_DEFERRED: + // Something else will later call Close() + break; + case PAGE_DONE: + // Redirect or something like that, it's done, just make sure + // the connection will be closed + Close(CLT_AFTERWRITE); + break; + case PAGE_NOTFOUND: + default: + PrintNotFound(); + break; } } -CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CString& sPageRet) { +CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, + CString& sPageRet) { // Check that their session really belongs to their IP address. IP-based // authentication is bad, but here it's just an extra layer that makes // stealing cookies harder to pull off. // // When their IP is wrong, we give them an invalid cookie. This makes // sure that they will get a new cookie on their next request. - if (CZNC::Get().GetProtectWebSessions() && GetSession()->GetIP() != GetRemoteIP()) { + if (CZNC::Get().GetProtectWebSessions() && + GetSession()->GetIP() != GetRemoteIP()) { DEBUG("Expected IP: " << GetSession()->GetIP()); DEBUG("Remote IP: " << GetRemoteIP()); SendCookie("SessionId", "WRONG_IP_FOR_SESSION"); - PrintErrorPage(403, "Access denied", "This session does not belong to your IP."); + PrintErrorPage(403, "Access denied", + "This session does not belong to your IP."); return PAGE_DONE; } @@ -604,12 +652,16 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS // cookies-enabled check which would break otherwise. // Don't do this, if user authenticated using http-basic auth, because: // 1. they obviously know the password, - // 2. it's easier to automate some tasks e.g. user creation, without need to care about cookies and csrf - if (IsPost() && !m_bBasicAuth && GetParam("_CSRF_Check") != GetCSRFCheck() && sURI != "/login") { + // 2. it's easier to automate some tasks e.g. user creation, without need to + // care about cookies and csrf + if (IsPost() && !m_bBasicAuth && + GetParam("_CSRF_Check") != GetCSRFCheck() && sURI != "/login") { DEBUG("Expected _CSRF_Check: " << GetCSRFCheck()); DEBUG("Actual _CSRF_Check: " << GetParam("_CSRF_Check")); - PrintErrorPage(403, "Access denied", "POST requests need to send " - "a secret token to prevent cross-site request forgery attacks."); + PrintErrorPage( + 403, "Access denied", + "POST requests need to send " + "a secret token to prevent cross-site request forgery attacks."); return PAGE_DONE; } @@ -622,8 +674,10 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS // Handle the static pages that don't require a login if (sURI == "/") { - if(!m_bLoggedIn && GetParam("cookie_check", false).ToBool() && GetRequestCookie("SessionId").empty()) { - GetSession()->AddError("Your browser does not have cookies enabled for this site!"); + if (!m_bLoggedIn && GetParam("cookie_check", false).ToBool() && + GetRequestCookie("SessionId").empty()) { + GetSession()->AddError( + "Your browser does not have cookies enabled for this site!"); } return PrintTemplate("index", sPageRet); } else if (sURI == "/favicon.ico") { @@ -647,7 +701,7 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS return PAGE_DEFERRED; } - Redirect("/"); // the login form is here + Redirect("/"); // the login form is here return PAGE_DONE; } else if (sURI.StartsWith("/pub/")) { return PrintStaticFile(sURI, sPageRet); @@ -670,7 +724,8 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS return PAGE_NOTFOUND; } else if (sURI.StartsWith("/mods/") || sURI.StartsWith("/modfiles/")) { // Make sure modules are treated as directories - if (!sURI.EndsWith("/") && !sURI.Contains(".") && !sURI.TrimLeft_n("/mods/").TrimLeft_n("/").Contains("/")) { + if (!sURI.EndsWith("/") && !sURI.Contains(".") && + !sURI.TrimLeft_n("/mods/").TrimLeft_n("/").Contains("/")) { Redirect(sURI + "/"); return PAGE_DONE; } @@ -694,7 +749,8 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS } else if (sType.Equals("network")) { eModType = CModInfo::NetworkModule; } else { - PrintErrorPage(403, "Forbidden", "Unknown module type [" + sType + "]"); + PrintErrorPage(403, "Forbidden", + "Unknown module type [" + sType + "]"); return PAGE_DONE; } @@ -703,7 +759,7 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS return PAGE_DONE; } - CIRCNetwork *pNetwork = nullptr; + CIRCNetwork* pNetwork = nullptr; if (eModType == CModInfo::NetworkModule) { CString sNetwork = m_sPath.Token(0, false, "/"); m_sPath = m_sPath.Token(1, true, "/"); @@ -711,7 +767,8 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS pNetwork = GetSession()->GetUser()->FindNetwork(sNetwork); if (!pNetwork) { - PrintErrorPage(404, "Not Found", "Network [" + sNetwork + "] not found."); + PrintErrorPage(404, "Not Found", + "Network [" + sNetwork + "] not found."); return PAGE_DONE; } } @@ -723,24 +780,25 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS m_sPage = "index"; } - DEBUG("Path [" + m_sPath + "], Module [" + m_sModName + "], Page [" + m_sPage + "]"); + DEBUG("Path [" + m_sPath + "], Module [" + m_sModName + "], Page [" + + m_sPage + "]"); - CModule *pModule = nullptr; + CModule* pModule = nullptr; switch (eModType) { case CModInfo::GlobalModule: pModule = CZNC::Get().GetModules().FindModule(m_sModName); break; case CModInfo::UserModule: - pModule = GetSession()->GetUser()->GetModules().FindModule(m_sModName); + pModule = GetSession()->GetUser()->GetModules().FindModule( + m_sModName); break; case CModInfo::NetworkModule: pModule = pNetwork->GetModules().FindModule(m_sModName); break; } - if (!pModule) - return PAGE_NOTFOUND; + if (!pModule) return PAGE_NOTFOUND; m_Template["ModPath"] = pModule->GetWebPath(); m_Template["ModFilesPath"] = pModule->GetWebFilesPath(); @@ -748,10 +806,15 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS if (pModule->WebRequiresLogin() && !ForceLogin()) { return PAGE_PRINT; } else if (pModule->WebRequiresAdmin() && !GetSession()->IsAdmin()) { - PrintErrorPage(403, "Forbidden", "You need to be an admin to access this module"); + PrintErrorPage(403, "Forbidden", + "You need to be an admin to access this module"); return PAGE_DONE; - } else if (pModule->GetType() != CModInfo::GlobalModule && pModule->GetUser() != GetSession()->GetUser()) { - PrintErrorPage(403, "Forbidden", "You must login as " + pModule->GetUser()->GetUserName() + " in order to view this page"); + } else if (pModule->GetType() != CModInfo::GlobalModule && + pModule->GetUser() != GetSession()->GetUser()) { + PrintErrorPage(403, "Forbidden", + "You must login as " + + pModule->GetUser()->GetUserName() + + " in order to view this page"); return PAGE_DONE; } else if (pModule->OnWebPreRequest(*this, m_sPage)) { return PAGE_DEFERRED; @@ -760,20 +823,25 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS VWebSubPages& vSubPages = pModule->GetSubPages(); for (TWebSubPage& SubPage : vSubPages) { - bool bActive = (m_sModName == pModule->GetModName() && m_sPage == SubPage->GetName()); + bool bActive = (m_sModName == pModule->GetModName() && + m_sPage == SubPage->GetName()); - if (bActive && SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) { - PrintErrorPage(403, "Forbidden", "You need to be an admin to access this page"); + if (bActive && SubPage->RequiresAdmin() && + !GetSession()->IsAdmin()) { + PrintErrorPage(403, "Forbidden", + "You need to be an admin to access this page"); return PAGE_DONE; } } - if (pModule && pModule->GetType() != CModInfo::GlobalModule && (!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) { + if (pModule && pModule->GetType() != CModInfo::GlobalModule && + (!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) { AddModLoop("UserModLoop", *pModule); } if (sURI.StartsWith("/modfiles/")) { - m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" + m_sModName + "/files/"); + m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" + + m_sModName + "/files/"); m_Template.AppendPath(pModule->GetModDataDir() + "/files/"); if (PrintFile(m_Template.ExpandFile(m_sPage.TrimLeft_n("/")))) { @@ -789,7 +857,8 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS breadModule["URL"] = pModule->GetWebPath(); /* if a module returns false from OnWebRequest, it does not - want the template to be printed, usually because it did a redirect. */ + want the template to be printed, usually because it did a + redirect. */ if (pModule->OnWebRequest(*this, m_sPage, m_Template)) { // If they already sent a reply, let's assume // they did what they wanted to do. @@ -800,7 +869,9 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS } if (!SentHeader()) { - PrintErrorPage(404, "Not Implemented", "The requested module does not acknowledge web requests"); + PrintErrorPage( + 404, "Not Implemented", + "The requested module does not acknowledge web requests"); } return PAGE_DONE; } @@ -810,7 +881,8 @@ CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CS for (unsigned int a = 0; a < sPage.length(); a++) { unsigned char c = sPage[a]; - if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') { + if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && + (c < 'A' || c > 'Z') && c != '_') { return PAGE_NOTFOUND; } } @@ -830,7 +902,9 @@ void CWebSock::PrintErrorPage(const CString& sMessage) { m_Template["Error"] = sMessage; } -static inline bool compareLastActive(const std::pair &first, const std::pair &second) { +static inline bool compareLastActive( + const std::pair& first, + const std::pair& second) { return first.second->GetLastActive() < second.second->GetLastActive(); } @@ -840,22 +914,30 @@ std::shared_ptr CWebSock::GetSession() { } const CString sCookieSessionId = GetRequestCookie("SessionId"); - std::shared_ptr *pSession = Sessions.m_mspSessions.GetItem(sCookieSessionId); + std::shared_ptr* pSession = + Sessions.m_mspSessions.GetItem(sCookieSessionId); if (pSession != nullptr) { // Refresh the timeout Sessions.m_mspSessions.AddItem((*pSession)->GetId(), *pSession); (*pSession)->UpdateLastActive(); m_spSession = *pSession; - DEBUG("Found existing session from cookie: [" + sCookieSessionId + "] IsLoggedIn(" + CString((*pSession)->IsLoggedIn() ? "true, " + ((*pSession)->GetUser()->GetUserName()) : "false") + ")"); + DEBUG("Found existing session from cookie: [" + sCookieSessionId + + "] IsLoggedIn(" + + CString((*pSession)->IsLoggedIn() + ? "true, " + ((*pSession)->GetUser()->GetUserName()) + : "false") + + ")"); return *pSession; } if (Sessions.m_mIPSessions.count(GetRemoteIP()) > m_uiMaxSessions) { pair p = - Sessions.m_mIPSessions.equal_range(GetRemoteIP()); - mIPSessionsIterator it = std::min_element(p.first, p.second, compareLastActive); - DEBUG("Remote IP: " << GetRemoteIP() << "; discarding session [" << it->second->GetId() << "]"); + Sessions.m_mIPSessions.equal_range(GetRemoteIP()); + mIPSessionsIterator it = + std::min_element(p.first, p.second, compareLastActive); + DEBUG("Remote IP: " << GetRemoteIP() << "; discarding session [" + << it->second->GetId() << "]"); Sessions.m_mspSessions.RemItem(it->second->GetId()); } @@ -863,14 +945,15 @@ std::shared_ptr CWebSock::GetSession() { do { sSessionID = CString::RandomString(32); sSessionID += ":" + GetRemoteIP() + ":" + CString(GetRemotePort()); - sSessionID += ":" + GetLocalIP() + ":" + CString(GetLocalPort()); + sSessionID += ":" + GetLocalIP() + ":" + CString(GetLocalPort()); sSessionID += ":" + CString(time(nullptr)); sSessionID = sSessionID.SHA256(); DEBUG("Auto generated session: [" + sSessionID + "]"); } while (Sessions.m_mspSessions.HasItem(sSessionID)); - std::shared_ptr spSession(new CWebSession(sSessionID, GetRemoteIP())); + std::shared_ptr spSession( + new CWebSession(sSessionID, GetRemoteIP())); Sessions.m_mspSessions.AddItem(spSession->GetId(), spSession); m_spSession = spSession; @@ -883,8 +966,10 @@ CString CWebSock::GetCSRFCheck() { return pSession->GetId().MD5(); } -bool CWebSock::OnLogin(const CString& sUser, const CString& sPass, bool bBasic) { - DEBUG("=================== CWebSock::OnLogin(), basic auth? " << std::boolalpha << bBasic); +bool CWebSock::OnLogin(const CString& sUser, const CString& sPass, + bool bBasic) { + DEBUG("=================== CWebSock::OnLogin(), basic auth? " + << std::boolalpha << bBasic); m_spAuth = std::make_shared(this, sUser, sPass, bBasic); // Some authentication module could need some time, block this socket @@ -906,10 +991,10 @@ Csock* CWebSock::GetSockObj(const CString& sHost, unsigned short uPort) { CString CWebSock::GetSkinName() { std::shared_ptr spSession = GetSession(); - if (spSession->IsLoggedIn() && !spSession->GetUser()->GetSkinName().empty()) { + if (spSession->IsLoggedIn() && + !spSession->GetUser()->GetSkinName().empty()) { return spSession->GetUser()->GetSkinName(); } return CZNC::Get().GetSkinName(); } - diff --git a/src/ZNCDebug.cpp b/src/ZNCDebug.cpp index be2f77f2..82efa73e 100644 --- a/src/ZNCDebug.cpp +++ b/src/ZNCDebug.cpp @@ -23,21 +23,23 @@ bool CDebug::stdoutIsTTY = true; bool CDebug::debug = #ifdef _DEBUG - true; + true; #else - false; + false; #endif CDebugStream::~CDebugStream() { timeval tTime; gettimeofday(&tTime, nullptr); - time_t tSec = (time_t)tTime.tv_sec; // some systems (e.g. openbsd) define tv_sec as long int instead of time_t + time_t tSec = (time_t)tTime.tv_sec; // some systems (e.g. openbsd) define + // tv_sec as long int instead of time_t tm tM; - tzset();// localtime_r requires this + tzset(); // localtime_r requires this localtime_r(&tSec, &tM); char sTime[20] = {}; strftime(sTime, sizeof(sTime), "%Y-%m-%d %H:%M:%S", &tM); char sUsec[7] = {}; snprintf(sUsec, sizeof(sUsec), "%06lu", (unsigned long int)tTime.tv_usec); - std::cout << "[" << sTime << "." << sUsec << "] " << CString(this->str()).Escape_n(CString::EDEBUG) << std::endl; + std::cout << "[" << sTime << "." << sUsec << "] " + << CString(this->str()).Escape_n(CString::EDEBUG) << std::endl; } diff --git a/src/ZNCString.cpp b/src/ZNCString.cpp index 09c13e14..2a45498a 100644 --- a/src/ZNCString.cpp +++ b/src/ZNCString.cpp @@ -23,20 +23,72 @@ using std::stringstream; -CString::CString(char c) : string() { stringstream s; s << c; *this = s.str(); } -CString::CString(unsigned char c) : string() { stringstream s; s << c; *this = s.str(); } -CString::CString(short i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(unsigned short i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(int i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(unsigned int i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(long i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(unsigned long i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(long long i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(unsigned long long i) : string() { stringstream s; s << i; *this = s.str(); } -CString::CString(double i, int precision) : string() { stringstream s; s.precision(precision); s << std::fixed << i; *this = s.str(); } -CString::CString(float i, int precision) : string() { stringstream s; s.precision(precision); s << std::fixed << i; *this = s.str(); } +CString::CString(char c) : string() { + stringstream s; + s << c; + *this = s.str(); +} +CString::CString(unsigned char c) : string() { + stringstream s; + s << c; + *this = s.str(); +} +CString::CString(short i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(unsigned short i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(int i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(unsigned int i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(long i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(unsigned long i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(long long i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(unsigned long long i) : string() { + stringstream s; + s << i; + *this = s.str(); +} +CString::CString(double i, int precision) : string() { + stringstream s; + s.precision(precision); + s << std::fixed << i; + *this = s.str(); +} +CString::CString(float i, int precision) : string() { + stringstream s; + s.precision(precision); + s << std::fixed << i; + *this = s.str(); +} -unsigned char* CString::strnchr(const unsigned char* src, unsigned char c, unsigned int iMaxBytes, unsigned char* pFill, unsigned int* piCount) const { +unsigned char* CString::strnchr(const unsigned char* src, unsigned char c, + unsigned int iMaxBytes, unsigned char* pFill, + unsigned int* piCount) const { for (unsigned int a = 0; a < iMaxBytes && *src; a++, src++) { if (pFill) { pFill[a] = *src; @@ -44,14 +96,14 @@ unsigned char* CString::strnchr(const unsigned char* src, unsigned char c, unsig if (*src == c) { if (pFill) { - pFill[a +1] = 0; + pFill[a + 1] = 0; } if (piCount) { *piCount = a; } - return (unsigned char*) src; + return (unsigned char*)src; } } @@ -88,7 +140,8 @@ bool CString::Equals(const CString& s, CaseSensitivity cs) const { } } -bool CString::Equals(const CString& s, bool bCaseSensitive, CString::size_type uLen) const { +bool CString::Equals(const CString& s, bool bCaseSensitive, + CString::size_type uLen) const { if (bCaseSensitive) { return (StrCmp(s, uLen) == 0); } else { @@ -96,16 +149,19 @@ bool CString::Equals(const CString& s, bool bCaseSensitive, CString::size_type u } } -bool CString::WildCmp(const CString& sWild, const CString& sString, CaseSensitivity cs) { - // avoid a copy when cs == CaseSensitive (C++ deliberately specifies that binding - // a temporary object to a reference to const on the stack lengthens the lifetime +bool CString::WildCmp(const CString& sWild, const CString& sString, + CaseSensitivity cs) { + // avoid a copy when cs == CaseSensitive (C++ deliberately specifies that + // binding + // a temporary object to a reference to const on the stack lengthens the + // lifetime // of the temporary to the lifetime of the reference itself) const CString& sWld = (cs == CaseSensitive ? sWild : sWild.AsLower()); const CString& sStr = (cs == CaseSensitive ? sString : sString.AsLower()); // Written by Jack Handy - jakkhandy@hotmail.com - const char *wild = sWld.c_str(), *CString = sStr.c_str(); - const char *cp = nullptr, *mp = nullptr; + const char* wild = sWld.c_str(), *CString = sStr.c_str(); + const char* cp = nullptr, *mp = nullptr; while ((*CString) && (*wild != '*')) { if ((*wild != *CString) && (*wild != '?')) { @@ -123,7 +179,7 @@ bool CString::WildCmp(const CString& sWild, const CString& sString, CaseSensitiv } mp = wild; - cp = CString+1; + cp = CString + 1; } else if ((*wild == *CString) || (*wild == '?')) { wild++; CString++; @@ -146,7 +202,7 @@ bool CString::WildCmp(const CString& sWild, CaseSensitivity cs) const { CString& CString::MakeUpper() { for (char& c : *this) { - //TODO use unicode + // TODO use unicode c = (char)toupper(c); } @@ -155,7 +211,7 @@ CString& CString::MakeUpper() { CString& CString::MakeLower() { for (char& c : *this) { - //TODO use unicode + // TODO use unicode c = (char)tolower(c); } @@ -199,10 +255,10 @@ CString::EEscape CString::ToEscape(const CString& sEsc) { CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { CString sRet; const char szHex[] = "0123456789ABCDEF"; - const unsigned char *pStart = (const unsigned char*) data(); - const unsigned char *p = (const unsigned char*) data(); + const unsigned char* pStart = (const unsigned char*)data(); + const unsigned char* p = (const unsigned char*)data(); size_type iLength = length(); - sRet.reserve(iLength *3); + sRet.reserve(iLength * 3); unsigned char pTmp[21]; unsigned int iCounted = 0; @@ -211,10 +267,14 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { switch (eFrom) { case EHTML: - if ((*p == '&') && (strnchr((unsigned char*) p, ';', sizeof(pTmp) - 1, pTmp, &iCounted))) { - // please note that we do not have any Unicode or UTF-8 support here at all. + if ((*p == '&') && + (strnchr((unsigned char*)p, ';', sizeof(pTmp) - 1, pTmp, + &iCounted))) { + // please note that we do not have any Unicode or UTF-8 + // support here at all. - if ((iCounted >= 3) && (pTmp[1] == '#')) { // do XML and HTML a < + if ((iCounted >= 3) && + (pTmp[1] == '#')) { // do XML and HTML a < int base = 10; if ((pTmp[2] & 0xDF) == 'X') { @@ -222,9 +282,13 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { } char* endptr = nullptr; - unsigned long int b = strtol((const char*) (pTmp +2 + (base == 16)), &endptr, base); + unsigned long int b = + strtol((const char*)(pTmp + 2 + (base == 16)), + &endptr, base); - if ((*endptr == ';') && (b <= 255)) { // incase they do something like � + if ((*endptr == ';') && (b <= 255)) { // incase they do + // something like + // � ch = (unsigned char)b; a += iCounted; break; @@ -232,16 +296,20 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { } if (ch == 0) { - if (!strncasecmp((const char*) &pTmp, "<", 2)) ch = '<'; - else if (!strncasecmp((const char*) &pTmp, ">", 2)) ch = '>'; - else if (!strncasecmp((const char*) &pTmp, """, 4)) ch = '"'; - else if (!strncasecmp((const char*) &pTmp, "&", 3)) ch = '&'; + if (!strncasecmp((const char*)&pTmp, "<", 2)) + ch = '<'; + else if (!strncasecmp((const char*)&pTmp, ">", 2)) + ch = '>'; + else if (!strncasecmp((const char*)&pTmp, """, 4)) + ch = '"'; + else if (!strncasecmp((const char*)&pTmp, "&", 3)) + ch = '&'; } if (ch > 0) { a += iCounted; } else { - ch = *p; // Not a valid escape, just record the & + ch = *p; // Not a valid escape, just record the & } } else { ch = *p; @@ -251,19 +319,20 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { ch = *p; break; case EURL: - if (*p == '%' && (a +2) < iLength && isxdigit(*(p +1)) && isxdigit(*(p +2))) { + if (*p == '%' && (a + 2) < iLength && isxdigit(*(p + 1)) && + isxdigit(*(p + 2))) { p++; if (isdigit(*p)) { ch = (unsigned char)((*p - '0') << 4); } else { - ch = (unsigned char)((tolower(*p) - 'a' +10) << 4); + ch = (unsigned char)((tolower(*p) - 'a' + 10) << 4); } p++; if (isdigit(*p)) { ch |= (unsigned char)(*p - '0'); } else { - ch |= (unsigned char)(tolower(*p) - 'a' +10); + ch |= (unsigned char)(tolower(*p) - 'a' + 10); } a += 2; @@ -275,7 +344,7 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case ESQL: - if (*p != '\\' || iLength < (a +1)) { + if (*p != '\\' || iLength < (a + 1)) { ch = *p; } else { a++; @@ -298,7 +367,7 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case ENAMEDFMT: - if (*p != '\\' || iLength < (a +1)) { + if (*p != '\\' || iLength < (a + 1)) { ch = *p; } else { a++; @@ -308,23 +377,24 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case EDEBUG: - if (*p == '\\' && (a +3) < iLength && *(p +1) == 'x' && isxdigit(*(p +2)) && isxdigit(*(p +3))) { + if (*p == '\\' && (a + 3) < iLength && *(p + 1) == 'x' && + isxdigit(*(p + 2)) && isxdigit(*(p + 3))) { p += 2; if (isdigit(*p)) { ch = (unsigned char)((*p - '0') << 4); } else { - ch = (unsigned char)((tolower(*p) - 'a' +10) << 4); + ch = (unsigned char)((tolower(*p) - 'a' + 10) << 4); } p++; if (isdigit(*p)) { ch |= (unsigned char)(*p - '0'); } else { - ch |= (unsigned char)(tolower(*p) - 'a' +10); + ch |= (unsigned char)(tolower(*p) - 'a' + 10); } a += 3; - } else if (*p == '\\' && a+1 < iLength && *(p+1) == '.') { + } else if (*p == '\\' && a + 1 < iLength && *(p + 1) == '.') { a++; p++; ch = '\\'; @@ -334,7 +404,7 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case EMSGTAG: - if (*p != '\\' || iLength < (a +1)) { + if (*p != '\\' || iLength < (a + 1)) { ch = *p; } else { a++; @@ -359,42 +429,45 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case EHEXCOLON: { - while (!isxdigit(*p) && a < iLength) { - a++; - p++; - } - if (a == iLength) { - continue; - } - if (isdigit(*p)) { - ch = (unsigned char)((*p - '0') << 4); - } else { - ch = (unsigned char)((tolower(*p) - 'a' +10) << 4); - } + while (!isxdigit(*p) && a < iLength) { a++; p++; - while (!isxdigit(*p) && a < iLength) { - a++; - p++; - } - if (a == iLength) { - continue; - } - if (isdigit(*p)) { - ch |= (unsigned char)(*p - '0'); - } else { - ch |= (unsigned char)(tolower(*p) - 'a' +10); - } } - break; + if (a == iLength) { + continue; + } + if (isdigit(*p)) { + ch = (unsigned char)((*p - '0') << 4); + } else { + ch = (unsigned char)((tolower(*p) - 'a' + 10) << 4); + } + a++; + p++; + while (!isxdigit(*p) && a < iLength) { + a++; + p++; + } + if (a == iLength) { + continue; + } + if (isdigit(*p)) { + ch |= (unsigned char)(*p - '0'); + } else { + ch |= (unsigned char)(tolower(*p) - 'a' + 10); + } + } break; } switch (eTo) { case EHTML: - if (ch == '<') sRet += "<"; - else if (ch == '>') sRet += ">"; - else if (ch == '"') sRet += """; - else if (ch == '&') sRet += "&"; + if (ch == '<') + sRet += "<"; + else if (ch == '>') + sRet += ">"; + else if (ch == '"') + sRet += """; + else if (ch == '&') + sRet += "&"; else { sRet += ch; } @@ -416,22 +489,48 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case ESQL: - if (ch == '\0') { sRet += '\\'; sRet += '0'; - } else if (ch == '\n') { sRet += '\\'; sRet += 'n'; - } else if (ch == '\t') { sRet += '\\'; sRet += 't'; - } else if (ch == '\r') { sRet += '\\'; sRet += 'r'; - } else if (ch == '\b') { sRet += '\\'; sRet += 'b'; - } else if (ch == '\"') { sRet += '\\'; sRet += '\"'; - } else if (ch == '\'') { sRet += '\\'; sRet += '\''; - } else if (ch == '\\') { sRet += '\\'; sRet += '\\'; - } else { sRet += ch; } + if (ch == '\0') { + sRet += '\\'; + sRet += '0'; + } else if (ch == '\n') { + sRet += '\\'; + sRet += 'n'; + } else if (ch == '\t') { + sRet += '\\'; + sRet += 't'; + } else if (ch == '\r') { + sRet += '\\'; + sRet += 'r'; + } else if (ch == '\b') { + sRet += '\\'; + sRet += 'b'; + } else if (ch == '\"') { + sRet += '\\'; + sRet += '\"'; + } else if (ch == '\'') { + sRet += '\\'; + sRet += '\''; + } else if (ch == '\\') { + sRet += '\\'; + sRet += '\\'; + } else { + sRet += ch; + } break; case ENAMEDFMT: - if (ch == '\\') { sRet += '\\'; sRet += '\\'; - } else if (ch == '{') { sRet += '\\'; sRet += '{'; - } else if (ch == '}') { sRet += '\\'; sRet += '}'; - } else { sRet += ch; } + if (ch == '\\') { + sRet += '\\'; + sRet += '\\'; + } else if (ch == '{') { + sRet += '\\'; + sRet += '{'; + } else if (ch == '}') { + sRet += '\\'; + sRet += '}'; + } else { + sRet += ch; + } break; case EDEBUG: @@ -447,21 +546,34 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { break; case EMSGTAG: - if (ch == ';') { sRet += '\\'; sRet += ':'; - } else if (ch == ' ') { sRet += '\\'; sRet += 's'; - } else if (ch == '\0') { sRet += '\\'; sRet += '0'; - } else if (ch == '\\') { sRet += '\\'; sRet += '\\'; - } else if (ch == '\r') { sRet += '\\'; sRet += 'r'; - } else if (ch == '\n') { sRet += '\\'; sRet += 'n'; - } else { sRet += ch; } + if (ch == ';') { + sRet += '\\'; + sRet += ':'; + } else if (ch == ' ') { + sRet += '\\'; + sRet += 's'; + } else if (ch == '\0') { + sRet += '\\'; + sRet += '0'; + } else if (ch == '\\') { + sRet += '\\'; + sRet += '\\'; + } else if (ch == '\r') { + sRet += '\\'; + sRet += 'r'; + } else if (ch == '\n') { + sRet += '\\'; + sRet += 'n'; + } else { + sRet += ch; + } break; case EHEXCOLON: { - sRet += tolower(szHex[ch >> 4]); - sRet += tolower(szHex[ch & 0xf]); - sRet += ":"; - } - break; + sRet += tolower(szHex[ch >> 4]); + sRet += tolower(szHex[ch & 0xf]); + sRet += ":"; + } break; } } @@ -472,29 +584,32 @@ CString CString::Escape_n(EEscape eFrom, EEscape eTo) const { return sRet; } -CString CString::Escape_n(EEscape eTo) const { - return Escape_n(EASCII, eTo); -} +CString CString::Escape_n(EEscape eTo) const { return Escape_n(EASCII, eTo); } CString& CString::Escape(EEscape eFrom, EEscape eTo) { return (*this = Escape_n(eFrom, eTo)); } -CString& CString::Escape(EEscape eTo) { - return (*this = Escape_n(eTo)); -} +CString& CString::Escape(EEscape eTo) { return (*this = Escape_n(eTo)); } -CString CString::Replace_n(const CString& sReplace, const CString& sWith, const CString& sLeft, const CString& sRight, bool bRemoveDelims) const { +CString CString::Replace_n(const CString& sReplace, const CString& sWith, + const CString& sLeft, const CString& sRight, + bool bRemoveDelims) const { CString sRet = *this; CString::Replace(sRet, sReplace, sWith, sLeft, sRight, bRemoveDelims); return sRet; } -unsigned int CString::Replace(const CString& sReplace, const CString& sWith, const CString& sLeft, const CString& sRight, bool bRemoveDelims) { - return CString::Replace(*this, sReplace, sWith, sLeft, sRight, bRemoveDelims); +unsigned int CString::Replace(const CString& sReplace, const CString& sWith, + const CString& sLeft, const CString& sRight, + bool bRemoveDelims) { + return CString::Replace(*this, sReplace, sWith, sLeft, sRight, + bRemoveDelims); } -unsigned int CString::Replace(CString& sStr, const CString& sReplace, const CString& sWith, const CString& sLeft, const CString& sRight, bool bRemoveDelims) { +unsigned int CString::Replace(CString& sStr, const CString& sReplace, + const CString& sWith, const CString& sLeft, + const CString& sRight, bool bRemoveDelims) { unsigned int uRet = 0; CString sCopy = sStr; sStr.clear(); @@ -506,23 +621,26 @@ unsigned int CString::Replace(CString& sStr, const CString& sReplace, const CStr bool bInside = false; while (*p) { - if (!bInside && uLeftWidth && strncmp(p, sLeft.c_str(), uLeftWidth) == 0) { + if (!bInside && uLeftWidth && + strncmp(p, sLeft.c_str(), uLeftWidth) == 0) { if (!bRemoveDelims) { sStr += sLeft; } - p += uLeftWidth -1; + p += uLeftWidth - 1; bInside = true; - } else if (bInside && uRightWidth && strncmp(p, sRight.c_str(), uRightWidth) == 0) { + } else if (bInside && uRightWidth && + strncmp(p, sRight.c_str(), uRightWidth) == 0) { if (!bRemoveDelims) { sStr += sRight; } - p += uRightWidth -1; + p += uRightWidth - 1; bInside = false; - } else if (!bInside && strncmp(p, sReplace.c_str(), uReplaceWidth) == 0) { + } else if (!bInside && + strncmp(p, sReplace.c_str(), uReplaceWidth) == 0) { sStr += sWith; - p += uReplaceWidth -1; + p += uReplaceWidth - 1; uRet++; } else { sStr.append(p, 1); @@ -534,8 +652,9 @@ unsigned int CString::Replace(CString& sStr, const CString& sReplace, const CStr return uRet; } -CString CString::Token(size_t uPos, bool bRest, const CString& sSep, bool bAllowEmpty, - const CString& sLeft, const CString& sRight, bool bTrimQuotes) const { +CString CString::Token(size_t uPos, bool bRest, const CString& sSep, + bool bAllowEmpty, const CString& sLeft, + const CString& sRight, bool bTrimQuotes) const { VCString vsTokens; if (Split(sSep, vsTokens, bAllowEmpty, sLeft, sRight, bTrimQuotes) > uPos) { CString sRet; @@ -558,10 +677,11 @@ CString CString::Token(size_t uPos, bool bRest, const CString& sSep, bool bAllow return Token(uPos, bRest, sSep, bAllowEmpty); } -CString CString::Token(size_t uPos, bool bRest, const CString& sSep, bool bAllowEmpty) const { - const char *sep_str = sSep.c_str(); +CString CString::Token(size_t uPos, bool bRest, const CString& sSep, + bool bAllowEmpty) const { + const char* sep_str = sSep.c_str(); size_t sep_len = sSep.length(); - const char *str = c_str(); + const char* str = c_str(); size_t str_len = length(); size_t start_pos = 0; size_t end_pos; @@ -576,7 +696,8 @@ CString CString::Token(size_t uPos, bool bRest, const CString& sSep, bool bAllow while (uPos != 0 && start_pos < str_len) { bool bFoundSep = false; - while (strncmp(&str[start_pos], sep_str, sep_len) == 0 && (!bFoundSep || !bAllowEmpty)) { + while (strncmp(&str[start_pos], sep_str, sep_len) == 0 && + (!bFoundSep || !bAllowEmpty)) { start_pos += sep_len; bFoundSep = true; } @@ -589,8 +710,7 @@ CString CString::Token(size_t uPos, bool bRest, const CString& sSep, bool bAllow } // String is over? - if (start_pos >= str_len) - return ""; + if (start_pos >= str_len) return ""; // If they want everything from here on, give it to them if (bRest) { @@ -626,7 +746,7 @@ CString CString::Ellipsize(unsigned int uLen) const { return sRet; } - sRet = substr(0, uLen -3) + "..."; + sRet = substr(0, uLen - 3) + "..."; return sRet; } @@ -648,20 +768,24 @@ CString::size_type CString::URLSplit(MCString& msRet) const { Split("&", vsPairs); for (const CString& sPair : vsPairs) { - msRet[sPair.Token(0, false, "=").Escape(CString::EURL, CString::EASCII)] = sPair.Token(1, true, "=").Escape(CString::EURL, CString::EASCII); + msRet[sPair.Token(0, false, "=") + .Escape(CString::EURL, CString::EASCII)] = + sPair.Token(1, true, "=").Escape(CString::EURL, CString::EASCII); } return msRet.size(); } -CString::size_type CString::OptionSplit(MCString& msRet, bool bUpperKeys) const { +CString::size_type CString::OptionSplit(MCString& msRet, + bool bUpperKeys) const { CString sName; CString sCopy(*this); msRet.clear(); while (!sCopy.empty()) { sName = sCopy.Token(0, false, "=", false, "\"", "\"", false).Trim_n(); - sCopy = sCopy.Token(1, true, "=", false, "\"", "\"", false).TrimLeft_n(); + sCopy = + sCopy.Token(1, true, "=", false, "\"", "\"", false).TrimLeft_n(); if (sName.empty()) { continue; @@ -677,7 +801,7 @@ CString::size_type CString::OptionSplit(MCString& msRet, bool bUpperKeys) const sKeyName.MakeUpper(); } - if ((a +1) == vsNames.size()) { + if ((a + 1) == vsNames.size()) { msRet[sKeyName] = sCopy.Token(0, false, " ", false, "\"", "\""); sCopy = sCopy.Token(1, true, " ", false, "\"", "\"", false); } else { @@ -694,8 +818,10 @@ CString::size_type CString::QuoteSplit(VCString& vsRet) const { return Split(" ", vsRet, false, "\"", "\"", true); } -CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, bool bAllowEmpty, - const CString& sLeft, const CString& sRight, bool bTrimQuotes, bool bTrimWhiteSpace) const { +CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, + bool bAllowEmpty, const CString& sLeft, + const CString& sRight, bool bTrimQuotes, + bool bTrimWhiteSpace) const { vsRet.clear(); if (empty()) { @@ -716,7 +842,8 @@ CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, bool b } while (*p) { - if (uLeftLen && uRightLen && !bInside && strncasecmp(p, sLeft.c_str(), uLeftLen) == 0) { + if (uLeftLen && uRightLen && !bInside && + strncasecmp(p, sLeft.c_str(), uLeftLen) == 0) { if (!bTrimQuotes) { sTmp += sLeft; } @@ -726,7 +853,8 @@ CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, bool b continue; } - if (uLeftLen && uRightLen && bInside && strncasecmp(p, sRight.c_str(), uRightLen) == 0) { + if (uLeftLen && uRightLen && bInside && + strncasecmp(p, sRight.c_str(), uRightLen) == 0) { if (!bTrimQuotes) { sTmp += sRight; } @@ -736,7 +864,8 @@ CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, bool b continue; } - if (uDelimLen && !bInside && strncasecmp(p, sDelim.c_str(), uDelimLen) == 0) { + if (uDelimLen && !bInside && + strncasecmp(p, sDelim.c_str(), uDelimLen) == 0) { if (bTrimWhiteSpace) { sTmp.Trim(); } @@ -771,10 +900,14 @@ CString::size_type CString::Split(const CString& sDelim, VCString& vsRet, bool b return vsRet.size(); } -CString::size_type CString::Split(const CString& sDelim, SCString& ssRet, bool bAllowEmpty, const CString& sLeft, const CString& sRight, bool bTrimQuotes, bool bTrimWhiteSpace) const { +CString::size_type CString::Split(const CString& sDelim, SCString& ssRet, + bool bAllowEmpty, const CString& sLeft, + const CString& sRight, bool bTrimQuotes, + bool bTrimWhiteSpace) const { VCString vsTokens; - Split(sDelim, vsTokens, bAllowEmpty, sLeft, sRight, bTrimQuotes, bTrimWhiteSpace); + Split(sDelim, vsTokens, bAllowEmpty, sLeft, sRight, bTrimQuotes, + bTrimWhiteSpace); ssRet.clear(); @@ -831,16 +964,17 @@ CString CString::NamedFormat(const CString& sFormat, const MCString& msValues) { } CString CString::RandomString(unsigned int uLength) { - const char chars[] = "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!?.,:;/*-+_()"; + const char chars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!?.,:;/*-+_()"; // -1 because sizeof() includes the trailing '\0' byte const size_t len = sizeof(chars) / sizeof(chars[0]) - 1; size_t p; CString sRet; for (unsigned int a = 0; a < uLength; a++) { - p = (size_t) (len * (rand() / (RAND_MAX + 1.0))); + p = (size_t)(len * (rand() / (RAND_MAX + 1.0))); sRet += chars[p]; } @@ -870,12 +1004,13 @@ CString CString::Base64Decode_n() const { } bool CString::Base64Encode(CString& sRet, unsigned int uWrap) const { - const char b64table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const char b64table[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; sRet.clear(); size_t len = size(); - const unsigned char* input = (const unsigned char*) c_str(); - unsigned char *output, *p; - size_t i = 0, mod = len % 3, toalloc; + const unsigned char* input = (const unsigned char*)c_str(); + unsigned char* output, *p; + size_t i = 0, mod = len % 3, toalloc; toalloc = (len / 3) * 4 + (3 - mod) % 3 + 1 + 8; if (uWrap) { @@ -889,7 +1024,7 @@ bool CString::Base64Encode(CString& sRet, unsigned int uWrap) const { return 0; } - p = output = new unsigned char [toalloc]; + p = output = new unsigned char[toalloc]; while (i < len - mod) { *p++ = b64table[input[i++] >> 2]; @@ -924,7 +1059,7 @@ bool CString::Base64Encode(CString& sRet, unsigned int uWrap) const { } *p = 0; - sRet = (char*) output; + sRet = (char*)output; delete[] output; return true; } @@ -958,7 +1093,8 @@ unsigned long CString::Base64Decode(CString& sRet) const { if (in[i] == '=') { break; } - *p++ = char(((c << 6) & 0xc0) | (char)base64_table[(unsigned char)in[i]]); + *p++ = char(((c << 6) & 0xc0) | + (char)base64_table[(unsigned char)in[i]]); } } @@ -971,26 +1107,26 @@ unsigned long CString::Base64Decode(CString& sRet) const { return uRet; } -CString CString::MD5() const { - return (const char*) CMD5(*this); -} +CString CString::MD5() const { return (const char*)CMD5(*this); } CString CString::SHA256() const { unsigned char digest[SHA256_DIGEST_SIZE]; char digest_hex[SHA256_DIGEST_SIZE * 2 + 1]; - const unsigned char *message = (const unsigned char *) c_str(); + const unsigned char* message = (const unsigned char*)c_str(); sha256(message, length(), digest); snprintf(digest_hex, sizeof(digest_hex), - "%02x%02x%02x%02x%02x%02x%02x%02x" - "%02x%02x%02x%02x%02x%02x%02x%02x" - "%02x%02x%02x%02x%02x%02x%02x%02x" - "%02x%02x%02x%02x%02x%02x%02x%02x", - digest[ 0], digest[ 1], digest[ 2], digest[ 3], digest[ 4], digest[ 5], digest[ 6], digest[ 7], - digest[ 8], digest[ 9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15], - digest[16], digest[17], digest[18], digest[19], digest[20], digest[21], digest[22], digest[23], - digest[24], digest[25], digest[26], digest[27], digest[28], digest[29], digest[30], digest[31]); + "%02x%02x%02x%02x%02x%02x%02x%02x" + "%02x%02x%02x%02x%02x%02x%02x%02x" + "%02x%02x%02x%02x%02x%02x%02x%02x" + "%02x%02x%02x%02x%02x%02x%02x%02x", + digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], + digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], + digest[12], digest[13], digest[14], digest[15], digest[16], + digest[17], digest[18], digest[19], digest[20], digest[21], + digest[22], digest[23], digest[24], digest[25], digest[26], + digest[27], digest[28], digest[29], digest[30], digest[31]); return digest_hex; } @@ -1017,14 +1153,15 @@ void CString::Decrypt(const CString& sPass, const CString& sIvec) { } void CString::Crypt(const CString& sPass, bool bEncrypt, const CString& sIvec) { - unsigned char szIvec[8] = {0,0,0,0,0,0,0,0}; + unsigned char szIvec[8] = {0, 0, 0, 0, 0, 0, 0, 0}; BF_KEY bKey; if (sIvec.length() >= 8) { memcpy(szIvec, sIvec.data(), 8); } - BF_set_key(&bKey, (unsigned int)sPass.length(), (unsigned char*) sPass.data()); + BF_set_key(&bKey, (unsigned int)sPass.length(), + (unsigned char*)sPass.data()); unsigned int uPad = (length() % 8); if (uPad) { @@ -1033,14 +1170,15 @@ void CString::Crypt(const CString& sPass, bool bEncrypt, const CString& sIvec) { } size_t uLen = length(); - unsigned char* szBuff = (unsigned char*) malloc(uLen); - BF_cbc_encrypt((const unsigned char*) data(), szBuff, uLen, &bKey, szIvec, ((bEncrypt) ? BF_ENCRYPT : BF_DECRYPT)); + unsigned char* szBuff = (unsigned char*)malloc(uLen); + BF_cbc_encrypt((const unsigned char*)data(), szBuff, uLen, &bKey, szIvec, + ((bEncrypt) ? BF_ENCRYPT : BF_DECRYPT)); clear(); - append((const char*) szBuff, uLen); + append((const char*)szBuff, uLen); free(szBuff); } -#endif // HAVE_LIBSSL +#endif // HAVE_LIBSSL CString CString::ToPercent(double d) { char szRet[32]; @@ -1075,8 +1213,8 @@ CString CString::ToTimeStr(unsigned long s) { const unsigned long y = d * 365; CString sRet; -#define TIMESPAN(time, str) \ - if (s >= time) { \ +#define TIMESPAN(time, str) \ + if (s >= time) { \ sRet += CString(s / time) + str " "; \ s = s % time; \ } @@ -1087,32 +1225,40 @@ CString CString::ToTimeStr(unsigned long s) { TIMESPAN(m, "m"); TIMESPAN(1, "s"); - if (sRet.empty()) - return "0s"; + if (sRet.empty()) return "0s"; return sRet.RightChomp_n(); } bool CString::ToBool() const { CString sTrimmed = Trim_n(); - return (!sTrimmed.Trim_n("0").empty() && - !sTrimmed.Equals("false") && - !sTrimmed.Equals("off") && - !sTrimmed.Equals("no") && - !sTrimmed.Equals("n")); + return (!sTrimmed.Trim_n("0").empty() && !sTrimmed.Equals("false") && + !sTrimmed.Equals("off") && !sTrimmed.Equals("no") && + !sTrimmed.Equals("n")); } -short CString::ToShort() const { return (short int)strtol(this->c_str(), (char**) nullptr, 10); } -unsigned short CString::ToUShort() const { return (unsigned short int)strtoul(this->c_str(), (char**) nullptr, 10); } -unsigned int CString::ToUInt() const { return (unsigned int)strtoul(this->c_str(), (char**) nullptr, 10); } -int CString::ToInt() const { return (int)strtol(this->c_str(), (char**) nullptr, 10); } -long CString::ToLong() const { return strtol(this->c_str(), (char**) nullptr, 10); } +short CString::ToShort() const { + return (short int)strtol(this->c_str(), (char**)nullptr, 10); +} +unsigned short CString::ToUShort() const { + return (unsigned short int)strtoul(this->c_str(), (char**)nullptr, 10); +} +unsigned int CString::ToUInt() const { + return (unsigned int)strtoul(this->c_str(), (char**)nullptr, 10); +} +int CString::ToInt() const { + return (int)strtol(this->c_str(), (char**)nullptr, 10); +} +long CString::ToLong() const { + return strtol(this->c_str(), (char**)nullptr, 10); +} unsigned long CString::ToULong() const { return strtoul(c_str(), nullptr, 10); } -unsigned long long CString::ToULongLong() const { return strtoull(c_str(), nullptr, 10); } +unsigned long long CString::ToULongLong() const { + return strtoull(c_str(), nullptr, 10); +} long long CString::ToLongLong() const { return strtoll(c_str(), nullptr, 10); } double CString::ToDouble() const { return strtod(c_str(), nullptr); } - bool CString::Trim(const CString& s) { bool bLeft = TrimLeft(s); return (TrimRight(s) || bLeft); @@ -1121,8 +1267,7 @@ bool CString::Trim(const CString& s) { bool CString::TrimLeft(const CString& s) { size_type i = find_first_not_of(s); - if (i == 0) - return false; + if (i == 0) return false; if (i != npos) this->erase(0, i); @@ -1135,8 +1280,7 @@ bool CString::TrimLeft(const CString& s) { bool CString::TrimRight(const CString& s) { size_type i = find_last_not_of(s); - if (i + 1 == length()) - return false; + if (i + 1 == length()) return false; if (i != npos) this->erase(i + 1, npos); @@ -1202,7 +1346,6 @@ bool CString::Contains(const CString& s, CaseSensitivity cs) const { return Find(s, cs) != npos; } - CString CString::TrimPrefix_n(const CString& sPrefix) const { CString sRet = *this; sRet.TrimPrefix(sPrefix); @@ -1242,7 +1385,7 @@ bool CString::RightChomp(size_type uLen) { bool bRet = false; while ((uLen--) && (length())) { - erase(length() -1); + erase(length() - 1); bRet = true; } @@ -1251,7 +1394,7 @@ bool CString::RightChomp(size_type uLen) { CString CString::StripControls_n() const { CString sRet; - const unsigned char *pStart = (const unsigned char*) data(); + const unsigned char* pStart = (const unsigned char*)data(); unsigned char ch = *pStart; size_type iLength = length(); sRet.reserve(iLength); @@ -1280,13 +1423,14 @@ CString CString::StripControls_n() const { colorCode = false; - if (digits == 0 && comma) { // There was a ',' which wasn't followed by digits, we should print it. + if (digits == 0 && comma) { // There was a ',' which wasn't + // followed by digits, we should print + // it. sRet += ','; } } // CO controls codes - if (ch < 0x20 || ch == 0x7F) - continue; + if (ch < 0x20 || ch == 0x7F) continue; sRet += ch; } if (colorCode && digits == 0 && comma) { @@ -1297,24 +1441,21 @@ CString CString::StripControls_n() const { return sRet; } -CString& CString::StripControls() { - return (*this = StripControls_n()); -} +CString& CString::StripControls() { return (*this = StripControls_n()); } //////////////// MCString //////////////// const MCString MCString::EmptyMap; -MCString::status_t MCString::WriteToDisk(const CString& sPath, mode_t iMode) const { +MCString::status_t MCString::WriteToDisk(const CString& sPath, + mode_t iMode) const { CFile cFile(sPath); if (this->empty()) { - if (!cFile.Exists()) - return MCS_SUCCESS; - if (cFile.Delete()) - return MCS_SUCCESS; + if (!cFile.Exists()) return MCS_SUCCESS; + if (cFile.Delete()) return MCS_SUCCESS; } - if (!cFile.Open(O_WRONLY|O_CREAT|O_TRUNC, iMode)) { + if (!cFile.Open(O_WRONLY | O_CREAT | O_TRUNC, iMode)) { return MCS_EOPEN; } @@ -1329,7 +1470,7 @@ MCString::status_t MCString::WriteToDisk(const CString& sPath, mode_t iMode) con continue; } - if (cFile.Write(Encode(sKey) + " " + Encode(sValue) + "\n") <= 0) { + if (cFile.Write(Encode(sKey) + " " + Encode(sValue) + "\n") <= 0) { return MCS_EWRITE; } } @@ -1355,8 +1496,7 @@ MCString::status_t MCString::ReadFromDisk(const CString& sPath) { Decode(sKey); Decode(sValue); - if (!ReadFilter(sKey, sValue)) - return MCS_EREADFIL; + if (!ReadFilter(sKey, sValue)) return MCS_EREADFIL; (*this)[sKey] = sValue; } @@ -1365,7 +1505,6 @@ MCString::status_t MCString::ReadFromDisk(const CString& sPath) { return MCS_SUCCESS; } - static const char hexdigits[] = "0123456789abcdef"; CString& MCString::Encode(CString& sValue) const { @@ -1387,15 +1526,15 @@ CString& MCString::Encode(CString& sValue) const { } CString& MCString::Decode(CString& sValue) const { - const char *pTmp = sValue.c_str(); - char *endptr; + const char* pTmp = sValue.c_str(); + char* endptr; CString sTmp; while (*pTmp) { if (*pTmp != '%') { sTmp += *pTmp++; } else { - char ch = (char) strtol(pTmp + 1, &endptr, 16); + char ch = (char)strtol(pTmp + 1, &endptr, 16); if (*endptr == ';') { sTmp += ch; pTmp = ++endptr; diff --git a/src/main.cpp b/src/main.cpp index 773bc6e4..46935974 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,10 +24,10 @@ #include #include -static std::vector > lock_cs; +static std::vector> lock_cs; -static void locking_callback(int mode, int type, const char *file, int line) { - if(mode & CRYPTO_LOCK) { +static void locking_callback(int mode, int type, const char* file, int line) { + if (mode & CRYPTO_LOCK) { lock_cs[type]->lock(); } else { lock_cs[type]->unlock(); @@ -38,22 +38,24 @@ static unsigned long thread_id_callback() { return (unsigned long)pthread_self(); } -static CRYPTO_dynlock_value *dyn_create_callback(const char *file, int line) { +static CRYPTO_dynlock_value* dyn_create_callback(const char* file, int line) { return (CRYPTO_dynlock_value*)new CMutex; } -static void dyn_lock_callback(int mode, CRYPTO_dynlock_value *dlock, const char *file, int line) { - CMutex *mtx = (CMutex*)dlock; +static void dyn_lock_callback(int mode, CRYPTO_dynlock_value* dlock, + const char* file, int line) { + CMutex* mtx = (CMutex*)dlock; - if(mode & CRYPTO_LOCK) { + if (mode & CRYPTO_LOCK) { mtx->lock(); } else { mtx->unlock(); } } -static void dyn_destroy_callback(CRYPTO_dynlock_value *dlock, const char *file, int line) { - CMutex *mtx = (CMutex*)dlock; +static void dyn_destroy_callback(CRYPTO_dynlock_value* dlock, const char* file, + int line) { + CMutex* mtx = (CMutex*)dlock; delete mtx; } @@ -61,7 +63,7 @@ static void dyn_destroy_callback(CRYPTO_dynlock_value *dlock, const char *file, static void thread_setup() { lock_cs.resize(CRYPTO_num_locks()); - for(std::unique_ptr &mtx: lock_cs) + for (std::unique_ptr& mtx : lock_cs) mtx = std::unique_ptr(new CMutex()); CRYPTO_set_id_callback(&thread_id_callback); @@ -88,64 +90,73 @@ using std::set; #define optional_argument 2 struct option { - const char *a; + const char* a; int opt; - int *flag; + int* flag; int val; }; -static inline int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *, int *) -{ +static inline int getopt_long(int argc, char* const argv[], + const char* optstring, const struct option*, + int*) { return getopt(argc, argv, optstring); } #endif static const struct option g_LongOpts[] = { - { "help", no_argument, nullptr, 'h' }, - { "version", no_argument, nullptr, 'v' }, - { "debug", no_argument, nullptr, 'D' }, - { "foreground", no_argument, nullptr, 'f' }, - { "no-color", no_argument, nullptr, 'n' }, - { "allow-root", no_argument, nullptr, 'r' }, - { "makeconf", no_argument, nullptr, 'c' }, - { "makepass", no_argument, nullptr, 's' }, - { "makepem", no_argument, nullptr, 'p' }, - { "datadir", required_argument, nullptr, 'd' }, - { nullptr, 0, nullptr, 0 } -}; + {"help", no_argument, nullptr, 'h'}, + {"version", no_argument, nullptr, 'v'}, + {"debug", no_argument, nullptr, 'D'}, + {"foreground", no_argument, nullptr, 'f'}, + {"no-color", no_argument, nullptr, 'n'}, + {"allow-root", no_argument, nullptr, 'r'}, + {"makeconf", no_argument, nullptr, 'c'}, + {"makepass", no_argument, nullptr, 's'}, + {"makepem", no_argument, nullptr, 'p'}, + {"datadir", required_argument, nullptr, 'd'}, + {nullptr, 0, nullptr, 0}}; -static void GenerateHelp(const char *appname) { +static void GenerateHelp(const char* appname) { CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]"); CUtils::PrintMessage("Options are:"); - CUtils::PrintMessage("\t-h, --help List available command line options (this page)"); - CUtils::PrintMessage("\t-v, --version Output version information and exit"); + CUtils::PrintMessage( + "\t-h, --help List available command line options (this page)"); + CUtils::PrintMessage( + "\t-v, --version Output version information and exit"); CUtils::PrintMessage("\t-f, --foreground Don't fork into the background"); - CUtils::PrintMessage("\t-D, --debug Output debugging information (Implies -f)"); - CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output"); - CUtils::PrintMessage("\t-r, --allow-root Don't complain if ZNC is run as root"); - CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config"); - CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config"); + CUtils::PrintMessage( + "\t-D, --debug Output debugging information (Implies -f)"); + CUtils::PrintMessage( + "\t-n, --no-color Don't use escape sequences in the output"); + CUtils::PrintMessage( + "\t-r, --allow-root Don't complain if ZNC is run as root"); + CUtils::PrintMessage( + "\t-c, --makeconf Interactively create a new config"); + CUtils::PrintMessage( + "\t-s, --makepass Generates a password for use in config"); #ifdef HAVE_LIBSSL - CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL"); + CUtils::PrintMessage( + "\t-p, --makepem Generates a pemfile for use with SSL"); #endif /* HAVE_LIBSSL */ - CUtils::PrintMessage("\t-d, --datadir Set a different ZNC repository (default is ~/.znc)"); + CUtils::PrintMessage( + "\t-d, --datadir Set a different ZNC repository (default is " + "~/.znc)"); } class CSignalHandler { -public: + public: CSignalHandler(CZNC* pZNC) { sigset_t signals; sigfillset(&signals); pthread_sigmask(SIG_SETMASK, &signals, nullptr); - m_thread = std::thread([=]() { - HandleSignals(pZNC); - }); + m_thread = std::thread([=]() { HandleSignals(pZNC); }); } ~CSignalHandler() { pthread_cancel(m_thread.native_handle()); m_thread.join(); } -private: + + private: void HandleSignals(CZNC* pZNC) { sigset_t signals; sigemptyset(&signals); @@ -155,7 +166,8 @@ private: sigaddset(&signals, SIGQUIT); sigaddset(&signals, SIGTERM); sigaddset(&signals, SIGPIPE); - // Handle only these signals specially; the rest will have their default action, but in this thread + // Handle only these signals specially; the rest will have their default + // action, but in this thread pthread_sigmask(SIG_SETMASK, &signals, nullptr); while (true) { int sig; @@ -178,7 +190,8 @@ private: // Reset handler to default by: // * not blocking it // * not waiting for it - // So, if ^C is pressed, but for some reason it didn't work, second ^C will kill the process for sure. + // So, if ^C is pressed, but for some reason it didn't work, + // second ^C will kill the process for sure. sigdelset(&signals, sig); pthread_sigmask(SIG_SETMASK, &signals, nullptr); break; @@ -193,7 +206,8 @@ private: }; static bool isRoot() { - // User root? If one of these were root, we could switch the others to root, too + // User root? If one of these were root, we could switch the others to root, + // too return (geteuid() == 0 || getuid() == 0); } @@ -240,56 +254,60 @@ int main(int argc, char** argv) { #endif CZNC::CreateInstance(); - while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, &iOptIndex)) != -1) { + while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, + &iOptIndex)) != -1) { switch (iArg) { - case 'h': - GenerateHelp(argv[0]); - return 0; - case 'v': - cout << CZNC::GetTag() << endl; - cout << CZNC::GetCompileOptionsString() << endl; - return 0; - case 'n': - CDebug::SetStdoutIsTTY(false); - break; - case 'r': - bAllowRoot = true; - break; - case 'c': - bMakeConf = true; - break; - case 's': - bMakePass = true; - break; - case 'p': + case 'h': + GenerateHelp(argv[0]); + return 0; + case 'v': + cout << CZNC::GetTag() << endl; + cout << CZNC::GetCompileOptionsString() << endl; + return 0; + case 'n': + CDebug::SetStdoutIsTTY(false); + break; + case 'r': + bAllowRoot = true; + break; + case 'c': + bMakeConf = true; + break; + case 's': + bMakePass = true; + break; + case 'p': #ifdef HAVE_LIBSSL - bMakePem = true; - break; + bMakePem = true; + break; #else - CUtils::PrintError("ZNC is compiled without SSL support."); - return 1; + CUtils::PrintError("ZNC is compiled without SSL support."); + return 1; #endif /* HAVE_LIBSSL */ - case 'd': - sDataDir = CString(optarg); - break; - case 'f': - bForeground = true; - break; - case 'D': - bForeground = true; - CDebug::SetDebug(true); - break; - case '?': - default: - GenerateHelp(argv[0]); - return 1; + case 'd': + sDataDir = CString(optarg); + break; + case 'f': + bForeground = true; + break; + case 'D': + bForeground = true; + CDebug::SetDebug(true); + break; + case '?': + default: + GenerateHelp(argv[0]); + return 1; } } if (optind < argc) { CUtils::PrintError("Unrecognized command line arguments."); - CUtils::PrintError("Did you mean to run `/znc " + CString(argv[optind]) + "' in IRC client instead?"); - CUtils::PrintError("Hint: `/znc " + CString(argv[optind]) + "' is an alias for `/msg *status " + CString(argv[optind]) + "'"); + CUtils::PrintError("Did you mean to run `/znc " + + CString(argv[optind]) + "' in IRC client instead?"); + CUtils::PrintError("Hint: `/znc " + CString(argv[optind]) + + "' is an alias for `/msg *status " + + CString(argv[optind]) + "'"); return 1; } @@ -310,14 +328,19 @@ int main(int argc, char** argv) { CUtils::PrintMessage("Type your new password."); CString sHash = CUtils::GetSaltedHashPass(sSalt); CUtils::PrintMessage("Kill ZNC process, if it's running."); - CUtils::PrintMessage("Then replace password in the section of your config with this:"); - // Not PrintMessage(), to remove [**] from the beginning, to ease copypasting + CUtils::PrintMessage( + "Then replace password in the section of your config with " + "this:"); + // Not PrintMessage(), to remove [**] from the beginning, to ease + // copypasting std::cout << "" << std::endl; std::cout << "\tMethod = " << CUtils::sDefaultHash << std::endl; std::cout << "\tHash = " << sHash << std::endl; std::cout << "\tSalt = " << sSalt << std::endl; std::cout << "" << std::endl; - CUtils::PrintMessage("After that start ZNC again, and you should be able to login with the new password."); + CUtils::PrintMessage( + "After that start ZNC again, and you should be able to login with " + "the new password."); CZNC::DestroyInstance(); return 0; @@ -328,14 +351,21 @@ int main(int argc, char** argv) { set ssUserMods; set ssNetworkMods; CUtils::PrintAction("Checking for list of available modules"); - pZNC->GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule); + pZNC->GetModules().GetAvailableMods(ssGlobalMods, + CModInfo::GlobalModule); pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule); - pZNC->GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule); - if (ssGlobalMods.empty() && ssUserMods.empty() && ssNetworkMods.empty()) { + pZNC->GetModules().GetAvailableMods(ssNetworkMods, + CModInfo::NetworkModule); + if (ssGlobalMods.empty() && ssUserMods.empty() && + ssNetworkMods.empty()) { CUtils::PrintStatus(false, ""); - CUtils::PrintError("No modules found. Perhaps you didn't install ZNC properly?"); - CUtils::PrintError("Read http://wiki.znc.in/Installation for instructions."); - if (!CUtils::GetBoolInput("Do you really want to run ZNC without any modules?", false)) { + CUtils::PrintError( + "No modules found. Perhaps you didn't install ZNC properly?"); + CUtils::PrintError( + "Read http://wiki.znc.in/Installation for instructions."); + if (!CUtils::GetBoolInput( + "Do you really want to run ZNC without any modules?", + false)) { CZNC::DestroyInstance(); return 1; } @@ -344,14 +374,18 @@ int main(int argc, char** argv) { } if (isRoot()) { - CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid"); - CUtils::PrintError("reasons for this and it can, in theory, cause great damage!"); + CUtils::PrintError( + "You are running ZNC as root! Don't do that! There are not many " + "valid"); + CUtils::PrintError( + "reasons for this and it can, in theory, cause great damage!"); if (!bAllowRoot) { CZNC::DestroyInstance(); return 1; } CUtils::PrintError("You have been warned."); - CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root."); + CUtils::PrintError( + "Hit CTRL+C now if you don't want to run ZNC as root."); CUtils::PrintError("ZNC will start in 30 seconds."); sleep(30); } @@ -379,7 +413,8 @@ int main(int argc, char** argv) { if (bForeground) { int iPid = getpid(); - CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]"); + CUtils::PrintMessage("Staying open for debugging [pid: " + + CString(iPid) + "]"); pZNC->WritePidFile(iPid); CUtils::PrintMessage(CZNC::GetTag()); @@ -409,15 +444,19 @@ int main(int argc, char** argv) { * call to avoid race condition with parent exiting. */ if (!pZNC->WaitForChildLock()) { - CUtils::PrintError("Child was unable to obtain lock on config file."); + CUtils::PrintError( + "Child was unable to obtain lock on config file."); CZNC::DestroyInstance(); return 1; } // Redirect std in/out/err to /dev/null - close(0); open("/dev/null", O_RDONLY); - close(1); open("/dev/null", O_WRONLY); - close(2); open("/dev/null", O_WRONLY); + close(0); + open("/dev/null", O_RDONLY); + close(1); + open("/dev/null", O_WRONLY); + close(2); + open("/dev/null", O_WRONLY); CDebug::SetStdoutIsTTY(false); @@ -442,31 +481,26 @@ int main(int argc, char** argv) { break; case CException::EX_Restart: { // strdup() because GCC is stupid - char *args[] = { - strdup(argv[0]), - strdup("--datadir"), - strdup(pZNC->GetZNCPath().c_str()), - nullptr, - nullptr, - nullptr, - nullptr - }; + char* args[] = { + strdup(argv[0]), strdup("--datadir"), + strdup(pZNC->GetZNCPath().c_str()), nullptr, + nullptr, nullptr, + nullptr}; int pos = 3; if (CDebug::Debug()) args[pos++] = strdup("--debug"); else if (bForeground) args[pos++] = strdup("--foreground"); - if (!CDebug::StdoutIsTTY()) - args[pos++] = strdup("--no-color"); - if (bAllowRoot) - args[pos++] = strdup("--allow-root"); + if (!CDebug::StdoutIsTTY()) args[pos++] = strdup("--no-color"); + if (bAllowRoot) args[pos++] = strdup("--allow-root"); // The above code adds 3 entries to args tops // which means the array should be big enough SignalHandler.reset(); CZNC::DestroyInstance(); execvp(args[0], args); - CUtils::PrintError("Unable to restart ZNC [" + CString(strerror(errno)) + "]"); + CUtils::PrintError("Unable to restart ZNC [" + + CString(strerror(errno)) + "]"); } /* Fall through */ default: iRet = 1; diff --git a/src/znc.cpp b/src/znc.cpp index 1f7d92ac..82702996 100644 --- a/src/znc.cpp +++ b/src/znc.cpp @@ -35,46 +35,46 @@ using std::tuple; using std::make_tuple; static inline CString FormatBindError() { - CString sError = (errno == 0 ? CString("unknown error, check the host name") : CString(strerror(errno))); + CString sError = (errno == 0 ? CString("unknown error, check the host name") + : CString(strerror(errno))); return "Unable to bind [" + sError + "]"; } CZNC::CZNC() - : m_TimeStarted(time(nullptr)), - m_eConfigState(ECONFIG_NOTHING), - m_vpListeners(), - m_msUsers(), - m_msDelUsers(), - m_Manager(), - m_sCurPath(""), - m_sZNCPath(""), - m_sConfigFile(""), - m_sSkinName(""), - m_sStatusPrefix(""), - m_sPidFile(""), - m_sSSLCertFile(""), - m_sSSLKeyFile(""), - m_sSSLDHParamFile(""), - m_sSSLCiphers(""), - m_sSSLProtocols(""), - m_vsBindHosts(), - m_vsTrustedProxies(), - m_vsMotd(), - m_pLockFile(nullptr), - m_uiConnectDelay(5), - m_uiAnonIPLimit(10), - m_uiMaxBufferSize(500), - m_uDisabledSSLProtocols(Csock::EDP_SSL), - m_pModules(new CModules), - m_uBytesRead(0), - m_uBytesWritten(0), - m_lpConnectQueue(), - m_pConnectQueueTimer(nullptr), - m_uiConnectPaused(0), - m_sConnectThrottle(), - m_bProtectWebSessions(true), - m_bHideVersion(false) -{ + : m_TimeStarted(time(nullptr)), + m_eConfigState(ECONFIG_NOTHING), + m_vpListeners(), + m_msUsers(), + m_msDelUsers(), + m_Manager(), + m_sCurPath(""), + m_sZNCPath(""), + m_sConfigFile(""), + m_sSkinName(""), + m_sStatusPrefix(""), + m_sPidFile(""), + m_sSSLCertFile(""), + m_sSSLKeyFile(""), + m_sSSLDHParamFile(""), + m_sSSLCiphers(""), + m_sSSLProtocols(""), + m_vsBindHosts(), + m_vsTrustedProxies(), + m_vsMotd(), + m_pLockFile(nullptr), + m_uiConnectDelay(5), + m_uiAnonIPLimit(10), + m_uiMaxBufferSize(500), + m_uDisabledSSLProtocols(Csock::EDP_SSL), + m_pModules(new CModules), + m_uBytesRead(0), + m_uBytesWritten(0), + m_lpConnectQueue(), + m_pConnectQueueTimer(nullptr), + m_uiConnectPaused(0), + m_sConnectThrottle(), + m_bProtectWebSessions(true), + m_bHideVersion(false) { if (!InitCsocket()) { CUtils::PrintError("Could not initialize Csocket!"); exit(-1); @@ -122,7 +122,8 @@ CString CZNC::GetTag(bool bIncludeVersion, bool bHTML) { if (!Get().m_bHideVersion) { bIncludeVersion = true; } - CString sAddress = bHTML ? "http://znc.in" : "http://znc.in"; + CString sAddress = + bHTML ? "http://znc.in" : "http://znc.in"; if (!bIncludeVersion) { return "ZNC - " + sAddress; @@ -134,32 +135,31 @@ CString CZNC::GetTag(bool bIncludeVersion, bool bHTML) { } CString CZNC::GetCompileOptionsString() { - return - "IPv6: " + return "IPv6: " #ifdef HAVE_IPV6 - "yes" + "yes" #else - "no" + "no" #endif - ", SSL: " + ", SSL: " #ifdef HAVE_LIBSSL - "yes" + "yes" #else - "no" + "no" #endif - ", DNS: " + ", DNS: " #ifdef HAVE_THREADED_DNS - "threads" + "threads" #else - "blocking" + "blocking" #endif - ", charset: " + ", charset: " #ifdef HAVE_ICU - "yes" + "yes" #else - "no" + "no" #endif - ; + ; } CString CZNC::GetUptime() const { @@ -175,10 +175,8 @@ bool CZNC::OnBoot() { return true; } -bool CZNC::HandleUserDeletion() -{ - if (m_msDelUsers.empty()) - return false; +bool CZNC::HandleUserDeletion() { + if (m_msDelUsers.empty()) return false; for (const auto& it : m_msDelUsers) { CUser* pUser = it.second; @@ -204,30 +202,31 @@ void CZNC::Loop() { ConfigState eState = GetConfigState(); switch (eState) { - case ECONFIG_NEED_REHASH: - SetConfigState(ECONFIG_NOTHING); + case ECONFIG_NEED_REHASH: + SetConfigState(ECONFIG_NOTHING); - if (RehashConfig(sError)) { - Broadcast("Rehashing succeeded", true); - } else { - Broadcast("Rehashing failed: " + sError, true); - Broadcast("ZNC is in some possibly inconsistent state!", true); - } - break; - case ECONFIG_NEED_WRITE: - case ECONFIG_NEED_VERBOSE_WRITE: - SetConfigState(ECONFIG_NOTHING); + if (RehashConfig(sError)) { + Broadcast("Rehashing succeeded", true); + } else { + Broadcast("Rehashing failed: " + sError, true); + Broadcast("ZNC is in some possibly inconsistent state!", + true); + } + break; + case ECONFIG_NEED_WRITE: + case ECONFIG_NEED_VERBOSE_WRITE: + SetConfigState(ECONFIG_NOTHING); - if (!WriteConfig()) { - Broadcast("Writing the config file failed", true); - } else if (eState == ECONFIG_NEED_VERBOSE_WRITE) { - Broadcast("Writing the config succeeded", true); - } - break; - case ECONFIG_NOTHING: - break; - case ECONFIG_NEED_QUIT: - return; + if (!WriteConfig()) { + Broadcast("Writing the config file failed", true); + } else if (eState == ECONFIG_NEED_VERBOSE_WRITE) { + Broadcast("Writing the config succeeded", true); + } + break; + case ECONFIG_NOTHING: + break; + case ECONFIG_NEED_QUIT: + return; } // Check for users that need to be deleted @@ -260,8 +259,7 @@ CFile* CZNC::InitPidFile() { bool CZNC::WritePidFile(int iPid) { CFile* File = InitPidFile(); - if (File == nullptr) - return false; + if (File == nullptr) return false; CUtils::PrintAction("Writing pid file [" + File->GetLongName() + "]"); @@ -279,8 +277,7 @@ bool CZNC::WritePidFile(int iPid) { bool CZNC::DeletePidFile() { CFile* File = InitPidFile(); - if (File == nullptr) - return false; + if (File == nullptr) return false; CUtils::PrintAction("Deleting pid file [" + File->GetLongName() + "]"); @@ -300,14 +297,14 @@ bool CZNC::WritePemFile() { CUtils::PrintAction("Writing Pem file [" + sPemFile + "]"); #ifndef _WIN32 - int fd = creat(sPemFile.c_str(), 0600); + int fd = creat(sPemFile.c_str(), 0600); if (fd == -1) { CUtils::PrintStatus(false, "Unable to open"); return false; } - FILE *f = fdopen(fd, "w"); + FILE* f = fdopen(fd, "w"); #else - FILE *f = fopen(sPemFile.c_str(), "w"); + FILE* f = fopen(sPemFile.c_str(), "w"); #endif if (!f) { @@ -344,13 +341,13 @@ bool CZNC::IsHostAllowed(const CString& sHostMask) const { } bool CZNC::AllowConnectionFrom(const CString& sIP) const { - if (m_uiAnonIPLimit == 0) - return true; + if (m_uiAnonIPLimit == 0) return true; return (GetManager().GetAnonConnectionCount(sIP) < m_uiAnonIPLimit); } void CZNC::InitDirs(const CString& sArgvPath, const CString& sDataDir) { - // If the bin was not ran from the current directory, we need to add that dir onto our cwd + // If the bin was not ran from the current directory, we need to add that + // dir onto our cwd CString::size_type uPos = sArgvPath.rfind('/'); if (uPos == CString::npos) m_sCurPath = "./"; @@ -366,7 +363,8 @@ void CZNC::InitDirs(const CString& sArgvPath, const CString& sDataDir) { m_sZNCPath = sDataDir; } - m_sSSLCertFile = m_sSSLKeyFile = m_sSSLDHParamFile = m_sZNCPath + "/znc.pem"; + m_sSSLCertFile = m_sSSLKeyFile = m_sSSLDHParamFile = + m_sZNCPath + "/znc.pem"; } CString CZNC::GetConfPath(bool bAllowMkDir) const { @@ -400,9 +398,7 @@ const CString& CZNC::GetCurPath() const { return m_sCurPath; } -const CString& CZNC::GetHomePath() const { - return CFile::GetHomePath(); -} +const CString& CZNC::GetHomePath() const { return CFile::GetHomePath(); } const CString& CZNC::GetZNCPath() const { if (!CFile::Exists(m_sZNCPath)) { @@ -448,10 +444,11 @@ bool CZNC::WriteConfig() { } // We first write to a temporary file and then move it to the right place - CFile *pFile = new CFile(GetConfigFile() + "~"); + CFile* pFile = new CFile(GetConfigFile() + "~"); if (!pFile->Open(O_WRONLY | O_CREAT | O_TRUNC, 0600)) { - DEBUG("Could not write config to " + GetConfigFile() + "~: " + CString(strerror(errno))); + DEBUG("Could not write config to " + GetConfigFile() + "~: " + + CString(strerror(errno))); delete pFile; return false; } @@ -460,7 +457,8 @@ bool CZNC::WriteConfig() { // The old file (= inode) is going away and thus a lock on it would be // useless. These lock should always succeed (races, anyone?). if (!pFile->TryExLock()) { - DEBUG("Error while locking the new config file, errno says: " + CString(strerror(errno))); + DEBUG("Error while locking the new config file, errno says: " + + CString(strerror(errno))); pFile->Delete(); delete pFile; return false; @@ -474,7 +472,8 @@ bool CZNC::WriteConfig() { config.AddKeyValuePair("SSLCertFile", CString(m_sSSLCertFile)); config.AddKeyValuePair("SSLKeyFile", CString(m_sSSLKeyFile)); config.AddKeyValuePair("SSLDHParamFile", CString(m_sSSLDHParamFile)); - config.AddKeyValuePair("ProtectWebSessions", CString(m_bProtectWebSessions)); + config.AddKeyValuePair("ProtectWebSessions", + CString(m_bProtectWebSessions)); config.AddKeyValuePair("HideVersion", CString(m_bHideVersion)); config.AddKeyValuePair("Version", CString(VERSION_STR)); @@ -483,22 +482,31 @@ bool CZNC::WriteConfig() { CConfig listenerConfig; listenerConfig.AddKeyValuePair("Host", pListener->GetBindHost()); - listenerConfig.AddKeyValuePair("URIPrefix", pListener->GetURIPrefix() + "/"); + listenerConfig.AddKeyValuePair("URIPrefix", + pListener->GetURIPrefix() + "/"); listenerConfig.AddKeyValuePair("Port", CString(pListener->GetPort())); - listenerConfig.AddKeyValuePair("IPv4", CString(pListener->GetAddrType() != ADDR_IPV6ONLY)); - listenerConfig.AddKeyValuePair("IPv6", CString(pListener->GetAddrType() != ADDR_IPV4ONLY)); + listenerConfig.AddKeyValuePair( + "IPv4", CString(pListener->GetAddrType() != ADDR_IPV6ONLY)); + listenerConfig.AddKeyValuePair( + "IPv6", CString(pListener->GetAddrType() != ADDR_IPV4ONLY)); listenerConfig.AddKeyValuePair("SSL", CString(pListener->IsSSL())); - listenerConfig.AddKeyValuePair("AllowIRC", CString(pListener->GetAcceptType() != CListener::ACCEPT_HTTP)); - listenerConfig.AddKeyValuePair("AllowWeb", CString(pListener->GetAcceptType() != CListener::ACCEPT_IRC)); + listenerConfig.AddKeyValuePair( + "AllowIRC", + CString(pListener->GetAcceptType() != CListener::ACCEPT_HTTP)); + listenerConfig.AddKeyValuePair( + "AllowWeb", + CString(pListener->GetAcceptType() != CListener::ACCEPT_IRC)); - config.AddSubConfig("Listener", "listener" + CString(l++), listenerConfig); + config.AddSubConfig("Listener", "listener" + CString(l++), + listenerConfig); } config.AddKeyValuePair("ConnectDelay", CString(m_uiConnectDelay)); - config.AddKeyValuePair("ServerThrottle", CString(m_sConnectThrottle.GetTTL()/1000)); + config.AddKeyValuePair("ServerThrottle", + CString(m_sConnectThrottle.GetTTL() / 1000)); if (!m_sPidFile.empty()) { config.AddKeyValuePair("PidFile", m_sPidFile.FirstLine()); @@ -545,11 +553,13 @@ bool CZNC::WriteConfig() { CString sErr; if (!it.second->IsValid(sErr)) { - DEBUG("** Error writing config for user [" << it.first << "] [" << sErr << "]"); + DEBUG("** Error writing config for user [" << it.first << "] [" + << sErr << "]"); continue; } - config.AddSubConfig("User", it.second->GetUserName(), it.second->ToConfig()); + config.AddSubConfig("User", it.second->GetUserName(), + it.second->ToConfig()); } config.Write(*pFile); @@ -558,7 +568,8 @@ bool CZNC::WriteConfig() { pFile->Sync(); if (pFile->HadError()) { - DEBUG("Error while writing the config, errno says: " + CString(strerror(errno))); + DEBUG("Error while writing the config, errno says: " + + CString(strerror(errno))); pFile->Delete(); delete pFile; return false; @@ -566,7 +577,10 @@ bool CZNC::WriteConfig() { // We wrote to a temporary name, move it to the right place if (!pFile->Move(GetConfigFile(), true)) { - DEBUG("Error while replacing the config file with a new version, errno says " << strerror(errno)); + DEBUG( + "Error while replacing the config file with a new version, errno " + "says " + << strerror(errno)); pFile->Delete(); delete pFile; return false; @@ -583,16 +597,16 @@ bool CZNC::WriteConfig() { } CString CZNC::MakeConfigHeader() { - return - "// WARNING\n" - "//\n" - "// Do NOT edit this file while ZNC is running!\n" - "// Use webadmin or *controlpanel instead.\n" - "//\n" - "// Altering this file by hand will forfeit all support.\n" - "//\n" - "// But if you feel risky, you might want to read help on /znc saveconfig and /znc rehash.\n" - "// Also check http://en.znc.in/wiki/Configuration\n"; + return "// WARNING\n" + "//\n" + "// Do NOT edit this file while ZNC is running!\n" + "// Use webadmin or *controlpanel instead.\n" + "//\n" + "// Altering this file by hand will forfeit all support.\n" + "//\n" + "// But if you feel risky, you might want to read help on /znc " + "saveconfig and /znc rehash.\n" + "// Also check http://en.znc.in/wiki/Configuration\n"; } bool CZNC::WriteNewConfig(const CString& sConfigFile) { @@ -605,14 +619,15 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { m_sConfigFile = ExpandConfigPath(sConfigFile); if (CFile::Exists(m_sConfigFile)) { - CUtils::PrintStatus(false, "WARNING: config [" + m_sConfigFile + "] already exists."); + CUtils::PrintStatus( + false, "WARNING: config [" + m_sConfigFile + "] already exists."); } CUtils::PrintMessage(""); CUtils::PrintMessage("-- Global settings --"); CUtils::PrintMessage(""); - // Listen +// Listen #ifdef HAVE_IPV6 bool b6 = true; #else @@ -627,20 +642,25 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { do { bSuccess = true; while (true) { - if (!CUtils::GetNumInput("Listen on port", uListenPort, 1025, 65534)) { + if (!CUtils::GetNumInput("Listen on port", uListenPort, 1025, + 65534)) { continue; } if (uListenPort == 6667) { - CUtils::PrintStatus(false, "WARNING: Some web browsers reject port 6667. If you intend to"); - CUtils::PrintStatus(false, "use ZNC's web interface, you might want to use another port."); - if (!CUtils::GetBoolInput("Proceed with port 6667 anyway?", true)) { + CUtils::PrintStatus(false, + "WARNING: Some web browsers reject port " + "6667. If you intend to"); + CUtils::PrintStatus(false, + "use ZNC's web interface, you might want " + "to use another port."); + if (!CUtils::GetBoolInput("Proceed with port 6667 anyway?", + true)) { continue; } } break; } - #ifdef HAVE_LIBSSL bListenSSL = CUtils::GetBoolInput("Listen using SSL", bListenSSL); #endif @@ -652,8 +672,9 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { // Don't ask for listen host, it may be configured later if needed. CUtils::PrintAction("Verifying the listener"); - CListener* pListener = new CListener((unsigned short int)uListenPort, sListenHost, sURIPrefix, bListenSSL, - b6 ? ADDR_ALL : ADDR_IPV4ONLY, CListener::ACCEPT_ALL); + CListener* pListener = new CListener( + (unsigned short int)uListenPort, sListenHost, sURIPrefix, + bListenSSL, b6 ? ADDR_ALL : ADDR_IPV4ONLY, CListener::ACCEPT_ALL); if (!pListener->Listen()) { CUtils::PrintStatus(false, FormatBindError()); bSuccess = false; @@ -665,7 +686,8 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { #ifdef HAVE_LIBSSL CString sPemFile = GetPemLocation(); if (!CFile::Exists(sPemFile)) { - CUtils::PrintMessage("Unable to locate pem file: [" + sPemFile + "], creating it"); + CUtils::PrintMessage("Unable to locate pem file: [" + sPemFile + + "], creating it"); WritePemFile(); } #endif @@ -688,7 +710,10 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { vsGlobalModNames.push_back(Info.GetName()); vsLines.push_back("LoadModule = " + Info.GetName()); } - CUtils::PrintMessage("Enabled global modules [" + CString(", ").Join(vsGlobalModNames.begin(), vsGlobalModNames.end()) + "]"); + CUtils::PrintMessage( + "Enabled global modules [" + + CString(", ").Join(vsGlobalModNames.begin(), vsGlobalModNames.end()) + + "]"); // User CUtils::PrintMessage(""); @@ -704,7 +729,8 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { vsLines.push_back(""); CString sSalt; sAnswer = CUtils::GetSaltedHashPass(sSalt); - vsLines.push_back("\tPass = " + CUtils::sDefaultHash + "#" + sAnswer + "#" + sSalt + "#"); + vsLines.push_back("\tPass = " + CUtils::sDefaultHash + "#" + sAnswer + + "#" + sSalt + "#"); vsLines.push_back("\tAdmin = true"); @@ -732,7 +758,9 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { vsUserModNames.push_back(Info.GetName()); vsLines.push_back("\tLoadModule = " + Info.GetName()); } - CUtils::PrintMessage("Enabled user modules [" + CString(", ").Join(vsUserModNames.begin(), vsUserModNames.end()) + "]"); + CUtils::PrintMessage( + "Enabled user modules [" + + CString(", ").Join(vsUserModNames.begin(), vsUserModNames.end()) + "]"); CUtils::PrintMessage(""); if (CUtils::GetBoolInput("Set up a network?", true)) { @@ -769,14 +797,19 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { sHint = "host only"; } - while (!CUtils::GetInput("Server host", sHost, sHost, sHint) || !CServer::IsValidHostName(sHost)); + while (!CUtils::GetInput("Server host", sHost, sHost, sHint) || + !CServer::IsValidHostName(sHost)) + ; #ifdef HAVE_LIBSSL bSSL = CUtils::GetBoolInput("Server uses SSL?", bSSL); #endif - while (!CUtils::GetNumInput("Server port", uServerPort, 1, 65535, bSSL ? 6697 : 6667)); + while (!CUtils::GetNumInput("Server port", uServerPort, 1, 65535, + bSSL ? 6697 : 6667)) + ; CUtils::GetInput("Server password (probably empty)", sPass); - vsLines.push_back("\t\tServer = " + sHost + ((bSSL) ? " +" : " ") + CString(uServerPort) + " " + sPass); + vsLines.push_back("\t\tServer = " + sHost + ((bSSL) ? " +" : " ") + + CString(uServerPort) + " " + sPass); CString sChans; if (CUtils::GetInput("Initial channels", sChans)) { @@ -791,7 +824,10 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { } } - CUtils::PrintMessage("Enabled network modules [" + CString(", ").Join(vsNetworkModNames.begin(), vsNetworkModNames.end()) + "]"); + CUtils::PrintMessage("Enabled network modules [" + + CString(", ").Join(vsNetworkModNames.begin(), + vsNetworkModNames.end()) + + "]"); vsLines.push_back("\t
"); } @@ -809,13 +845,16 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { bFileOK = true; if (CFile::Exists(m_sConfigFile)) { if (!File.TryExLock(m_sConfigFile)) { - CUtils::PrintStatus(false, "ZNC is currently running on this config."); + CUtils::PrintStatus(false, + "ZNC is currently running on this config."); bFileOK = false; } else { File.Close(); CUtils::PrintStatus(false, "This config already exists."); - if (CUtils::GetBoolInput("Are you sure you want to overwrite it?", false)) - CUtils::PrintAction("Overwriting config [" + m_sConfigFile + "]"); + if (CUtils::GetBoolInput( + "Are you sure you want to overwrite it?", false)) + CUtils::PrintAction("Overwriting config [" + m_sConfigFile + + "]"); else bFileOK = false; } @@ -831,7 +870,10 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { } } if (!bFileOK) { - while (!CUtils::GetInput("Please specify an alternate location", m_sConfigFile, "", "or \"stdout\" for displaying the config")); + while (!CUtils::GetInput("Please specify an alternate location", + m_sConfigFile, "", + "or \"stdout\" for displaying the config")) + ; if (m_sConfigFile.Equals("stdout")) bFileOK = true; else @@ -843,7 +885,8 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { CUtils::PrintMessage(""); CUtils::PrintMessage("Printing the new config to stdout:"); CUtils::PrintMessage(""); - cout << endl << "----------------------------------------------------------------------------" << endl << endl; + cout << endl << "------------------------------------------------------" + "----------------------" << endl << endl; } for (const CString& sLine : vsLines) { @@ -857,43 +900,59 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { if (bFileOpen) { File.Close(); if (File.HadError()) - CUtils::PrintStatus(false, "There was an error while writing the config"); + CUtils::PrintStatus(false, + "There was an error while writing the config"); else CUtils::PrintStatus(true); } else { - cout << endl << "----------------------------------------------------------------------------" << endl << endl; + cout << endl << "------------------------------------------------------" + "----------------------" << endl << endl; } if (File.HadError()) { bFileOpen = false; CUtils::PrintMessage("Printing the new config to stdout instead:"); - cout << endl << "----------------------------------------------------------------------------" << endl << endl; + cout << endl << "------------------------------------------------------" + "----------------------" << endl << endl; for (const CString& sLine : vsLines) { cout << sLine << endl; } - cout << endl << "----------------------------------------------------------------------------" << endl << endl; + cout << endl << "------------------------------------------------------" + "----------------------" << endl << endl; } const CString sProtocol(bListenSSL ? "https" : "http"); const CString sSSL(bListenSSL ? "+" : ""); CUtils::PrintMessage(""); - CUtils::PrintMessage("To connect to this ZNC you need to connect to it as your IRC server", true); - CUtils::PrintMessage("using the port that you supplied. You have to supply your login info", true); - CUtils::PrintMessage("as the IRC server password like this: user/network:pass.", true); + CUtils::PrintMessage( + "To connect to this ZNC you need to connect to it as your IRC server", + true); + CUtils::PrintMessage( + "using the port that you supplied. You have to supply your login info", + true); + CUtils::PrintMessage( + "as the IRC server password like this: user/network:pass.", true); CUtils::PrintMessage(""); CUtils::PrintMessage("Try something like this in your IRC client...", true); - CUtils::PrintMessage("/server " + sSSL + CString(uListenPort) + " " + sUser + ":", true); + CUtils::PrintMessage("/server " + sSSL + + CString(uListenPort) + " " + sUser + ":", + true); CUtils::PrintMessage(""); - CUtils::PrintMessage("To manage settings, users and networks, point your web browser to", true); - CUtils::PrintMessage(sProtocol + "://:" + CString(uListenPort) + "/", true); + CUtils::PrintMessage( + "To manage settings, users and networks, point your web browser to", + true); + CUtils::PrintMessage( + sProtocol + "://:" + CString(uListenPort) + "/", true); CUtils::PrintMessage(""); File.UnLock(); bool bWantLaunch = bFileOpen; if (bWantLaunch) { - // "export ZNC_NO_LAUNCH_AFTER_MAKECONF=1" would cause znc --makeconf to not offer immediate launch. - // Useful for distros which want to create config when znc package is installed. + // "export ZNC_NO_LAUNCH_AFTER_MAKECONF=1" would cause znc --makeconf to + // not offer immediate launch. + // Useful for distros which want to create config when znc package is + // installed. // See https://github.com/znc/znc/pull/257 char* szNoLaunch = getenv("ZNC_NO_LAUNCH_AFTER_MAKECONF"); if (szNoLaunch && *szNoLaunch == '1') { @@ -908,8 +967,7 @@ bool CZNC::WriteNewConfig(const CString& sConfigFile) { void CZNC::BackupConfigOnce(const CString& sSuffix) { static bool didBackup = false; - if (didBackup) - return; + if (didBackup) return; didBackup = true; CUtils::PrintAction("Creating a config backup"); @@ -925,14 +983,11 @@ bool CZNC::ParseConfig(const CString& sConfig, CString& sError) { m_sConfigFile = ExpandConfigPath(sConfig, false); CConfig config; - if (!ReadConfig(config, sError)) - return false; + if (!ReadConfig(config, sError)) return false; - if (!LoadGlobal(config, sError)) - return false; + if (!LoadGlobal(config, sError)) return false; - if (!LoadUsers(config, sError)) - return false; + if (!LoadUsers(config, sError)) return false; return true; } @@ -945,7 +1000,9 @@ bool CZNC::ReadConfig(CConfig& config, CString& sError) { if (!CFile::Exists(m_sConfigFile)) { sError = "No such file"; CUtils::PrintStatus(false, sError); - CUtils::PrintMessage("Restart ZNC with the --makeconf option if you wish to create this config."); + CUtils::PrintMessage( + "Restart ZNC with the --makeconf option if you wish to create this " + "config."); return false; } @@ -955,7 +1012,7 @@ bool CZNC::ReadConfig(CConfig& config, CString& sError) { return false; } - CFile *pFile = new CFile(m_sConfigFile); + CFile* pFile = new CFile(m_sConfigFile); // need to open the config file Read/Write for fcntl() // exclusive locking to work properly! @@ -976,7 +1033,7 @@ bool CZNC::ReadConfig(CConfig& config, CString& sError) { // (re)open the config file delete m_pLockFile; m_pLockFile = pFile; - CFile &File = *pFile; + CFile& File = *pFile; if (!config.Parse(File, sError)) { CUtils::PrintStatus(false, sError); @@ -989,18 +1046,25 @@ bool CZNC::ReadConfig(CConfig& config, CString& sError) { CString sSavedVersion; config.FindStringEntry("version", sSavedVersion); if (sSavedVersion.empty()) { - CUtils::PrintError("Config does not contain a version identifier. It may be be too old or corrupt."); + CUtils::PrintError( + "Config does not contain a version identifier. It may be be too " + "old or corrupt."); return false; } - tuple tSavedVersion = make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(), - sSavedVersion.Token(1, false, ".").ToUInt()); - tuple tCurrentVersion = make_tuple(VERSION_MAJOR, VERSION_MINOR); + tuple tSavedVersion = + make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(), + sSavedVersion.Token(1, false, ".").ToUInt()); + tuple tCurrentVersion = + make_tuple(VERSION_MAJOR, VERSION_MINOR); if (tSavedVersion < tCurrentVersion) { - CUtils::PrintMessage("Found old config from ZNC " + sSavedVersion + ". Saving a backup of it."); + CUtils::PrintMessage("Found old config from ZNC " + sSavedVersion + + ". Saving a backup of it."); BackupConfigOnce("pre-" + CString(VERSION_STR)); } else if (tSavedVersion > tCurrentVersion) { - CUtils::PrintError("Config was saved from ZNC " + sSavedVersion + ". It may or may not work with current ZNC " + GetVersion()); + CUtils::PrintError("Config was saved from ZNC " + sSavedVersion + + ". It may or may not work with current ZNC " + + GetVersion()); } return true; @@ -1010,11 +1074,9 @@ bool CZNC::RehashConfig(CString& sError) { ALLMODULECALL(OnPreRehash(), NOTHING); CConfig config; - if (!ReadConfig(config, sError)) - return false; + if (!ReadConfig(config, sError)) return false; - if (!LoadGlobal(config, sError)) - return false; + if (!LoadGlobal(config, sError)) return false; // do not reload users - it's dangerous! @@ -1025,7 +1087,7 @@ bool CZNC::RehashConfig(CString& sError) { bool CZNC::LoadGlobal(CConfig& config, CString& sError) { sError.clear(); - MCString msModules; // Modules are queued for later loading + MCString msModules; // Modules are queued for later loading VCString vsList; config.FindStringVector("loadmodule", vsList); @@ -1036,10 +1098,13 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { // compatibility for pre-1.0 configs CString sSavedVersion; config.FindStringEntry("version", sSavedVersion); - tuple tSavedVersion = make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(), - sSavedVersion.Token(1, false, ".").ToUInt()); + tuple tSavedVersion = + make_tuple(sSavedVersion.Token(0, false, ".").ToUInt(), + sSavedVersion.Token(1, false, ".").ToUInt()); if (sModName == "saslauth" && tSavedVersion < make_tuple(0, 207)) { - CUtils::PrintMessage("saslauth module was renamed to cyrusauth. Loading cyrusauth instead."); + CUtils::PrintMessage( + "saslauth module was renamed to cyrusauth. Loading cyrusauth " + "instead."); sModName = "cyrusauth"; } // end-compatibility for pre-1.0 configs @@ -1050,13 +1115,15 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { return false; } CString sModRet; - CModule *pOldMod; + CModule* pOldMod; pOldMod = GetModules().FindModule(sModName); if (!pOldMod) { CUtils::PrintAction("Loading global module [" + sModName + "]"); - bool bModRet = GetModules().LoadModule(sModName, sArgs, CModInfo::GlobalModule, nullptr, nullptr, sModRet); + bool bModRet = + GetModules().LoadModule(sModName, sArgs, CModInfo::GlobalModule, + nullptr, nullptr, sModRet); CUtils::PrintStatus(bModRet, bModRet ? "" : sModRet); if (!bModRet) { @@ -1066,7 +1133,8 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { } else if (pOldMod->GetArgs() != sArgs) { CUtils::PrintAction("Reloading global module [" + sModName + "]"); - bool bModRet = GetModules().ReloadModule(sModName, sArgs, nullptr, nullptr, sModRet); + bool bModRet = GetModules().ReloadModule(sModName, sArgs, nullptr, + nullptr, sModRet); CUtils::PrintStatus(bModRet, sModRet); if (!bModRet) { @@ -1086,13 +1154,17 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { } if (config.FindStringVector("bindhost", vsList)) { - CUtils::PrintStatus(false, "WARNING: the global BindHost list is deprecated. Ignoring the following lines:"); + CUtils::PrintStatus(false, + "WARNING: the global BindHost list is deprecated. " + "Ignoring the following lines:"); for (const CString& sHost : vsList) { CUtils::PrintStatus(false, "BindHost = " + sHost); } } if (config.FindStringVector("vhost", vsList)) { - CUtils::PrintStatus(false, "WARNING: the global vHost list is deprecated. Ignoring the following lines:"); + CUtils::PrintStatus(false, + "WARNING: the global vHost list is deprecated. " + "Ignoring the following lines:"); for (const CString& sHost : vsList) { CUtils::PrintStatus(false, "vHost = " + sHost); } @@ -1105,20 +1177,14 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { } CString sVal; - if (config.FindStringEntry("pidfile", sVal)) - m_sPidFile = sVal; - if (config.FindStringEntry("statusprefix", sVal)) - m_sStatusPrefix = sVal; - if (config.FindStringEntry("sslcertfile", sVal)) - m_sSSLCertFile = sVal; - if (config.FindStringEntry("sslkeyfile", sVal)) - m_sSSLKeyFile = sVal; + if (config.FindStringEntry("pidfile", sVal)) m_sPidFile = sVal; + if (config.FindStringEntry("statusprefix", sVal)) m_sStatusPrefix = sVal; + if (config.FindStringEntry("sslcertfile", sVal)) m_sSSLCertFile = sVal; + if (config.FindStringEntry("sslkeyfile", sVal)) m_sSSLKeyFile = sVal; if (config.FindStringEntry("ssldhparamfile", sVal)) m_sSSLDHParamFile = sVal; - if (config.FindStringEntry("sslciphers", sVal)) - m_sSSLCiphers = sVal; - if (config.FindStringEntry("skin", sVal)) - SetSkinName(sVal); + if (config.FindStringEntry("sslciphers", sVal)) m_sSSLCiphers = sVal; + if (config.FindStringEntry("skin", sVal)) SetSkinName(sVal); if (config.FindStringEntry("connectdelay", sVal)) SetConnectDelay(sVal.ToUInt()); if (config.FindStringEntry("serverthrottle", sVal)) @@ -1135,16 +1201,19 @@ bool CZNC::LoadGlobal(CConfig& config, CString& sError) { if (!SetSSLProtocols(sVal)) { VCString vsProtocols = GetAvailableSSLProtocols(); CUtils::PrintError("Invalid SSLProtocols value [" + sVal + "]"); - CUtils::PrintError("The syntax is [SSLProtocols = [+|-] ...]"); - CUtils::PrintError("Available protocols are [" + CString(", ").Join(vsProtocols.begin(), vsProtocols.end()) + "]"); + CUtils::PrintError( + "The syntax is [SSLProtocols = [+|-] ...]"); + CUtils::PrintError( + "Available protocols are [" + + CString(", ").Join(vsProtocols.begin(), vsProtocols.end()) + + "]"); return false; } } UnloadRemovedModules(msModules); - if (!LoadListeners(config, sError)) - return false; + if (!LoadListeners(config, sError)) return false; return true; } @@ -1167,7 +1236,8 @@ bool CZNC::LoadUsers(CConfig& config, CString& sError) { if (!m_sStatusPrefix.empty()) { if (!pUser->SetStatusPrefix(m_sStatusPrefix)) { - sError = "Invalid StatusPrefix [" + m_sStatusPrefix + "] Must be 1-5 chars, no spaces."; + sError = "Invalid StatusPrefix [" + m_sStatusPrefix + + "] Must be 1-5 chars, no spaces."; CUtils::PrintError(sError); return false; } @@ -1225,10 +1295,8 @@ bool CZNC::LoadListeners(CConfig& config, CString& sError) { } // compatibility for pre-1.0 configs - const char *szListenerEntries[] = { - "listen", "listen6", "listen4", - "listener", "listener6", "listener4" - }; + const char* szListenerEntries[] = {"listen", "listen6", "listen4", + "listener", "listener6", "listener4"}; VCString vsList; config.FindStringVector("loadmodule", vsList); @@ -1248,8 +1316,7 @@ bool CZNC::LoadListeners(CConfig& config, CString& sError) { for (const auto& subIt : subConf) { CConfig* pSubConf = subIt.second.m_pSubConfig; - if (!AddListener(pSubConf, sError)) - return false; + if (!AddListener(pSubConf, sError)) return false; if (!pSubConf->empty()) { sError = "Unhandled lines in Listener config!"; CUtils::PrintError(sError); @@ -1272,7 +1339,7 @@ void CZNC::UnloadRemovedModules(const MCString& msModules) { // unload modules which are no longer in the config set ssUnload; - for (CModule *pCurMod : GetModules()) { + for (CModule* pCurMod : GetModules()) { if (msModules.find(pCurMod->GetModName()) == msModules.end()) ssUnload.insert(pCurMod->GetModName()); } @@ -1309,9 +1376,7 @@ void CZNC::DumpConfig(const CConfig* pConfig) { } } -void CZNC::ClearTrustedProxies() { - m_vsTrustedProxies.clear(); -} +void CZNC::ClearTrustedProxies() { m_vsTrustedProxies.clear(); } bool CZNC::AddTrustedProxy(const CString& sHost) { if (sHost.empty()) { @@ -1330,7 +1395,8 @@ bool CZNC::AddTrustedProxy(const CString& sHost) { bool CZNC::RemTrustedProxy(const CString& sHost) { VCString::iterator it; - for (it = m_vsTrustedProxies.begin(); it != m_vsTrustedProxies.end(); ++it) { + for (it = m_vsTrustedProxies.begin(); it != m_vsTrustedProxies.end(); + ++it) { if (sHost.Equals(*it)) { m_vsTrustedProxies.erase(it); return true; @@ -1340,11 +1406,10 @@ bool CZNC::RemTrustedProxy(const CString& sHost) { return false; } -void CZNC::Broadcast(const CString& sMessage, bool bAdminOnly, - CUser* pSkipUser, CClient *pSkipClient) { +void CZNC::Broadcast(const CString& sMessage, bool bAdminOnly, CUser* pSkipUser, + CClient* pSkipClient) { for (const auto& it : m_msUsers) { - if (bAdminOnly && !it.second->IsAdmin()) - continue; + if (bAdminOnly && !it.second->IsAdmin()) continue; if (it.second != pSkipUser) { CString sMsg = sMessage; @@ -1376,15 +1441,15 @@ CModule* CZNC::FindModule(const CString& sModName, CUser* pUser) { return CZNC::Get().GetModules().FindModule(sModName); } -bool CZNC::UpdateModule(const CString &sModule) { - CModule *pModule; +bool CZNC::UpdateModule(const CString& sModule) { + CModule* pModule; map musLoaded; map mnsLoaded; // Unload the module for every user and network for (const auto& it : m_msUsers) { - CUser *pUser = it.second; + CUser* pUser = it.second; pModule = pUser->GetModules().FindModule(sModule); if (pModule) { @@ -1420,33 +1485,40 @@ bool CZNC::UpdateModule(const CString &sModule) { // Reload the global module if (bGlobal) { - if (!GetModules().LoadModule(sModule, sGlobalArgs, CModInfo::GlobalModule, nullptr, nullptr, sErr)) { - DEBUG("Failed to reload [" << sModule << "] globally [" << sErr << "]"); + if (!GetModules().LoadModule(sModule, sGlobalArgs, + CModInfo::GlobalModule, nullptr, nullptr, + sErr)) { + DEBUG("Failed to reload [" << sModule << "] globally [" << sErr + << "]"); bError = true; } } // Reload the module for all users for (const auto& it : musLoaded) { - CUser *pUser = it.first; + CUser* pUser = it.first; const CString& sArgs = it.second; - if (!pUser->GetModules().LoadModule(sModule, sArgs, CModInfo::UserModule, pUser, nullptr, sErr)) { - DEBUG("Failed to reload [" << sModule << "] for [" - << pUser->GetUserName() << "] [" << sErr << "]"); + if (!pUser->GetModules().LoadModule( + sModule, sArgs, CModInfo::UserModule, pUser, nullptr, sErr)) { + DEBUG("Failed to reload [" << sModule << "] for [" + << pUser->GetUserName() << "] [" << sErr + << "]"); bError = true; } } // Reload the module for all networks for (const auto& it : mnsLoaded) { - CIRCNetwork *pNetwork = it.first; + CIRCNetwork* pNetwork = it.first; const CString& sArgs = it.second; - if (!pNetwork->GetModules().LoadModule(sModule, sArgs, CModInfo::NetworkModule, pNetwork->GetUser(), pNetwork, sErr)) { - DEBUG("Failed to reload [" << sModule << "] for [" - << pNetwork->GetUser()->GetUserName() << "/" - << pNetwork->GetName() << "] [" << sErr << "]"); + if (!pNetwork->GetModules().LoadModule( + sModule, sArgs, CModInfo::NetworkModule, pNetwork->GetUser(), + pNetwork, sErr)) { + DEBUG("Failed to reload [" + << sModule << "] for [" << pNetwork->GetUser()->GetUserName() + << "/" << pNetwork->GetName() << "] [" << sErr << "]"); bError = true; } } @@ -1455,7 +1527,7 @@ bool CZNC::UpdateModule(const CString &sModule) { } CUser* CZNC::FindUser(const CString& sUsername) { - map::iterator it = m_msUsers.find(sUsername); + map::iterator it = m_msUsers.find(sUsername); if (it != m_msUsers.end()) { return it->second; @@ -1482,8 +1554,8 @@ bool CZNC::AddUser(CUser* pUser, CString& sErrorRet, bool bStartup) { return false; } if (!pUser->IsValid(sErrorRet)) { - DEBUG("Invalid user [" << pUser->GetUserName() << "] - [" - << sErrorRet << "]"); + DEBUG("Invalid user [" << pUser->GetUserName() << "] - [" << sErrorRet + << "]"); return false; } bool bFailed = false; @@ -1495,21 +1567,19 @@ bool CZNC::AddUser(CUser* pUser, CString& sErrorRet, bool bStartup) { if (bFailed) { DEBUG("AddUser [" << pUser->GetUserName() << "] aborted by a module [" - << sErrorRet << "]"); + << sErrorRet << "]"); return false; } m_msUsers[pUser->GetUserName()] = pUser; return true; } -CListener* CZNC::FindListener(u_short uPort, const CString& sBindHost, EAddrType eAddr) { +CListener* CZNC::FindListener(u_short uPort, const CString& sBindHost, + EAddrType eAddr) { for (CListener* pListener : m_vpListeners) { - if (pListener->GetPort() != uPort) - continue; - if (pListener->GetBindHost() != sBindHost) - continue; - if (pListener->GetAddrType() != eAddr) - continue; + if (pListener->GetPort() != uPort) continue; + if (pListener->GetBindHost() != sBindHost) continue; + if (pListener->GetAddrType() != eAddr) continue; return pListener; } return nullptr; @@ -1520,7 +1590,8 @@ bool CZNC::AddListener(const CString& sLine, CString& sError) { CString sValue = sLine.Token(1, true); EAddrType eAddr = ADDR_ALL; - if (sName.Equals("Listen4") || sName.Equals("Listen") || sName.Equals("Listener4")) { + if (sName.Equals("Listen4") || sName.Equals("Listen") || + sName.Equals("Listener4")) { eAddr = ADDR_IPV4ONLY; } if (sName.Equals("Listener6")) { @@ -1555,12 +1626,13 @@ bool CZNC::AddListener(const CString& sLine, CString& sError) { // No support for URIPrefix for old-style configs. CString sURIPrefix; unsigned short uPort = sPort.ToUShort(); - return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept, sError); + return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept, + sError); } bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost, - const CString& sURIPrefixRaw, bool bSSL, - EAddrType eAddr, CListener::EAcceptType eAccept, CString& sError) { + const CString& sURIPrefixRaw, bool bSSL, EAddrType eAddr, + CListener::EAcceptType eAccept, CString& sError) { CString sHostComment; if (!sBindHost.empty()) { @@ -1580,7 +1652,8 @@ bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost, sIPV6Comment = " using ipv6"; } - CUtils::PrintAction("Binding to port [" + CString((bSSL) ? "+" : "") + CString(uPort) + "]" + sHostComment + sIPV6Comment); + CUtils::PrintAction("Binding to port [" + CString((bSSL) ? "+" : "") + + CString(uPort) + "]" + sHostComment + sIPV6Comment); #ifndef HAVE_IPV6 if (ADDR_IPV6ONLY == eAddr) { @@ -1605,14 +1678,17 @@ bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost, // If stdin is e.g. /dev/null and we call GetBoolInput(), // we are stuck in an endless loop! - if (isatty(0) && CUtils::GetBoolInput("Would you like to create a new pem file?", true)) { + if (isatty(0) && + CUtils::GetBoolInput("Would you like to create a new pem file?", + true)) { sError.clear(); WritePemFile(); } else { return false; } - CUtils::PrintAction("Binding to port [+" + CString(uPort) + "]" + sHostComment + sIPV6Comment); + CUtils::PrintAction("Binding to port [+" + CString(uPort) + "]" + + sHostComment + sIPV6Comment); } #endif if (!uPort) { @@ -1623,7 +1699,7 @@ bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost, // URIPrefix must start with a slash and end without one. CString sURIPrefix = CString(sURIPrefixRaw); - if(!sURIPrefix.empty()) { + if (!sURIPrefix.empty()) { if (!sURIPrefix.StartsWith("/")) { sURIPrefix = "/" + sURIPrefix; } @@ -1632,7 +1708,8 @@ bool CZNC::AddListener(unsigned short uPort, const CString& sBindHost, } } - CListener* pListener = new CListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept); + CListener* pListener = + new CListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept); if (!pListener->Listen()) { sError = FormatBindError(); @@ -1699,7 +1776,8 @@ bool CZNC::AddListener(CConfig* pConfig, CString& sError) { return false; } - return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept, sError); + return AddListener(uPort, sBindHost, sURIPrefix, bSSL, eAddr, eAccept, + sError); } bool CZNC::AddListener(CListener* pListener) { @@ -1730,64 +1808,64 @@ bool CZNC::DelListener(CListener* pListener) { static CZNC* s_pZNC = nullptr; void CZNC::CreateInstance() { - if (s_pZNC) - abort(); + if (s_pZNC) abort(); s_pZNC = new CZNC(); } -CZNC& CZNC::Get() { - return *s_pZNC; -} +CZNC& CZNC::Get() { return *s_pZNC; } void CZNC::DestroyInstance() { delete s_pZNC; s_pZNC = nullptr; } -CZNC::TrafficStatsMap CZNC::GetTrafficStats(TrafficStatsPair &Users, - TrafficStatsPair &ZNC, TrafficStatsPair &Total) { +CZNC::TrafficStatsMap CZNC::GetTrafficStats(TrafficStatsPair& Users, + TrafficStatsPair& ZNC, + TrafficStatsPair& Total) { TrafficStatsMap ret; unsigned long long uiUsers_in, uiUsers_out, uiZNC_in, uiZNC_out; const map& msUsers = CZNC::Get().GetUserMap(); uiUsers_in = uiUsers_out = 0; - uiZNC_in = BytesRead(); + uiZNC_in = BytesRead(); uiZNC_out = BytesWritten(); for (const auto& it : msUsers) { - ret[it.first] = TrafficStatsPair(it.second->BytesRead(), it.second->BytesWritten()); - uiUsers_in += it.second->BytesRead(); + ret[it.first] = + TrafficStatsPair(it.second->BytesRead(), it.second->BytesWritten()); + uiUsers_in += it.second->BytesRead(); uiUsers_out += it.second->BytesWritten(); } for (Csock* pSock : m_Manager) { - CUser *pUser = nullptr; + CUser* pUser = nullptr; if (pSock->GetSockName().StartsWith("IRC::")) { - pUser = ((CIRCSock *) pSock)->GetNetwork()->GetUser(); + pUser = ((CIRCSock*)pSock)->GetNetwork()->GetUser(); } else if (pSock->GetSockName().StartsWith("USR::")) { - pUser = ((CClient*) pSock)->GetUser(); + pUser = ((CClient*)pSock)->GetUser(); } if (pUser) { - ret[pUser->GetUserName()].first += pSock->GetBytesRead(); + ret[pUser->GetUserName()].first += pSock->GetBytesRead(); ret[pUser->GetUserName()].second += pSock->GetBytesWritten(); - uiUsers_in += pSock->GetBytesRead(); + uiUsers_in += pSock->GetBytesRead(); uiUsers_out += pSock->GetBytesWritten(); } else { - uiZNC_in += pSock->GetBytesRead(); + uiZNC_in += pSock->GetBytesRead(); uiZNC_out += pSock->GetBytesWritten(); } } Users = TrafficStatsPair(uiUsers_in, uiUsers_out); - ZNC = TrafficStatsPair(uiZNC_in, uiZNC_out); + ZNC = TrafficStatsPair(uiZNC_in, uiZNC_out); Total = TrafficStatsPair(uiUsers_in + uiZNC_in, uiUsers_out + uiZNC_out); return ret; } -CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername, TrafficStatsPair& Total) { +CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername, + TrafficStatsPair& Total) { TrafficStatsMap Networks; CUser* pUser = FindUser(sUsername); @@ -1800,11 +1878,11 @@ CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername, Tra } for (Csock* pSock : m_Manager) { - CIRCNetwork *pNetwork = nullptr; + CIRCNetwork* pNetwork = nullptr; if (pSock->GetSockName().StartsWith("IRC::")) { - pNetwork = ((CIRCSock *) pSock)->GetNetwork(); + pNetwork = ((CIRCSock*)pSock)->GetNetwork(); } else if (pSock->GetSockName().StartsWith("USR::")) { - pNetwork = ((CClient *) pSock)->GetNetwork(); + pNetwork = ((CClient*)pSock)->GetNetwork(); } if (pNetwork && pNetwork->GetUser() == pUser) { @@ -1820,7 +1898,8 @@ CZNC::TrafficStatsMap CZNC::GetNetworkTrafficStats(const CString& sUsername, Tra } void CZNC::AuthUser(std::shared_ptr AuthClass) { - // TODO unless the auth module calls it, CUser::IsHostAllowed() is not honoured + // TODO unless the auth module calls it, CUser::IsHostAllowed() is not + // honoured bool bReturn = false; GLOBALMODULECALL(OnLoginAttempt(AuthClass), &bReturn); if (bReturn) return; @@ -1843,7 +1922,7 @@ void CZNC::AuthUser(std::shared_ptr AuthClass) { } class CConnectQueueTimer : public CCron { -public: + public: CConnectQueueTimer(int iSecs) : CCron() { SetName("Connect users"); Start(iSecs); @@ -1863,10 +1942,11 @@ public: CZNC::Get().LeakConnectQueueTimer(this); } -protected: + protected: void RunJob() override { list ConnectionQueue; - list& RealConnectionQueue = CZNC::Get().GetConnectionQueue(); + list& RealConnectionQueue = + CZNC::Get().GetConnectionQueue(); // Problem: If a network can't connect right now because e.g. it // is throttled, it will re-insert itself into the connection @@ -1878,7 +1958,7 @@ protected: ConnectionQueue.swap(RealConnectionQueue); while (!ConnectionQueue.empty()) { - CIRCNetwork *pNetwork = ConnectionQueue.front(); + CIRCNetwork* pNetwork = ConnectionQueue.front(); ConnectionQueue.pop_front(); if (pNetwork->Connect()) { @@ -1889,7 +1969,8 @@ protected: /* Now re-insert anything that is left in our local list into * the real connection queue. */ - RealConnectionQueue.splice(RealConnectionQueue.begin(), ConnectionQueue); + RealConnectionQueue.splice(RealConnectionQueue.begin(), + ConnectionQueue); if (RealConnectionQueue.empty()) { DEBUG("ConnectQueueTimer done"); @@ -1909,14 +1990,12 @@ void CZNC::SetConnectDelay(unsigned int i) { m_uiConnectDelay = i; } -VCString CZNC::GetAvailableSSLProtocols() -{ +VCString CZNC::GetAvailableSSLProtocols() { // NOTE: keep in sync with SetSSLProtocols() return {"SSLv2", "SSLv3", "TLSv1", "TLSV1.1", "TLSv1.2"}; } -bool CZNC::SetSSLProtocols(const CString& sProtocols) -{ +bool CZNC::SetSSLProtocols(const CString& sProtocols) { VCString vsProtocols; sProtocols.Split(" ", vsProtocols, false, "", "", true, true); @@ -1958,7 +2037,8 @@ bool CZNC::SetSSLProtocols(const CString& sProtocols) } void CZNC::EnableConnectQueue() { - if (!m_pConnectQueueTimer && !m_uiConnectPaused && !m_lpConnectQueue.empty()) { + if (!m_pConnectQueueTimer && !m_uiConnectPaused && + !m_lpConnectQueue.empty()) { m_pConnectQueueTimer = new CConnectQueueTimer(m_uiConnectDelay); GetManager().AddCron(m_pConnectQueueTimer); } @@ -1991,9 +2071,10 @@ void CZNC::ResumeConnectQueue() { } } -void CZNC::AddNetworkToQueue(CIRCNetwork *pNetwork) { +void CZNC::AddNetworkToQueue(CIRCNetwork* pNetwork) { // Make sure we are not already in the queue - if (std::find(m_lpConnectQueue.begin(), m_lpConnectQueue.end(), pNetwork) != m_lpConnectQueue.end()) { + if (std::find(m_lpConnectQueue.begin(), m_lpConnectQueue.end(), pNetwork) != + m_lpConnectQueue.end()) { return; } @@ -2001,11 +2082,8 @@ void CZNC::AddNetworkToQueue(CIRCNetwork *pNetwork) { EnableConnectQueue(); } -void CZNC::LeakConnectQueueTimer(CConnectQueueTimer *pTimer) { - if (m_pConnectQueueTimer == pTimer) - m_pConnectQueueTimer = nullptr; +void CZNC::LeakConnectQueueTimer(CConnectQueueTimer* pTimer) { + if (m_pConnectQueueTimer == pTimer) m_pConnectQueueTimer = nullptr; } -bool CZNC::WaitForChildLock() { - return m_pLockFile && m_pLockFile->ExLock(); -} +bool CZNC::WaitForChildLock() { return m_pLockFile && m_pLockFile->ExLock(); } diff --git a/test/BufferTest.cpp b/test/BufferTest.cpp index 3399f4ac..e292b462 100644 --- a/test/BufferTest.cpp +++ b/test/BufferTest.cpp @@ -23,16 +23,17 @@ using ::testing::SizeIs; using ::testing::ContainerEq; class BufferTest : public ::testing::Test { -protected: + protected: void SetUp() { CZNC::CreateInstance(); } void TearDown() { CZNC::DestroyInstance(); } }; TEST_F(BufferTest, BufLine) { CBuffer buffer(1); - buffer.AddLine(CMessage("@key=value :nick PRIVMSG {target} {text}"), "hello there"); + buffer.AddLine(CMessage("@key=value :nick PRIVMSG {target} {text}"), + "hello there"); const CBufLine& line = buffer.GetBufLine(0); - EXPECT_THAT(line.GetTags(), ContainerEq(MCString{{"key","value"}})); + EXPECT_THAT(line.GetTags(), ContainerEq(MCString{{"key", "value"}})); EXPECT_EQ(":nick PRIVMSG {target} {text}", line.GetFormat()); EXPECT_EQ("hello there", line.GetText()); EXPECT_EQ("PRIVMSG", line.GetCommand()); diff --git a/test/ClientTest.cpp b/test/ClientTest.cpp index 8638f821..2a4f3295 100644 --- a/test/ClientTest.cpp +++ b/test/ClientTest.cpp @@ -22,8 +22,10 @@ using ::testing::IsEmpty; using ::testing::ElementsAre; class ClientTest : public IRCTest { -protected: - void testPass(const CString& sInput, const CString& sUser, const CString& sIdentifier, const CString& sNetwork, const CString& sPass) const { + protected: + void testPass(const CString& sInput, const CString& sUser, + const CString& sIdentifier, const CString& sNetwork, + const CString& sPass) const { CClient client; client.ParsePass(sInput); EXPECT_EQ(sUser, client.m_sUser); @@ -32,7 +34,8 @@ protected: EXPECT_EQ(sPass, client.m_sPass); } - void testUser(const CString& sInput, const CString& sUser, const CString& sIdentifier, const CString& sNetwork) const { + void testUser(const CString& sInput, const CString& sUser, + const CString& sIdentifier, const CString& sNetwork) const { CClient client; client.ParseUser(sInput); EXPECT_EQ(sUser, client.m_sUser); @@ -90,49 +93,66 @@ TEST_F(ClientTest, AwayNotify) { EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); } -TEST_F(ClientTest, MultiPrefixWho) { // aka NAMESX - m_pTestSock->ReadLine(":server 005 guest PREFIX=(qaohv)~&@%+ NAMESX :are supported by this server"); +TEST_F(ClientTest, MultiPrefixWho) { // aka NAMESX + m_pTestSock->ReadLine( + ":server 005 guest PREFIX=(qaohv)~&@%+ NAMESX :are supported by this " + "server"); m_pTestClient->Reset(); - CMessage msg(":kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M."); - CMessage extmsg(":kenny.chatspike.net 352 guest #test grawity broken.symlink *.chatspike.net grawity H@%+ :0 Mantas M."); + CMessage msg( + ":kenny.chatspike.net 352 guest #test grawity broken.symlink " + "*.chatspike.net grawity H@%+ :0 Mantas M."); + CMessage extmsg( + ":kenny.chatspike.net 352 guest #test grawity broken.symlink " + "*.chatspike.net grawity H@%+ :0 Mantas M."); EXPECT_FALSE(m_pTestClient->HasNamesx()); m_pTestClient->PutClient(extmsg); EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); m_pTestClient->SetNamesx(true); EXPECT_TRUE(m_pTestClient->HasNamesx()); m_pTestClient->PutClient(extmsg); - EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString(), extmsg.ToString())); + EXPECT_THAT(m_pTestClient->vsLines, + ElementsAre(msg.ToString(), extmsg.ToString())); } -TEST_F(ClientTest, MultiPrefixNames) { // aka NAMESX - m_pTestSock->ReadLine(":server 005 guest PREFIX=(qaohv)~&@%+ NAMESX :are supported by this server"); +TEST_F(ClientTest, MultiPrefixNames) { // aka NAMESX + m_pTestSock->ReadLine( + ":server 005 guest PREFIX=(qaohv)~&@%+ NAMESX :are supported by this " + "server"); m_pTestClient->Reset(); - CMessage msg(":hades.arpa 353 guest = #tethys :~aji &Attila @alyx +KindOne Argure"); - CMessage extmsg(":hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne Argure"); + CMessage msg( + ":hades.arpa 353 guest = #tethys :~aji &Attila @alyx +KindOne Argure"); + CMessage extmsg( + ":hades.arpa 353 guest = #tethys :~&@%+aji &@Attila @+alyx +KindOne " + "Argure"); EXPECT_FALSE(m_pTestClient->HasNamesx()); m_pTestClient->PutClient(extmsg); EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); m_pTestClient->SetNamesx(true); EXPECT_TRUE(m_pTestClient->HasNamesx()); m_pTestClient->PutClient(extmsg); - EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString(), extmsg.ToString())); + EXPECT_THAT(m_pTestClient->vsLines, + ElementsAre(msg.ToString(), extmsg.ToString())); } -TEST_F(ClientTest, UserhostInNames) { // aka UHNAMES - m_pTestSock->ReadLine(":server 005 guest UHNAMES :are supported by this server"); +TEST_F(ClientTest, UserhostInNames) { // aka UHNAMES + m_pTestSock->ReadLine( + ":server 005 guest UHNAMES :are supported by this server"); m_pTestClient->Reset(); CMessage msg(":irc.bnc.im 353 guest = #atheme :Rylee somasonic"); - CMessage extmsg(":irc.bnc.im 353 guest = #atheme :Rylee!rylai@localhost somasonic!andrew@somasonic.org"); + CMessage extmsg( + ":irc.bnc.im 353 guest = #atheme :Rylee!rylai@localhost " + "somasonic!andrew@somasonic.org"); EXPECT_FALSE(m_pTestClient->HasUHNames()); m_pTestClient->PutClient(extmsg); EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); m_pTestClient->SetUHNames(true); EXPECT_TRUE(m_pTestClient->HasUHNames()); m_pTestClient->PutClient(extmsg); - EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString(), extmsg.ToString())); + EXPECT_THAT(m_pTestClient->vsLines, + ElementsAre(msg.ToString(), extmsg.ToString())); } TEST_F(ClientTest, ExtendedJoin) { @@ -147,12 +167,16 @@ TEST_F(ClientTest, ExtendedJoin) { m_pTestClient->SetExtendedJoin(true); EXPECT_TRUE(m_pTestClient->HasExtendedJoin()); m_pTestClient->PutClient(extmsg); - EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString(), extmsg.ToString())); + EXPECT_THAT(m_pTestClient->vsLines, + ElementsAre(msg.ToString(), extmsg.ToString())); } TEST_F(ClientTest, StatusMsg) { - m_pTestSock->ReadLine(":irc.znc.in 001 me :Welcome to the Internet Relay Network me"); - m_pTestSock->ReadLine(":irc.znc.in 005 me CHANTYPES=# PREFIX=(ov)@+ STATUSMSG=@+ :are supported by this server"); + m_pTestSock->ReadLine( + ":irc.znc.in 001 me :Welcome to the Internet Relay Network me"); + m_pTestSock->ReadLine( + ":irc.znc.in 005 me CHANTYPES=# PREFIX=(ov)@+ STATUSMSG=@+ :are " + "supported by this server"); m_pTestUser->SetAutoClearChanBuffer(false); m_pTestClient->ReadLine("PRIVMSG @#chan :hello ops"); @@ -160,7 +184,8 @@ TEST_F(ClientTest, StatusMsg) { EXPECT_EQ(1u, m_pTestChan->GetBuffer().Size()); m_pTestUser->SetTimestampPrepend(false); - EXPECT_EQ(":me PRIVMSG @#chan :hello ops", m_pTestChan->GetBuffer().GetLine(0, *m_pTestClient)); + EXPECT_EQ(":me PRIVMSG @#chan :hello ops", + m_pTestChan->GetBuffer().GetLine(0, *m_pTestClient)); } TEST_F(ClientTest, OnUserCTCPReplyMessage) { @@ -168,14 +193,15 @@ TEST_F(ClientTest, OnUserCTCPReplyMessage) { m_pTestModule->eAction = CModule::HALT; m_pTestClient->ReadLine(msg.ToString()); - CString sReply = "NOTICE someone :\x01VERSION 123 via " + CZNC::GetTag(false) + "\x01"; + CString sReply = + "NOTICE someone :\x01VERSION 123 via " + CZNC::GetTag(false) + "\x01"; EXPECT_THAT(m_pTestModule->vsHooks, ElementsAre("OnUserCTCPReplyMessage")); EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(sReply)); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -192,7 +218,7 @@ TEST_F(ClientTest, OnUserCTCPMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -209,7 +235,7 @@ TEST_F(ClientTest, OnUserActionMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -226,7 +252,7 @@ TEST_F(ClientTest, OnUserTextMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -243,7 +269,7 @@ TEST_F(ClientTest, OnUserNoticeMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -260,7 +286,7 @@ TEST_F(ClientTest, OnUserJoinMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -277,7 +303,7 @@ TEST_F(ClientTest, OnUserPartMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -294,7 +320,7 @@ TEST_F(ClientTest, OnUserTopicMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); @@ -311,9 +337,9 @@ TEST_F(ClientTest, OnUserQuitMessage) { EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(nullptr)); EXPECT_THAT(m_pTestModule->vClients, ElementsAre(m_pTestClient)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestClient->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // quit is never forwarded + EXPECT_THAT(m_pTestSock->vsLines, IsEmpty()); // quit is never forwarded } diff --git a/test/ConfigTest.cpp b/test/ConfigTest.cpp index bfcd2950..4023a0bb 100644 --- a/test/ConfigTest.cpp +++ b/test/ConfigTest.cpp @@ -19,10 +19,10 @@ #include class CConfigTest : public ::testing::Test { -public: + public: virtual ~CConfigTest() { m_File.Delete(); } -protected: + protected: CFile& WriteFile(const CString& sConfig) { char sName[] = "./temp-XXXXXX"; int fd = mkstemp(sName); @@ -34,15 +34,14 @@ protected: return m_File; } -private: - CFile m_File; + private: + CFile m_File; }; class CConfigErrorTest : public CConfigTest { -public: - + public: void TEST_ERROR(const CString& sConfig, const CString& sExpectError) { - CFile &File = WriteFile(sConfig); + CFile& File = WriteFile(sConfig); CConfig conf; CString sError; @@ -53,10 +52,9 @@ public: }; class CConfigSuccessTest : public CConfigTest { -public: - + public: void TEST_SUCCESS(const CString& sConfig, const CString& sExpectedOutput) { - CFile &File = WriteFile(sConfig); + CFile& File = WriteFile(sConfig); // Verify that Parse() rewinds the file File.Seek(12); @@ -89,7 +87,8 @@ public: CConfig::SubConfigMapIterator it2 = conf.BeginSubConfigs(); while (it2 != conf.EndSubConfigs()) { - std::map::const_iterator it3 = it2->second.begin(); + std::map::const_iterator it3 = + it2->second.begin(); while (it3 != it2->second.end()) { sRes += "->" + it2->first + "/" + it3->first + "\n"; @@ -102,12 +101,10 @@ public: } } -private: + private: }; -TEST_F(CConfigSuccessTest, Empty) { - TEST_SUCCESS("", ""); -} +TEST_F(CConfigSuccessTest, Empty) { TEST_SUCCESS("", ""); } /* duplicate entries */ TEST_F(CConfigSuccessTest, Duble1) { @@ -119,19 +116,25 @@ TEST_F(CConfigSuccessTest, Duble2) { /* sub configs */ TEST_F(CConfigErrorTest, SubConf1) { - TEST_ERROR("", "Error on line 1: Closing tag \"foo\" which is not open."); + TEST_ERROR("", + "Error on line 1: Closing tag \"foo\" which is not open."); } TEST_F(CConfigErrorTest, SubConf2) { - TEST_ERROR("\n\n", "Error on line 2: Closing tag \"bar\" which is not open."); + TEST_ERROR("\n\n", + "Error on line 2: Closing tag \"bar\" which is not open."); } TEST_F(CConfigErrorTest, SubConf3) { - TEST_ERROR("", "Error on line 1: Not all tags are closed at the end of the file. Inner-most open tag is \"foo\"."); + TEST_ERROR("", + "Error on line 1: Not all tags are closed at the end of the " + "file. Inner-most open tag is \"foo\"."); } TEST_F(CConfigErrorTest, SubConf4) { - TEST_ERROR("\n", "Error on line 1: Empty block name at begin of block."); + TEST_ERROR("\n", + "Error on line 1: Empty block name at begin of block."); } TEST_F(CConfigErrorTest, SubConf5) { - TEST_ERROR("\n\n\n", "Error on line 4: Duplicate entry for tag \"foo\" name \"1\"."); + TEST_ERROR("\n\n\n", + "Error on line 4: Duplicate entry for tag \"foo\" name \"1\"."); } TEST_F(CConfigSuccessTest, SubConf6) { TEST_SUCCESS("\n", "->foo/a\n<-\n"); @@ -140,7 +143,8 @@ TEST_F(CConfigSuccessTest, SubConf7) { TEST_SUCCESS("\n \n \n", "->a/b\n->c/d\n<-\n<-\n"); } TEST_F(CConfigSuccessTest, SubConf8) { - TEST_SUCCESS(" \t \nfoo = bar\n\tFooO = bar\n", "->a/B\nfoo=bar\nfooo=bar\n<-\n"); + TEST_SUCCESS(" \t \nfoo = bar\n\tFooO = bar\n", + "->a/B\nfoo=bar\nfooo=bar\n<-\n"); } /* comments */ @@ -148,16 +152,14 @@ TEST_F(CConfigSuccessTest, Comment1) { TEST_SUCCESS("Foo = bar // baz\n// Bar = baz", "foo=bar // baz\n"); } TEST_F(CConfigSuccessTest, Comment2) { - TEST_SUCCESS("Foo = bar /* baz */\n/*** Foo = baz ***/\n /**** asdsdfdf \n Some quite invalid stuff ***/\n", "foo=bar /* baz */\n"); + TEST_SUCCESS( + "Foo = bar /* baz */\n/*** Foo = baz ***/\n /**** asdsdfdf \n Some " + "quite invalid stuff ***/\n", + "foo=bar /* baz */\n"); } TEST_F(CConfigErrorTest, Comment3) { - TEST_ERROR("\n/* Just a comment\n", "Error on line 3: Comment not closed at end of file."); + TEST_ERROR("\n/* Just a comment\n", + "Error on line 3: Comment not closed at end of file."); } -TEST_F(CConfigSuccessTest, Comment4) { - TEST_SUCCESS("/* Foo\n/* Bar */", ""); -} -TEST_F(CConfigSuccessTest, Comment5) { - TEST_SUCCESS("/* Foo\n// */", ""); -} - - +TEST_F(CConfigSuccessTest, Comment4) { TEST_SUCCESS("/* Foo\n/* Bar */", ""); } +TEST_F(CConfigSuccessTest, Comment5) { TEST_SUCCESS("/* Foo\n// */", ""); } diff --git a/test/IRCSockTest.cpp b/test/IRCSockTest.cpp index 2fceb899..cb0dc1a4 100644 --- a/test/IRCSockTest.cpp +++ b/test/IRCSockTest.cpp @@ -29,24 +29,23 @@ using testing::ResultOf; using testing::_; class IRCSockTest : public IRCTest { -protected: + protected: }; TEST_F(IRCSockTest, OnAccountMessage) { CMessage msg(":nick!user@host ACCOUNT accountname"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnAccountMessage() hook (yet?) - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // account-notify disabled + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnAccountMessage() hook (yet?) + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // account-notify disabled } TEST_F(IRCSockTest, OnActionMessage) { // 2 callbacks are called in row: OnCTCP, OnAction. // If OnCTCP returns HALT, OnAction isn't called. struct ActionModule : TestModule { - ActionModule() { - Reset(); - } + ActionModule() { Reset(); } void Reset() { Mock::VerifyAndClear(this); EXPECT_CALL(*this, OnPrivCTCPMessage(_)).Times(0); @@ -77,7 +76,10 @@ TEST_F(IRCSockTest, OnActionMessage) { EXPECT_EQ(pExpectedChan, m.GetChan()); return CModule::HALT; }); - auto Reset = [&]() { testModule.Reset(); m_pTestClient->Reset(); }; + auto Reset = [&]() { + testModule.Reset(); + m_pTestClient->Reset(); + }; Reset(); { @@ -133,15 +135,17 @@ TEST_F(IRCSockTest, OnAwayMessage) { CMessage msg(":nick!user@host AWAY :reason"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnAwayMessage() hook (yet?) - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // away-notify disabled + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnAwayMessage() hook (yet?) + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // away-notify disabled } TEST_F(IRCSockTest, OnCapabilityMessage) { CMessage msg(":server CAP * LS :multi-prefix sasl"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnCapabilityMessage() hook (yet?) + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnCapabilityMessage() hook (yet?) EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); } @@ -154,7 +158,7 @@ TEST_F(IRCSockTest, OnCTCPMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(m_pTestChan)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -172,7 +176,7 @@ TEST_F(IRCSockTest, OnCTCPMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -190,7 +194,7 @@ TEST_F(IRCSockTest, OnCTCPMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -202,15 +206,20 @@ TEST_F(IRCSockTest, OnErrorMessage) { CMessage msg(":server ERROR :foo bar"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnErrorMessage() hook (yet?) - EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(":*status!znc@znc.in PRIVMSG me :Error from Server [foo bar]")); + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnErrorMessage() hook (yet?) + EXPECT_THAT( + m_pTestClient->vsLines, + ElementsAre( + ":*status!znc@znc.in PRIVMSG me :Error from Server [foo bar]")); } TEST_F(IRCSockTest, OnInviteMessage) { CMessage msg(":nick INVITE me #znc"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnInviteMessage() hook (yet?) + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnInviteMessage() hook (yet?) EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); } @@ -238,7 +247,8 @@ TEST_F(IRCSockTest, OnModeMessage) { CMessage msg(":nick MODE #chan +k key"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnModeMessage() hook (yet?) + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnModeMessage() hook (yet?) EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); } @@ -267,7 +277,7 @@ TEST_F(IRCSockTest, OnNoticeMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(m_pTestChan)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -285,7 +295,7 @@ TEST_F(IRCSockTest, OnNoticeMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -302,7 +312,7 @@ TEST_F(IRCSockTest, OnNumericMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -360,7 +370,7 @@ TEST_F(IRCSockTest, OnTextMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(m_pTestChan)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -378,7 +388,7 @@ TEST_F(IRCSockTest, OnTextMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(nullptr)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -395,7 +405,7 @@ TEST_F(IRCSockTest, OnTopicMessage) { EXPECT_THAT(m_pTestModule->vsMessages, ElementsAre(msg.ToString())); EXPECT_THAT(m_pTestModule->vNetworks, ElementsAre(m_pTestNetwork)); EXPECT_THAT(m_pTestModule->vChannels, ElementsAre(m_pTestChan)); - EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt + EXPECT_THAT(m_pTestClient->vsLines, IsEmpty()); // halt m_pTestModule->eAction = CModule::CONTINUE; m_pTestSock->ReadLine(msg.ToString()); @@ -407,68 +417,74 @@ TEST_F(IRCSockTest, OnWallopsMessage) { CMessage msg(":blub!dummy@rox-8DBEFE92 WALLOPS :this is a test"); m_pTestSock->ReadLine(msg.ToString()); - EXPECT_THAT(m_pTestModule->vsHooks, IsEmpty()); // no OnWallopsMessage() hook (yet?) + EXPECT_THAT(m_pTestModule->vsHooks, + IsEmpty()); // no OnWallopsMessage() hook (yet?) EXPECT_THAT(m_pTestClient->vsLines, ElementsAre(msg.ToString())); } TEST_F(IRCSockTest, ISupport) { MCString m1 = { - {"CHANTYPES", "#"}, - {"EXCEPTS", ""}, - {"INVEX", ""}, - {"CHANMODES", "eIbq,k,flj,CFLMPQScgimnprstz"}, - {"CHANLIMIT", "#:120"}, - {"PREFIX", "(ov)@+"}, - {"MAXLIST", "bqeI:100"}, - {"MODES", "4"}, - {"NETWORK", "znc"}, - {"KNOCK", ""}, - {"STATUSMSG", "@+"}, - {"CALLERID", "g"}, + {"CHANTYPES", "#"}, {"EXCEPTS", ""}, + {"INVEX", ""}, {"CHANMODES", "eIbq,k,flj,CFLMPQScgimnprstz"}, + {"CHANLIMIT", "#:120"}, {"PREFIX", "(ov)@+"}, + {"MAXLIST", "bqeI:100"}, {"MODES", "4"}, + {"NETWORK", "znc"}, {"KNOCK", ""}, + {"STATUSMSG", "@+"}, {"CALLERID", "g"}, }; - m_pTestSock->ReadLine(":irc.znc.in 005 user CHANTYPES=# EXCEPTS INVEX CHANMODES=eIbq,k,flj,CFLMPQScgimnprstz CHANLIMIT=#:120 PREFIX=(ov)@+ MAXLIST=bqeI:100 MODES=4 NETWORK=znc KNOCK STATUSMSG=@+ CALLERID=g :are supported by this server"); + m_pTestSock->ReadLine( + ":irc.znc.in 005 user CHANTYPES=# EXCEPTS INVEX " + "CHANMODES=eIbq,k,flj,CFLMPQScgimnprstz CHANLIMIT=#:120 PREFIX=(ov)@+ " + "MAXLIST=bqeI:100 MODES=4 NETWORK=znc KNOCK STATUSMSG=@+ CALLERID=g " + ":are supported by this server"); EXPECT_THAT(m_pTestSock->GetISupport(), ContainerEq(m1)); for (const auto& it : m1) { EXPECT_EQ(it.second, m_pTestSock->GetISupport(it.first)); } MCString m2 = { - {"CASEMAPPING", "rfc1459"}, - {"CHARSET", "ascii"}, - {"NICKLEN", "16"}, - {"CHANNELLEN", "50"}, - {"TOPICLEN", "390"}, - {"ETRACE", ""}, - {"CPRIVMSG", ""}, - {"CNOTICE", ""}, - {"DEAF", "D"}, - {"MONITOR", "100"}, - {"FNC", ""}, - {"TARGMAX", "NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:,MONITOR:"}, + {"CASEMAPPING", "rfc1459"}, + {"CHARSET", "ascii"}, + {"NICKLEN", "16"}, + {"CHANNELLEN", "50"}, + {"TOPICLEN", "390"}, + {"ETRACE", ""}, + {"CPRIVMSG", ""}, + {"CNOTICE", ""}, + {"DEAF", "D"}, + {"MONITOR", "100"}, + {"FNC", ""}, + {"TARGMAX", + "NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:,MONITOR:"}, }; MCString m12; - std::merge(m1.begin(), m1.end(), m2.begin(), m2.end(), std::inserter(m12, m12.begin())); + std::merge(m1.begin(), m1.end(), m2.begin(), m2.end(), + std::inserter(m12, m12.begin())); - m_pTestSock->ReadLine(":server 005 user CASEMAPPING=rfc1459 CHARSET=ascii NICKLEN=16 CHANNELLEN=50 TOPICLEN=390 ETRACE CPRIVMSG CNOTICE DEAF=D MONITOR=100 FNC TARGMAX=NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:,MONITOR: :are supported by this server"); + m_pTestSock->ReadLine( + ":server 005 user CASEMAPPING=rfc1459 CHARSET=ascii NICKLEN=16 " + "CHANNELLEN=50 TOPICLEN=390 ETRACE CPRIVMSG CNOTICE DEAF=D MONITOR=100 " + "FNC " + "TARGMAX=NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:," + "MONITOR: :are supported by this server"); EXPECT_THAT(m_pTestSock->GetISupport(), ContainerEq(m12)); for (const auto& it : m2) { EXPECT_EQ(it.second, m_pTestSock->GetISupport(it.first)); } MCString m3 = { - {"EXTBAN", "$,ajrxz"}, - {"WHOX", ""}, - {"CLIENTVER", "3.0"}, - {"SAFELIST", ""}, - {"ELIST", "CTU"}, + {"EXTBAN", "$,ajrxz"}, {"WHOX", ""}, {"CLIENTVER", "3.0"}, + {"SAFELIST", ""}, {"ELIST", "CTU"}, }; MCString m123; - std::merge(m12.begin(), m12.end(), m3.begin(), m3.end(), std::inserter(m123, m123.begin())); + std::merge(m12.begin(), m12.end(), m3.begin(), m3.end(), + std::inserter(m123, m123.begin())); - m_pTestSock->ReadLine(":server 005 zzzzzz EXTBAN=$,ajrxz WHOX CLIENTVER=3.0 SAFELIST ELIST=CTU :are supported by this server"); + m_pTestSock->ReadLine( + ":server 005 zzzzzz EXTBAN=$,ajrxz WHOX CLIENTVER=3.0 SAFELIST " + "ELIST=CTU :are supported by this server"); EXPECT_THAT(m_pTestSock->GetISupport(), ContainerEq(m123)); for (const auto& it : m3) { EXPECT_EQ(it.second, m_pTestSock->GetISupport(it.first)); @@ -480,8 +496,11 @@ TEST_F(IRCSockTest, ISupport) { } TEST_F(IRCSockTest, StatusMsg) { - m_pTestSock->ReadLine(":irc.znc.in 001 me :Welcome to the Internet Relay Network me"); - m_pTestSock->ReadLine(":irc.znc.in 005 me CHANTYPES=# PREFIX=(ov)@+ STATUSMSG=@+ :are supported by this server"); + m_pTestSock->ReadLine( + ":irc.znc.in 001 me :Welcome to the Internet Relay Network me"); + m_pTestSock->ReadLine( + ":irc.znc.in 005 me CHANTYPES=# PREFIX=(ov)@+ STATUSMSG=@+ :are " + "supported by this server"); m_pTestUser->SetAutoClearChanBuffer(false); m_pTestSock->ReadLine(":someone PRIVMSG @#chan :hello ops"); @@ -489,5 +508,6 @@ TEST_F(IRCSockTest, StatusMsg) { EXPECT_EQ(1u, m_pTestChan->GetBuffer().Size()); m_pTestUser->SetTimestampPrepend(false); - EXPECT_EQ(":someone PRIVMSG @#chan :hello ops", m_pTestChan->GetBuffer().GetLine(0, *m_pTestClient)); + EXPECT_EQ(":someone PRIVMSG @#chan :hello ops", + m_pTestChan->GetBuffer().GetLine(0, *m_pTestClient)); } diff --git a/test/IRCTest.h b/test/IRCTest.h index 5e59f668..1c078cfc 100644 --- a/test/IRCTest.h +++ b/test/IRCTest.h @@ -28,7 +28,7 @@ #include class TestClient : public CClient { -public: + public: TestClient() { SetNick("me"); } bool Write(const CString& sData) override { vsLines.push_back(sData.TrimSuffix_n("\r\n")); @@ -44,8 +44,10 @@ public: }; class TestIRCSock : public CIRCSock { -public: - TestIRCSock(CIRCNetwork* pNetwork) : CIRCSock(pNetwork) { m_Nick.SetNick("me"); } + public: + TestIRCSock(CIRCNetwork* pNetwork) : CIRCSock(pNetwork) { + m_Nick.SetNick("me"); + } bool Write(const CString& sData) override { vsLines.push_back(sData.TrimSuffix_n("\r\n")); return true; @@ -55,35 +57,114 @@ public: }; class TestModule : public CModule { -public: - TestModule() : CModule(nullptr, nullptr, nullptr, "testmod", "", CModInfo::NetworkModule) {} + public: + TestModule() + : CModule(nullptr, nullptr, nullptr, "testmod", "", + CModInfo::NetworkModule) {} - EModRet OnCTCPReplyMessage(CCTCPMessage& msg) override { vsHooks.push_back("OnCTCPReplyMessage"); return OnMessage(msg); } - EModRet OnPrivCTCPMessage(CCTCPMessage& msg) override { vsHooks.push_back("OnPrivCTCPMessage"); return OnMessage(msg); } - EModRet OnChanCTCPMessage(CCTCPMessage& msg) override { vsHooks.push_back("OnChanCTCPMessage"); return OnMessage(msg); } - EModRet OnPrivActionMessage(CActionMessage& msg) override { vsHooks.push_back("OnPrivActionMessage"); return OnMessage(msg); } - EModRet OnChanActionMessage(CActionMessage& msg) override { vsHooks.push_back("OnChanActionMessage"); return OnMessage(msg); } - EModRet OnPrivMessage(CTextMessage& msg) override { vsHooks.push_back("OnPrivMessage"); return OnMessage(msg); } - EModRet OnChanMessage(CTextMessage& msg) override { vsHooks.push_back("OnChanMessage"); return OnMessage(msg); } - EModRet OnPrivNoticeMessage(CNoticeMessage& msg) override { vsHooks.push_back("OnPrivNoticeMessage"); return OnMessage(msg); } - EModRet OnChanNoticeMessage(CNoticeMessage& msg) override { vsHooks.push_back("OnChanNoticeMessage"); return OnMessage(msg); } - EModRet OnTopicMessage(CTopicMessage& msg) override { vsHooks.push_back("OnTopicMessage"); return OnMessage(msg); } - EModRet OnNumericMessage(CNumericMessage& msg) override { vsHooks.push_back("OnNumericMessage"); return OnMessage(msg); } - void OnJoinMessage(CJoinMessage& msg) override { vsHooks.push_back("OnJoinMessage"); OnMessage(msg); } - void OnKickMessage(CKickMessage& msg) override { vsHooks.push_back("OnKickMessage"); OnMessage(msg); } - void OnNickMessage(CNickMessage& msg, const std::vector& vChans) override { vsHooks.push_back("OnNickMessage"); OnMessage(msg); } - void OnPartMessage(CPartMessage& msg) override { vsHooks.push_back("OnPartMessage"); OnMessage(msg); } - void OnQuitMessage(CQuitMessage& msg, const std::vector& vChans) override { vsHooks.push_back("OnQuitMessage"); OnMessage(msg); } + EModRet OnCTCPReplyMessage(CCTCPMessage& msg) override { + vsHooks.push_back("OnCTCPReplyMessage"); + return OnMessage(msg); + } + EModRet OnPrivCTCPMessage(CCTCPMessage& msg) override { + vsHooks.push_back("OnPrivCTCPMessage"); + return OnMessage(msg); + } + EModRet OnChanCTCPMessage(CCTCPMessage& msg) override { + vsHooks.push_back("OnChanCTCPMessage"); + return OnMessage(msg); + } + EModRet OnPrivActionMessage(CActionMessage& msg) override { + vsHooks.push_back("OnPrivActionMessage"); + return OnMessage(msg); + } + EModRet OnChanActionMessage(CActionMessage& msg) override { + vsHooks.push_back("OnChanActionMessage"); + return OnMessage(msg); + } + EModRet OnPrivMessage(CTextMessage& msg) override { + vsHooks.push_back("OnPrivMessage"); + return OnMessage(msg); + } + EModRet OnChanMessage(CTextMessage& msg) override { + vsHooks.push_back("OnChanMessage"); + return OnMessage(msg); + } + EModRet OnPrivNoticeMessage(CNoticeMessage& msg) override { + vsHooks.push_back("OnPrivNoticeMessage"); + return OnMessage(msg); + } + EModRet OnChanNoticeMessage(CNoticeMessage& msg) override { + vsHooks.push_back("OnChanNoticeMessage"); + return OnMessage(msg); + } + EModRet OnTopicMessage(CTopicMessage& msg) override { + vsHooks.push_back("OnTopicMessage"); + return OnMessage(msg); + } + EModRet OnNumericMessage(CNumericMessage& msg) override { + vsHooks.push_back("OnNumericMessage"); + return OnMessage(msg); + } + void OnJoinMessage(CJoinMessage& msg) override { + vsHooks.push_back("OnJoinMessage"); + OnMessage(msg); + } + void OnKickMessage(CKickMessage& msg) override { + vsHooks.push_back("OnKickMessage"); + OnMessage(msg); + } + void OnNickMessage(CNickMessage& msg, + const std::vector& vChans) override { + vsHooks.push_back("OnNickMessage"); + OnMessage(msg); + } + void OnPartMessage(CPartMessage& msg) override { + vsHooks.push_back("OnPartMessage"); + OnMessage(msg); + } + void OnQuitMessage(CQuitMessage& msg, + const std::vector& vChans) override { + vsHooks.push_back("OnQuitMessage"); + OnMessage(msg); + } - EModRet OnUserCTCPReplyMessage(CCTCPMessage& msg) override { vsHooks.push_back("OnUserCTCPReplyMessage"); return OnMessage(msg); } - EModRet OnUserCTCPMessage(CCTCPMessage& msg) override { vsHooks.push_back("OnUserCTCPMessage"); return OnMessage(msg); } - EModRet OnUserActionMessage(CActionMessage& msg) override { vsHooks.push_back("OnUserActionMessage"); return OnMessage(msg); } - EModRet OnUserTextMessage(CTextMessage& msg) override { vsHooks.push_back("OnUserTextMessage"); return OnMessage(msg); } - EModRet OnUserNoticeMessage(CNoticeMessage& msg) override { vsHooks.push_back("OnUserNoticeMessage"); return OnMessage(msg); } - EModRet OnUserJoinMessage(CJoinMessage& msg) override { vsHooks.push_back("OnUserJoinMessage"); return OnMessage(msg); } - EModRet OnUserPartMessage(CPartMessage& msg) override { vsHooks.push_back("OnUserPartMessage"); return OnMessage(msg); } - EModRet OnUserTopicMessage(CTopicMessage& msg) override { vsHooks.push_back("OnUserTopicMessage"); return OnMessage(msg); } - EModRet OnUserQuitMessage(CQuitMessage& msg) override { vsHooks.push_back("OnUserQuitMessage"); return OnMessage(msg); } + EModRet OnUserCTCPReplyMessage(CCTCPMessage& msg) override { + vsHooks.push_back("OnUserCTCPReplyMessage"); + return OnMessage(msg); + } + EModRet OnUserCTCPMessage(CCTCPMessage& msg) override { + vsHooks.push_back("OnUserCTCPMessage"); + return OnMessage(msg); + } + EModRet OnUserActionMessage(CActionMessage& msg) override { + vsHooks.push_back("OnUserActionMessage"); + return OnMessage(msg); + } + EModRet OnUserTextMessage(CTextMessage& msg) override { + vsHooks.push_back("OnUserTextMessage"); + return OnMessage(msg); + } + EModRet OnUserNoticeMessage(CNoticeMessage& msg) override { + vsHooks.push_back("OnUserNoticeMessage"); + return OnMessage(msg); + } + EModRet OnUserJoinMessage(CJoinMessage& msg) override { + vsHooks.push_back("OnUserJoinMessage"); + return OnMessage(msg); + } + EModRet OnUserPartMessage(CPartMessage& msg) override { + vsHooks.push_back("OnUserPartMessage"); + return OnMessage(msg); + } + EModRet OnUserTopicMessage(CTopicMessage& msg) override { + vsHooks.push_back("OnUserTopicMessage"); + return OnMessage(msg); + } + EModRet OnUserQuitMessage(CQuitMessage& msg) override { + vsHooks.push_back("OnUserQuitMessage"); + return OnMessage(msg); + } EModRet OnMessage(const CMessage& msg) { vsMessages.push_back(msg.ToString()); @@ -110,8 +191,11 @@ public: }; class IRCTest : public ::testing::Test { -protected: - IRCTest() { CDebug::SetDebug(false); CZNC::CreateInstance(); } + protected: + IRCTest() { + CDebug::SetDebug(false); + CZNC::CreateInstance(); + } ~IRCTest() { CZNC::DestroyInstance(); } void SetUp() { @@ -126,7 +210,8 @@ protected: m_pTestNetwork->AddChan(m_pTestChan); m_pTestChan->AddNick("nick"); m_pTestClient->AcceptLogin(*m_pTestUser); - m_pTestClient->vsLines.clear(); // :irc.znc.in 001 me :- Welcome to ZNC - + m_pTestClient->vsLines + .clear(); // :irc.znc.in 001 me :- Welcome to ZNC - CZNC::Get().GetModules().push_back(m_pTestModule); } @@ -150,4 +235,4 @@ protected: TestModule* m_pTestModule; }; -#endif // IRCTEST_H +#endif // IRCTEST_H diff --git a/test/Integration.cpp b/test/Integration.cpp index 3955c501..025deacd 100644 --- a/test/Integration.cpp +++ b/test/Integration.cpp @@ -33,7 +33,13 @@ #include -#define Z do { if (::testing::Test::HasFatalFailure()) { std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; return; } } while (0) +#define Z \ + do { \ + if (::testing::Test::HasFatalFailure()) { \ + std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; \ + return; \ + } \ + } while (0) using testing::HasSubstr; @@ -41,8 +47,9 @@ namespace { template class IO { -public: - IO(Device* device, bool verbose = false) : m_device(device), m_verbose(verbose) {} + public: + IO(Device* device, bool verbose = false) + : m_device(device), m_verbose(verbose) {} virtual ~IO() {} void ReadUntil(QByteArray pattern) { auto deadline = QDateTime::currentDateTime().addSecs(30); @@ -55,9 +62,11 @@ public: if (m_readed.length() > pattern.length()) { m_readed = m_readed.right(pattern.length()); } - const int timeout_ms = QDateTime::currentDateTime().msecsTo(deadline); + const int timeout_ms = + QDateTime::currentDateTime().msecsTo(deadline); ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString(); - ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) << "Wanted: " << pattern.toStdString(); + ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) + << "Wanted: " << pattern.toStdString(); QByteArray chunk = m_device->readAll(); if (m_verbose) { std::cout << chunk.toStdString() << std::flush; @@ -83,19 +92,19 @@ public: void Close() { #ifdef __CYGWIN__ #ifdef __x86_64__ - // Qt on cygwin64 silently doesn't send the rest of buffer from socket without this line + // Qt on cygwin64 silently doesn't send the rest of buffer from socket + // without this line sleep(1); #endif #endif m_device->disconnectFromHost(); } -private: - // QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() at all... + private: + // QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() + // at all... static void FlushIfCan(QIODevice*) {} - static void FlushIfCan(QTcpSocket* sock) { - sock->flush(); - } + static void FlushIfCan(QTcpSocket* sock) { sock->flush(); } Device* m_device; bool m_verbose; @@ -110,8 +119,9 @@ IO WrapIO(Device* d) { using Socket = IO; class Process : public IO { -public: - Process(QString cmd, QStringList args, bool interactive) : IO(&m_proc, true) { + public: + Process(QString cmd, QStringList args, bool interactive) + : IO(&m_proc, true) { if (!interactive) { m_proc.setProcessChannelMode(QProcess::ForwardedChannels); } @@ -141,11 +151,9 @@ public: m_kill = false; m_exit = code; } - void CanDie() { - m_allowDie = true; - } + void CanDie() { m_allowDie = true; } -private: + private: bool m_kill = true; int m_exit = 0; bool m_allowDie = false; @@ -180,32 +188,43 @@ void WriteConfig(QString path) { TEST(Config, AlreadyExists) { QTemporaryDir dir; - WriteConfig(dir.path());Z; - Process p("./znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf", true); - p.ReadUntil("already exists");Z; + WriteConfig(dir.path()); + Z; + Process p("./znc", QStringList() << "--debug" + << "--datadir" << dir.path() + << "--makeconf", + true); + p.ReadUntil("already exists"); + Z; p.CanDie(); } // Can't use QEventLoop without existing QCoreApplication class App { -public: + public: App() : m_argv(new char{}), m_app(m_argc, &m_argv) {} ~App() { delete m_argv; } -private: + + private: int m_argc = 1; char* m_argv; QCoreApplication m_app; }; class ZNCTest : public testing::Test { -protected: + protected: void SetUp() override { - WriteConfig(m_dir.path());Z; - ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667)) << m_server.errorString().toStdString();Z; + WriteConfig(m_dir.path()); + Z; + ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667)) + << m_server.errorString().toStdString(); + Z; } Socket ConnectIRCd() { - [this]{ ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */)); }(); + [this] { + ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */)); + }(); return WrapIO(m_server.nextPendingConnection()); } @@ -213,12 +232,18 @@ protected: m_clients.emplace_back(); QTcpSocket& sock = m_clients.back(); sock.connectToHost("127.0.0.1", 12345); - [&]{ ASSERT_TRUE(sock.waitForConnected()) << sock.errorString().toStdString(); }(); + [&] { + ASSERT_TRUE(sock.waitForConnected()) + << sock.errorString().toStdString(); + }(); return WrapIO(&sock); } std::unique_ptr Run() { - return std::unique_ptr(new Process("./znc", QStringList() << "--debug" << "--datadir" << m_dir.path(), false)); + return std::unique_ptr( + new Process("./znc", QStringList() << "--debug" + << "--datadir" << m_dir.path(), + false)); } Socket LoginClient() { @@ -232,20 +257,25 @@ protected: std::unique_ptr HttpGet(QNetworkRequest request) { return HandleHttp(m_network.get(request)); } - std::unique_ptr HttpPost(QNetworkRequest request, QList> data) { - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + std::unique_ptr HttpPost( + QNetworkRequest request, QList> data) { + request.setHeader(QNetworkRequest::ContentTypeHeader, + "application/x-www-form-urlencoded"); QUrlQuery q; q.setQueryItems(data); return HandleHttp(m_network.post(request, q.toString().toUtf8())); } std::unique_ptr HandleHttp(QNetworkReply* reply) { QEventLoop loop; - QObject::connect(reply, &QNetworkReply::finished, [&]() { - loop.quit(); - }); - QObject::connect(reply, static_cast(&QNetworkReply::error), [&](QNetworkReply::NetworkError e) { - ADD_FAILURE() << reply->errorString().toStdString(); - }); + QObject::connect(reply, &QNetworkReply::finished, + [&]() { loop.quit(); }); + QObject::connect( + reply, + static_cast( + &QNetworkReply::error), + [&](QNetworkReply::NetworkError e) { + ADD_FAILURE() << reply->errorString().toStdString(); + }); QTimer::singleShot(30000 /* msec */, &loop, [&]() { ADD_FAILURE() << "connection timeout"; loop.quit(); @@ -262,109 +292,143 @@ protected: }; TEST_F(ZNCTest, Connect) { - auto znc = Run();Z; + auto znc = Run(); + Z; - auto ircd = ConnectIRCd();Z; - ircd.ReadUntil("CAP LS");Z; + auto ircd = ConnectIRCd(); + Z; + ircd.ReadUntil("CAP LS"); + Z; - auto client = ConnectClient();Z; + auto client = ConnectClient(); + Z; client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); - client.ReadUntil("Welcome");Z; + client.ReadUntil("Welcome"); + Z; client.Close(); - client = ConnectClient();Z; + client = ConnectClient(); + Z; client.Write("PASS :user:hunter2"); client.Write("NICK nick"); client.Write("USER u x x x"); - client.ReadUntil("Welcome");Z; + client.ReadUntil("Welcome"); + Z; client.Close(); - client = ConnectClient();Z; + client = ConnectClient(); + Z; client.Write("NICK nick"); client.Write("USER user x x x"); client.ReadUntil("Configure your client to send a server password"); client.Close(); ircd.Write(":server 001 nick :Hello"); - ircd.ReadUntil("WHO");Z; + ircd.ReadUntil("WHO"); + Z; } TEST_F(ZNCTest, Channel) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; - auto client = LoginClient();Z; - client.ReadUntil("Welcome");Z; + auto client = LoginClient(); + Z; + client.ReadUntil("Welcome"); + Z; client.Write("JOIN #znc"); client.Close(); ircd.Write(":server 001 nick :Hello"); - ircd.ReadUntil("JOIN #znc");Z; + ircd.ReadUntil("JOIN #znc"); + Z; ircd.Write(":nick JOIN :#znc"); ircd.Write(":server 353 nick #znc :nick"); ircd.Write(":server 366 nick #znc :End of /NAMES list"); ircd.Write(":server PING :1"); ircd.ReadUntil("PONG 1"); - client = LoginClient();Z; - client.ReadUntil(":nick JOIN :#znc");Z; + client = LoginClient(); + Z; + client.ReadUntil(":nick JOIN :#znc"); + Z; } TEST_F(ZNCTest, HTTP) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; - auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; + auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/"))); + Z; EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC")); } TEST_F(ZNCTest, FixCVE20149403) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; ircd.Write(":server 001 nick :Hello"); ircd.Write(":server 005 nick CHANTYPES=# :supports"); ircd.Write(":server PING :1"); - ircd.ReadUntil("PONG 1");Z; + ircd.ReadUntil("PONG 1"); + Z; QNetworkRequest request; - request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); + request.setRawHeader("Authorization", + "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); HttpPost(request, { - {"user", "user"}, - {"network", "test"}, - {"submitted", "1"}, - {"name", "znc"}, - }); - ircd.ReadUntil("JOIN #znc");Z; - EXPECT_THAT(HttpPost(request, { - {"user", "user"}, - {"network", "test"}, - {"submitted", "1"}, - {"name", "znc"}, - })->readAll().toStdString(), HasSubstr("Channel [#znc] already exists")); + {"user", "user"}, + {"network", "test"}, + {"submitted", "1"}, + {"name", "znc"}, + }); + ircd.ReadUntil("JOIN #znc"); + Z; + EXPECT_THAT(HttpPost(request, + { + {"user", "user"}, + {"network", "test"}, + {"submitted", "1"}, + {"name", "znc"}, + }) + ->readAll() + .toStdString(), + HasSubstr("Channel [#znc] already exists")); } TEST_F(ZNCTest, FixFixOfCVE20149403) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; ircd.Write(":server 001 nick :Hello"); ircd.Write(":nick JOIN @#znc"); - ircd.ReadUntil("MODE @#znc");Z; + ircd.ReadUntil("MODE @#znc"); + Z; ircd.Write(":server 005 nick STATUSMSG=@ :supports"); ircd.Write(":server PING :12345"); - ircd.ReadUntil("PONG 12345");Z; + ircd.ReadUntil("PONG 12345"); + Z; QNetworkRequest request; - request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); + request.setRawHeader("Authorization", + "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); auto reply = HttpPost(request, { - {"user", "user"}, - {"network", "test"}, - {"submitted", "1"}, - {"name", "@#znc"}, - }); - EXPECT_THAT(reply->readAll().toStdString(), HasSubstr("Could not add channel [@#znc]")); + {"user", "user"}, + {"network", "test"}, + {"submitted", "1"}, + {"name", "@#znc"}, + }); + EXPECT_THAT(reply->readAll().toStdString(), + HasSubstr("Could not add channel [@#znc]")); } TEST_F(ZNCTest, InvalidConfigInChan) { @@ -381,14 +445,18 @@ TEST_F(ZNCTest, InvalidConfigInChan) {
)"; out.flush(); - auto znc = Run();Z; + auto znc = Run(); + Z; znc->ShouldFinishItself(1); } TEST_F(ZNCTest, ControlpanelModule) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; - auto client = LoginClient();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; + auto client = LoginClient(); + Z; const QString request = "PRIVMSG *controlpanel :"; const QByteArray response = ":*controlpanel!znc@znc.in PRIVMSG nick :"; @@ -402,852 +470,1186 @@ TEST_F(ZNCTest, ControlpanelModule) { // Add myself so I can test other things along with "user". client.Write(request + "AddUser KindOne hunter2"); - client.ReadUntil(response + "User [KindOne] added!");Z; + client.ReadUntil(response + "User [KindOne] added!"); + Z; client.Write(request + "AddUser KindOne hunter2"); - client.ReadUntil(response + "Error: User [KindOne] already exists!");Z; + client.ReadUntil(response + "Error: User [KindOne] already exists!"); + Z; client.Write(request + "AddCTCP user VERSION Test"); - client.ReadUntil(response + "Added!");Z; + client.ReadUntil(response + "Added!"); + Z; client.Write(request + "AddNetwork user freenode"); - client.ReadUntil(response + "Network [freenode] added for user [user].");Z; + client.ReadUntil(response + "Network [freenode] added for user [user]."); + Z; client.Write(request + "AddServer user freenode 127.0.0.1 6667"); - client.ReadUntil(response + "Added IRC Server [127.0.0.1 6667] for network [freenode] for user [user].");Z; + client.ReadUntil(response + + "Added IRC Server [127.0.0.1 6667] for network [freenode] " + "for user [user]."); + Z; client.Write(request + "AddChan user freenode #znc"); - client.ReadUntil(response + "Channel [#znc] for user [user] added.");Z; + client.ReadUntil(response + "Channel [#znc] for user [user] added."); + Z; client.Write(request + "AddChan user freenode #znc"); - client.ReadUntil(response + "Error: [user] already has a channel named [#znc].");Z; + client.ReadUntil(response + + "Error: [user] already has a channel named [#znc]."); + Z; client.Write(request + "AddUser user hunter2"); - client.ReadUntil(response + "Error: User [user] already exists!");Z; + client.ReadUntil(response + "Error: User [user] already exists!"); + Z; client.Write(request + "CloneUser user user_clone"); - client.ReadUntil(response + "User [user_clone] added!");Z; + client.ReadUntil(response + "User [user_clone] added!"); + Z; client.Write(request + "CloneUser user user_clone"); - client.ReadUntil(response + "Error: User not added! [User already exists]");Z; + client.ReadUntil(response + "Error: User not added! [User already exists]"); + Z; client.Write(request + "DelCTCP user VERSION"); - client.ReadUntil(response + "Successfully removed [VERSION] for user [user].");Z; + client.ReadUntil(response + + "Successfully removed [VERSION] for user [user]."); + Z; client.Write(request + "DelCTCP user VERSION"); - client.ReadUntil(response + "Error: [VERSION] not found for user [user]!");Z; + client.ReadUntil(response + "Error: [VERSION] not found for user [user]!"); + Z; client.Write(request + "DelChan user freenode #znc"); - client.ReadUntil(response + "Channel(s) [#znc] for user [user] deleted.");Z; + client.ReadUntil(response + "Channel(s) [#znc] for user [user] deleted."); + Z; client.Write(request + "DelChan user freenode #znc"); - client.ReadUntil(response + "Error: User [user] does not have any channel matching [#znc].");Z; + client.ReadUntil( + response + + "Error: User [user] does not have any channel matching [#znc]."); + Z; client.Write(request + "DelNetwork freenode"); - client.ReadUntil(response + "Network [freenode] deleted on user [user].");Z; + client.ReadUntil(response + "Network [freenode] deleted on user [user]."); + Z; client.Write(request + "DelNetwork freenode"); - client.ReadUntil(response + "Error: [user] does not have a network named [freenode].");Z; + client.ReadUntil(response + + "Error: [user] does not have a network named [freenode]."); + Z; client.Write(request + "AddNetwork user freenode"); - client.ReadUntil(response + "Network [freenode] added for user [user].");Z; + client.ReadUntil(response + "Network [freenode] added for user [user]."); + Z; client.Write(request + "AddChan user freenode #znc"); - client.ReadUntil(response + "Channel [#znc] for user [user] added.");Z; + client.ReadUntil(response + "Channel [#znc] for user [user] added."); + Z; client.Write(request + "DelUser user_clone"); - client.ReadUntil(response + "User [user_clone] deleted!");Z; + client.ReadUntil(response + "User [user_clone] deleted!"); + Z; client.Write(request + "DelUser user_clone"); - client.ReadUntil(response + "Error: User [user_clone] does not exist!");Z; + client.ReadUntil(response + "Error: User [user_clone] does not exist!"); + Z; client.Write(request + "Disconnect user freenode"); - client.ReadUntil(response + "Closed IRC connection for network [freenode] on user [user].");Z; + client.ReadUntil( + response + + "Closed IRC connection for network [freenode] on user [user]."); + Z; client.Write(request + "Disconnect user EFnet"); - client.ReadUntil(response + "Error: [user] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [user] does not have a network named [EFnet]."); + Z; client.Write(request + "Get Nick"); - client.ReadUntil(response + "Nick = user");Z; + client.ReadUntil(response + "Nick = user"); + Z; client.Write(request + "Get Altnick"); - client.ReadUntil(response + "AltNick = user_");Z; + client.ReadUntil(response + "AltNick = user_"); + Z; client.Write(request + "Get Ident"); - client.ReadUntil(response + "Ident = user");Z; + client.ReadUntil(response + "Ident = user"); + Z; client.Write(request + "Get RealName"); - client.ReadUntil(response + "RealName = ZNC");Z; + client.ReadUntil(response + "RealName = ZNC"); + Z; client.Write(request + "Get BindHost"); - client.ReadUntil(response + "BindHost = ");Z; + client.ReadUntil(response + "BindHost = "); + Z; client.Write(request + "Get DefaultChanModes"); - client.ReadUntil(response + "DefaultChanModes = ");Z; + client.ReadUntil(response + "DefaultChanModes = "); + Z; client.Write(request + "Get QuitMsg"); - client.ReadUntil(response + "QuitMsg = ");Z; + client.ReadUntil(response + "QuitMsg = "); + Z; client.Write(request + "Get Password"); - client.ReadUntil(response + "Error: Unknown variable");Z; + client.ReadUntil(response + "Error: Unknown variable"); + Z; client.Write(request + "Get Timezone"); - client.ReadUntil(response + "Timezone = ");Z; + client.ReadUntil(response + "Timezone = "); + Z; client.Write(request + "Get TimestampFormat"); - client.ReadUntil(response + "TimestampFormat = ");Z; + client.ReadUntil(response + "TimestampFormat = "); + Z; client.Write(request + "Get DCCBindHost"); - client.ReadUntil(response + "DCCBindHost = ");Z; + client.ReadUntil(response + "DCCBindHost = "); + Z; client.Write(request + "Get StatusPrefix"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "Get BufferCount"); - client.ReadUntil(response + "BufferCount = 50");Z; + client.ReadUntil(response + "BufferCount = 50"); + Z; client.Write(request + "Get JoinTries"); - client.ReadUntil(response + "JoinTries = ");Z; + client.ReadUntil(response + "JoinTries = "); + Z; client.Write(request + "Get MaxJoins"); - client.ReadUntil(response + "MaxJoins = ");Z; + client.ReadUntil(response + "MaxJoins = "); + Z; client.Write(request + "Get MaxNetworks"); - client.ReadUntil(response + "MaxNetworks = ");Z; + client.ReadUntil(response + "MaxNetworks = "); + Z; client.Write(request + "Get MaxQueryBuffers"); - client.ReadUntil(response + "MaxQueryBuffers = ");Z; + client.ReadUntil(response + "MaxQueryBuffers = "); + Z; client.Write(request + "Get Admin"); - client.ReadUntil(response + "Admin = true");Z; + client.ReadUntil(response + "Admin = true"); + Z; client.Write(request + "Get AppendTimestamp"); - client.ReadUntil(response + "AppendTimestamp = false");Z; + client.ReadUntil(response + "AppendTimestamp = false"); + Z; client.Write(request + "Get AutoClearChanBuffer"); - client.ReadUntil(response + "AutoClearChanBuffer = true");Z; + client.ReadUntil(response + "AutoClearChanBuffer = true"); + Z; client.Write(request + "Get AutoClearQueryBuffer"); - client.ReadUntil(response + "AutoClearQueryBuffer = true");Z; + client.ReadUntil(response + "AutoClearQueryBuffer = true"); + Z; client.Write(request + "Get DenyLoadMod"); - client.ReadUntil(response + "DenyLoadMod = false");Z; + client.ReadUntil(response + "DenyLoadMod = false"); + Z; client.Write(request + "Get DenySetBindHost"); - client.ReadUntil(response + "DenySetBindHost = false");Z; + client.ReadUntil(response + "DenySetBindHost = false"); + Z; client.Write(request + "Get MultiClients"); - client.ReadUntil(response + "MultiClients = true");Z; + client.ReadUntil(response + "MultiClients = true"); + Z; client.Write(request + "Get PrependTimestamp"); - client.ReadUntil(response + "PrependTimestamp = true");Z; + client.ReadUntil(response + "PrependTimestamp = true"); + Z; client.Write(request + "GetChan DefModes user freenode #znc"); - client.ReadUntil(response + "#znc: DefModes = ");Z; + client.ReadUntil(response + "#znc: DefModes = "); + Z; client.Write(request + "GetChan Key user freenode #znc"); - client.ReadUntil(response + "#znc: Key = ");Z; + client.ReadUntil(response + "#znc: Key = "); + Z; client.Write(request + "GetChan BufferSize user freenode #znc"); - client.ReadUntil(response + "#znc: BufferSize = 50 (default)");Z; + client.ReadUntil(response + "#znc: BufferSize = 50 (default)"); + Z; client.Write(request + "GetChan InConfig user freenode #znc"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; client.Write(request + "GetChan AutoClearChanBuffer user freenode #znc"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = true (default)");Z; + client.ReadUntil(response + "#znc: AutoClearChanBuffer = true (default)"); + Z; client.Write(request + "GetChan Detached user freenode #znc"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "GetNetwork Nick user freenode"); - client.ReadUntil(response + "Nick = user");Z; + client.ReadUntil(response + "Nick = user"); + Z; client.Write(request + "GetNetwork Altnick user freenode"); - client.ReadUntil(response + "AltNick = user_");Z; + client.ReadUntil(response + "AltNick = user_"); + Z; client.Write(request + "GetNetwork Ident user freenode"); - client.ReadUntil(response + "Ident = user");Z; + client.ReadUntil(response + "Ident = user"); + Z; client.Write(request + "GetNetwork BindHost user freenode"); - client.ReadUntil(response + "BindHost = ");Z; + client.ReadUntil(response + "BindHost = "); + Z; client.Write(request + "GetNetwork FloodRate user freenode"); - client.ReadUntil(response + "FloodRate = 1.00");Z; + client.ReadUntil(response + "FloodRate = 1.00"); + Z; client.Write(request + "GetNetwork FloodBurst user freenode"); - client.ReadUntil(response + "FloodBurst = 4");Z; + client.ReadUntil(response + "FloodBurst = 4"); + Z; client.Write(request + "GetNetwork JoinDelay user freenode"); - client.ReadUntil(response + "JoinDelay = 0");Z; + client.ReadUntil(response + "JoinDelay = 0"); + Z; client.Write(request + "GetNetwork QuitMsg user freenode"); - client.ReadUntil(response + "QuitMsg = ");Z; + client.ReadUntil(response + "QuitMsg = "); + Z; client.Write(request + "AddCTCP user VERSION Test"); - client.ReadUntil(response + "Added!");Z; + client.ReadUntil(response + "Added!"); + Z; client.Write(request + "ListCTCPs"); - client.ReadUntil(response + "Request: VERSION");Z; + client.ReadUntil(response + "Request: VERSION"); + Z; client.Write(request + "ListMods"); - client.ReadUntil(response + "Usage: ListMods ");Z; + client.ReadUntil(response + "Usage: ListMods "); + Z; client.Write(request + "ListNetMods"); - client.ReadUntil(response + "Usage: ListNetMods ");Z; + client.ReadUntil(response + "Usage: ListNetMods "); + Z; client.Write(request + "ListNetworks"); - client.ReadUntil(response + "Network: test");Z; + client.ReadUntil(response + "Network: test"); + Z; client.Write(request + "ListUsers"); - client.ReadUntil(response + "Username: user");Z; + client.ReadUntil(response + "Username: user"); + Z; client.Write(request + "LoadModule"); - client.ReadUntil(response + "Usage: LoadModule [args]");Z; + client.ReadUntil(response + + "Usage: LoadModule [args]"); + Z; client.Write(request + "LoadModule user"); - client.ReadUntil(response + "Usage: LoadModule [args]");Z; + client.ReadUntil(response + + "Usage: LoadModule [args]"); + Z; client.Write(request + "LoadModule user log"); - client.ReadUntil(response + "Loaded module [log]");Z; + client.ReadUntil(response + "Loaded module [log]"); + Z; client.Write(request + "LoadModule user log"); - client.ReadUntil(response + "Unable to load module [log] because it is already loaded");Z; + client.ReadUntil( + response + "Unable to load module [log] because it is already loaded"); + Z; client.Write(request + "LoadModule user autoop"); - client.ReadUntil(response + "Unable to load module [autoop] [Module [autoop] does not support module type [User].");Z; + client.ReadUntil(response + + "Unable to load module [autoop] [Module [autoop] does not " + "support module type [User]."); + Z; client.Write(request + "LoadNetModule user freenode log"); - client.ReadUntil(response + "Loaded module [log]");Z; + client.ReadUntil(response + "Loaded module [log]"); + Z; client.Write(request + "LoadNetModule user freenode log"); - client.ReadUntil(response + "Unable to load module [log] because it is already loaded");Z; + client.ReadUntil( + response + "Unable to load module [log] because it is already loaded"); + Z; client.Write(request + "LoadNetModule user EFnet log"); - client.ReadUntil(response + "Error: [user] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [user] does not have a network named [EFnet]."); + Z; client.Write(request + "Reconnect user freenode"); - client.ReadUntil(response + "Queued network [freenode] for user [user] for a reconnect.");Z; + client.ReadUntil( + response + + "Queued network [freenode] for user [user] for a reconnect."); + Z; client.Write(request + "Reconnect user EFnet"); - client.ReadUntil(response + "Error: [user] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [user] does not have a network named [EFnet]."); + Z; client.Write(request + "Set Nick user user1"); - client.ReadUntil(response + "Nick = user1");Z; + client.ReadUntil(response + "Nick = user1"); + Z; client.Write(request + "Set Altnick user user_1"); - client.ReadUntil(response + "AltNick = user_1");Z; + client.ReadUntil(response + "AltNick = user_1"); + Z; client.Write(request + "Set Ident user user1"); - client.ReadUntil(response + "Ident = user1");Z; + client.ReadUntil(response + "Ident = user1"); + Z; client.Write(request + "Set RealName user lol"); - client.ReadUntil(response + "RealName = lol");Z; + client.ReadUntil(response + "RealName = lol"); + Z; client.Write(request + "Set BindHost user 0.0.0.0"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "Set BindHost user 0.0.0.0"); - client.ReadUntil(response + "This bind host is already set!");Z; + client.ReadUntil(response + "This bind host is already set!"); + Z; // Need to clear the bindhost for testing in the 'setnetwork'. client.Write("PRIVMSG *status :ClearUserBindHost"); - client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Bind host cleared for your user.");Z; + client.ReadUntil( + ":*status!znc@znc.in PRIVMSG nick :Bind host cleared for your user."); + Z; client.Write(request + "Set DefaultChanModes user +znst"); - client.ReadUntil(response + "DefaultChanModes = +znst");Z; + client.ReadUntil(response + "DefaultChanModes = +znst"); + Z; client.Write(request + "Set QuitMsg user Writing this took forever."); - client.ReadUntil(response + "QuitMsg = Writing this took forever");Z; + client.ReadUntil(response + "QuitMsg = Writing this took forever"); + Z; client.Write(request + "Set Password user hunter2"); - client.ReadUntil(response + "Password has been changed!");Z; + client.ReadUntil(response + "Password has been changed!"); + Z; client.Write(request + "Set Timezone user America/New_York"); - client.ReadUntil(response + "Timezone = America/New_York");Z; + client.ReadUntil(response + "Timezone = America/New_York"); + Z; client.Write(request + "Set TimestampFormat user [%H:%M]"); - client.ReadUntil(response + "TimestampFormat = [%H:%M]");Z; + client.ReadUntil(response + "TimestampFormat = [%H:%M]"); + Z; client.Write(request + "Set DCCBindHost user 0.0.0.0"); - client.ReadUntil(response + "DCCBindHost = 0.0.0.0");Z; + client.ReadUntil(response + "DCCBindHost = 0.0.0.0"); + Z; client.Write(request + "Set StatusPrefix user &"); - client.ReadUntil(":&controlpanel!znc@znc.in PRIVMSG nick :StatusPrefix = &");Z; + client.ReadUntil( + ":&controlpanel!znc@znc.in PRIVMSG nick :StatusPrefix = &"); + Z; client.Write("PRIVMSG &controlpanel :Set StatusPrefix user *"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "SetChan DefModes user freenode #znc ms"); - client.ReadUntil(response + "#znc: DefModes = ms");Z; + client.ReadUntil(response + "#znc: DefModes = ms"); + Z; client.Write(request + "SetChan Key user freenode #znc KindOneRules"); - client.ReadUntil(response + "#znc: Key = KindOneRules");Z; + client.ReadUntil(response + "#znc: Key = KindOneRules"); + Z; client.Write(request + "SetChan BufferSize user freenode #znc 9001"); - client.ReadUntil(response + "#znc: BufferSize = 9001");Z; + client.ReadUntil(response + "#znc: BufferSize = 9001"); + Z; client.Write(request + "SetChan InConfig user freenode #znc true"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; - client.Write(request + "SetChan AutoClearChanBuffer user freenode #znc false"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = false");Z; + client.Write(request + + "SetChan AutoClearChanBuffer user freenode #znc false"); + client.ReadUntil(response + "#znc: AutoClearChanBuffer = false"); + Z; client.Write(request + "SetChan Detached user freenode #znc false"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "SetNetwork Nick user freenode NotUser"); - client.ReadUntil(response + "Nick = NotUser");Z; + client.ReadUntil(response + "Nick = NotUser"); + Z; client.Write(request + "SetNetwork Altnick user freenode NotUser_"); - client.ReadUntil(response + "AltNick = NotUser_");Z; + client.ReadUntil(response + "AltNick = NotUser_"); + Z; client.Write(request + "SetNetwork Ident user freenode identd"); - client.ReadUntil(response + "Ident = identd");Z; + client.ReadUntil(response + "Ident = identd"); + Z; client.Write(request + "SetNetwork BindHost user freenode 0.0.0.0"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "SetNetwork FloodRate user freenode 66.00"); - client.ReadUntil(response + "FloodRate = 66.00");Z; + client.ReadUntil(response + "FloodRate = 66.00"); + Z; client.Write(request + "SetNetwork FloodBurst user freenode 55"); - client.ReadUntil(response + "FloodBurst = 55");Z; + client.ReadUntil(response + "FloodBurst = 55"); + Z; client.Write(request + "SetNetwork JoinDelay user freenode 22"); - client.ReadUntil(response + "JoinDelay = 22");Z; + client.ReadUntil(response + "JoinDelay = 22"); + Z; client.Write(request + "SetNetwork QuitMsg user freenode telnet"); - client.ReadUntil(response + "QuitMsg = telnet");Z; + client.ReadUntil(response + "QuitMsg = telnet"); + Z; client.Write(request + "Get Nick user"); - client.ReadUntil(response + "Nick = user1");Z; + client.ReadUntil(response + "Nick = user1"); + Z; client.Write(request + "Get Altnick user"); - client.ReadUntil(response + "AltNick = user_1");Z; + client.ReadUntil(response + "AltNick = user_1"); + Z; client.Write(request + "Get Ident user"); - client.ReadUntil(response + "Ident = user1");Z; + client.ReadUntil(response + "Ident = user1"); + Z; client.Write(request + "Get RealName user"); - client.ReadUntil(response + "RealName = lol");Z; + client.ReadUntil(response + "RealName = lol"); + Z; client.Write(request + "Get BindHost user"); - client.ReadUntil(response + "BindHost = ");Z; + client.ReadUntil(response + "BindHost = "); + Z; client.Write(request + "Get DefaultChanModes user"); - client.ReadUntil(response + "DefaultChanModes = +znst");Z; + client.ReadUntil(response + "DefaultChanModes = +znst"); + Z; client.Write(request + "Get QuitMsg user"); - client.ReadUntil(response + "QuitMsg = Writing this took forever");Z; + client.ReadUntil(response + "QuitMsg = Writing this took forever"); + Z; client.Write(request + "Get Password user"); - client.ReadUntil(response + "Error: Unknown variable");Z; + client.ReadUntil(response + "Error: Unknown variable"); + Z; client.Write(request + "Get Timezone user"); - client.ReadUntil(response + "Timezone = America/New_York");Z; + client.ReadUntil(response + "Timezone = America/New_York"); + Z; client.Write(request + "Get TimestampFormat user"); - client.ReadUntil(response + "TimestampFormat = [%H:%M]");Z; + client.ReadUntil(response + "TimestampFormat = [%H:%M]"); + Z; client.Write(request + "Get DCCBindHost user"); - client.ReadUntil(response + "DCCBindHost = 0.0.0.0");Z; + client.ReadUntil(response + "DCCBindHost = 0.0.0.0"); + Z; client.Write(request + "Get StatusPrefix user"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "GetChan DefModes user freenode #znc"); - client.ReadUntil(response + "#znc: DefModes = ms");Z; + client.ReadUntil(response + "#znc: DefModes = ms"); + Z; client.Write(request + "GetChan Key user freenode #znc"); - client.ReadUntil(response + "#znc: Key = KindOneRules");Z; + client.ReadUntil(response + "#znc: Key = KindOneRules"); + Z; client.Write(request + "GetChan BufferSize user freenode #znc"); - client.ReadUntil(response + "#znc: BufferSize = 9001");Z; + client.ReadUntil(response + "#znc: BufferSize = 9001"); + Z; client.Write(request + "GetChan InConfig user freenode #znc"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; client.Write(request + "GetChan AutoClearChanBuffer user freenode #znc"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = false");Z; + client.ReadUntil(response + "#znc: AutoClearChanBuffer = false"); + Z; client.Write(request + "GetChan Detached user freenode #znc"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "GetNetwork Nick user freenode"); - client.ReadUntil(response + "Nick = NotUser");Z; + client.ReadUntil(response + "Nick = NotUser"); + Z; client.Write(request + "GetNetwork Altnick user freenode"); - client.ReadUntil(response + "AltNick = NotUser_");Z; + client.ReadUntil(response + "AltNick = NotUser_"); + Z; client.Write(request + "GetNetwork Ident user freenode"); - client.ReadUntil(response + "Ident = identd");Z; + client.ReadUntil(response + "Ident = identd"); + Z; client.Write(request + "GetNetwork BindHost user freenode"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "GetNetwork FloodRate user freenode"); - client.ReadUntil(response + "FloodRate = 66.00");Z; + client.ReadUntil(response + "FloodRate = 66.00"); + Z; client.Write(request + "GetNetwork FloodBurst user freenode 55"); - client.ReadUntil(response + "FloodBurst = 55");Z; + client.ReadUntil(response + "FloodBurst = 55"); + Z; client.Write(request + "GetNetwork JoinDelay user freenode 22"); - client.ReadUntil(response + "JoinDelay = 22");Z; + client.ReadUntil(response + "JoinDelay = 22"); + Z; client.Write(request + "GetNetwork QuitMsg user freenode"); - client.ReadUntil(response + "QuitMsg = telnet");Z; + client.ReadUntil(response + "QuitMsg = telnet"); + Z; client.Write(request + "UnLoadModule"); - client.ReadUntil(response + "Usage: UnloadModule ");Z; + client.ReadUntil(response + "Usage: UnloadModule "); + Z; client.Write(request + "UnLoadModule user"); - client.ReadUntil(response + "Usage: UnloadModule ");Z; + client.ReadUntil(response + "Usage: UnloadModule "); + Z; // https://github.com/znc/znc/issues/194 client.Write(request + "UnloadModule user controlpanel"); - client.ReadUntil(response + "Please use /znc unloadmod controlpanel");Z; + client.ReadUntil(response + "Please use /znc unloadmod controlpanel"); + Z; client.Write(request + "UnLoadModule user log"); - client.ReadUntil(response + "Unloaded module [log]");Z; + client.ReadUntil(response + "Unloaded module [log]"); + Z; client.Write(request + "UnLoadModule user log"); - client.ReadUntil(response + "Unable to unload module [log] [Module [log] not loaded.]");Z; + client.ReadUntil( + response + "Unable to unload module [log] [Module [log] not loaded.]"); + Z; client.Write(request + "UnLoadNetModule user freenode log"); - client.ReadUntil(response + "Unloaded module [log]");Z; + client.ReadUntil(response + "Unloaded module [log]"); + Z; client.Write(request + "UnLoadNetModule user freenode log"); - client.ReadUntil(response + "Unable to unload module [log] [Module [log] not loaded.]");Z; + client.ReadUntil( + response + "Unable to unload module [log] [Module [log] not loaded.]"); + Z; client.Write(request + "UnLoadNetModule user EFnet log"); - client.ReadUntil(response + "Error: [user] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [user] does not have a network named [EFnet]."); + Z; // Test on second user "KindOne" from "user". client.Write(request + "AddCTCP KindOne VERSION Test"); - client.ReadUntil(response + "Added!");Z; + client.ReadUntil(response + "Added!"); + Z; // Added at the very beginning. client.Write(request + "AddNetwork KindOne freenode"); - client.ReadUntil(response + "Network [freenode] added for user [KindOne].");Z; + client.ReadUntil(response + "Network [freenode] added for user [KindOne]."); + Z; client.Write(request + "AddServer KindOne freenode 127.0.0.1 6667"); - client.ReadUntil(response + "Added IRC Server [127.0.0.1 6667] for network [freenode] for user [KindOne].");Z; + client.ReadUntil(response + + "Added IRC Server [127.0.0.1 6667] for network [freenode] " + "for user [KindOne]."); + Z; client.Write(request + "AddChan KindOne freenode #znc"); - client.ReadUntil(response + "Channel [#znc] for user [KindOne] added.");Z; + client.ReadUntil(response + "Channel [#znc] for user [KindOne] added."); + Z; client.Write(request + "AddChan KindOne freenode #znc"); - client.ReadUntil(response + "Error: [KindOne] already has a channel named [#znc].");Z; + client.ReadUntil(response + + "Error: [KindOne] already has a channel named [#znc]."); + Z; client.Write(request + "AddUser KindOne hunter2"); - client.ReadUntil(response + "Error: User [KindOne] already exists!");Z; + client.ReadUntil(response + "Error: User [KindOne] already exists!"); + Z; client.Write(request + "CloneUser KindOne KindOne_clone"); - client.ReadUntil(response + "User [KindOne_clone] added!");Z; + client.ReadUntil(response + "User [KindOne_clone] added!"); + Z; client.Write(request + "CloneUser KindOne KindOne_clone"); - client.ReadUntil(response + "Error: User not added! [User already exists]");Z; + client.ReadUntil(response + "Error: User not added! [User already exists]"); + Z; client.Write(request + "DelCTCP KindOne VERSION"); - client.ReadUntil(response + "Successfully removed [VERSION] for user [KindOne].");Z; + client.ReadUntil(response + + "Successfully removed [VERSION] for user [KindOne]."); + Z; client.Write(request + "DelCTCP KindOne VERSION"); - client.ReadUntil(response + "Error: [VERSION] not found for user [KindOne]!");Z; + client.ReadUntil(response + + "Error: [VERSION] not found for user [KindOne]!"); + Z; client.Write(request + "DelChan KindOne freenode #znc"); - client.ReadUntil(response + "Channel(s) [#znc] for user [KindOne] deleted.");Z; + client.ReadUntil(response + + "Channel(s) [#znc] for user [KindOne] deleted."); + Z; client.Write(request + "DelChan KindOne freenode #znc"); - client.ReadUntil(response + "Error: User [KindOne] does not have any channel matching [#znc].");Z; + client.ReadUntil( + response + + "Error: User [KindOne] does not have any channel matching [#znc]."); + Z; client.Write(request + "DelNetwork KindOne freenode"); - client.ReadUntil(response + "Network [freenode] deleted on user [KindOne].");Z; + client.ReadUntil(response + + "Network [freenode] deleted on user [KindOne]."); + Z; client.Write(request + "DelNetwork KindOne freenode"); - client.ReadUntil(response + "Error: [KindOne] does not have a network named [freenode].");Z; + client.ReadUntil( + response + + "Error: [KindOne] does not have a network named [freenode]."); + Z; client.Write(request + "AddNetwork KindOne freenode"); - client.ReadUntil(response + "Network [freenode] added for user [KindOne].");Z; + client.ReadUntil(response + "Network [freenode] added for user [KindOne]."); + Z; client.Write(request + "AddChan KindOne freenode #znc"); - client.ReadUntil(response + "Channel [#znc] for user [KindOne] added.");Z; + client.ReadUntil(response + "Channel [#znc] for user [KindOne] added."); + Z; client.Write(request + "DelUser KindOne_clone"); - client.ReadUntil(response + "User [KindOne_clone] deleted!");Z; + client.ReadUntil(response + "User [KindOne_clone] deleted!"); + Z; client.Write(request + "DelUser KindOne_clone"); - client.ReadUntil(response + "Error: User [KindOne_clone] does not exist!");Z; + client.ReadUntil(response + "Error: User [KindOne_clone] does not exist!"); + Z; client.Write(request + "Disconnect KindOne freenode"); - client.ReadUntil(response + "Closed IRC connection for network [freenode] on user [KindOne].");Z; + client.ReadUntil( + response + + "Closed IRC connection for network [freenode] on user [KindOne]."); + Z; client.Write(request + "Disconnect KindOne EFnet"); - client.ReadUntil(response + "Error: [KindOne] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [KindOne] does not have a network named [EFnet]."); + Z; client.Write(request + "Get Nick KindOne"); - client.ReadUntil(response + "Nick = KindOne");Z; + client.ReadUntil(response + "Nick = KindOne"); + Z; client.Write(request + "Get AltNick KindOne"); - client.ReadUntil(response + "AltNick = KindOne");Z; + client.ReadUntil(response + "AltNick = KindOne"); + Z; client.Write(request + "Get Ident KindOne"); - client.ReadUntil(response + "Ident = KindOne");Z; + client.ReadUntil(response + "Ident = KindOne"); + Z; client.Write(request + "Get RealName KindOne"); - client.ReadUntil(response + "RealName = ");Z; + client.ReadUntil(response + "RealName = "); + Z; client.Write(request + "Get BindHost KindOne"); - client.ReadUntil(response + "BindHost = ");Z; + client.ReadUntil(response + "BindHost = "); + Z; client.Write(request + "Get DefaultChanModes KindOne"); - client.ReadUntil(response + "DefaultChanModes = ");Z; + client.ReadUntil(response + "DefaultChanModes = "); + Z; client.Write(request + "Get QuitMsg KindOne"); - client.ReadUntil(response + "QuitMsg = ");Z; + client.ReadUntil(response + "QuitMsg = "); + Z; client.Write(request + "Get Password KindOne"); - client.ReadUntil(response + "Error: Unknown variable");Z; + client.ReadUntil(response + "Error: Unknown variable"); + Z; client.Write(request + "Get Timezone KindOne"); - client.ReadUntil(response + "Timezone = ");Z; + client.ReadUntil(response + "Timezone = "); + Z; client.Write(request + "Get TimestampFormat KindOne"); - client.ReadUntil(response + "TimestampFormat = ");Z; + client.ReadUntil(response + "TimestampFormat = "); + Z; client.Write(request + "Get DCCBindHost KindOne"); - client.ReadUntil(response + "DCCBindHost = ");Z; + client.ReadUntil(response + "DCCBindHost = "); + Z; client.Write(request + "Get StatusPrefix KindOne"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "Get BufferCount KindOne"); - client.ReadUntil(response + "BufferCount = 50");Z; + client.ReadUntil(response + "BufferCount = 50"); + Z; client.Write(request + "Get JoinTries KindOne"); - client.ReadUntil(response + "JoinTries = ");Z; + client.ReadUntil(response + "JoinTries = "); + Z; client.Write(request + "Get MaxJoins KindOne"); - client.ReadUntil(response + "MaxJoins = ");Z; + client.ReadUntil(response + "MaxJoins = "); + Z; client.Write(request + "Get MaxNetworks KindOne"); - client.ReadUntil(response + "MaxNetworks = ");Z; + client.ReadUntil(response + "MaxNetworks = "); + Z; client.Write(request + "Get MaxQueryBuffers KindOne"); - client.ReadUntil(response + "MaxQueryBuffers = ");Z; + client.ReadUntil(response + "MaxQueryBuffers = "); + Z; client.Write(request + "Get Admin KindOne"); - client.ReadUntil(response + "Admin = false");Z; + client.ReadUntil(response + "Admin = false"); + Z; client.Write(request + "Get AppendTimestamp KindOne"); - client.ReadUntil(response + "AppendTimestamp = false");Z; + client.ReadUntil(response + "AppendTimestamp = false"); + Z; client.Write(request + "Get AutoClearChanBuffer KindOne"); - client.ReadUntil(response + "AutoClearChanBuffer = true");Z; + client.ReadUntil(response + "AutoClearChanBuffer = true"); + Z; client.Write(request + "Get AutoClearQueryBuffer KindOne"); - client.ReadUntil(response + "AutoClearQueryBuffer = true");Z; + client.ReadUntil(response + "AutoClearQueryBuffer = true"); + Z; client.Write(request + "Get DenyLoadMod KindOne"); - client.ReadUntil(response + "DenyLoadMod = false");Z; + client.ReadUntil(response + "DenyLoadMod = false"); + Z; client.Write(request + "Get DenySetBindHost KindOne"); - client.ReadUntil(response + "DenySetBindHost = false");Z; + client.ReadUntil(response + "DenySetBindHost = false"); + Z; client.Write(request + "Get MultiClients KindOne"); - client.ReadUntil(response + "MultiClients = true");Z; + client.ReadUntil(response + "MultiClients = true"); + Z; client.Write(request + "Get PrependTimestamp KindOne"); - client.ReadUntil(response + "PrependTimestamp = true");Z; + client.ReadUntil(response + "PrependTimestamp = true"); + Z; client.Write(request + "GetChan DefModes KindOne freenode #znc"); - client.ReadUntil(response + "#znc: DefModes = ");Z; + client.ReadUntil(response + "#znc: DefModes = "); + Z; client.Write(request + "GetChan Key KindOne freenode #znc"); - client.ReadUntil(response + "#znc: Key = ");Z; + client.ReadUntil(response + "#znc: Key = "); + Z; client.Write(request + "GetChan BufferSize KindOne freenode #znc"); - client.ReadUntil(response + "#znc: BufferSize = 50 (default)");Z; + client.ReadUntil(response + "#znc: BufferSize = 50 (default)"); + Z; client.Write(request + "GetChan InConfig KindOne freenode #znc"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; client.Write(request + "GetChan AutoClearChanBuffer KindOne freenode #znc"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = true (default)");Z; + client.ReadUntil(response + "#znc: AutoClearChanBuffer = true (default)"); + Z; client.Write(request + "GetChan Detached KindOne freenode #znc"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "GetNetwork Nick KindOne freenode"); - client.ReadUntil(response + "Nick = KindOne");Z; + client.ReadUntil(response + "Nick = KindOne"); + Z; client.Write(request + "GetNetwork Altnick KindOne freenode"); - client.ReadUntil(response + "AltNick = KindOne");Z; + client.ReadUntil(response + "AltNick = KindOne"); + Z; client.Write(request + "GetNetwork Ident KindOne freenode"); - client.ReadUntil(response + "Ident = KindOne");Z; + client.ReadUntil(response + "Ident = KindOne"); + Z; client.Write(request + "GetNetwork BindHost KindOne freenode"); - client.ReadUntil(response + "BindHost = ");Z; + client.ReadUntil(response + "BindHost = "); + Z; client.Write(request + "GetNetwork FloodRate KindOne freenode"); - client.ReadUntil(response + "FloodRate = 1.00");Z; + client.ReadUntil(response + "FloodRate = 1.00"); + Z; client.Write(request + "GetNetwork FloodBurst KindOne freenode"); - client.ReadUntil(response + "FloodBurst = 4");Z; + client.ReadUntil(response + "FloodBurst = 4"); + Z; client.Write(request + "GetNetwork JoinDelay KindOne freenode"); - client.ReadUntil(response + "JoinDelay = 0");Z; + client.ReadUntil(response + "JoinDelay = 0"); + Z; client.Write(request + "GetNetwork QuitMsg KindOne freenode"); - client.ReadUntil(response + "QuitMsg = ");Z; + client.ReadUntil(response + "QuitMsg = "); + Z; client.Write(request + "AddCTCP KindOne VERSION Test"); - client.ReadUntil(response + "Added!");Z; + client.ReadUntil(response + "Added!"); + Z; client.Write(request + "ListCTCPs KindOne"); - client.ReadUntil(response + "Request: VERSION");Z; + client.ReadUntil(response + "Request: VERSION"); + Z; client.Write(request + "ListMods KindOne"); - client.ReadUntil(response + "User [KindOne] has no modules loaded.");Z; + client.ReadUntil(response + "User [KindOne] has no modules loaded."); + Z; client.Write(request + "LoadModule KindOne autoop"); - client.ReadUntil(response + "Unable to load module [autoop] [Module [autoop] does not support module type [User].]");Z; + client.ReadUntil(response + + "Unable to load module [autoop] [Module [autoop] does not " + "support module type [User].]"); + Z; client.Write(request + "LoadModule KindOne perform"); - client.ReadUntil(response + "Loaded module [perform]");Z; + client.ReadUntil(response + "Loaded module [perform]"); + Z; client.Write(request + "ListMods KindOne"); - client.ReadUntil(response + "Name: perform");Z; + client.ReadUntil(response + "Name: perform"); + Z; client.Write(request + "ListNetMods KindOne"); - client.ReadUntil(response + "Usage: ListNetMods ");Z; + client.ReadUntil(response + "Usage: ListNetMods "); + Z; client.Write(request + "ListNetworks KindOne"); - client.ReadUntil(response + "Network: freenode");Z; + client.ReadUntil(response + "Network: freenode"); + Z; client.Write(request + "ListUsers"); - client.ReadUntil(response + "Username: user");Z; + client.ReadUntil(response + "Username: user"); + Z; client.Write(request + "LoadModule"); - client.ReadUntil(response + "Usage: LoadModule [args]");Z; + client.ReadUntil(response + + "Usage: LoadModule [args]"); + Z; client.Write(request + "LoadModule KindOne"); - client.ReadUntil(response + "Usage: LoadModule [args]");Z; + client.ReadUntil(response + + "Usage: LoadModule [args]"); + Z; client.Write(request + "LoadModule KindOne log"); - client.ReadUntil(response + "Loaded module [log]");Z; + client.ReadUntil(response + "Loaded module [log]"); + Z; client.Write(request + "LoadModule KindOne log"); - client.ReadUntil(response + "Unable to load module [log] because it is already loaded");Z; + client.ReadUntil( + response + "Unable to load module [log] because it is already loaded"); + Z; client.Write(request + "LoadNetModule KindOne freenode log"); - client.ReadUntil(response + "Loaded module [log]");Z; + client.ReadUntil(response + "Loaded module [log]"); + Z; client.Write(request + "LoadNetModule KindOne freenode log"); - client.ReadUntil(response + "Unable to load module [log] because it is already loaded");Z; + client.ReadUntil( + response + "Unable to load module [log] because it is already loaded"); + Z; client.Write(request + "LoadNetModule KindOne EFnet log"); - client.ReadUntil(response + "Error: [KindOne] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [KindOne] does not have a network named [EFnet]."); + Z; client.Write(request + "Reconnect KindOne freenode"); - client.ReadUntil(response + "Queued network [freenode] for user [KindOne] for a reconnect.");Z; + client.ReadUntil( + response + + "Queued network [freenode] for user [KindOne] for a reconnect."); + Z; client.Write(request + "Reconnect KindOne EFnet"); - client.ReadUntil(response + "Error: [KindOne] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [KindOne] does not have a network named [EFnet]."); + Z; client.Write(request + "Set Nick KindOne KindTwo"); - client.ReadUntil(response + "Nick = KindTwo");Z; + client.ReadUntil(response + "Nick = KindTwo"); + Z; client.Write(request + "Set Altnick KindOne KindTwo_"); - client.ReadUntil(response + "AltNick = KindTwo_");Z; + client.ReadUntil(response + "AltNick = KindTwo_"); + Z; client.Write(request + "Set Ident KindOne znc"); - client.ReadUntil(response + "Ident = znc");Z; + client.ReadUntil(response + "Ident = znc"); + Z; client.Write(request + "Set RealName KindOne real_name"); - client.ReadUntil(response + "RealName = real_name");Z; + client.ReadUntil(response + "RealName = real_name"); + Z; client.Write(request + "Set BindHost KindOne 0.0.0.0"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "Set DefaultChanModes KindOne +inst"); - client.ReadUntil(response + "DefaultChanModes = +inst");Z; + client.ReadUntil(response + "DefaultChanModes = +inst"); + Z; client.Write(request + "Set QuitMsg KindOne Writing this took forever."); - client.ReadUntil(response + "QuitMsg = Writing this took forever");Z; + client.ReadUntil(response + "QuitMsg = Writing this took forever"); + Z; client.Write(request + "Set Password KindOne hunter2"); - client.ReadUntil(response + "Password has been changed!");Z; + client.ReadUntil(response + "Password has been changed!"); + Z; client.Write(request + "Set Timezone KindOne America/New_York"); - client.ReadUntil(response + "Timezone = America/New_York");Z; + client.ReadUntil(response + "Timezone = America/New_York"); + Z; client.Write(request + "Set TimestampFormat KindOne [%H:%M]"); - client.ReadUntil(response + "TimestampFormat = [%H:%M]");Z; + client.ReadUntil(response + "TimestampFormat = [%H:%M]"); + Z; client.Write(request + "Set DCCBindHost KindOne 0.0.0.0"); - client.ReadUntil(response + "DCCBindHost = 0.0.0.0");Z; + client.ReadUntil(response + "DCCBindHost = 0.0.0.0"); + Z; client.Write(request + "Set StatusPrefix KindOne &"); - client.ReadUntil(response + "StatusPrefix = &");Z; + client.ReadUntil(response + "StatusPrefix = &"); + Z; client.Write(request + "Set StatusPrefix KindOne *"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "SetChan DefModes KindOne freenode #znc is"); - client.ReadUntil(response + "#znc: DefModes = is");Z; + client.ReadUntil(response + "#znc: DefModes = is"); + Z; client.Write(request + "SetChan Key KindOne freenode #znc KindOneRules"); - client.ReadUntil(response + "#znc: Key = KindOneRules");Z; + client.ReadUntil(response + "#znc: Key = KindOneRules"); + Z; client.Write(request + "SetChan BufferSize KindOne freenode #znc 9001"); - client.ReadUntil(response + "#znc: BufferSize = 9001");Z; + client.ReadUntil(response + "#znc: BufferSize = 9001"); + Z; client.Write(request + "SetChan InConfig KindOne freenode #znc true"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; - client.Write(request + "SetChan AutoClearChanBuffer KindOne freenode #znc false"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = false");Z; + client.Write(request + + "SetChan AutoClearChanBuffer KindOne freenode #znc false"); + client.ReadUntil(response + "#znc: AutoClearChanBuffer = false"); + Z; client.Write(request + "SetChan Detached KindOne freenode #znc false"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "SetNetwork Nick KindOne freenode KindTwo"); - client.ReadUntil(response + "Nick = KindTwo");Z; + client.ReadUntil(response + "Nick = KindTwo"); + Z; client.Write(request + "SetNetwork Altnick KindOne freenode KindTwo_"); - client.ReadUntil(response + "AltNick = KindTwo_");Z; + client.ReadUntil(response + "AltNick = KindTwo_"); + Z; client.Write(request + "SetNetwork Ident KindOne freenode znc"); - client.ReadUntil(response + "Ident = znc");Z; + client.ReadUntil(response + "Ident = znc"); + Z; client.Write(request + "SetNetwork BindHost KindOne freenode 0.0.0.0"); - client.ReadUntil(response + "This bind host is already set!");Z; + client.ReadUntil(response + "This bind host is already set!"); + Z; client.Write(request + "SetNetwork FloodRate KindOne freenode 42.00"); - client.ReadUntil(response + "FloodRate = 42.00");Z; + client.ReadUntil(response + "FloodRate = 42.00"); + Z; client.Write(request + "SetNetwork FloodBurst KindOne freenode 20"); - client.ReadUntil(response + "FloodBurst = 20");Z; + client.ReadUntil(response + "FloodBurst = 20"); + Z; client.Write(request + "SetNetwork JoinDelay KindOne freenode 5"); - client.ReadUntil(response + "JoinDelay = 5");Z; + client.ReadUntil(response + "JoinDelay = 5"); + Z; client.Write(request + "SetNetwork QuitMsg KindOne freenode telnet"); - client.ReadUntil(response + "QuitMsg = telnet");Z; + client.ReadUntil(response + "QuitMsg = telnet"); + Z; client.Write(request + "Get Nick KindOne"); - client.ReadUntil(response + "Nick = KindTwo");Z; + client.ReadUntil(response + "Nick = KindTwo"); + Z; client.Write(request + "Get Altnick KindOne"); - client.ReadUntil(response + "AltNick = KindTwo_");Z; + client.ReadUntil(response + "AltNick = KindTwo_"); + Z; client.Write(request + "Get Ident KindOne"); - client.ReadUntil(response + "Ident = znc");Z; + client.ReadUntil(response + "Ident = znc"); + Z; client.Write(request + "Get RealName KindOne"); - client.ReadUntil(response + "RealName = real_name");Z; + client.ReadUntil(response + "RealName = real_name"); + Z; client.Write(request + "Get BindHost KindOne"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "Get DefaultChanModes KindOne"); - client.ReadUntil(response + "DefaultChanModes = +inst");Z; + client.ReadUntil(response + "DefaultChanModes = +inst"); + Z; client.Write(request + "Get QuitMsg KindOne"); - client.ReadUntil(response + "QuitMsg = Writing this took forever");Z; + client.ReadUntil(response + "QuitMsg = Writing this took forever"); + Z; client.Write(request + "Get Password KindOne"); - client.ReadUntil(response + "Error: Unknown variable");Z; + client.ReadUntil(response + "Error: Unknown variable"); + Z; client.Write(request + "Get Timezone KindOne"); - client.ReadUntil(response + "Timezone = America/New_York");Z; + client.ReadUntil(response + "Timezone = America/New_York"); + Z; client.Write(request + "Get TimestampFormat KindOne"); - client.ReadUntil(response + "TimestampFormat = [%H:%M]");Z; + client.ReadUntil(response + "TimestampFormat = [%H:%M]"); + Z; client.Write(request + "Get DCCBindHost KindOne"); - client.ReadUntil(response + "DCCBindHost = 0.0.0.0");Z; + client.ReadUntil(response + "DCCBindHost = 0.0.0.0"); + Z; client.Write(request + "Get StatusPrefix KindOne"); - client.ReadUntil(response + "StatusPrefix = *");Z; + client.ReadUntil(response + "StatusPrefix = *"); + Z; client.Write(request + "GetChan DefModes KindOne freenode #znc"); - client.ReadUntil(response + "#znc: DefModes = is");Z; + client.ReadUntil(response + "#znc: DefModes = is"); + Z; client.Write(request + "GetChan Key KindOne freenode #znc"); - client.ReadUntil(response + "#znc: Key = KindOneRules");Z; + client.ReadUntil(response + "#znc: Key = KindOneRules"); + Z; client.Write(request + "GetChan BufferSize KindOne freenode #znc"); - client.ReadUntil(response + "#znc: BufferSize = 9001");Z; + client.ReadUntil(response + "#znc: BufferSize = 9001"); + Z; client.Write(request + "GetChan InConfig KindOne freenode #znc"); - client.ReadUntil(response + "#znc: InConfig = true");Z; + client.ReadUntil(response + "#znc: InConfig = true"); + Z; client.Write(request + "GetChan AutoClearChanBuffer KindOne freenode #znc"); - client.ReadUntil(response + "#znc: AutoClearChanBuffer = false");Z; + client.ReadUntil(response + "#znc: AutoClearChanBuffer = false"); + Z; client.Write(request + "GetChan Detached KindOne freenode #znc"); - client.ReadUntil(response + "#znc: Detached = false");Z; + client.ReadUntil(response + "#znc: Detached = false"); + Z; client.Write(request + "GetNetwork Nick KindOne freenode"); - client.ReadUntil(response + "Nick = KindTwo");Z; + client.ReadUntil(response + "Nick = KindTwo"); + Z; client.Write(request + "GetNetwork Altnick KindOne freenode"); - client.ReadUntil(response + "AltNick = KindTwo_");Z; + client.ReadUntil(response + "AltNick = KindTwo_"); + Z; client.Write(request + "GetNetwork Ident KindOne freenode"); - client.ReadUntil(response + "Ident = znc");Z; + client.ReadUntil(response + "Ident = znc"); + Z; client.Write(request + "GetNetwork BindHost KindOne freenode"); - client.ReadUntil(response + "BindHost = 0.0.0.0");Z; + client.ReadUntil(response + "BindHost = 0.0.0.0"); + Z; client.Write(request + "GetNetwork FloodRate KindOne freenode"); - client.ReadUntil(response + "FloodRate = 42.00");Z; + client.ReadUntil(response + "FloodRate = 42.00"); + Z; client.Write(request + "GetNetwork FloodBurst KindOne freenode"); - client.ReadUntil(response + "FloodBurst = 20");Z; + client.ReadUntil(response + "FloodBurst = 20"); + Z; client.Write(request + "GetNetwork JoinDelay KindOne freenode"); - client.ReadUntil(response + "JoinDelay = 5");Z; + client.ReadUntil(response + "JoinDelay = 5"); + Z; client.Write(request + "GetNetwork QuitMsg KindOne freenode"); - client.ReadUntil(response + "QuitMsg = telnet");Z; + client.ReadUntil(response + "QuitMsg = telnet"); + Z; client.Write(request + "UnLoadModule"); - client.ReadUntil(response + "Usage: UnloadModule ");Z; + client.ReadUntil(response + "Usage: UnloadModule "); + Z; client.Write(request + "UnLoadModule KindOne"); - client.ReadUntil(response + "Usage: UnloadModule ");Z; + client.ReadUntil(response + "Usage: UnloadModule "); + Z; client.Write(request + "UnLoadModule KindOne log"); - client.ReadUntil(response + "Unloaded module [log]");Z; + client.ReadUntil(response + "Unloaded module [log]"); + Z; client.Write(request + "UnLoadModule KindOne log"); - client.ReadUntil(response + "Unable to unload module [log] [Module [log] not loaded.]");Z; + client.ReadUntil( + response + "Unable to unload module [log] [Module [log] not loaded.]"); + Z; client.Write(request + "UnLoadNetModule KindOne freenode log"); - client.ReadUntil(response + "Unloaded module [log]");Z; + client.ReadUntil(response + "Unloaded module [log]"); + Z; client.Write(request + "UnLoadNetModule KindOne freenode log"); - client.ReadUntil(response + "Unable to unload module [log] [Module [log] not loaded.]");Z; + client.ReadUntil( + response + "Unable to unload module [log] [Module [log] not loaded.]"); + Z; client.Write(request + "UnLoadNetModule KindOne EFnet log"); - client.ReadUntil(response + "Error: [KindOne] does not have a network named [EFnet].");Z; + client.ReadUntil(response + + "Error: [KindOne] does not have a network named [EFnet]."); + Z; // Test on "foobar", a user that does not exist. client.Write(request + "AddCTCP foobar VERSION Test"); - client.ReadUntil(response + "Error: User [foobar] not found.");Z; - + client.ReadUntil(response + "Error: User [foobar] not found."); + Z; } TEST_F(ZNCTest, ShellModule) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; - auto client = LoginClient();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; + auto client = LoginClient(); + Z; client.Write("znc loadmod shell"); client.Write("PRIVMSG *shell :echo blahblah"); client.ReadUntil("PRIVMSG nick :blahblah"); @@ -1255,44 +1657,59 @@ TEST_F(ZNCTest, ShellModule) { } TEST_F(ZNCTest, NotifyConnectModule) { - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; - auto client = LoginClient();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; + auto client = LoginClient(); + Z; client.Write("znc loadmod notify_connect"); auto client2 = ConnectClient(); client2.Write("PASS :hunter2"); client2.Write("NICK nick"); client2.Write("USER user/test x x :x"); - client.ReadUntil("NOTICE nick :*** user attached (from 127.0.0.1)");Z; + client.ReadUntil("NOTICE nick :*** user attached (from 127.0.0.1)"); + Z; auto client3 = ConnectClient(); client3.Write("PASS :hunter2"); client3.Write("NICK nick"); client3.Write("USER user@identifier/test x x :x"); - client.ReadUntil("NOTICE nick :*** user@identifier attached (from 127.0.0.1)");Z; - client2.ReadUntil("NOTICE nick :*** user@identifier attached (from 127.0.0.1)");Z; + client.ReadUntil( + "NOTICE nick :*** user@identifier attached (from 127.0.0.1)"); + Z; + client2.ReadUntil( + "NOTICE nick :*** user@identifier attached (from 127.0.0.1)"); + Z; client2.Write("QUIT"); - client.ReadUntil("NOTICE nick :*** user detached (from 127.0.0.1)");Z; + client.ReadUntil("NOTICE nick :*** user detached (from 127.0.0.1)"); + Z; client3.Close(); - client.ReadUntil("NOTICE nick :*** user@identifier detached (from 127.0.0.1)");Z; + client.ReadUntil( + "NOTICE nick :*** user@identifier detached (from 127.0.0.1)"); + Z; } TEST_F(ZNCTest, WatchModule) { // TODO test other messages // TODO test options - auto znc = Run();Z; - auto ircd = ConnectIRCd();Z; - auto client = LoginClient();Z; + auto znc = Run(); + Z; + auto ircd = ConnectIRCd(); + Z; + auto client = LoginClient(); + Z; client.Write("znc loadmod watch"); client.Write("PRIVMSG *watch :add *"); client.ReadUntil("Adding entry:"); ircd.Write(":server 001 nick :Hello"); ircd.Write(":nick JOIN :#znc"); ircd.Write(":n!i@h PRIVMSG #znc :\001ACTION foo\001"); - client.ReadUntil(":$*!watch@znc.in PRIVMSG nick :* CTCP: n [ACTION foo] to [#znc]"); + client.ReadUntil( + ":$*!watch@znc.in PRIVMSG nick :* CTCP: n [ACTION foo] to [#znc]"); } } // namespace diff --git a/test/MessageTest.cpp b/test/MessageTest.cpp index 9ff7608a..af3030d9 100644 --- a/test/MessageTest.cpp +++ b/test/MessageTest.cpp @@ -32,7 +32,8 @@ TEST(MessageTest, SetParam) { EXPECT_THAT(msg.GetParams(), ContainerEq(VCString{"foo", "bar"})); msg.SetParam(3, "baz"); - EXPECT_THAT(msg.GetParams(), ContainerEq(VCString{"foo", "bar", "", "baz"})); + EXPECT_THAT(msg.GetParams(), + ContainerEq(VCString{"foo", "bar", "", "baz"})); } TEST(MessageTest, GetParams) { @@ -77,8 +78,10 @@ TEST(MessageTest, ToString) { EXPECT_EQ(":irc.znc.in", CMessage(":irc.znc.in").ToString()); EXPECT_EQ(":irc.znc.in CMD", CMessage(":irc.znc.in CMD").ToString()); EXPECT_EQ(":irc.znc.in CMD p1", CMessage(":irc.znc.in CMD p1").ToString()); - EXPECT_EQ(":irc.znc.in CMD p1 p2", CMessage(":irc.znc.in CMD p1 p2").ToString()); - EXPECT_EQ(":irc.znc.in CMD :p p p", CMessage(":irc.znc.in CMD :p p p").ToString()); + EXPECT_EQ(":irc.znc.in CMD p1 p2", + CMessage(":irc.znc.in CMD p1 p2").ToString()); + EXPECT_EQ(":irc.znc.in CMD :p p p", + CMessage(":irc.znc.in CMD :p p p").ToString()); EXPECT_EQ(":irc.znc.in CMD :", CMessage(":irc.znc.in CMD :").ToString()); EXPECT_EQ("CMD", CMessage(CNick(), "CMD").ToString()); @@ -86,49 +89,81 @@ TEST(MessageTest, ToString) { EXPECT_EQ("CMD p1 p2", CMessage(CNick(), "CMD", {"p1", "p2"}).ToString()); EXPECT_EQ("CMD :p p p", CMessage(CNick(), "CMD", {"p p p"}).ToString()); EXPECT_EQ(":irc.znc.in", CMessage(CNick(":irc.znc.in"), "").ToString()); - EXPECT_EQ(":irc.znc.in CMD", CMessage(CNick(":irc.znc.in"), "CMD").ToString()); - EXPECT_EQ(":irc.znc.in CMD p1", CMessage(CNick(":irc.znc.in"), "CMD", {"p1"}).ToString()); - EXPECT_EQ(":irc.znc.in CMD p1 p2", CMessage(CNick(":irc.znc.in"), "CMD", {"p1", "p2"}).ToString()); - EXPECT_EQ(":irc.znc.in CMD :p p p", CMessage(CNick(":irc.znc.in"), "CMD", {"p p p"}).ToString()); - EXPECT_EQ(":irc.znc.in CMD :", CMessage(CNick(":irc.znc.in"), "CMD", {""}).ToString()); + EXPECT_EQ(":irc.znc.in CMD", + CMessage(CNick(":irc.znc.in"), "CMD").ToString()); + EXPECT_EQ(":irc.znc.in CMD p1", + CMessage(CNick(":irc.znc.in"), "CMD", {"p1"}).ToString()); + EXPECT_EQ(":irc.znc.in CMD p1 p2", + CMessage(CNick(":irc.znc.in"), "CMD", {"p1", "p2"}).ToString()); + EXPECT_EQ(":irc.znc.in CMD :p p p", + CMessage(CNick(":irc.znc.in"), "CMD", {"p p p"}).ToString()); + EXPECT_EQ(":irc.znc.in CMD :", + CMessage(CNick(":irc.znc.in"), "CMD", {""}).ToString()); // #1045 - retain the colon if it was there - EXPECT_EQ(":services. 328 user #chan http://znc.in", CMessage(":services. 328 user #chan http://znc.in").ToString()); - EXPECT_EQ(":services. 328 user #chan :http://znc.in", CMessage(":services. 328 user #chan :http://znc.in").ToString()); + EXPECT_EQ(":services. 328 user #chan http://znc.in", + CMessage(":services. 328 user #chan http://znc.in").ToString()); + EXPECT_EQ(":services. 328 user #chan :http://znc.in", + CMessage(":services. 328 user #chan :http://znc.in").ToString()); } TEST(MessageTest, Tags) { EXPECT_THAT(CMessage("").GetTags(), IsEmpty()); - EXPECT_THAT(CMessage(":nick!ident@host PRIVMSG #chan :hello world").GetTags(), IsEmpty()); + EXPECT_THAT( + CMessage(":nick!ident@host PRIVMSG #chan :hello world").GetTags(), + IsEmpty()); - EXPECT_THAT(CMessage("@a=b").GetTags(), ContainerEq(MCString{{"a","b"}})); - EXPECT_THAT(CMessage("@a=b :nick!ident@host PRIVMSG #chan :hello world").GetTags(), ContainerEq(MCString{{"a","b"}})); - EXPECT_THAT(CMessage("@a=b :rest").GetTags(), ContainerEq(MCString{{"a","b"}})); + EXPECT_THAT(CMessage("@a=b").GetTags(), ContainerEq(MCString{{"a", "b"}})); + EXPECT_THAT( + CMessage("@a=b :nick!ident@host PRIVMSG #chan :hello world").GetTags(), + ContainerEq(MCString{{"a", "b"}})); + EXPECT_THAT(CMessage("@a=b :rest").GetTags(), + ContainerEq(MCString{{"a", "b"}})); - EXPECT_THAT(CMessage("@ab=cdef;znc.in/gh-ij=klmn,op :rest").GetTags(), ContainerEq(MCString{{"ab","cdef"},{"znc.in/gh-ij","klmn,op"}})); - EXPECT_THAT(CMessage("@a===b== :rest").GetTags(), ContainerEq(MCString{{"a","==b=="}})); + EXPECT_THAT( + CMessage("@ab=cdef;znc.in/gh-ij=klmn,op :rest").GetTags(), + ContainerEq(MCString{{"ab", "cdef"}, {"znc.in/gh-ij", "klmn,op"}})); + EXPECT_THAT(CMessage("@a===b== :rest").GetTags(), + ContainerEq(MCString{{"a", "==b=="}})); - EXPECT_THAT(CMessage("@a;b=c;d :rest").GetTags(), ContainerEq(MCString{{"a",""},{"b","c"},{"d",""}})); + EXPECT_THAT(CMessage("@a;b=c;d :rest").GetTags(), + ContainerEq(MCString{{"a", ""}, {"b", "c"}, {"d", ""}})); - EXPECT_THAT(CMessage(R"(@semi-colon=\:;space=\s;NUL=\0;backslash=\\;CR=\r;LF=\n :rest)").GetTags(), - ContainerEq(MCString{{"semi-colon",";"},{"space"," "},{"NUL",{'\0'}},{"backslash","\\"},{"CR",{'\r'}},{"LF",{'\n'}}})); + EXPECT_THAT( + CMessage( + R"(@semi-colon=\:;space=\s;NUL=\0;backslash=\\;CR=\r;LF=\n :rest)") + .GetTags(), + ContainerEq(MCString{{"semi-colon", ";"}, + {"space", " "}, + {"NUL", {'\0'}}, + {"backslash", "\\"}, + {"CR", {'\r'}}, + {"LF", {'\n'}}})); - EXPECT_THAT(CMessage(R"(@a=\:\s\\\r\n :rest)").GetTags(), ContainerEq(MCString{{"a","; \\\r\n"}})); + EXPECT_THAT(CMessage(R"(@a=\:\s\\\r\n :rest)").GetTags(), + ContainerEq(MCString{{"a", "; \\\r\n"}})); CMessage msg(":rest"); - msg.SetTags({{"a","b"}}); + msg.SetTags({{"a", "b"}}); EXPECT_EQ("@a=b :rest", msg.ToString()); - msg.SetTags({{"a","b"}, {"c","d"}}); + msg.SetTags({{"a", "b"}, {"c", "d"}}); EXPECT_EQ("@a=b;c=d :rest", msg.ToString()); - msg.SetTags({{"a","b"},{"c","d"},{"e",""}}); + msg.SetTags({{"a", "b"}, {"c", "d"}, {"e", ""}}); EXPECT_EQ("@a=b;c=d;e :rest", msg.ToString()); - msg.SetTags({{"semi-colon",";"},{"space"," "},{"NUL",{'\0'}},{"backslash","\\"},{"CR",{'\r'}},{"LF",{'\n'}}}); - EXPECT_EQ(R"(@CR=\r;LF=\n;NUL=\0;backslash=\\;semi-colon=\:;space=\s :rest)", msg.ToString()); + msg.SetTags({{"semi-colon", ";"}, + {"space", " "}, + {"NUL", {'\0'}}, + {"backslash", "\\"}, + {"CR", {'\r'}}, + {"LF", {'\n'}}}); + EXPECT_EQ( + R"(@CR=\r;LF=\n;NUL=\0;backslash=\\;semi-colon=\:;space=\s :rest)", + msg.ToString()); - msg.SetTags({{"a","; \\\r\n"}}); + msg.SetTags({{"a", "; \\\r\n"}}); EXPECT_EQ(R"(@a=\:\s\\\r\n :rest)", msg.ToString()); } @@ -137,30 +172,42 @@ TEST(MessageTest, FormatFlags) { CMessage msg(line); EXPECT_EQ(line, msg.ToString()); - EXPECT_EQ(":irc.example.com COMMAND param", msg.ToString(CMessage::ExcludeTags)); + EXPECT_EQ(":irc.example.com COMMAND param", + msg.ToString(CMessage::ExcludeTags)); EXPECT_EQ("@foo=bar COMMAND param", msg.ToString(CMessage::ExcludePrefix)); - EXPECT_EQ("COMMAND param", msg.ToString(CMessage::ExcludePrefix|CMessage::ExcludeTags)); + EXPECT_EQ("COMMAND param", + msg.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); } TEST(MessageTest, Equals) { EXPECT_TRUE(CMessage("JOIN #chan").Equals(CMessage("JOIN #chan"))); EXPECT_FALSE(CMessage("JOIN #chan").Equals(CMessage("JOIN #znc"))); - EXPECT_TRUE(CMessage(":nick JOIN #chan").Equals(CMessage(":nick JOIN #chan"))); - EXPECT_FALSE(CMessage(":nick JOIN #chan").Equals(CMessage(":nick JOIN #znc"))); - EXPECT_FALSE(CMessage(":nick JOIN #chan").Equals(CMessage(":someone JOIN #chan"))); + EXPECT_TRUE( + CMessage(":nick JOIN #chan").Equals(CMessage(":nick JOIN #chan"))); + EXPECT_FALSE( + CMessage(":nick JOIN #chan").Equals(CMessage(":nick JOIN #znc"))); + EXPECT_FALSE( + CMessage(":nick JOIN #chan").Equals(CMessage(":someone JOIN #chan"))); - EXPECT_TRUE(CMessage("PRIVMSG nick :hi").Equals(CMessage("PRIVMSG nick :hi"))); - EXPECT_TRUE(CMessage("PRIVMSG nick hi").Equals(CMessage("PRIVMSG nick :hi"))); - EXPECT_TRUE(CMessage("PRIVMSG nick :hi").Equals(CMessage("PRIVMSG nick hi"))); - EXPECT_TRUE(CMessage("PRIVMSG nick hi").Equals(CMessage("PRIVMSG nick hi"))); + EXPECT_TRUE( + CMessage("PRIVMSG nick :hi").Equals(CMessage("PRIVMSG nick :hi"))); + EXPECT_TRUE( + CMessage("PRIVMSG nick hi").Equals(CMessage("PRIVMSG nick :hi"))); + EXPECT_TRUE( + CMessage("PRIVMSG nick :hi").Equals(CMessage("PRIVMSG nick hi"))); + EXPECT_TRUE( + CMessage("PRIVMSG nick hi").Equals(CMessage("PRIVMSG nick hi"))); EXPECT_TRUE(CMessage("CMD nick p1 p2").Equals(CMessage("CMD nick p1 p2"))); - EXPECT_TRUE(CMessage("CMD nick :p1 p2").Equals(CMessage("CMD nick :p1 p2"))); + EXPECT_TRUE( + CMessage("CMD nick :p1 p2").Equals(CMessage("CMD nick :p1 p2"))); EXPECT_TRUE(CMessage("CMD nick p1 :p2").Equals(CMessage("CMD nick p1 p2"))); - EXPECT_FALSE(CMessage("CMD nick :p1 p2").Equals(CMessage("CMD nick p1 p2"))); + EXPECT_FALSE( + CMessage("CMD nick :p1 p2").Equals(CMessage("CMD nick p1 p2"))); - EXPECT_TRUE(CMessage("@t=now :sender CMD p").Equals(CMessage("@t=then :sender CMD p"))); + EXPECT_TRUE(CMessage("@t=now :sender CMD p") + .Equals(CMessage("@t=then :sender CMD p"))); } TEST(MessageTest, Type) { @@ -364,7 +411,8 @@ TEST(MessageTest, PrivAction) { msg.SetText("foo bar"); EXPECT_EQ("foo bar", msg.GetText()); - EXPECT_EQ(":sender PRIVMSG receiver :\001ACTION foo bar\001", msg.ToString()); + EXPECT_EQ(":sender PRIVMSG receiver :\001ACTION foo bar\001", + msg.ToString()); } TEST(MessageTest, PrivCTCP) { @@ -431,57 +479,79 @@ TEST(MessageTest, Parse) { EXPECT_EQ(":)", msg.GetParam(0)); } -// The test data for MessageTest.Parse originates from https://github.com/SaberUK/ircparser +// The test data for MessageTest.Parse originates from +// https://github.com/SaberUK/ircparser // // IRCParser - Internet Relay Chat Message Parser // // Copyright (C) 2015 Peter "SaberUK" Powell // -// Permission to use, copy, modify, and/or distribute this software for any purpose with or without -// fee is hereby granted, provided that the above copyright notice and this permission notice appear +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without +// fee is hereby granted, provided that the above copyright notice and this +// permission notice appear // in all copies. // -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -// SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE -// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS +// SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN +// NO EVENT SHALL THE +// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +// OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, +// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE +// USE OR PERFORMANCE // OF THIS SOFTWARE. // when checking a valid message with tags and a source TEST(MessageTest, ParseWithTags) { - const CString line = "@tag1=value1;tag2;vendor1/tag3=value2;vendor2/tag4 :irc.example.com COMMAND param1 param2 :param3 param3"; + const CString line = + "@tag1=value1;tag2;vendor1/tag3=value2;vendor2/tag4 :irc.example.com " + "COMMAND param1 param2 :param3 param3"; CMessage msg(line); EXPECT_EQ(line, msg.ToString()); - EXPECT_THAT(msg.GetTags(), ContainerEq(MCString{{"tag1","value1"},{"tag2",""},{"vendor1/tag3","value2"},{"vendor2/tag4",""}})); + EXPECT_THAT(msg.GetTags(), ContainerEq(MCString{{"tag1", "value1"}, + {"tag2", ""}, + {"vendor1/tag3", "value2"}, + {"vendor2/tag4", ""}})); EXPECT_EQ("irc.example.com", msg.GetNick().GetNick()); EXPECT_EQ("COMMAND", msg.GetCommand()); - EXPECT_THAT(msg.GetParams(), ContainerEq(VCString{"param1", "param2", "param3 param3"})); + EXPECT_THAT(msg.GetParams(), + ContainerEq(VCString{"param1", "param2", "param3 param3"})); } // when checking a valid message with a source but no tags TEST(MessageTest, ParseWithoutTags) { - const CString line = ":irc.example.com COMMAND param1 param2 :param3 param3"; + const CString line = + ":irc.example.com COMMAND param1 param2 :param3 param3"; CMessage msg(line); EXPECT_EQ(line, msg.ToString()); EXPECT_EQ(MCString(), msg.GetTags()); EXPECT_EQ("irc.example.com", msg.GetNick().GetNick()); EXPECT_EQ("COMMAND", msg.GetCommand()); - EXPECT_THAT(msg.GetParams(), ContainerEq(VCString{"param1", "param2", "param3 param3"})); + EXPECT_THAT(msg.GetParams(), + ContainerEq(VCString{"param1", "param2", "param3 param3"})); } // when checking a valid message with tags but no source TEST(MessageTest, ParseWithoutSource) { - const CString line = "@tag1=value1;tag2;vendor1/tag3=value2;vendor2/tag4 COMMAND param1 param2 :param3 param3"; + const CString line = + "@tag1=value1;tag2;vendor1/tag3=value2;vendor2/tag4 COMMAND param1 " + "param2 :param3 param3"; CMessage msg(line); EXPECT_EQ(line, msg.ToString()); - EXPECT_THAT(msg.GetTags(), ContainerEq(MCString{{"tag1","value1"},{"tag2",""},{"vendor1/tag3","value2"},{"vendor2/tag4",""}})); + EXPECT_THAT(msg.GetTags(), ContainerEq(MCString{{"tag1", "value1"}, + {"tag2", ""}, + {"vendor1/tag3", "value2"}, + {"vendor2/tag4", ""}})); EXPECT_EQ("", msg.GetNick().GetNick()); EXPECT_EQ("COMMAND", msg.GetCommand()); - EXPECT_THAT(msg.GetParams(), ContainerEq(VCString{"param1", "param2", "param3 param3"})); + EXPECT_THAT(msg.GetParams(), + ContainerEq(VCString{"param1", "param2", "param3 param3"})); } // when checking a valid message with no tags, source or parameters diff --git a/test/ModulesTest.cpp b/test/ModulesTest.cpp index 688c35bd..f6cd3b79 100644 --- a/test/ModulesTest.cpp +++ b/test/ModulesTest.cpp @@ -19,64 +19,225 @@ #include class ModulesTest : public ::testing::Test { -protected: + protected: void SetUp() { CZNC::CreateInstance(); } void TearDown() { CZNC::DestroyInstance(); } }; class CLegacyModule : public CModule { -public: - CLegacyModule() : CModule(nullptr, nullptr, nullptr, "legacy", "", CModInfo::NetworkModule) {} + public: + CLegacyModule() + : CModule(nullptr, nullptr, nullptr, "legacy", "", + CModInfo::NetworkModule) {} - EModRet OnUserCTCPReply(CString& sTarget, CString& sMessage) override { sTarget = "#legacy"; sMessage = "CLegacyModule::OnUserCTCPReply"; return eAction; } - EModRet OnUserCTCP(CString& sTarget, CString& sMessage) override { sTarget = "#legacy"; sMessage = "CLegacyModule::OnUserCTCP"; return eAction; } - EModRet OnUserAction(CString& sTarget, CString& sMessage) override { sTarget = "#legacy"; sMessage = "CLegacyModule::OnUserAction"; return eAction; } - EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { sTarget = "#legacy"; sMessage = "CLegacyModule::OnUserMsg"; return eAction; } - EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { sTarget = "#legacy"; sMessage = "CLegacyModule::OnUserNotice"; return eAction; } - EModRet OnUserJoin(CString& sChannel, CString& sKey) override { sChannel = "#legacy"; sKey = "CLegacyModule::OnUserJoin"; return eAction; } - EModRet OnUserPart(CString& sChannel, CString& sMessage) override { sChannel = "#legacy"; sMessage = "CLegacyModule::OnUserPart"; return eAction; } - EModRet OnUserTopic(CString& sChannel, CString& sTopic) override { sChannel = "#legacy"; sTopic = "CLegacyModule::OnUserTopic"; return eAction; } - EModRet OnUserQuit(CString& sMessage) override { sMessage = "CLegacyModule::OnUserQuit"; return eAction; } + EModRet OnUserCTCPReply(CString& sTarget, CString& sMessage) override { + sTarget = "#legacy"; + sMessage = "CLegacyModule::OnUserCTCPReply"; + return eAction; + } + EModRet OnUserCTCP(CString& sTarget, CString& sMessage) override { + sTarget = "#legacy"; + sMessage = "CLegacyModule::OnUserCTCP"; + return eAction; + } + EModRet OnUserAction(CString& sTarget, CString& sMessage) override { + sTarget = "#legacy"; + sMessage = "CLegacyModule::OnUserAction"; + return eAction; + } + EModRet OnUserMsg(CString& sTarget, CString& sMessage) override { + sTarget = "#legacy"; + sMessage = "CLegacyModule::OnUserMsg"; + return eAction; + } + EModRet OnUserNotice(CString& sTarget, CString& sMessage) override { + sTarget = "#legacy"; + sMessage = "CLegacyModule::OnUserNotice"; + return eAction; + } + EModRet OnUserJoin(CString& sChannel, CString& sKey) override { + sChannel = "#legacy"; + sKey = "CLegacyModule::OnUserJoin"; + return eAction; + } + EModRet OnUserPart(CString& sChannel, CString& sMessage) override { + sChannel = "#legacy"; + sMessage = "CLegacyModule::OnUserPart"; + return eAction; + } + EModRet OnUserTopic(CString& sChannel, CString& sTopic) override { + sChannel = "#legacy"; + sTopic = "CLegacyModule::OnUserTopic"; + return eAction; + } + EModRet OnUserQuit(CString& sMessage) override { + sMessage = "CLegacyModule::OnUserQuit"; + return eAction; + } - EModRet OnCTCPReply(CNick& Nick, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnCTCPReply"; return eAction; } - EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnPrivCTCP"; return eAction; } - EModRet OnChanCTCP(CNick& Nick, CChan& Channel, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnChanCTCP"; return eAction; } - EModRet OnPrivAction(CNick& Nick, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnPrivAction"; return eAction; } - EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnChanAction"; return eAction; } - EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnPrivMsg"; return eAction; } - EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnChanMsg"; return eAction; } - EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnPrivNotice"; return eAction; } - EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage) override { Nick.Parse("legacy!znc@znc.in"); sMessage = "CLegacyModule::OnChanNotice"; return eAction; } - EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override { Nick.Parse("legacy!znc@znc.in"); sTopic = "CLegacyModule::OnTopic"; return eAction; } + EModRet OnCTCPReply(CNick& Nick, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnCTCPReply"; + return eAction; + } + EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnPrivCTCP"; + return eAction; + } + EModRet OnChanCTCP(CNick& Nick, CChan& Channel, + CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnChanCTCP"; + return eAction; + } + EModRet OnPrivAction(CNick& Nick, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnPrivAction"; + return eAction; + } + EModRet OnChanAction(CNick& Nick, CChan& Channel, + CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnChanAction"; + return eAction; + } + EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnPrivMsg"; + return eAction; + } + EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnChanMsg"; + return eAction; + } + EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnPrivNotice"; + return eAction; + } + EModRet OnChanNotice(CNick& Nick, CChan& Channel, + CString& sMessage) override { + Nick.Parse("legacy!znc@znc.in"); + sMessage = "CLegacyModule::OnChanNotice"; + return eAction; + } + EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic) override { + Nick.Parse("legacy!znc@znc.in"); + sTopic = "CLegacyModule::OnTopic"; + return eAction; + } EModRet eAction = CONTINUE; }; class CMessageModule : public CModule { -public: - CMessageModule() : CModule(nullptr, nullptr, nullptr, "CMessage", "", CModInfo::NetworkModule) {} + public: + CMessageModule() + : CModule(nullptr, nullptr, nullptr, "CMessage", "", + CModInfo::NetworkModule) {} - EModRet OnUserCTCPReplyMessage(CCTCPMessage& Message) override { Message.SetTarget("#target"); Message.SetText("CMessageModule::OnUserCTCPReplyMessage"); return eAction; } - EModRet OnUserCTCPMessage(CCTCPMessage& Message) override { Message.SetTarget("#target"); Message.SetText("CMessageModule::OnUserCTCPMessage"); return eAction; } - EModRet OnUserActionMessage(CActionMessage& Message) override { Message.SetTarget("#target"); Message.SetText("CMessageModule::OnUserActionMessage"); return eAction; } - EModRet OnUserTextMessage(CTextMessage& Message) override { Message.SetTarget("#target"); Message.SetText("CMessageModule::OnUserTextMessage"); return eAction; } - EModRet OnUserNoticeMessage(CNoticeMessage& Message) override { Message.SetTarget("#target"); Message.SetText("CMessageModule::OnUserNoticeMessage"); return eAction; } - EModRet OnUserJoinMessage(CJoinMessage& Message) override { Message.SetTarget("#target"); Message.SetKey("CMessageModule::OnUserJoinMessage"); return eAction; } - EModRet OnUserPartMessage(CPartMessage& Message) override { Message.SetTarget("#target"); Message.SetReason("CMessageModule::OnUserPartMessage"); return eAction; } - EModRet OnUserTopicMessage(CTopicMessage& Message) override { Message.SetTarget("#target"); Message.SetTopic("CMessageModule::OnUserTopicMessage"); return eAction; } - EModRet OnUserQuitMessage(CQuitMessage& Message) override { Message.SetReason("CMessageModule::OnUserQuitMessage"); return eAction; } + EModRet OnUserCTCPReplyMessage(CCTCPMessage& Message) override { + Message.SetTarget("#target"); + Message.SetText("CMessageModule::OnUserCTCPReplyMessage"); + return eAction; + } + EModRet OnUserCTCPMessage(CCTCPMessage& Message) override { + Message.SetTarget("#target"); + Message.SetText("CMessageModule::OnUserCTCPMessage"); + return eAction; + } + EModRet OnUserActionMessage(CActionMessage& Message) override { + Message.SetTarget("#target"); + Message.SetText("CMessageModule::OnUserActionMessage"); + return eAction; + } + EModRet OnUserTextMessage(CTextMessage& Message) override { + Message.SetTarget("#target"); + Message.SetText("CMessageModule::OnUserTextMessage"); + return eAction; + } + EModRet OnUserNoticeMessage(CNoticeMessage& Message) override { + Message.SetTarget("#target"); + Message.SetText("CMessageModule::OnUserNoticeMessage"); + return eAction; + } + EModRet OnUserJoinMessage(CJoinMessage& Message) override { + Message.SetTarget("#target"); + Message.SetKey("CMessageModule::OnUserJoinMessage"); + return eAction; + } + EModRet OnUserPartMessage(CPartMessage& Message) override { + Message.SetTarget("#target"); + Message.SetReason("CMessageModule::OnUserPartMessage"); + return eAction; + } + EModRet OnUserTopicMessage(CTopicMessage& Message) override { + Message.SetTarget("#target"); + Message.SetTopic("CMessageModule::OnUserTopicMessage"); + return eAction; + } + EModRet OnUserQuitMessage(CQuitMessage& Message) override { + Message.SetReason("CMessageModule::OnUserQuitMessage"); + return eAction; + } - EModRet OnCTCPReplyMessage(CCTCPMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnCTCPReplyMessage"); return eAction; } - EModRet OnPrivCTCPMessage(CCTCPMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnPrivCTCPMessage"); return eAction; } - EModRet OnChanCTCPMessage(CCTCPMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnChanCTCPMessage"); return eAction; } - EModRet OnPrivActionMessage(CActionMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnPrivActionMessage"); return eAction; } - EModRet OnChanActionMessage(CActionMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnChanActionMessage"); return eAction; } - EModRet OnPrivMessage(CTextMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnPrivMessage"); return eAction; } - EModRet OnChanMessage(CTextMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnChanMessage"); return eAction; } - EModRet OnPrivNoticeMessage(CNoticeMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnPrivNoticeMessage"); return eAction; } - EModRet OnChanNoticeMessage(CNoticeMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetText("CMessageModule::OnChanNoticeMessage"); return eAction; } - EModRet OnTopicMessage(CTopicMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetTopic("CMessageModule::OnTopicMessage"); return eAction; } - EModRet OnNumericMessage(CNumericMessage& Message) override { Message.GetNick().SetNick("nick"); Message.SetCommand("123"); return eAction; } + EModRet OnCTCPReplyMessage(CCTCPMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnCTCPReplyMessage"); + return eAction; + } + EModRet OnPrivCTCPMessage(CCTCPMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnPrivCTCPMessage"); + return eAction; + } + EModRet OnChanCTCPMessage(CCTCPMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnChanCTCPMessage"); + return eAction; + } + EModRet OnPrivActionMessage(CActionMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnPrivActionMessage"); + return eAction; + } + EModRet OnChanActionMessage(CActionMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnChanActionMessage"); + return eAction; + } + EModRet OnPrivMessage(CTextMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnPrivMessage"); + return eAction; + } + EModRet OnChanMessage(CTextMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnChanMessage"); + return eAction; + } + EModRet OnPrivNoticeMessage(CNoticeMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnPrivNoticeMessage"); + return eAction; + } + EModRet OnChanNoticeMessage(CNoticeMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetText("CMessageModule::OnChanNoticeMessage"); + return eAction; + } + EModRet OnTopicMessage(CTopicMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetTopic("CMessageModule::OnTopicMessage"); + return eAction; + } + EModRet OnNumericMessage(CNumericMessage& Message) override { + Message.GetNick().SetNick("nick"); + Message.SetCommand("123"); + return eAction; + } EModRet eAction = CONTINUE; }; @@ -98,7 +259,8 @@ TEST_F(ModulesTest, Hooks) { LegacyMod.eAction = CModule::CONTINUE; Modules.OnUserCTCPReplyMessage(UserCTCPReply); EXPECT_EQ("#target", UserCTCPReply.GetTarget()); - EXPECT_EQ("CMessageModule::OnUserCTCPReplyMessage", UserCTCPReply.GetText()); + EXPECT_EQ("CMessageModule::OnUserCTCPReplyMessage", + UserCTCPReply.GetText()); CCTCPMessage UserCTCPMsg; LegacyMod.eAction = CModule::HALT; diff --git a/test/NetworkTest.cpp b/test/NetworkTest.cpp index e1e035ae..ef222128 100644 --- a/test/NetworkTest.cpp +++ b/test/NetworkTest.cpp @@ -20,7 +20,7 @@ #include class NetworkTest : public ::testing::Test { -protected: + protected: void SetUp() { CZNC::CreateInstance(); } void TearDown() { CZNC::DestroyInstance(); } }; diff --git a/test/QueryTest.cpp b/test/QueryTest.cpp index 7fec4ee6..4552ee44 100644 --- a/test/QueryTest.cpp +++ b/test/QueryTest.cpp @@ -24,7 +24,7 @@ using ::testing::ElementsAre; using ::testing::MatchesRegex; class QueryTest : public ::testing::Test { -protected: + protected: void SetUp() { CZNC::CreateInstance(); } void TearDown() { CZNC::DestroyInstance(); } }; @@ -85,19 +85,28 @@ TEST_F(QueryTest, SendBuffer) { client.Reset(); query.SendBuffer(&client); - EXPECT_THAT(client.vsLines, ElementsAre(MatchesRegex(R"(:sender PRIVMSG me :\[\d\d:\d\d:\d\d\] a message)"), - MatchesRegex(R"(:sender NOTICE #znc :\[\d\d:\d\d:\d\d\] a notice)"))); + EXPECT_THAT( + client.vsLines, + ElementsAre( + MatchesRegex(R"(:sender PRIVMSG me :\[\d\d:\d\d:\d\d\] a message)"), + MatchesRegex( + R"(:sender NOTICE #znc :\[\d\d:\d\d:\d\d\] a notice)"))); client.Reset(); user.SetTimestampPrepend(false); query.SendBuffer(&client); - EXPECT_THAT(client.vsLines, ElementsAre(":sender PRIVMSG me :a message", ":sender NOTICE #znc :a notice")); + EXPECT_THAT(client.vsLines, ElementsAre(":sender PRIVMSG me :a message", + ":sender NOTICE #znc :a notice")); client.Reset(); user.SetTimestampAppend(true); query.SendBuffer(&client); - EXPECT_THAT(client.vsLines, ElementsAre(MatchesRegex(R"(:sender PRIVMSG me :a message \[\d\d:\d\d:\d\d\])"), - MatchesRegex(R"(:sender NOTICE #znc :a notice \[\d\d:\d\d:\d\d\])"))); + EXPECT_THAT( + client.vsLines, + ElementsAre( + MatchesRegex(R"(:sender PRIVMSG me :a message \[\d\d:\d\d:\d\d\])"), + MatchesRegex( + R"(:sender NOTICE #znc :a notice \[\d\d:\d\d:\d\d\])"))); network.ClientDisconnected(&client); } diff --git a/test/StringTest.cpp b/test/StringTest.cpp index 4f049abf..045e5359 100644 --- a/test/StringTest.cpp +++ b/test/StringTest.cpp @@ -23,8 +23,9 @@ static void PrintTo(const CString& s, std::ostream* o) { } class EscapeTest : public ::testing::Test { -protected: - void testEncode(const CString& in, const CString& expectedOut, const CString& sformat) { + protected: + void testEncode(const CString& in, const CString& expectedOut, + const CString& sformat) { CString::EEscape format = CString::ToEscape(sformat); CString out; @@ -37,14 +38,14 @@ protected: EXPECT_EQ(in, out); } - void testString(const CString& in, const CString& url, - const CString& html, const CString& sql, const CString& tag) { + void testString(const CString& in, const CString& url, const CString& html, + const CString& sql, const CString& tag) { SCOPED_TRACE("String: " + in); - testEncode(in, url, "URL"); + testEncode(in, url, "URL"); testEncode(in, html, "HTML"); - testEncode(in, sql, "SQL"); - testEncode(in, tag, "MSGTAG"); + testEncode(in, sql, "SQL"); + testEncode(in, tag, "MSGTAG"); } }; @@ -64,7 +65,7 @@ TEST(StringTest, Bool) { EXPECT_FALSE(CString(false).ToBool()); } -#define CS(s) (CString((s), sizeof(s)-1)) +#define CS(s) (CString((s), sizeof(s) - 1)) TEST(StringTest, Cmp) { CString s = "Bbb"; @@ -93,26 +94,30 @@ TEST(StringTest, Wild) { EXPECT_FALSE(CString::WildCmp("*a*b*c*", "xy", CString::CaseSensitive)); EXPECT_FALSE(CString::WildCmp("*a*b*c*", "xy", CString::CaseInsensitive)); - EXPECT_TRUE(CString::WildCmp("*!?bar@foo", "I_am!~bar@foo", CString::CaseSensitive)); - EXPECT_TRUE(CString::WildCmp("*!?bar@foo", "I_am!~bar@foo", CString::CaseInsensitive)); + EXPECT_TRUE(CString::WildCmp("*!?bar@foo", "I_am!~bar@foo", + CString::CaseSensitive)); + EXPECT_TRUE(CString::WildCmp("*!?bar@foo", "I_am!~bar@foo", + CString::CaseInsensitive)); - EXPECT_FALSE(CString::WildCmp("*!?BAR@foo", "I_am!~bar@foo", CString::CaseSensitive)); - EXPECT_TRUE (CString::WildCmp("*!?BAR@foo", "I_am!~bar@foo", CString::CaseInsensitive)); + EXPECT_FALSE(CString::WildCmp("*!?BAR@foo", "I_am!~bar@foo", + CString::CaseSensitive)); + EXPECT_TRUE(CString::WildCmp("*!?BAR@foo", "I_am!~bar@foo", + CString::CaseInsensitive)); EXPECT_TRUE(CString::WildCmp("*a*b*c*", "abc", CString::CaseSensitive)); EXPECT_TRUE(CString::WildCmp("*a*b*c*", "abc", CString::CaseInsensitive)); EXPECT_FALSE(CString::WildCmp("*A*b*c*", "abc", CString::CaseSensitive)); - EXPECT_TRUE (CString::WildCmp("*A*b*c*", "abc", CString::CaseInsensitive)); + EXPECT_TRUE(CString::WildCmp("*A*b*c*", "abc", CString::CaseInsensitive)); EXPECT_FALSE(CString::WildCmp("*a*b*c*", "Abc", CString::CaseSensitive)); - EXPECT_TRUE (CString::WildCmp("*a*b*c*", "Abc", CString::CaseInsensitive)); + EXPECT_TRUE(CString::WildCmp("*a*b*c*", "Abc", CString::CaseInsensitive)); EXPECT_TRUE(CString::WildCmp("*a*b*c*", "axbyc", CString::CaseSensitive)); EXPECT_TRUE(CString::WildCmp("*a*b*c*", "axbyc", CString::CaseInsensitive)); EXPECT_FALSE(CString::WildCmp("*a*B*c*", "AxByC", CString::CaseSensitive)); - EXPECT_TRUE (CString::WildCmp("*a*B*c*", "AxByC", CString::CaseInsensitive)); + EXPECT_TRUE(CString::WildCmp("*a*B*c*", "AxByC", CString::CaseInsensitive)); } TEST(StringTest, Case) { @@ -151,8 +156,10 @@ TEST(StringTest, Split) { EXPECT_EQ(" c", CS("a c").Token(1, false, " ")); EXPECT_EQ("c", CS("a c").Token(1, false, " ")); EXPECT_EQ("b c", CS("a (b c) d").Token(1, false, " ", false, "(", ")")); - EXPECT_EQ("(b c)", CS("a (b c) d").Token(1, false, " ", false, "(", ")", false)); - EXPECT_EQ("d", CS("a (b c) d").Token(2, false, " ", false, "(", ")", false)); + EXPECT_EQ("(b c)", + CS("a (b c) d").Token(1, false, " ", false, "(", ")", false)); + EXPECT_EQ("d", + CS("a (b c) d").Token(2, false, " ", false, "(", ")", false)); VCString vexpected; VCString vresult; @@ -163,7 +170,7 @@ TEST(StringTest, Split) { CS("a b c").Split(" ", vresult); EXPECT_EQ(vexpected, vresult); - MCString mexpected = { {"a","b"}, {"c","d"} }; + MCString mexpected = {{"a", "b"}, {"c", "d"}}; MCString mresult; CS("a=x&c=d&a=b").URLSplit(mresult); @@ -171,7 +178,7 @@ TEST(StringTest, Split) { } TEST(StringTest, NamedFormat) { - MCString m = { {"a","b"} }; + MCString m = {{"a", "b"}}; EXPECT_EQ("{xbyb", CString::NamedFormat(CS("\\{x{a}y{a}"), m)); } @@ -179,58 +186,80 @@ TEST(StringTest, Hash) { EXPECT_EQ("d41d8cd98f00b204e9800998ecf8427e", CS("").MD5()); EXPECT_EQ("0cc175b9c0f1b6a831c399e269772661", CS("a").MD5()); - EXPECT_EQ("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", CS("").SHA256()); - EXPECT_EQ("ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", CS("a").SHA256()); + EXPECT_EQ( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + CS("").SHA256()); + EXPECT_EQ( + "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", + CS("a").SHA256()); } TEST(StringTest, Equals) { EXPECT_TRUE(CS("ABC").Equals("abc")); EXPECT_TRUE(CS("ABC").Equals("abc", CString::CaseInsensitive)); EXPECT_FALSE(CS("ABC").Equals("abc", CString::CaseSensitive)); - EXPECT_TRUE(CS("ABC").Equals("abc", false)); // deprecated - EXPECT_FALSE(CS("ABC").Equals("abc", true)); // deprecated + EXPECT_TRUE(CS("ABC").Equals("abc", false)); // deprecated + EXPECT_FALSE(CS("ABC").Equals("abc", true)); // deprecated } TEST(StringTest, Find) { EXPECT_EQ(0u, CString("Hello, I'm Bob").Find("Hello")); - EXPECT_EQ(0u, CString("Hello, I'm Bob").Find("Hello", CString::CaseInsensitive)); - EXPECT_EQ(0u, CString("Hello, I'm Bob").Find("Hello", CString::CaseSensitive)); + EXPECT_EQ( + 0u, CString("Hello, I'm Bob").Find("Hello", CString::CaseInsensitive)); + EXPECT_EQ(0u, + CString("Hello, I'm Bob").Find("Hello", CString::CaseSensitive)); EXPECT_EQ(7u, CString("Hello, I'm Bob").Find("i'm")); - EXPECT_EQ(7u, CString("Hello, I'm Bob").Find("i'm", CString::CaseInsensitive)); - EXPECT_EQ(CString::npos, CString("Hello, I'm Bob").Find("i'm", CString::CaseSensitive)); + EXPECT_EQ(7u, + CString("Hello, I'm Bob").Find("i'm", CString::CaseInsensitive)); + EXPECT_EQ(CString::npos, + CString("Hello, I'm Bob").Find("i'm", CString::CaseSensitive)); } TEST(StringTest, StartsWith) { EXPECT_TRUE(CString("Hello, I'm Bob").StartsWith("Hello")); - EXPECT_TRUE(CString("Hello, I'm Bob").StartsWith("Hello", CString::CaseInsensitive)); - EXPECT_TRUE(CString("Hello, I'm Bob").StartsWith("Hello", CString::CaseSensitive)); + EXPECT_TRUE(CString("Hello, I'm Bob") + .StartsWith("Hello", CString::CaseInsensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").StartsWith("Hello", CString::CaseSensitive)); EXPECT_TRUE(CString("Hello, I'm Bob").StartsWith("hello")); - EXPECT_TRUE(CString("Hello, I'm Bob").StartsWith("hello", CString::CaseInsensitive)); - EXPECT_FALSE(CString("Hello, I'm Bob").StartsWith("hello", CString::CaseSensitive)); + EXPECT_TRUE(CString("Hello, I'm Bob") + .StartsWith("hello", CString::CaseInsensitive)); + EXPECT_FALSE( + CString("Hello, I'm Bob").StartsWith("hello", CString::CaseSensitive)); } TEST(StringTest, EndsWith) { EXPECT_TRUE(CString("Hello, I'm Bob").EndsWith("Bob")); - EXPECT_TRUE(CString("Hello, I'm Bob").EndsWith("Bob", CString::CaseInsensitive)); - EXPECT_TRUE(CString("Hello, I'm Bob").EndsWith("Bob", CString::CaseSensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").EndsWith("Bob", CString::CaseInsensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").EndsWith("Bob", CString::CaseSensitive)); EXPECT_TRUE(CString("Hello, I'm Bob").EndsWith("bob")); - EXPECT_TRUE(CString("Hello, I'm Bob").EndsWith("bob", CString::CaseInsensitive)); - EXPECT_FALSE(CString("Hello, I'm Bob").EndsWith("bob", CString::CaseSensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").EndsWith("bob", CString::CaseInsensitive)); + EXPECT_FALSE( + CString("Hello, I'm Bob").EndsWith("bob", CString::CaseSensitive)); } TEST(StringTest, Contains) { EXPECT_TRUE(CString("Hello, I'm Bob").Contains("Hello")); - EXPECT_TRUE(CString("Hello, I'm Bob").Contains("Hello", CString::CaseInsensitive)); - EXPECT_TRUE(CString("Hello, I'm Bob").Contains("Hello", CString::CaseSensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").Contains("Hello", CString::CaseInsensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").Contains("Hello", CString::CaseSensitive)); EXPECT_TRUE(CString("Hello, I'm Bob").Contains("i'm")); - EXPECT_TRUE(CString("Hello, I'm Bob").Contains("i'm", CString::CaseInsensitive)); - EXPECT_FALSE(CString("Hello, I'm Bob").Contains("i'm", CString::CaseSensitive)); + EXPECT_TRUE( + CString("Hello, I'm Bob").Contains("i'm", CString::CaseInsensitive)); + EXPECT_FALSE( + CString("Hello, I'm Bob").Contains("i'm", CString::CaseSensitive)); EXPECT_TRUE(CString("Hello, I'm Bob").Contains("i'm bob")); - EXPECT_TRUE(CString("Hello, I'm Bob").Contains("i'm bob", CString::CaseInsensitive)); - EXPECT_FALSE(CString("Hello, I'm Bob").Contains("i'm bob", CString::CaseSensitive)); + EXPECT_TRUE(CString("Hello, I'm Bob") + .Contains("i'm bob", CString::CaseInsensitive)); + EXPECT_FALSE( + CString("Hello, I'm Bob").Contains("i'm bob", CString::CaseSensitive)); } diff --git a/test/ThreadTest.cpp b/test/ThreadTest.cpp index 8f06b14f..d7229aad 100644 --- a/test/ThreadTest.cpp +++ b/test/ThreadTest.cpp @@ -19,11 +19,13 @@ #include class CWaitingJob : public CJob { -public: + public: CWaitingJob(bool& destroyed) - : m_bDestroyed(destroyed), m_Mutex(), m_CV(), m_bThreadReady(false), m_bThreadDone(false) { - }; - + : m_bDestroyed(destroyed), + m_Mutex(), + m_CV(), + m_bThreadReady(false), + m_bThreadDone(false){}; ~CWaitingJob() { EXPECT_TRUE(m_bThreadReady); @@ -35,8 +37,7 @@ public: void signal() { CMutexLocker locker(m_Mutex); // Wait for the thread to run - while (!m_bThreadReady) - m_CV.wait(m_Mutex); + while (!m_bThreadReady) m_CV.wait(m_Mutex); // and signal it to exit m_bThreadDone = true; @@ -50,13 +51,12 @@ public: m_CV.notify_all(); // wait for our exit signal - while (!m_bThreadDone) - m_CV.wait(m_Mutex); + while (!m_bThreadDone) m_CV.wait(m_Mutex); } virtual void runMain() {} -private: + private: bool& m_bDestroyed; CMutex m_Mutex; CConditionVariable m_CV; @@ -66,20 +66,21 @@ private: TEST(Thread, RunJob) { bool destroyed = false; - CWaitingJob *pJob = new CWaitingJob(destroyed); + CWaitingJob* pJob = new CWaitingJob(destroyed); CThreadPool::Get().addJob(pJob); pJob->signal(); - while (!destroyed) - CThreadPool::Get().handlePipeReadable(); + while (!destroyed) CThreadPool::Get().handlePipeReadable(); } class CCancelJob : public CJob { -public: + public: CCancelJob(bool& destroyed) - : m_bDestroyed(destroyed), m_Mutex(), m_CVThreadReady(), m_bThreadReady(false) { - } + : m_bDestroyed(destroyed), + m_Mutex(), + m_CVThreadReady(), + m_bThreadReady(false) {} ~CCancelJob() { EXPECT_TRUE(wasCancelled()); @@ -89,8 +90,7 @@ public: void wait() { CMutexLocker locker(m_Mutex); // Wait for the thread to run - while (!m_bThreadReady) - m_CVThreadReady.wait(m_Mutex); + while (!m_bThreadReady) m_CVThreadReady.wait(m_Mutex); } virtual void runThread() { @@ -113,9 +113,9 @@ public: } } - virtual void runMain() { } + virtual void runMain() {} -private: + private: bool& m_bDestroyed; CMutex m_Mutex; CConditionVariable m_CVThreadReady; @@ -124,7 +124,7 @@ private: TEST(Thread, CancelJobEarly) { bool destroyed = false; - CCancelJob *pJob = new CCancelJob(destroyed); + CCancelJob* pJob = new CCancelJob(destroyed); CThreadPool::Get().addJob(pJob); // Don't wait for the job to run. The idea here is that we are calling @@ -137,7 +137,7 @@ TEST(Thread, CancelJobEarly) { TEST(Thread, CancelJobWhileRunning) { bool destroyed = false; - CCancelJob *pJob = new CCancelJob(destroyed); + CCancelJob* pJob = new CCancelJob(destroyed); CThreadPool::Get().addJob(pJob); // Wait for the job to run @@ -149,26 +149,24 @@ TEST(Thread, CancelJobWhileRunning) { } class CEmptyJob : public CJob { -public: - CEmptyJob(bool& destroyed) - : m_bDestroyed(destroyed) { - } + public: + CEmptyJob(bool& destroyed) : m_bDestroyed(destroyed) {} ~CEmptyJob() { EXPECT_TRUE(wasCancelled()); m_bDestroyed = true; } - virtual void runThread() { } - virtual void runMain() { } + virtual void runThread() {} + virtual void runMain() {} -private: + private: bool& m_bDestroyed; }; TEST(Thread, CancelJobWhenDone) { bool destroyed = false; - CEmptyJob *pJob = new CEmptyJob(destroyed); + CEmptyJob* pJob = new CEmptyJob(destroyed); CThreadPool::Get().addJob(pJob); @@ -176,7 +174,8 @@ TEST(Thread, CancelJobWhenDone) { fd_set fds; FD_ZERO(&fds); FD_SET(CThreadPool::Get().getReadFD(), &fds); - EXPECT_EQ(1, select(1 + CThreadPool::Get().getReadFD(), &fds, nullptr, nullptr, nullptr)); + EXPECT_EQ(1, select(1 + CThreadPool::Get().getReadFD(), &fds, nullptr, + nullptr, nullptr)); // And only cancel it afterwards CThreadPool::Get().cancelJob(pJob); diff --git a/test/UtilsTest.cpp b/test/UtilsTest.cpp index 13d72cf5..42e3da25 100644 --- a/test/UtilsTest.cpp +++ b/test/UtilsTest.cpp @@ -20,29 +20,36 @@ TEST(IRC32, GetMessageTags) { EXPECT_EQ(MCString(), CUtils::GetMessageTags("")); - EXPECT_EQ(MCString(), CUtils::GetMessageTags(":nick!ident@host PRIVMSG #chan :hello world")); + EXPECT_EQ(MCString(), CUtils::GetMessageTags( + ":nick!ident@host PRIVMSG #chan :hello world")); - MCString exp = { {"a","b"} }; + MCString exp = {{"a", "b"}}; EXPECT_EQ(exp, CUtils::GetMessageTags("@a=b")); - EXPECT_EQ(exp, CUtils::GetMessageTags("@a=b :nick!ident@host PRIVMSG #chan :hello world")); + EXPECT_EQ(exp, CUtils::GetMessageTags( + "@a=b :nick!ident@host PRIVMSG #chan :hello world")); EXPECT_EQ(exp, CUtils::GetMessageTags("@a=b :rest")); exp.clear(); - exp = { {"ab","cdef"}, {"znc.in/gh-ij","klmn,op"} }; - EXPECT_EQ(exp, CUtils::GetMessageTags("@ab=cdef;znc.in/gh-ij=klmn,op :rest")); + exp = {{"ab", "cdef"}, {"znc.in/gh-ij", "klmn,op"}}; + EXPECT_EQ(exp, + CUtils::GetMessageTags("@ab=cdef;znc.in/gh-ij=klmn,op :rest")); - exp = { {"a","==b=="} }; + exp = {{"a", "==b=="}}; EXPECT_EQ(exp, CUtils::GetMessageTags("@a===b== :rest")); exp.clear(); - exp = { {"a",""}, {"b","c"}, {"d",""} }; + exp = {{"a", ""}, {"b", "c"}, {"d", ""}}; EXPECT_EQ(exp, CUtils::GetMessageTags("@a;b=c;d :rest")); - exp = { {"semi-colon",";"}, {"space"," "}, {"NUL",{'\0'}}, {"backslash","\\"}, {"CR",{'\r'}}, {"LF",{'\n'}} }; - EXPECT_EQ(exp, CUtils::GetMessageTags(R"(@semi-colon=\:;space=\s;NUL=\0;backslash=\\;CR=\r;LF=\n :rest)")); + exp = {{"semi-colon", ";"}, {"space", " "}, {"NUL", {'\0'}}, + {"backslash", "\\"}, {"CR", {'\r'}}, {"LF", {'\n'}}}; + EXPECT_EQ( + exp, + CUtils::GetMessageTags( + R"(@semi-colon=\:;space=\s;NUL=\0;backslash=\\;CR=\r;LF=\n :rest)")); exp.clear(); - exp = { {"a","; \\\r\n"} }; + exp = {{"a", "; \\\r\n"}}; EXPECT_EQ(exp, CUtils::GetMessageTags(R"(@a=\:\s\\\r\n :rest)")); exp.clear(); } @@ -54,23 +61,26 @@ TEST(IRC32, SetMessageTags) { CUtils::SetMessageTags(sLine, MCString()); EXPECT_EQ(":rest", sLine); - MCString tags = { {"a","b"} }; + MCString tags = {{"a", "b"}}; CUtils::SetMessageTags(sLine, tags); EXPECT_EQ("@a=b :rest", sLine); - tags = { {"a","b"}, {"c","d"} }; + tags = {{"a", "b"}, {"c", "d"}}; CUtils::SetMessageTags(sLine, tags); EXPECT_EQ("@a=b;c=d :rest", sLine); - tags = { {"a","b"}, {"c","d"}, {"e",""} }; + tags = {{"a", "b"}, {"c", "d"}, {"e", ""}}; CUtils::SetMessageTags(sLine, tags); EXPECT_EQ("@a=b;c=d;e :rest", sLine); - tags = { {"semi-colon",";"}, {"space"," "}, {"NUL",{'\0'}}, {"backslash","\\"}, {"CR",{'\r'}}, {"LF",{'\n'}} }; + tags = {{"semi-colon", ";"}, {"space", " "}, {"NUL", {'\0'}}, + {"backslash", "\\"}, {"CR", {'\r'}}, {"LF", {'\n'}}}; CUtils::SetMessageTags(sLine, tags); - EXPECT_EQ(R"(@CR=\r;LF=\n;NUL=\0;backslash=\\;semi-colon=\:;space=\s :rest)", sLine); + EXPECT_EQ( + R"(@CR=\r;LF=\n;NUL=\0;backslash=\\;semi-colon=\:;space=\s :rest)", + sLine); - tags = { {"a","; \\\r\n"} }; + tags = {{"a", "; \\\r\n"}}; CUtils::SetMessageTags(sLine, tags); EXPECT_EQ(R"(@a=\:\s\\\r\n :rest)", sLine); }